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: 197 214 92.1 %
Date: 2020-07-19 22:14:24 Branches: 102 134 76.1 %

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

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

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

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

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

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

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

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

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

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

19890
NODE_MODULE_EXTERNAL_REFERENCE(binding,
689
                               node::binding::RegisterExternalReferences)