GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_binding.cc Lines: 196 211 92.9 %
Date: 2022-06-14 04:15:41 Branches: 98 126 77.8 %

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(mksnapshot)                                                                \
63
  V(native_module)                                                             \
64
  V(options)                                                                   \
65
  V(os)                                                                        \
66
  V(performance)                                                               \
67
  V(pipe_wrap)                                                                 \
68
  V(process_wrap)                                                              \
69
  V(process_methods)                                                           \
70
  V(report)                                                                    \
71
  V(serdes)                                                                    \
72
  V(signal_wrap)                                                               \
73
  V(spawn_sync)                                                                \
74
  V(stream_pipe)                                                               \
75
  V(stream_wrap)                                                               \
76
  V(string_decoder)                                                            \
77
  V(symbols)                                                                   \
78
  V(task_queue)                                                                \
79
  V(tcp_wrap)                                                                  \
80
  V(timers)                                                                    \
81
  V(trace_events)                                                              \
82
  V(tty_wrap)                                                                  \
83
  V(types)                                                                     \
84
  V(udp_wrap)                                                                  \
85
  V(url)                                                                       \
86
  V(util)                                                                      \
87
  V(uv)                                                                        \
88
  V(v8)                                                                        \
89
  V(wasi)                                                                      \
90
  V(wasm_web_api)                                                              \
91
  V(watchdog)                                                                  \
92
  V(worker)                                                                    \
93
  V(zlib)
94
95
#define NODE_BUILTIN_MODULES(V)                                                \
96
  NODE_BUILTIN_STANDARD_MODULES(V)                                             \
97
  NODE_BUILTIN_OPENSSL_MODULES(V)                                              \
98
  NODE_BUILTIN_ICU_MODULES(V)                                                  \
99
  NODE_BUILTIN_PROFILER_MODULES(V)                                             \
100
  NODE_BUILTIN_DTRACE_MODULES(V)
101
102
// This is used to load built-in modules. Instead of using
103
// __attribute__((constructor)), we call the _register_<modname>
104
// function for each built-in modules explicitly in
105
// binding::RegisterBuiltinModules(). This is only forward declaration.
106
// The definitions are in each module's implementation when calling
107
// the NODE_MODULE_CONTEXT_AWARE_INTERNAL.
108
#define V(modname) void _register_##modname();
109
NODE_BUILTIN_MODULES(V)
110
#undef V
111
112
#ifdef _AIX
113
// On AIX, dlopen() behaves differently from other operating systems, in that
114
// it returns unique values from each call, rather than identical values, when
115
// loading the same handle.
116
// We try to work around that by providing wrappers for the dlopen() family of
117
// functions, and using st_dev and st_ino for the file that is to be loaded
118
// as keys for a cache.
119
120
namespace node {
121
namespace dlwrapper {
122
123
struct dl_wrap {
124
  uint64_t st_dev;
125
  uint64_t st_ino;
126
  uint64_t refcount;
127
  void* real_handle;
128
129
  struct hash {
130
    size_t operator()(const dl_wrap* wrap) const {
131
      return std::hash<uint64_t>()(wrap->st_dev) ^
132
             std::hash<uint64_t>()(wrap->st_ino);
133
    }
134
  };
135
136
  struct equal {
137
    bool operator()(const dl_wrap* a,
138
                    const dl_wrap* b) const {
139
      return a->st_dev == b->st_dev && a->st_ino == b->st_ino;
140
    }
141
  };
142
};
143
144
static Mutex dlhandles_mutex;
145
static std::unordered_set<dl_wrap*, dl_wrap::hash, dl_wrap::equal>
146
    dlhandles;
147
static thread_local std::string dlerror_storage;
148
149
char* wrapped_dlerror() {
150
  return &dlerror_storage[0];
151
}
152
153
void* wrapped_dlopen(const char* filename, int flags) {
154
  CHECK_NOT_NULL(filename);  // This deviates from the 'real' dlopen().
155
  Mutex::ScopedLock lock(dlhandles_mutex);
156
157
  uv_fs_t req;
158
  auto cleanup = OnScopeLeave([&]() { uv_fs_req_cleanup(&req); });
159
  int rc = uv_fs_stat(nullptr, &req, filename, nullptr);
160
161
  if (rc != 0) {
162
    dlerror_storage = uv_strerror(rc);
163
    return nullptr;
164
  }
165
166
  dl_wrap search = {
167
    req.statbuf.st_dev,
168
    req.statbuf.st_ino,
169
    0, nullptr
170
  };
171
172
  auto it = dlhandles.find(&search);
173
  if (it != dlhandles.end()) {
174
    (*it)->refcount++;
175
    return *it;
176
  }
177
178
  void* real_handle = dlopen(filename, flags);
179
  if (real_handle == nullptr) {
180
    dlerror_storage = dlerror();
181
    return nullptr;
182
  }
183
  dl_wrap* wrap = new dl_wrap();
184
  wrap->st_dev = req.statbuf.st_dev;
185
  wrap->st_ino = req.statbuf.st_ino;
186
  wrap->refcount = 1;
187
  wrap->real_handle = real_handle;
188
  dlhandles.insert(wrap);
189
  return wrap;
190
}
191
192
int wrapped_dlclose(void* handle) {
193
  Mutex::ScopedLock lock(dlhandles_mutex);
194
  dl_wrap* wrap = static_cast<dl_wrap*>(handle);
195
  int ret = 0;
196
  CHECK_GE(wrap->refcount, 1);
197
  if (--wrap->refcount == 0) {
198
    ret = dlclose(wrap->real_handle);
199
    if (ret != 0) dlerror_storage = dlerror();
200
    dlhandles.erase(wrap);
201
    delete wrap;
202
  }
203
  return ret;
204
}
205
206
void* wrapped_dlsym(void* handle, const char* symbol) {
207
  if (handle == RTLD_DEFAULT || handle == RTLD_NEXT)
208
    return dlsym(handle, symbol);
209
  dl_wrap* wrap = static_cast<dl_wrap*>(handle);
210
  return dlsym(wrap->real_handle, symbol);
211
}
212
213
#define dlopen node::dlwrapper::wrapped_dlopen
214
#define dlerror node::dlwrapper::wrapped_dlerror
215
#define dlclose node::dlwrapper::wrapped_dlclose
216
#define dlsym node::dlwrapper::wrapped_dlsym
217
218
}  // namespace dlwrapper
219
}  // namespace node
220
221
#endif  // _AIX
222
223
#ifdef __linux__
224
19
static bool libc_may_be_musl() {
225

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

173
  if (args.Length() > 2 && !args[2]->Int32Value(context).To(&flags)) {
437
    return THROW_ERR_INVALID_ARG_TYPE(env, "flag argument must be an integer.");
438
  }
439
440
  Local<Object> module;
441
  Local<Object> exports;
442
  Local<Value> exports_v;
443
171
  if (!args[0]->ToObject(context).ToLocal(&module) ||
444

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

513
      !exports_v->ToObject(context).ToLocal(&exports)) {
446
1
    return;  // Exception pending.
447
  }
448
449
170
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
450
170
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
451

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

6
        if (mp == nullptr || mp->nm_context_register_func == nullptr) {
493
3
          dlib->Close();
494
          char errmsg[1024];
495
6
          snprintf(errmsg,
496
                   sizeof(errmsg),
497
                   "Module did not self-register: '%s'.",
498
3
                   *filename);
499
3
          THROW_ERR_DLOPEN_FAILED(env, errmsg);
500
3
          return false;
501
        }
502
      }
503
    }
504
505
    // -1 is used for N-API modules
506

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

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

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