GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_binding.cc Lines: 194 208 93.3 %
Date: 2021-08-24 04:12:49 Branches: 96 124 77.4 %

Line Branch Exec Source
1
#include "node_binding.h"
2
#include <atomic>
3
#include "env-inl.h"
4
#include "node_errors.h"
5
#include "node_external_reference.h"
6
#include "node_native_module_env.h"
7
#include "util.h"
8
9
#include <string>
10
11
#if HAVE_OPENSSL
12
#define NODE_BUILTIN_OPENSSL_MODULES(V) V(crypto) V(tls_wrap)
13
#else
14
#define NODE_BUILTIN_OPENSSL_MODULES(V)
15
#endif
16
17
#if NODE_HAVE_I18N_SUPPORT
18
#define NODE_BUILTIN_ICU_MODULES(V) V(icu)
19
#else
20
#define NODE_BUILTIN_ICU_MODULES(V)
21
#endif
22
23
#if HAVE_INSPECTOR
24
#define NODE_BUILTIN_PROFILER_MODULES(V) V(profiler)
25
#else
26
#define NODE_BUILTIN_PROFILER_MODULES(V)
27
#endif
28
29
#if HAVE_DTRACE || HAVE_ETW
30
#define NODE_BUILTIN_DTRACE_MODULES(V) V(dtrace)
31
#else
32
#define NODE_BUILTIN_DTRACE_MODULES(V)
33
#endif
34
35
// A list of built-in modules. In order to do module registration
36
// in node::Init(), need to add built-in modules in the following list.
37
// Then in binding::RegisterBuiltinModules(), it calls modules' registration
38
// function. This helps the built-in modules are loaded properly when
39
// node is built as static library. No need to depend on the
40
// __attribute__((constructor)) like mechanism in GCC.
41
#define NODE_BUILTIN_STANDARD_MODULES(V)                                       \
42
  V(async_wrap)                                                                \
43
  V(blob)                                                                      \
44
  V(block_list)                                                                \
45
  V(buffer)                                                                    \
46
  V(cares_wrap)                                                                \
47
  V(config)                                                                    \
48
  V(contextify)                                                                \
49
  V(credentials)                                                               \
50
  V(errors)                                                                    \
51
  V(fs)                                                                        \
52
  V(fs_dir)                                                                    \
53
  V(fs_event_wrap)                                                             \
54
  V(heap_utils)                                                                \
55
  V(http2)                                                                     \
56
  V(http_parser)                                                               \
57
  V(inspector)                                                                 \
58
  V(js_stream)                                                                 \
59
  V(js_udp_wrap)                                                               \
60
  V(messaging)                                                                 \
61
  V(module_wrap)                                                               \
62
  V(native_module)                                                             \
63
  V(options)                                                                   \
64
  V(os)                                                                        \
65
  V(performance)                                                               \
66
  V(pipe_wrap)                                                                 \
67
  V(process_wrap)                                                              \
68
  V(process_methods)                                                           \
69
  V(report)                                                                    \
70
  V(serdes)                                                                    \
71
  V(signal_wrap)                                                               \
72
  V(spawn_sync)                                                                \
73
  V(stream_pipe)                                                               \
74
  V(stream_wrap)                                                               \
75
  V(string_decoder)                                                            \
76
  V(symbols)                                                                   \
77
  V(task_queue)                                                                \
78
  V(tcp_wrap)                                                                  \
79
  V(timers)                                                                    \
80
  V(trace_events)                                                              \
81
  V(tty_wrap)                                                                  \
82
  V(types)                                                                     \
83
  V(udp_wrap)                                                                  \
84
  V(url)                                                                       \
85
  V(util)                                                                      \
86
  V(uv)                                                                        \
87
  V(v8)                                                                        \
88
  V(wasi)                                                                      \
89
  V(worker)                                                                    \
90
  V(watchdog)                                                                  \
91
  V(zlib)
92
93
#define NODE_BUILTIN_MODULES(V)                                                \
94
  NODE_BUILTIN_STANDARD_MODULES(V)                                             \
