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

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

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

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

805
      !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
443
483
      !exports_v->ToObject(context).ToLocal(&exports)) {
444
1
    return;  // Exception pending.
445
  }
446
447
320
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
448
640
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
449

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

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

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

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

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

18687
NODE_MODULE_EXTERNAL_REFERENCE(binding,
688
                               node::binding::RegisterExternalReferences)