GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_binding.cc Lines: 196 211 92.9 %
Date: 2021-10-01 04:12:33 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(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
266048
extern "C" void node_module_register(void* m) {
254
266048
  struct node_module* mp = reinterpret_cast<struct node_module*>(m);
255
256
266048
  if (mp->nm_flags & NM_F_INTERNAL) {
257
265896
    mp->nm_link = modlist_internal;
258
265896
    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
266048
}
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
171
void DLOpen(const FunctionCallbackInfo<Value>& args) {
417
171
  Environment* env = Environment::GetCurrent(args);
418
419
171
  if (env->no_native_addons()) {
420
6
    return THROW_ERR_DLOPEN_DISABLED(
421
7
      env, "Cannot load native addon because loading addons is disabled.");
422
  }
423
424
165
  auto context = env->context();
425
426
165
  CHECK_NULL(thread_local_modpending);
427
428
165
  if (args.Length() < 2) {
429
    return THROW_ERR_MISSING_ARGS(
430
        env, "process.dlopen needs at least 2 arguments");
431
  }
432
433
165
  int32_t flags = DLib::kDefaultFlags;
434

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

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

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

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

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

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

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

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