95
  NODE_BUILTIN_OPENSSL_MODULES(V)                                              \
96
  NODE_BUILTIN_ICU_MODULES(V)                                                  \
97
  NODE_BUILTIN_PROFILER_MODULES(V)                                             \
98
  NODE_BUILTIN_DTRACE_MODULES(V)
99
100
// This is used to load built-in modules. Instead of using
101
// __attribute__((constructor)), we call the _register_<modname>
102
// function for each built-in modules explicitly in
103
// binding::RegisterBuiltinModules(). This is only forward declaration.
104
// The definitions are in each module's implementation when calling
105
// the NODE_MODULE_CONTEXT_AWARE_INTERNAL.
106
#define V(modname) void _register_##modname();
107
NODE_BUILTIN_MODULES(V)
108
#undef V
109
110
#ifdef _AIX
111
// On AIX, dlopen() behaves differently from other operating systems, in that
112
// it returns unique values from each call, rather than identical values, when
113
// loading the same handle.
114
// We try to work around that by providing wrappers for the dlopen() family of
115
// functions, and using st_dev and st_ino for the file that is to be loaded
116
// as keys for a cache.
117
118
namespace node {
119
namespace dlwrapper {
120
121
struct dl_wrap {
122
  uint64_t st_dev;
123
  uint64_t st_ino;
124
  uint64_t refcount;
125
  void* real_handle;
126
127
  struct hash {
128
    size_t operator()(const dl_wrap* wrap) const {
129
      return std::hash<uint64_t>()(wrap->st_dev) ^
130
             std::hash<uint64_t>()(wrap->st_ino);
131
    }
132
  };
133
134
  struct equal {
135
    bool operator()(const dl_wrap* a,
136
                    const dl_wrap* b) const {
137
      return a->st_dev == b->st_dev && a->st_ino == b->st_ino;
138
    }
139
  };
140
};
141
142
static Mutex dlhandles_mutex;
143
static std::unordered_set<dl_wrap*, dl_wrap::hash, dl_wrap::equal>
144
    dlhandles;
145
static thread_local std::string dlerror_storage;
146
147
char* wrapped_dlerror() {
148
  return &dlerror_storage[0];
149
}
150
151
void* wrapped_dlopen(const char* filename, int flags) {
152
  CHECK_NOT_NULL(filename);  // This deviates from the 'real' dlopen().
153
  Mutex::ScopedLock lock(dlhandles_mutex);
154
155
  uv_fs_t req;
156
  auto cleanup = OnScopeLeave([&]() { uv_fs_req_cleanup(&req); });
157
  int rc = uv_fs_stat(nullptr, &req, filename, nullptr);
158
159
  if (rc != 0) {
160
    dlerror_storage = uv_strerror(rc);
161
    return nullptr;
162
  }
163
164
  dl_wrap search = {
165
    req.statbuf.st_dev,
166
    req.statbuf.st_ino,
167
    0, nullptr
168
  };
169
170
  auto it = dlhandles.find(&search);
171
  if (it != dlhandles.end()) {
172
    (*it)->refcount++;
173
    return *it;
174
  }
175
176
  void* real_handle = dlopen(filename, flags);
177
  if (real_handle == nullptr) {
178
    dlerror_storage = dlerror();
179
    return nullptr;
180
  }
181
  dl_wrap* wrap = new dl_wrap();
182
  wrap->st_dev = req.statbuf.st_dev;
183
  wrap->st_ino = req.statbuf.st_ino;
184
  wrap->refcount = 1;
185
  wrap->real_handle = real_handle;
186
  dlhandles.insert(wrap);
187
  return wrap;
188
}
189
190
int wrapped_dlclose(void* handle) {
191
  Mutex::ScopedLock lock(dlhandles_mutex);
192
  dl_wrap* wrap = static_cast<dl_wrap*>(handle);
193
  int ret = 0;
194
  CHECK_GE(wrap->refcount, 1);
195
  if (--wrap->refcount == 0) {
196
    ret = dlclose(wrap->real_handle);
197
    if (ret != 0) dlerror_storage = dlerror();
198
    dlhandles.erase(wrap);
199
    delete wrap;
200
  }
201
  return ret;
202
}
203
204
void* wrapped_dlsym(void* handle, const char* symbol) {
205
  if (handle == RTLD_DEFAULT || handle == RTLD_NEXT)
206
    return dlsym(handle, symbol);
207
  dl_wrap* wrap = static_cast<dl_wrap*>(handle);
208
  return dlsym(wrap->real_handle, symbol);
209
}
210
211
#define dlopen node::dlwrapper::wrapped_dlopen
212
#define dlerror node::dlwrapper::wrapped_dlerror
213
#define dlclose node::dlwrapper::wrapped_dlclose
214
#define dlsym node::dlwrapper::wrapped_dlsym
215
216
}  // namespace dlwrapper
217
}  // namespace node
218
219
#endif  // _AIX
220
221
#ifdef __linux__
222
19
static bool libc_may_be_musl() {
223

19
  static std::atomic_bool retval;  // Cache the return value.
224
  static std::atomic_bool has_cached_retval { false };
225
19
  if (has_cached_retval) return retval;
226
18
  retval = dlsym(RTLD_DEFAULT, "gnu_get_libc_version") == nullptr;
227
18
  has_cached_retval = true;
228
18
  return retval;
229
}
230
#else  // __linux__
231
static bool libc_may_be_musl() { return false; }
232
#endif  // __linux__
233
234
namespace node {
235
236
using v8::Context;
237
using v8::Exception;
238
using v8::Function;
239
using v8::FunctionCallbackInfo;
240
using v8::Local;
241
using v8::Object;
242
using v8::String;
243
using v8::Value;
244
245
// Globals per process
246
static node_module* modlist_internal;
247
static node_module* modlist_linked;
248
static thread_local node_module* thread_local_modpending;
249
250
// This is set by node::Init() which is used by embedders
251
bool node_is_initialized = false;
252
253
265022
extern "C" void node_module_register(void* m) {
254
265022
  struct node_module* mp = reinterpret_cast<struct node_module*>(m);
255
256
265022
  if (mp->nm_flags & NM_F_INTERNAL) {
257
264870
    mp->nm_link = modlist_internal;
258
264870
    modlist_internal = mp;
259
152
  } else if (!node_is_initialized) {
260
    // "Linked" modules are included as part of the node project.
261
    // Like builtins they are registered *before* node::Init runs.
262
1
    mp->nm_flags = NM_F_LINKED;
263
1
    mp->nm_link = modlist_linked;
264
1
    modlist_linked = mp;
265
  } else {
266
151
    thread_local_modpending = mp;
267
  }
268
265022
}
269
270
namespace binding {
271
272
static struct global_handle_map_t {
273
 public:
274
150
  void set(void* handle, node_module* mod) {
275
150
    CHECK_NE(handle, nullptr);
276
150
    Mutex::ScopedLock lock(mutex_);
277
278
150
    map_[handle].module = mod;
279
    // We need to store this flag internally to avoid a chicken-and-egg problem
280
    // during cleanup. By the time we actually use the flag's value,
281
    // the shared object has been unloaded, and its memory would be gone,
282
    // making it impossible to access fields of `mod` --
283
    // unless `mod` *is* dynamically allocated, but we cannot know that
284
    // without checking the flag.
285
150
    map_[handle].wants_delete_module = mod->nm_flags & NM_F_DELETEME;
286
150
    map_[handle].refcount++;
287
150
  }
288
289
6
  node_module* get_and_increase_refcount(void* handle) {
290
6
    CHECK_NE(handle, nullptr);
291
12
    Mutex::ScopedLock lock(mutex_);
292
293
6
    auto it = map_.find(handle);
294
6
    if (it == map_.end()) return nullptr;
295
5
    it->second.refcount++;
296
5
    return it->second.module;
297
  }
298
299
16
  void erase(void* handle) {
300
16
    CHECK_NE(handle, nullptr);
301
16
    Mutex::ScopedLock lock(mutex_);
302
303
16
    auto it = map_.find(handle);
304
16
    if (it == map_.end()) return;
305
15
    CHECK_GE(it->second.refcount, 1);
306
15
    if (--it->second.refcount == 0) {
307
10
      if (it->second.wants_delete_module)
308
4
        delete it->second.module;
309
10
      map_.erase(handle);
310
    }
311
  }
312
313
 private:
314
  Mutex mutex_;
315
  struct Entry {
316
    unsigned int refcount;
317
    bool wants_delete_module;
318
    node_module* module;
319
  };
320
  std::unordered_map<void*, Entry> map_;
321
} global_handle_map;
322
323
164
DLib::DLib(const char* filename, int flags)
324
164
    : filename_(filename), flags_(flags), handle_(nullptr) {}
325
326
#ifdef __POSIX__
327
164
bool DLib::Open() {
328
164
  handle_ = dlopen(filename_.c_str(), flags_);
329
164
  if (handle_ != nullptr) return true;
330
3
  errmsg_ = dlerror();
331
3
  return false;
332
}
333
334
22
void DLib::Close() {
335
22
  if (handle_ == nullptr) return;
336
337
19
  if (libc_may_be_musl()) {
338
    // musl libc implements dlclose() as a no-op which returns 0.
339
    // As a consequence, trying to re-load a previously closed addon at a later
340
    // point will not call its static constructors, which Node.js uses.
341
    // Therefore, when we may be using musl libc, we assume that the shared
342
    // object exists indefinitely and keep it in our handle map.
343
    return;
344
  }
345
346
19
  int err = dlclose(handle_);
347
19
  if (err == 0) {
348
19
    if (has_entry_in_global_handle_map_)
349
16
      global_handle_map.erase(handle_);
350
  }
351
19
  handle_ = nullptr;
352
}
353
354
22
void* DLib::GetSymbolAddress(const char* name) {
355
22
  return dlsym(handle_, name);
356
}
357
#else   // !__POSIX__
358
bool DLib::Open() {
359
  int ret = uv_dlopen(filename_.c_str(), &lib_);
360
  if (ret == 0) {
361
    handle_ = static_cast<void*>(lib_.handle);
362
    return true;
363
  }
364
  errmsg_ = uv_dlerror(&lib_);
365
  uv_dlclose(&lib_);
366
  return false;
367
}
368
369
void DLib::Close() {
370
  if (handle_ == nullptr) return;
371
  if (has_entry_in_global_handle_map_)
372
    global_handle_map.erase(handle_);
373
  uv_dlclose(&lib_);
374
  handle_ = nullptr;
375
}
376
377
void* DLib::GetSymbolAddress(const char* name) {
378
  void* address;
379
  if (0 == uv_dlsym(&lib_, name, &address)) return address;
380
  return nullptr;
381
}
382
#endif  // !__POSIX__
383
384
150
void DLib::SaveInGlobalHandleMap(node_module* mp) {
385
150
  has_entry_in_global_handle_map_ = true;
386
150
  global_handle_map.set(handle_, mp);
387
150
}
388
389
6
node_module* DLib::GetSavedModuleFromGlobalHandleMap() {
390
6
  has_entry_in_global_handle_map_ = true;
391
6
  return global_handle_map.get_and_increase_refcount(handle_);
392
}
393
394
using InitializerCallback = void (*)(Local<Object> exports,
395
                                     Local<Value> module,
396
                                     Local<Context> context);
397
398
13
inline InitializerCallback GetInitializerCallback(DLib* dlib) {
399
13
  const char* name = "node_register_module_v" STRINGIFY(NODE_MODULE_VERSION);
400
13
  return reinterpret_cast<InitializerCallback>(dlib->GetSymbolAddress(name));
401
}
402
403
9
inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) {
404
9
  const char* name =
405
      STRINGIFY(NAPI_MODULE_INITIALIZER_BASE) STRINGIFY(NAPI_MODULE_VERSION);
406
  return reinterpret_cast<napi_addon_register_func>(
407
9
      dlib->GetSymbolAddress(name));
408
}
409
410
// DLOpen is process.dlopen(module, filename, flags).
411
// Used to load 'module.node' dynamically shared objects.
412
//
413
// FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
414
// when two contexts try to load the same shared object. Maybe have a shadow
415
// cache that's a plain C list or hash table that's shared across contexts?
416
165
void DLOpen(const FunctionCallbackInfo<Value>& args) {
417
165
  Environment* env = Environment::GetCurrent(args);
418
165
  auto context = env->context();
419
420
165
  CHECK_NULL(thread_local_modpending);
421
422
165
  if (args.Length() < 2) {
423
    return THROW_ERR_MISSING_ARGS(
424
1
        env, "process.dlopen needs at least 2 arguments");
425
  }
426
427
165
  int32_t flags = DLib::kDefaultFlags;
428

167
  if (args.Length() > 2 && !args[2]->Int32Value(context).To(&flags)) {
429
    return THROW_ERR_INVALID_ARG_TYPE(env, "flag argument must be an integer.");
430
  }
431
432
  Local<Object> module;
433
  Local<Object> exports;
434
  Local<Value> exports_v;
435
165
  if (!args[0]->ToObject(context).ToLocal(&module) ||
436

825
      !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
437

495
      !exports_v->ToObject(context).ToLocal(&exports)) {
438
1
    return;  // Exception pending.
439
  }
440
441
164
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
442
164
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
443

164
    static Mutex dlib_load_mutex;
444
328
    Mutex::ScopedLock lock(dlib_load_mutex);
445
446
164
    const bool is_opened = dlib->Open();
447
448
    // Objects containing v14 or later modules will have registered themselves
449
    // on the pending list.  Activate all of them now.  At present, only one
450
    // module per object is supported.
451
164
    node_module* mp = thread_local_modpending;
452
164
    thread_local_modpending = nullptr;
453
454
164
    if (!is_opened) {
455
3
      std::string errmsg = dlib->errmsg_.c_str();
456
3
      dlib->Close();
457
#ifdef _WIN32
458
      // Windows needs to add the filename into the error message
459
      errmsg += *filename;
460
#endif  // _WIN32
461
3
      THROW_ERR_DLOPEN_FAILED(env, errmsg.c_str());
462
3
      return false;
463
    }
464
465
161
    if (mp != nullptr) {
466
151
      if (mp->nm_context_register_func == nullptr) {
467
41
        if (env->force_context_aware()) {
468
1
          dlib->Close();
469
1
          THROW_ERR_NON_CONTEXT_AWARE_DISABLED(env);
470
1
          return false;
471
        }
472
      }
473
150
      mp->nm_dso_handle = dlib->handle_;
474
150
      dlib->SaveInGlobalHandleMap(mp);
475
    } else {
476
10
      if (auto callback = GetInitializerCallback(dlib)) {
477
6
        callback(exports, module, context);
478
1
        return true;
479
9
      } else if (auto napi_callback = GetNapiInitializerCallback(dlib)) {
480
3
        napi_module_register_by_symbol(exports, module, context, napi_callback);
481
3
        return true;
482
      } else {
483
6
        mp = dlib->GetSavedModuleFromGlobalHandleMap();
484

6
        if (mp == nullptr || mp->nm_context_register_func == nullptr) {
485
3
          dlib->Close();
486
          char errmsg[1024];
487
6
          snprintf(errmsg,
488
                   sizeof(errmsg),
489
                   "Module did not self-register: '%s'.",
490
3
                   *filename);
491
3
          THROW_ERR_DLOPEN_FAILED(env, errmsg);
492
3
          return false;
493
        }
494
      }
495
    }
496
497
    // -1 is used for N-API modules
498

153
    if ((mp->nm_version != -1) && (mp->nm_version != NODE_MODULE_VERSION)) {
499
      // Even if the module did self-register, it may have done so with the
500
      // wrong version. We must only give up after having checked to see if it
501
      // has an appropriate initializer callback.
502
3
      if (auto callback = GetInitializerCallback(dlib)) {
503
2
        callback(exports, module, context);
504
2
        return true;
505
      }
506
      char errmsg[1024];
507
1
      snprintf(errmsg,
508
               sizeof(errmsg),
509
               "The module '%s'"
510
               "\nwas compiled against a different Node.js version using"
511
               "\nNODE_MODULE_VERSION %d. This version of Node.js requires"
512
               "\nNODE_MODULE_VERSION %d. Please try re-compiling or "
513
               "re-installing\nthe module (for instance, using `npm rebuild` "
514
               "or `npm install`).",
515
               *filename,
516
               mp->nm_version,
517
               NODE_MODULE_VERSION);
518
519
      // NOTE: `mp` is allocated inside of the shared library's memory, calling
520
      // `dlclose` will deallocate it
521
1
      dlib->Close();
522
1
      THROW_ERR_DLOPEN_FAILED(env, errmsg);
523
1
      return false;
524
    }
525
150
    CHECK_EQ(mp->nm_flags & NM_F_BUILTIN, 0);
526
527
    // Do not keep the lock while running userland addon loading code.
528
300
    Mutex::ScopedUnlock unlock(lock);
529
150
    if (mp->nm_context_register_func != nullptr) {
530
112
      mp->nm_context_register_func(exports, module, context, mp->nm_priv);
531
38
    } else if (mp->nm_register_func != nullptr) {
532
38
      mp->nm_register_func(exports, module, mp->nm_priv);
533
    } else {
534
      dlib->Close();
535
      THROW_ERR_DLOPEN_FAILED(env, "Module has no declared entry point.");
536
      return false;
537
    }
538
539
150
    return true;
540
  });
