• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <string>
9 
10 #if HAVE_OPENSSL
11 #define NODE_BUILTIN_OPENSSL_MODULES(V) V(crypto) V(tls_wrap)
12 #else
13 #define NODE_BUILTIN_OPENSSL_MODULES(V)
14 #endif
15 
16 #if NODE_HAVE_I18N_SUPPORT
17 #define NODE_BUILTIN_ICU_MODULES(V) V(icu)
18 #else
19 #define NODE_BUILTIN_ICU_MODULES(V)
20 #endif
21 
22 #if HAVE_INSPECTOR
23 #define NODE_BUILTIN_PROFILER_MODULES(V) V(profiler)
24 #else
25 #define NODE_BUILTIN_PROFILER_MODULES(V)
26 #endif
27 
28 #if HAVE_DTRACE || HAVE_ETW
29 #define NODE_BUILTIN_DTRACE_MODULES(V) V(dtrace)
30 #else
31 #define NODE_BUILTIN_DTRACE_MODULES(V)
32 #endif
33 
34 // A list of built-in modules. In order to do module registration
35 // in node::Init(), need to add built-in modules in the following list.
36 // Then in binding::RegisterBuiltinModules(), it calls modules' registration
37 // function. This helps the built-in modules are loaded properly when
38 // node is built as static library. No need to depend on the
39 // __attribute__((constructor)) like mechanism in GCC.
40 #define NODE_BUILTIN_STANDARD_MODULES(V)                                       \
41   V(async_wrap)                                                                \
42   V(block_list)                                                                \
43   V(buffer)                                                                    \
44   V(cares_wrap)                                                                \
45   V(config)                                                                    \
46   V(contextify)                                                                \
47   V(credentials)                                                               \
48   V(errors)                                                                    \
49   V(fs)                                                                        \
50   V(fs_dir)                                                                    \
51   V(fs_event_wrap)                                                             \
52   V(heap_utils)                                                                \
53   V(http2)                                                                     \
54   V(http_parser)                                                               \
55   V(inspector)                                                                 \
56   V(js_stream)                                                                 \
57   V(js_udp_wrap)                                                               \
58   V(messaging)                                                                 \
59   V(module_wrap)                                                               \
60   V(native_module)                                                             \
61   V(options)                                                                   \
62   V(os)                                                                        \
63   V(performance)                                                               \
64   V(pipe_wrap)                                                                 \
65   V(process_wrap)                                                              \
66   V(process_methods)                                                           \
67   V(report)                                                                    \
68   V(serdes)                                                                    \
69   V(signal_wrap)                                                               \
70   V(spawn_sync)                                                                \
71   V(stream_pipe)                                                               \
72   V(stream_wrap)                                                               \
73   V(string_decoder)                                                            \
74   V(symbols)                                                                   \
75   V(task_queue)                                                                \
76   V(tcp_wrap)                                                                  \
77   V(timers)                                                                    \
78   V(trace_events)                                                              \
79   V(tty_wrap)                                                                  \
80   V(types)                                                                     \
81   V(udp_wrap)                                                                  \
82   V(url)                                                                       \
83   V(util)                                                                      \
84   V(uv)                                                                        \
85   V(v8)                                                                        \
86   V(wasi)                                                                      \
87   V(worker)                                                                    \
88   V(watchdog)                                                                  \
89   V(zlib)
90 
91 #define NODE_BUILTIN_MODULES(V)                                                \
92   NODE_BUILTIN_STANDARD_MODULES(V)                                             \
93   NODE_BUILTIN_OPENSSL_MODULES(V)                                              \
94   NODE_BUILTIN_ICU_MODULES(V)                                                  \
95   NODE_BUILTIN_PROFILER_MODULES(V)                                             \
96   NODE_BUILTIN_DTRACE_MODULES(V)
97 
98 // This is used to load built-in modules. Instead of using
99 // __attribute__((constructor)), we call the _register_<modname>
100 // function for each built-in modules explicitly in
101 // binding::RegisterBuiltinModules(). This is only forward declaration.
102 // The definitions are in each module's implementation when calling
103 // the NODE_MODULE_CONTEXT_AWARE_INTERNAL.
104 #define V(modname) void _register_##modname();
105 NODE_BUILTIN_MODULES(V)
106 #undef V
107 
108 #ifdef _AIX
109 // On AIX, dlopen() behaves differently from other operating systems, in that
110 // it returns unique values from each call, rather than identical values, when
111 // loading the same handle.
112 // We try to work around that by providing wrappers for the dlopen() family of
113 // functions, and using st_dev and st_ino for the file that is to be loaded
114 // as keys for a cache.
115 
116 namespace node {
117 namespace dlwrapper {
118 
119 struct dl_wrap {
120   uint64_t st_dev;
121   uint64_t st_ino;
122   uint64_t refcount;
123   void* real_handle;
124 
125   struct hash {
operator ()node::dlwrapper::dl_wrap::hash126     size_t operator()(const dl_wrap* wrap) const {
127       return std::hash<uint64_t>()(wrap->st_dev) ^
128              std::hash<uint64_t>()(wrap->st_ino);
129     }
130   };
131 
132   struct equal {
operator ()node::dlwrapper::dl_wrap::equal133     bool operator()(const dl_wrap* a,
134                     const dl_wrap* b) const {
135       return a->st_dev == b->st_dev && a->st_ino == b->st_ino;
136     }
137   };
138 };
139 
140 static Mutex dlhandles_mutex;
141 static std::unordered_set<dl_wrap*, dl_wrap::hash, dl_wrap::equal>
142     dlhandles;
143 static thread_local std::string dlerror_storage;
144 
wrapped_dlerror()145 char* wrapped_dlerror() {
146   return &dlerror_storage[0];
147 }
148 
wrapped_dlopen(const char * filename,int flags)149 void* wrapped_dlopen(const char* filename, int flags) {
150   CHECK_NOT_NULL(filename);  // This deviates from the 'real' dlopen().
151   Mutex::ScopedLock lock(dlhandles_mutex);
152 
153   uv_fs_t req;
154   auto cleanup = OnScopeLeave([&]() { uv_fs_req_cleanup(&req); });
155   int rc = uv_fs_stat(nullptr, &req, filename, nullptr);
156 
157   if (rc != 0) {
158     dlerror_storage = uv_strerror(rc);
159     return nullptr;
160   }
161 
162   dl_wrap search = {
163     req.statbuf.st_dev,
164     req.statbuf.st_ino,
165     0, nullptr
166   };
167 
168   auto it = dlhandles.find(&search);
169   if (it != dlhandles.end()) {
170     (*it)->refcount++;
171     return *it;
172   }
173 
174   void* real_handle = dlopen(filename, flags);
175   if (real_handle == nullptr) {
176     dlerror_storage = dlerror();
177     return nullptr;
178   }
179   dl_wrap* wrap = new dl_wrap();
180   wrap->st_dev = req.statbuf.st_dev;
181   wrap->st_ino = req.statbuf.st_ino;
182   wrap->refcount = 1;
183   wrap->real_handle = real_handle;
184   dlhandles.insert(wrap);
185   return wrap;
186 }
187 
wrapped_dlclose(void * handle)188 int wrapped_dlclose(void* handle) {
189   Mutex::ScopedLock lock(dlhandles_mutex);
190   dl_wrap* wrap = static_cast<dl_wrap*>(handle);
191   int ret = 0;
192   CHECK_GE(wrap->refcount, 1);
193   if (--wrap->refcount == 0) {
194     ret = dlclose(wrap->real_handle);
195     if (ret != 0) dlerror_storage = dlerror();
196     dlhandles.erase(wrap);
197     delete wrap;
198   }
199   return ret;
200 }
201 
wrapped_dlsym(void * handle,const char * symbol)202 void* wrapped_dlsym(void* handle, const char* symbol) {
203   if (handle == RTLD_DEFAULT || handle == RTLD_NEXT)
204     return dlsym(handle, symbol);
205   dl_wrap* wrap = static_cast<dl_wrap*>(handle);
206   return dlsym(wrap->real_handle, symbol);
207 }
208 
209 #define dlopen node::dlwrapper::wrapped_dlopen
210 #define dlerror node::dlwrapper::wrapped_dlerror
211 #define dlclose node::dlwrapper::wrapped_dlclose
212 #define dlsym node::dlwrapper::wrapped_dlsym
213 
214 }  // namespace dlwrapper
215 }  // namespace node
216 
217 #endif  // _AIX
218 
219 #ifdef __linux__
libc_may_be_musl()220 static bool libc_may_be_musl() {
221   static std::atomic_bool retval;  // Cache the return value.
222   static std::atomic_bool has_cached_retval { false };
223   if (has_cached_retval) return retval;
224   retval = dlsym(RTLD_DEFAULT, "gnu_get_libc_version") == nullptr;
225   has_cached_retval = true;
226   return retval;
227 }
228 #else  // __linux__
libc_may_be_musl()229 static bool libc_may_be_musl() { return false; }
230 #endif  // __linux__
231 
232 namespace node {
233 
234 using v8::Context;
235 using v8::Exception;
236 using v8::Function;
237 using v8::FunctionCallbackInfo;
238 using v8::Local;
239 using v8::Object;
240 using v8::String;
241 using v8::Value;
242 
243 // Globals per process
244 static node_module* modlist_internal;
245 static node_module* modlist_linked;
246 static thread_local node_module* thread_local_modpending;
247 
248 // This is set by node::Init() which is used by embedders
249 bool node_is_initialized = false;
250 
node_module_register(void * m)251 extern "C" void node_module_register(void* m) {
252   struct node_module* mp = reinterpret_cast<struct node_module*>(m);
253 
254   if (mp->nm_flags & NM_F_INTERNAL) {
255     mp->nm_link = modlist_internal;
256     modlist_internal = mp;
257   } else if (!node_is_initialized) {
258     // "Linked" modules are included as part of the node project.
259     // Like builtins they are registered *before* node::Init runs.
260     mp->nm_flags = NM_F_LINKED;
261     mp->nm_link = modlist_linked;
262     modlist_linked = mp;
263   } else {
264     thread_local_modpending = mp;
265   }
266 }
267 
268 namespace binding {
269 
270 static struct global_handle_map_t {
271  public:
setnode::binding::global_handle_map_t272   void set(void* handle, node_module* mod) {
273     CHECK_NE(handle, nullptr);
274     Mutex::ScopedLock lock(mutex_);
275 
276     map_[handle].module = mod;
277     // We need to store this flag internally to avoid a chicken-and-egg problem
278     // during cleanup. By the time we actually use the flag's value,
279     // the shared object has been unloaded, and its memory would be gone,
280     // making it impossible to access fields of `mod` --
281     // unless `mod` *is* dynamically allocated, but we cannot know that
282     // without checking the flag.
283     map_[handle].wants_delete_module = mod->nm_flags & NM_F_DELETEME;
284     map_[handle].refcount++;
285   }
286 
get_and_increase_refcountnode::binding::global_handle_map_t287   node_module* get_and_increase_refcount(void* handle) {
288     CHECK_NE(handle, nullptr);
289     Mutex::ScopedLock lock(mutex_);
290 
291     auto it = map_.find(handle);
292     if (it == map_.end()) return nullptr;
293     it->second.refcount++;
294     return it->second.module;
295   }
296 
erasenode::binding::global_handle_map_t297   void erase(void* handle) {
298     CHECK_NE(handle, nullptr);
299     Mutex::ScopedLock lock(mutex_);
300 
301     auto it = map_.find(handle);
302     if (it == map_.end()) return;
303     CHECK_GE(it->second.refcount, 1);
304     if (--it->second.refcount == 0) {
305       if (it->second.wants_delete_module)
306         delete it->second.module;
307       map_.erase(handle);
308     }
309   }
310 
311  private:
312   Mutex mutex_;
313   struct Entry {
314     unsigned int refcount;
315     bool wants_delete_module;
316     node_module* module;
317   };
318   std::unordered_map<void*, Entry> map_;
319 } global_handle_map;
320 
DLib(const char * filename,int flags)321 DLib::DLib(const char* filename, int flags)
322     : filename_(filename), flags_(flags), handle_(nullptr) {}
323 
324 #ifdef __POSIX__
Open()325 bool DLib::Open() {
326   handle_ = dlopen(filename_.c_str(), flags_);
327   if (handle_ != nullptr) return true;
328   errmsg_ = dlerror();
329   return false;
330 }
331 
Close()332 void DLib::Close() {
333   if (handle_ == nullptr) return;
334 
335   if (libc_may_be_musl()) {
336     // musl libc implements dlclose() as a no-op which returns 0.
337     // As a consequence, trying to re-load a previously closed addon at a later
338     // point will not call its static constructors, which Node.js uses.
339     // Therefore, when we may be using musl libc, we assume that the shared
340     // object exists indefinitely and keep it in our handle map.
341     return;
342   }
343 
344   int err = dlclose(handle_);
345   if (err == 0) {
346     if (has_entry_in_global_handle_map_)
347       global_handle_map.erase(handle_);
348   }
349   handle_ = nullptr;
350 }
351 
GetSymbolAddress(const char * name)352 void* DLib::GetSymbolAddress(const char* name) {
353   return dlsym(handle_, name);
354 }
355 #else   // !__POSIX__
Open()356 bool DLib::Open() {
357   int ret = uv_dlopen(filename_.c_str(), &lib_);
358   if (ret == 0) {
359     handle_ = static_cast<void*>(lib_.handle);
360     return true;
361   }
362   errmsg_ = uv_dlerror(&lib_);
363   uv_dlclose(&lib_);
364   return false;
365 }
366 
Close()367 void DLib::Close() {
368   if (handle_ == nullptr) return;
369   if (has_entry_in_global_handle_map_)
370     global_handle_map.erase(handle_);
371   uv_dlclose(&lib_);
372   handle_ = nullptr;
373 }
374 
GetSymbolAddress(const char * name)375 void* DLib::GetSymbolAddress(const char* name) {
376   void* address;
377   if (0 == uv_dlsym(&lib_, name, &address)) return address;
378   return nullptr;
379 }
380 #endif  // !__POSIX__
381 
SaveInGlobalHandleMap(node_module * mp)382 void DLib::SaveInGlobalHandleMap(node_module* mp) {
383   has_entry_in_global_handle_map_ = true;
384   global_handle_map.set(handle_, mp);
385 }
386 
GetSavedModuleFromGlobalHandleMap()387 node_module* DLib::GetSavedModuleFromGlobalHandleMap() {
388   has_entry_in_global_handle_map_ = true;
389   return global_handle_map.get_and_increase_refcount(handle_);
390 }
391 
392 using InitializerCallback = void (*)(Local<Object> exports,
393                                      Local<Value> module,
394                                      Local<Context> context);
395 
GetInitializerCallback(DLib * dlib)396 inline InitializerCallback GetInitializerCallback(DLib* dlib) {
397   const char* name = "node_register_module_v" STRINGIFY(NODE_MODULE_VERSION);
398   return reinterpret_cast<InitializerCallback>(dlib->GetSymbolAddress(name));
399 }
400 
GetNapiInitializerCallback(DLib * dlib)401 inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) {
402   const char* name =
403       STRINGIFY(NAPI_MODULE_INITIALIZER_BASE) STRINGIFY(NAPI_MODULE_VERSION);
404   return reinterpret_cast<napi_addon_register_func>(
405       dlib->GetSymbolAddress(name));
406 }
407 
408 // DLOpen is process.dlopen(module, filename, flags).
409 // Used to load 'module.node' dynamically shared objects.
410 //
411 // FIXME(bnoordhuis) Not multi-context ready. TBD how to resolve the conflict
412 // when two contexts try to load the same shared object. Maybe have a shadow
413 // cache that's a plain C list or hash table that's shared across contexts?
DLOpen(const FunctionCallbackInfo<Value> & args)414 void DLOpen(const FunctionCallbackInfo<Value>& args) {
415   Environment* env = Environment::GetCurrent(args);
416 
417   if (env->no_native_addons()) {
418     return THROW_ERR_DLOPEN_DISABLED(
419       env, "Cannot load native addon because loading addons is disabled.");
420   }
421 
422   auto context = env->context();
423 
424   CHECK_NULL(thread_local_modpending);
425 
426   if (args.Length() < 2) {
427     return THROW_ERR_MISSING_ARGS(
428         env, "process.dlopen needs at least 2 arguments");
429   }
430 
431   int32_t flags = DLib::kDefaultFlags;
432   if (args.Length() > 2 && !args[2]->Int32Value(context).To(&flags)) {
433     return THROW_ERR_INVALID_ARG_TYPE(env, "flag argument must be an integer.");
434   }
435 
436   Local<Object> module;
437   Local<Object> exports;
438   Local<Value> exports_v;
439   if (!args[0]->ToObject(context).ToLocal(&module) ||
440       !module->Get(context, env->exports_string()).ToLocal(&exports_v) ||
441       !exports_v->ToObject(context).ToLocal(&exports)) {
442     return;  // Exception pending.
443   }
444 
445   node::Utf8Value filename(env->isolate(), args[1]);  // Cast
446   env->TryLoadAddon(*filename, flags, [&](DLib* dlib) {
447     static Mutex dlib_load_mutex;
448     Mutex::ScopedLock lock(dlib_load_mutex);
449 
450     const bool is_opened = dlib->Open();
451 
452     // Objects containing v14 or later modules will have registered themselves
453     // on the pending list.  Activate all of them now.  At present, only one
454     // module per object is supported.
455     node_module* mp = thread_local_modpending;
456     thread_local_modpending = nullptr;
457 
458     if (!is_opened) {
459       std::string errmsg = dlib->errmsg_.c_str();
460       dlib->Close();
461 #ifdef _WIN32
462       // Windows needs to add the filename into the error message
463       errmsg += *filename;
464 #endif  // _WIN32
465       THROW_ERR_DLOPEN_FAILED(env, errmsg.c_str());
466       return false;
467     }
468 
469     if (mp != nullptr) {
470       if (mp->nm_context_register_func == nullptr) {
471         if (env->force_context_aware()) {
472           dlib->Close();
473           THROW_ERR_NON_CONTEXT_AWARE_DISABLED(env);
474           return false;
475         }
476       }
477       mp->nm_dso_handle = dlib->handle_;
478       dlib->SaveInGlobalHandleMap(mp);
479     } else {
480       if (auto callback = GetInitializerCallback(dlib)) {
481         callback(exports, module, context);
482         return true;
483       } else if (auto napi_callback = GetNapiInitializerCallback(dlib)) {
484         napi_module_register_by_symbol(exports, module, context, napi_callback);
485         return true;
486       } else {
487         mp = dlib->GetSavedModuleFromGlobalHandleMap();
488         if (mp == nullptr || mp->nm_context_register_func == nullptr) {
489           dlib->Close();
490           char errmsg[1024];
491           snprintf(errmsg,
492                    sizeof(errmsg),
493                    "Module did not self-register: '%s'.",
494                    *filename);
495           THROW_ERR_DLOPEN_FAILED(env, errmsg);
496           return false;
497         }
498       }
499     }
500 
501     // -1 is used for N-API modules
502     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       if (auto callback = GetInitializerCallback(dlib)) {
507         callback(exports, module, context);
508         return true;
509       }
510       char errmsg[1024];
511       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                NODE_MODULE_VERSION);
522 
523       // NOTE: `mp` is allocated inside of the shared library's memory, calling
524       // `dlclose` will deallocate it
525       dlib->Close();
526       THROW_ERR_DLOPEN_FAILED(env, errmsg);
527       return false;
528     }
529     CHECK_EQ(mp->nm_flags & NM_F_BUILTIN, 0);
530 
531     // Do not keep the lock while running userland addon loading code.
532     Mutex::ScopedUnlock unlock(lock);
533     if (mp->nm_context_register_func != nullptr) {
534       mp->nm_context_register_func(exports, module, context, mp->nm_priv);
535     } else if (mp->nm_register_func != nullptr) {
536       mp->nm_register_func(exports, module, mp->nm_priv);
537     } else {
538       dlib->Close();
539       THROW_ERR_DLOPEN_FAILED(env, "Module has no declared entry point.");
540       return false;
541     }
542 
543     return true;
544   });
545 
546   // Tell coverity that 'handle' should not be freed when we return.
547   // coverity[leaked_storage]
548 }
549 
FindModule(struct node_module * list,const char * name,int flag)550 inline struct node_module* FindModule(struct node_module* list,
551                                       const char* name,
552                                       int flag) {
553   struct node_module* mp;
554 
555   for (mp = list; mp != nullptr; mp = mp->nm_link) {
556     if (strcmp(mp->nm_modname, name) == 0) break;
557   }
558 
559   CHECK(mp == nullptr || (mp->nm_flags & flag) != 0);
560   return mp;
561 }
562 
InitModule(Environment * env,node_module * mod,Local<String> module)563 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   Local<Function> ctor = env->binding_data_ctor_template()
568                              ->GetFunction(env->context())
569                              .ToLocalChecked();
570   Local<Object> exports = ctor->NewInstance(env->context()).ToLocalChecked();
571   CHECK_NULL(mod->nm_register_func);
572   CHECK_NOT_NULL(mod->nm_context_register_func);
573   Local<Value> unused = Undefined(env->isolate());
574   mod->nm_context_register_func(exports, unused, env->context(), mod->nm_priv);
575   return exports;
576 }
577 
GetInternalBinding(const FunctionCallbackInfo<Value> & args)578 void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
579   Environment* env = Environment::GetCurrent(args);
580 
581   CHECK(args[0]->IsString());
582 
583   Local<String> module = args[0].As<String>();
584   node::Utf8Value module_v(env->isolate(), module);
585   Local<Object> exports;
586 
587   node_module* mod = FindModule(modlist_internal, *module_v, NM_F_INTERNAL);
588   if (mod != nullptr) {
589     exports = InitModule(env, mod, module);
590   } else if (!strcmp(*module_v, "constants")) {
591     exports = Object::New(env->isolate());
592     CHECK(
593         exports->SetPrototype(env->context(), Null(env->isolate())).FromJust());
594     DefineConstants(env->isolate(), exports);
595   } else if (!strcmp(*module_v, "natives")) {
596     exports = native_module::NativeModuleEnv::GetSourceObject(env->context());
597     // Legacy feature: process.binding('natives').config contains stringified
598     // config.gypi
599     CHECK(exports
600               ->Set(env->context(),
601                     env->config_string(),
602                     native_module::NativeModuleEnv::GetConfigString(
603                         env->isolate()))
604               .FromJust());
605   } else {
606     char errmsg[1024];
607     snprintf(errmsg, sizeof(errmsg), "No such module: %s", *module_v);
608     return THROW_ERR_INVALID_MODULE(env, errmsg);
609   }
610 
611   args.GetReturnValue().Set(exports);
612 }
613 
GetLinkedBinding(const FunctionCallbackInfo<Value> & args)614 void GetLinkedBinding(const FunctionCallbackInfo<Value>& args) {
615   Environment* env = Environment::GetCurrent(args);
616 
617   CHECK(args[0]->IsString());
618 
619   Local<String> module_name = args[0].As<String>();
620 
621   node::Utf8Value module_name_v(env->isolate(), module_name);
622   const char* name = *module_name_v;
623   node_module* mod = nullptr;
624 
625   // Iterate from here to the nearest non-Worker Environment to see if there's
626   // a linked binding defined locally rather than through the global list.
627   Environment* cur_env = env;
628   while (mod == nullptr && cur_env != nullptr) {
629     Mutex::ScopedLock lock(cur_env->extra_linked_bindings_mutex());
630     mod = FindModule(cur_env->extra_linked_bindings_head(), name, NM_F_LINKED);
631     cur_env = cur_env->worker_parent_env();
632   }
633 
634   if (mod == nullptr)
635     mod = FindModule(modlist_linked, name, NM_F_LINKED);
636 
637   if (mod == nullptr) {
638     char errmsg[1024];
639     snprintf(errmsg,
640              sizeof(errmsg),
641              "No such module was linked: %s",
642              *module_name_v);
643     return THROW_ERR_INVALID_MODULE(env, errmsg);
644   }
645 
646   Local<Object> module = Object::New(env->isolate());
647   Local<Object> exports = Object::New(env->isolate());
648   Local<String> exports_prop =
649       String::NewFromUtf8Literal(env->isolate(), "exports");
650   module->Set(env->context(), exports_prop, exports).Check();
651 
652   if (mod->nm_context_register_func != nullptr) {
653     mod->nm_context_register_func(
654         exports, module, env->context(), mod->nm_priv);
655   } else if (mod->nm_register_func != nullptr) {
656     mod->nm_register_func(exports, module, mod->nm_priv);
657   } else {
658     return THROW_ERR_INVALID_MODULE(
659         env,
660         "Linked moduled has no declared entry point.");
661   }
662 
663   auto effective_exports =
664       module->Get(env->context(), exports_prop).ToLocalChecked();
665 
666   args.GetReturnValue().Set(effective_exports);
667 }
668 
669 // Call built-in modules' _register_<module name> function to
670 // do module registration explicitly.
RegisterBuiltinModules()671 void RegisterBuiltinModules() {
672 #define V(modname) _register_##modname();
673   NODE_BUILTIN_MODULES(V)
674 #undef V
675 }
676 
677 }  // namespace binding
678 }  // namespace node
679