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