GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_binding.cc Lines: 210 224 93.8 %
Date: 2022-12-31 04:22:30 Branches: 104 132 78.8 %

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

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

192
  if (args.Length() > 2 && !args[2]->Int32Value(context).To(&flags)) {
439
    return THROW_ERR_INVALID_ARG_TYPE(env, "flag argument must be an integer.");
440
  }
441
442
  Local<Object> module;
443
  Local<Object> exports;
444
  Local<Value> exports_v;
445
190
  if (!args[0]->ToObject(context).ToLocal(&module) ||
446

950
      !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
447

570
      !exports_v->ToObject(context).ToLocal(&exports)) {
448
1
    return;  // Exception pending.
449
  }
450
451
189
  node::Utf8Value filename(env->isolate(), args[1]);  // Cast
452
189
  env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
453

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

7
        if (mp == nullptr || mp->nm_context_register_func == nullptr) {
495
4
          dlib->Close();
496
4
          THROW_ERR_DLOPEN_FAILED(
497
4
              env, "Module did not self-register: '%s'.", *filename);
498
4
          return false;
499
        }
500
      }
501
    }
502
503
    // -1 is used for N-API modules
504

176
    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
513
1
      const int actual_nm_version = mp->nm_version;
514
      // NOTE: `mp` is allocated inside of the shared library's memory, calling
515
      // `dlclose` will deallocate it
516
1
      dlib->Close();
517
1
      THROW_ERR_DLOPEN_FAILED(
518
          env,
519
          "The module '%s'"
520
          "\nwas compiled against a different Node.js version using"
521
          "\nNODE_MODULE_VERSION %d. This version of Node.js requires"
522
          "\nNODE_MODULE_VERSION %d. Please try re-compiling or "
523
          "re-installing\nthe module (for instance, using `npm rebuild` "
524
          "or `npm install`).",
525
1
          *filename,
526
          actual_nm_version,
527
1
          NODE_MODULE_VERSION);
528
1
      return false;
529
    }
530
173
    CHECK_EQ(mp->nm_flags & NM_F_BUILTIN, 0);
531
532
    // Do not keep the lock while running userland addon loading code.
533
346
    Mutex::ScopedUnlock unlock(lock);
534
173
    if (mp->nm_context_register_func != nullptr) {
535
132
      mp->nm_context_register_func(exports, module, context, mp->nm_priv);
536
41
    } else if (mp->nm_register_func != nullptr) {
537
41
      mp->nm_register_func(exports, module, mp->nm_priv);
538
    } else {
539
      dlib->Close();
540
      THROW_ERR_DLOPEN_FAILED(env, "Module has no declared entry point.");
541
      return false;
542
    }
543
544
173
    return true;
545
  });
546
547
  // Tell coverity that 'handle' should not be freed when we return.
548
  // coverity[leaked_storage]
