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

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


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


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


1386
      !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
435
462
      !exports_v->ToObject(context).ToLocal(&exports)) {
436
1
    return;  // Exception pending.
437
  }
438
439
153
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
440
306
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
441

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

5
        if (mp == nullptr || mp->nm_context_register_func == nullptr) {
485
3
          dlib->Close();
486
3
          env->ThrowError("Module did not self-register.");
487
3
          return false;
488
        }
489
      }
490
    }
491
492
    // -1 is used for N-API modules
493

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

170636
  CHECK(mp == nullptr || (mp->nm_flags & flag) != 0);
551
170636
  return mp;
552
}
553
554
170636
node_module* get_internal_module(const char* name) {
555
170636
  return FindModule(modlist_internal, name, NM_F_INTERNAL);
556
}
557
node_module* get_linked_module(const char* name) {
558
  return FindModule(modlist_linked, name, NM_F_LINKED);
559
}
560
561
165152
static Local<Object> InitModule(Environment* env,
562
                                node_module* mod,
563
                                Local<String> module) {
564
165152
  Local<Object> exports = Object::New(env->isolate());
565
  // Internal bindings don't have a "module" object, only exports.
566
165152
  CHECK_NULL(mod->nm_register_func);
567
165152
  CHECK_NOT_NULL(mod->nm_context_register_func);
568
165152
  Local<Value> unused = Undefined(env->isolate());
569
165152
  mod->nm_context_register_func(exports, unused, env->context(), mod->nm_priv);
570
165152
  return exports;
571
}
572
573
static void ThrowIfNoSuchModule(Environment* env, const char* module_v) {
574
  char errmsg[1024];
575
  snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_v);
576
  env->ThrowError(errmsg);
577
}
578
579
170636
void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
580
170636
  Environment* env = Environment::GetCurrent(args);
581
582
511908
  CHECK(args[0]->IsString());
583
584
341272
  Local<String> module = args[0].As<String>();
585
170636
  node::Utf8Value module_v(env->isolate(), module);
586
  Local<Object> exports;
587
588
170636
  node_module* mod = get_internal_module(*module_v);
589
170636
  if (mod != nullptr) {
590
165152
    exports = InitModule(env, mod, module);
591
5484
  } else if (!strcmp(*module_v, "constants")) {
592
5156
    exports = Object::New(env->isolate());
593
20624
    CHECK(
594
        exports->SetPrototype(env->context(), Null(env->isolate())).FromJust());
595
5156
    DefineConstants(env->isolate(), exports);
596
328
  } else if (!strcmp(*module_v, "natives")) {
597
328
    exports = native_module::NativeModuleEnv::GetSourceObject(env->context());
598
    // Legacy feature: process.binding('natives').config contains stringified
599
    // config.gypi
600
1640
    CHECK(exports
601
              ->Set(env->context(),
602
                    env->config_string(),
603
                    native_module::NativeModuleEnv::GetConfigString(
604
                        env->isolate()))
605
              .FromJust());
606
  } else {
607
170636
    return ThrowIfNoSuchModule(env, *module_v);
608
  }
609
610
341272
  args.GetReturnValue().Set(exports);
611
}
612
613
void GetLinkedBinding(const FunctionCallbackInfo<Value>& args) {
614
  Environment* env = Environment::GetCurrent(args);
615
616
  CHECK(args[0]->IsString());
617
618
  Local<String> module_name = args[0].As<String>();
619
620
  node::Utf8Value module_name_v(env->isolate(), module_name);
621
  node_module* mod = get_linked_module(*module_name_v);
622
623
  if (mod == nullptr) {
624
    char errmsg[1024];
625
    snprintf(errmsg,
626
             sizeof(errmsg),
627
             "No such module was linked: %s",
628
             *module_name_v);
629
    return env->ThrowError(errmsg);
630
  }
631
632
  Local<Object> module = Object::New(env->isolate());
633
  Local<Object> exports = Object::New(env->isolate());
634
  Local<String> exports_prop =
635
      String::NewFromUtf8(env->isolate(), "exports", NewStringType::kNormal)
636
          .ToLocalChecked();
637
  module->Set(env->context(), exports_prop, exports).Check();
638
639
  if (mod->nm_context_register_func != nullptr) {
640
    mod->nm_context_register_func(
641
        exports, module, env->context(), mod->nm_priv);
642
  } else if (mod->nm_register_func != nullptr) {
643
    mod->nm_register_func(exports, module, mod->nm_priv);
644
  } else {
645
    return env->ThrowError("Linked module has no declared entry point.");
646
  }
647
648
  auto effective_exports =
649
      module->Get(env->context(), exports_prop).ToLocalChecked();
650
651
  args.GetReturnValue().Set(effective_exports);
652
}
653
654
// Call built-in modules' _register_<module name> function to
655
// do module registration explicitly.
656
5010
void RegisterBuiltinModules() {
657
#define V(modname) _register_##modname();
658
5010
  NODE_BUILTIN_MODULES(V)
659
#undef V
660
5010
}
661
662
}  // namespace binding
663

15033
}  // namespace node