541
542
  // Tell coverity that 'handle' should not be freed when we return.
543
  // coverity[leaked_storage]
544
}
545
546
71650
inline struct node_module* FindModule(struct node_module* list,
547
                                      const char* name,
548
                                      int flag) {
549
  struct node_module* mp;
550
551
1866563
  for (mp = list; mp != nullptr; mp = mp->nm_link) {
552
1865911
    if (strcmp(mp->nm_modname, name) == 0) break;
553
  }
554
555

71650
  CHECK(mp == nullptr || (mp->nm_flags & flag) != 0);
556
71650
  return mp;
557
}
558
559
70988
static Local<Object> InitModule(Environment* env,
560
                                node_module* mod,
561
                                Local<String> module) {
562
  // Internal bindings don't have a "module" object, only exports.
563
70988
  Local<Function> ctor = env->binding_data_ctor_template()
564
70988
                             ->GetFunction(env->context())
565
70988
                             .ToLocalChecked();
566
70988
  Local<Object> exports = ctor->NewInstance(env->context()).ToLocalChecked();
567
70988
  CHECK_NULL(mod->nm_register_func);
568
70988
  CHECK_NOT_NULL(mod->nm_context_register_func);
569
70988
  Local<Value> unused = Undefined(env->isolate());
570
70988
  mod->nm_context_register_func(exports, unused, env->context(), mod->nm_priv);
571
70988
  return exports;
572
}
573
574
71639
void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
575
71639
  Environment* env = Environment::GetCurrent(args);