549
}
550
551
97146
inline struct node_module* FindModule(struct node_module* list,
552
                                      const char* name,
553
                                      int flag) {
554
  struct node_module* mp;
555
556
2449209
  for (mp = list; mp != nullptr; mp = mp->nm_link) {
557
2448339
    if (strcmp(mp->nm_modname, name) == 0) break;
558
  }
559
560

97146
  CHECK(mp == nullptr || (mp->nm_flags & flag) != 0);
561
97146
  return mp;
562
}
563
564
831
void CreateInternalBindingTemplates(IsolateData* isolate_data) {
565
#define V(modname)                                                             \
566
  do {                                                                         \
567
    Local<FunctionTemplate> templ =                                            \
568
        FunctionTemplate::New(isolate_data->isolate());                        \
569
    templ->InstanceTemplate()->SetInternalFieldCount(                          \
570
        BaseObject::kInternalFieldCount);                                      \
571
    templ->Inherit(BaseObject::GetConstructorTemplate(isolate_data));          \
572
    _register_isolate_##modname(isolate_data, templ);                          \
573
    isolate_data->set_##modname##_binding(templ);                              \
574
  } while (0);
575
2493
  NODE_BINDINGS_WITH_PER_ISOLATE_INIT(V)
576
#undef V
577
831
}
578
579
96266
static Local<Object> GetInternalBindingExportObject(IsolateData* isolate_data,
580
                                                    const char* mod_name,
581
                                                    Local<Context> context) {
582
  Local<FunctionTemplate> ctor;
583
#define V(name)                                                                \
584
  if (strcmp(mod_name, #name) == 0) {                                          \
585
    ctor = isolate_data->name##_binding();                                     \
586
  } else  // NOLINT(readability/braces)
587

96266
  NODE_BINDINGS_WITH_PER_ISOLATE_INIT(V)
588
#undef V
589
  {
590
94612
    ctor = isolate_data->binding_data_ctor_template();
591
  }
592
593
96266
  Local<Object> obj = ctor->GetFunction(context)
594
96266
                          .ToLocalChecked()
595
96266
                          ->NewInstance(context)
596
96266
                          .ToLocalChecked();
597
96266
  return obj;
598
}
599
600
96266
static Local<Object> InitInternalBinding(Realm* realm, node_module* mod) {
601
96266
  EscapableHandleScope scope(realm->isolate());
602
96266
  Local<Context> context = realm->context();
603
  Local<Object> exports = GetInternalBindingExportObject(
604
96266
      realm->isolate_data(), mod->nm_modname, context);
605
96266
  CHECK_NULL(mod->nm_register_func);
606
96266
  CHECK_NOT_NULL(mod->nm_context_register_func);
607
96266
  Local<Value> unused = Undefined(realm->isolate());
608
  // Internal bindings don't have a "module" object, only exports.
609
96266
  mod->nm_context_register_func(exports, unused, context, mod->nm_priv);
610
96266
  return scope.Escape(exports);
611
}
612
613
97135
void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
614
97135
  Realm* realm = Realm::GetCurrent(args);
615
97135
  Isolate* isolate = realm->isolate();
616
97135
  HandleScope scope(isolate);
617
97135
  Local<Context> context = realm->context();
618
619
194270
  CHECK(args[0]->IsString());
620
621
194270
  Local<String> module = args[0].As<String>();
622
97135
  node::Utf8Value module_v(isolate, module);
623
  Local<Object> exports;
624
625
97135
  node_module* mod = FindModule(modlist_internal, *module_v, NM_F_INTERNAL);
626
97135
  if (mod != nullptr) {
627
96266
    exports = InitInternalBinding(realm, mod);
628
96266
    realm->internal_bindings.insert(mod);
629
869
  } else if (!strcmp(*module_v, "constants")) {
630
827
    exports = Object::New(isolate);
631
2481
    CHECK(exports->SetPrototype(context, Null(isolate)).FromJust());
632
827
    DefineConstants(isolate, exports);
633
42
  } else if (!strcmp(*module_v, "natives")) {
634
42
    exports = builtins::BuiltinLoader::GetSourceObject(context);
635
    // Legacy feature: process.binding('natives').config contains stringified
636
    // config.gypi
637
168
    CHECK(exports
638
              ->Set(context,
639
                    realm->isolate_data()->config_string(),
640
                    builtins::BuiltinLoader::GetConfigString(isolate))
641
              .FromJust());
642
  } else {
643
    return THROW_ERR_INVALID_MODULE(isolate, "No such binding: %s", *module_v);
644
  }
645
646
194270
  args.GetReturnValue().Set(exports);
647
}
648
649
10
void GetLinkedBinding(const FunctionCallbackInfo<Value>& args) {
650
10
  Environment* env = Environment::GetCurrent(args);
651
652
20
  CHECK(args[0]->IsString());
653
654
20
  Local<String> module_name = args[0].As<String>();
655
656
10
  node::Utf8Value module_name_v(env->isolate(), module_name);
657
10
  const char* name = *module_name_v;
658
10
  node_module* mod = nullptr;
659
660
  // Iterate from here to the nearest non-Worker Environment to see if there's
661
  // a linked binding defined locally rather than through the global list.
662
10
  Environment* cur_env = env;
663

20
  while (mod == nullptr && cur_env != nullptr) {
664
20
    Mutex::ScopedLock lock(cur_env->extra_linked_bindings_mutex());
665
10
    mod = FindModule(cur_env->extra_linked_bindings_head(), name, NM_F_LINKED);
666
10
    cur_env = cur_env->worker_parent_env();
667
  }
668
669
10
  if (mod == nullptr)
670
1
    mod = FindModule(modlist_linked, name, NM_F_LINKED);
671
672
10
  if (mod == nullptr) {
673
    return THROW_ERR_INVALID_MODULE(
674
        env, "No such binding was linked: %s", *module_name_v);
675
  }
676
677
10
  Local<Object> module = Object::New(env->isolate());
678
10
  Local<Object> exports = Object::New(env->isolate());
679
  Local<String> exports_prop =
680
10
      String::NewFromUtf8Literal(env->isolate(), "exports");
681
10
  module->Set(env->context(), exports_prop, exports).Check();
682
683
10
  if (mod->nm_context_register_func != nullptr) {
684
20
    mod->nm_context_register_func(
685
        exports, module, env->context(), mod->nm_priv);
686
  } else if (mod->nm_register_func != nullptr) {
687
    mod->nm_register_func(exports, module, mod->nm_priv);
688
  } else {
689
    return THROW_ERR_INVALID_MODULE(
690
        env, "Linked binding has no declared entry point.");
691
  }
692
693
  auto effective_exports =
694
20
      module->Get(env->context(), exports_prop).ToLocalChecked();
695
696
20
  args.GetReturnValue().Set(effective_exports);
697
}
698
699
// Call built-in bindings' _register_<module name> function to
700
// do binding registration explicitly.
701
5788
void RegisterBuiltinBindings() {
702
#define V(modname) _register_##modname();
703
5788
  NODE_BUILTIN_BINDINGS(V)
704
#undef V
705
5788
}
706
707
5717
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
708
5717
  registry->Register(GetLinkedBinding);
709
5717
  registry->Register(GetInternalBinding);
710
5717
}
711
712
}  // namespace binding
713
}  // namespace node
714
715
5717
NODE_BINDING_EXTERNAL_REFERENCE(binding,
716
                                node::binding::RegisterExternalReferences)