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

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

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

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

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

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

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

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

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

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