576
577
143278
  CHECK(args[0]->IsString());
578
579
143278
  Local<String> module = args[0].As<String>();
580
71639
  node::Utf8Value module_v(env->isolate(), module);
581
  Local<Object> exports;
582
583
71639
  node_module* mod = FindModule(modlist_internal, *module_v, NM_F_INTERNAL);
584
71639
  if (mod != nullptr) {
585
70988
    exports = InitModule(env, mod, module);
586
70988
    env->internal_bindings.insert(mod);
587
651
  } else if (!strcmp(*module_v, "constants")) {
588
615
    exports = Object::New(env->isolate());
589
1845
    CHECK(
590
        exports->SetPrototype(env->context(), Null(env->isolate())).FromJust());
591
615
    DefineConstants(env->isolate(), exports);
592
36
  } else if (!strcmp(*module_v, "natives")) {
593
36
    exports = native_module::NativeModuleEnv::GetSourceObject(env->context());
594
    // Legacy feature: process.binding('natives').config contains stringified
595
    // config.gypi
596
144
    CHECK(exports
597
              ->Set(env->context(),
598
                    env->config_string(),
599
                    native_module::NativeModuleEnv::GetConfigString(
600
                        env->isolate()))
601
              .FromJust());
602
  } else {
603
    char errmsg[1024];
604
    snprintf(errmsg, sizeof(errmsg), "No such module: %s", *module_v);
605
    return THROW_ERR_INVALID_MODULE(env, errmsg);
606
  }
