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

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

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

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

770
      !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
439
462
      !exports_v->ToObject(context).ToLocal(&exports)) {
440
1
    return;  // Exception pending.
441
  }
442
443
306
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
444
612
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
445

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

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

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

164959
  CHECK(mp == nullptr || (mp->nm_flags & flag) != 0);
560
164959
  return mp;
561
}
562
563
160247
static Local<Object> InitModule(Environment* env,
564
                                node_module* mod,
565
                                Local<String> module) {
566
  // Internal bindings don't have a "module" object, only exports.
567
320495
  Local<Function> ctor = env->binding_data_ctor_template()
568
480742
                             ->GetFunction(env->context())
569
160247
                             .ToLocalChecked();
570
480741
  Local<Object> exports = ctor->NewInstance(env->context()).ToLocalChecked();
571
160247
  CHECK_NULL(mod->nm_register_func);
572
160247
  CHECK_NOT_NULL(mod->nm_context_register_func);
573
160247
  Local<Value> unused = Undefined(env->isolate());
574
160247
  mod->nm_context_register_func(exports, unused, env->context(), mod->nm_priv);
575
160246
  return exports;
576
}
577
578
static void ThrowIfNoSuchModule(Environment* env, const char* module_v) {
579
  char errmsg[1024];
580
  snprintf(errmsg, sizeof(errmsg), "No such module: %s", module_v);
581
  env->ThrowError(errmsg);
582
}
583
584
164957
void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
585
164957
  Environment* env = Environment::GetCurrent(args);
586
587
494871
  CHECK(args[0]->IsString());
588
589
329914
  Local<String> module = args[0].As<String>();
590
329913
  node::Utf8Value module_v(env->isolate(), module);
591
  Local<Object> exports;
592
593
164956
  node_module* mod = FindModule(modlist_internal, *module_v, NM_F_INTERNAL);
594
164956
  if (mod != nullptr) {
595
160247
    exports = InitModule(env, mod, module);
596
4709
  } else if (!strcmp(*module_v, "constants")) {
597
4703
    exports = Object::New(env->isolate());
598
18812
    CHECK(
599
        exports->SetPrototype(env->context(), Null(env->isolate())).FromJust());
600
4703
    DefineConstants(env->isolate(), exports);
601
6
  } else if (!strcmp(*module_v, "natives")) {
602
6
    exports = native_module::NativeModuleEnv::GetSourceObject(env->context());
603
    // Legacy feature: process.binding('natives').config contains stringified
604
    // config.gypi
605
30
    CHECK(exports
606
              ->Set(env->context(),
607
                    env->config_string(),
608
                    native_module::NativeModuleEnv::GetConfigString(
609
                        env->isolate()))
610
              .FromJust());
611
  } else {
612
    return ThrowIfNoSuchModule(env, *module_v);
613
  }
614
615
329908
  args.GetReturnValue().Set(exports);
616
}
617
618
2
void GetLinkedBinding(const FunctionCallbackInfo<Value>& args) {
619
2
  Environment* env = Environment::GetCurrent(args);
620
621
6
  CHECK(args[0]->IsString());
622
623
4
  Local<String> module_name = args[0].As<String>();
624
625
4
  node::Utf8Value module_name_v(env->isolate(), module_name);
626
2
  const char* name = *module_name_v;
627
2
  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
2
  Environment* cur_env = env;
632

6
  while (mod == nullptr && cur_env != nullptr) {
633
4
    Mutex::ScopedLock lock(cur_env->extra_linked_bindings_mutex());
634
2
    mod = FindModule(cur_env->extra_linked_bindings_head(), name, NM_F_LINKED);
635
2
    cur_env = cur_env->worker_parent_env();
636
  }
637
638
2
  if (mod == nullptr)
639
1
    mod = FindModule(modlist_linked, name, NM_F_LINKED);
640
641
2
  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 env->ThrowError(errmsg);
648
  }
649
650
2
  Local<Object> module = Object::New(env->isolate());
651
2
  Local<Object> exports = Object::New(env->isolate());
652
  Local<String> exports_prop =
653
2
      String::NewFromUtf8Literal(env->isolate(), "exports");
654
6
  module->Set(env->context(), exports_prop, exports).Check();
655
656
2
  if (mod->nm_context_register_func != nullptr) {
657
4
    mod->nm_context_register_func(
658
2
        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 env->ThrowError("Linked module has no declared entry point.");
663
  }
664
665
  auto effective_exports =
666
6
      module->Get(env->context(), exports_prop).ToLocalChecked();
667
668
4
  args.GetReturnValue().Set(effective_exports);
669
}
670
671
// Call built-in modules' _register_<module name> function to
672
// do module registration explicitly.
673
4398
void RegisterBuiltinModules() {
674
#define V(modname) _register_##modname();
675
4398
  NODE_BUILTIN_MODULES(V)
676
#undef V
677
4398
}
678
679
}  // namespace binding
680

13197
}  // namespace node