GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_binding.cc Lines: 194 211 91.9 %
Date: 2020-05-27 22:15:15 Branches: 102 134 76.1 %

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

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

156
  if (args.Length() > 2 && !args[2]->Int32Value(context).To(&flags)) {
425
    return env->ThrowTypeError("flag argument must be an integer.");
426
  }
427
428
  Local<Object> module;
429
  Local<Object> exports;
430
  Local<Value> exports_v;
431

918
  if (!args[0]->ToObject(context).ToLocal(&module) ||
432

765
      !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
433
459
      !exports_v->ToObject(context).ToLocal(&exports)) {
434
1
    return;  // Exception pending.
435
  }
436
437
304
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
438
608
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
439

152
    static Mutex dlib_load_mutex;
440
304
    Mutex::ScopedLock lock(dlib_load_mutex);
441
442
152
    const bool is_opened = dlib->Open();
443
444
    // Objects containing v14 or later modules will have registered themselves
445
    // on the pending list.  Activate all of them now.  At present, only one
446
    // module per object is supported.
447
152
    node_module* mp = thread_local_modpending;
448
152
    thread_local_modpending = nullptr;
449
450
152
    if (!is_opened) {
451
      Local<String> errmsg =
452
53
          OneByteString(env->isolate(), dlib->errmsg_.c_str());
453
3
      dlib->Close();
454
#ifdef _WIN32
455
      // Windows needs to add the filename into the error message
456
      errmsg = String::Concat(
457
          env->isolate(), errmsg, args[1]->ToString(context).ToLocalChecked());
458
#endif  // _WIN32
459
6
      env->isolate()->ThrowException(Exception::Error(errmsg));
460
3
      return false;
461
    }
462
463
149
    if (mp != nullptr) {
464
139
      if (mp->nm_context_register_func == nullptr) {
465
42
        if (env->options()->force_context_aware) {
466
1
          dlib->Close();
467
1
          THROW_ERR_NON_CONTEXT_AWARE_DISABLED(env);
468
1
          return false;
469
        }
470
      }
471
138
      mp->nm_dso_handle = dlib->handle_;
472
138
      dlib->SaveInGlobalHandleMap(mp);
473
    } else {
474
10
      if (auto callback = GetInitializerCallback(dlib)) {
475
288
        callback(exports, module, context);
476
1
        return true;
477
9
      } else if (auto napi_callback = GetNapiInitializerCallback(dlib)) {
478
3
        napi_module_register_by_symbol(exports, module, context, napi_callback);
479
3
        return true;
480
      } else {
481
6
        mp = dlib->GetSavedModuleFromGlobalHandleMap();
482

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

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

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

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

12978
}  // namespace node