607
608
143278
  args.GetReturnValue().Set(exports);
609
}
610
611
10
void GetLinkedBinding(const FunctionCallbackInfo<Value>& args) {
612
10
  Environment* env = Environment::GetCurrent(args);
613
614
20
  CHECK(args[0]->IsString());
615
616
20
  Local<String> module_name = args[0].As<String>();
617
618
10
  node::Utf8Value module_name_v(env->isolate(), module_name);
619
10
  const char* name = *module_name_v;
620
10
  node_module* mod = nullptr;
621
622
  // Iterate from here to the nearest non-Worker Environment to see if there's
623
  // a linked binding defined locally rather than through the global list.
624
10
  Environment* cur_env = env;
625

20
  while (mod == nullptr && cur_env != nullptr) {
626
20
    Mutex::ScopedLock lock(cur_env->extra_linked_bindings_mutex());
627
10
    mod = FindModule(cur_env->extra_linked_bindings_head(), name, NM_F_LINKED);
628
10
    cur_env = cur_env->worker_parent_env();
629
  }
630
631
10
  if (mod == nullptr)
632
1
    mod = FindModule(modlist_linked, name, NM_F_LINKED);
633
634
10
  if (mod == nullptr) {
635
    char errmsg[1024];
636
    snprintf(errmsg,
637
             sizeof(errmsg),
638
             "No such module was linked: %s",
639
             *module_name_v);
640
    return THROW_ERR_INVALID_MODULE(env, errmsg);
641
  }
642
643
10
  Local<Object> module = Object::New(env->isolate());
644
10
  Local<Object> exports = Object::New(env->isolate());
645
  Local<String> exports_prop =
646
10
      String::NewFromUtf8Literal(env->isolate(), "exports");
647
10
  module->Set(env->context(), exports_prop, exports).Check();
648
649
10
  if (mod->nm_context_register_func != nullptr) {
650
20
    mod->nm_context_register_func(
651
        exports, module, env->context(), mod->nm_priv);
652
  } else if (mod->nm_register_func != nullptr) {
653
    mod->nm_register_func(exports, module, mod->nm_priv);
654
  } else {
655
    return THROW_ERR_INVALID_MODULE(
656
        env,
657
        "Linked moduled has no declared entry point.");
658
  }
659
660
  auto effective_exports =
661
20
      module->Get(env->context(), exports_prop).ToLocalChecked();
662
663
20
  args.GetReturnValue().Set(effective_exports);
664
}
665
666
// Call built-in modules' _register_<module name> function to
667
// do module registration explicitly.
668
4905
void RegisterBuiltinModules() {
669
#define V(modname) _register_##modname();
670
4905
  NODE_BUILTIN_MODULES(V)
671
#undef V
672
4905
}
673
674
4832
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
675
4832
  registry->Register(GetLinkedBinding);
676
4832
  registry->Register(GetInternalBinding);
677
4832
}
678
679
}  // namespace binding
680
}  // namespace node
681
682
4832
NODE_MODULE_EXTERNAL_REFERENCE(binding,
683
                               node::binding::RegisterExternalReferences)