Skip to content

Commit 866965e

Browse files
rpetrichtargos
authored andcommitted
src: fix race on modpending
Fixes a rare race condition on modpending when two native modules are loaded simultaneously on different threads by storing it thread- locally. PR-URL: #21611 Reviewed-By: Gabriel Schulhof <[email protected]> Reviewed-By: Anatoli Papirovski <[email protected]>
1 parent c894145 commit 866965e

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

src/node.cc

+12-5
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,8 @@ static int v8_thread_pool_size = v8_default_thread_pool_size;
187187
static bool prof_process = false;
188188
static bool v8_is_profiling = false;
189189
static bool node_is_initialized = false;
190-
static node_module* modpending;
190+
static uv_once_t init_modpending_once = UV_ONCE_INIT;
191+
static uv_key_t thread_local_modpending;
191192
static node_module* modlist_builtin;
192193
static node_module* modlist_internal;
193194
static node_module* modlist_linked;
@@ -1254,7 +1255,7 @@ extern "C" void node_module_register(void* m) {
12541255
mp->nm_link = modlist_linked;
12551256
modlist_linked = mp;
12561257
} else {
1257-
modpending = mp;
1258+
uv_key_set(&thread_local_modpending, mp);
12581259
}
12591260
}
12601261

@@ -1368,6 +1369,10 @@ inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) {
13681369
reinterpret_cast<napi_addon_register_func>(dlib->GetSymbolAddress(name));
13691370
}
13701371

1372+
void InitModpendingOnce() {
1373+
CHECK_EQ(0, uv_key_create(&thread_local_modpending));
1374+
}
1375+
13711376
// DLOpen is process.dlopen(module, filename, flags).
13721377
// Used to load 'module.node' dynamically shared objects.
13731378
//
@@ -1378,7 +1383,8 @@ static void DLOpen(const FunctionCallbackInfo<Value>& args) {
13781383
Environment* env = Environment::GetCurrent(args);
13791384
auto context = env->context();
13801385

1381-
CHECK_NULL(modpending);
1386+
uv_once(&init_modpending_once, InitModpendingOnce);
1387+
CHECK_NULL(uv_key_get(&thread_local_modpending));
13821388

13831389
if (args.Length() < 2) {
13841390
env->ThrowError("process.dlopen needs at least 2 arguments.");
@@ -1406,8 +1412,9 @@ static void DLOpen(const FunctionCallbackInfo<Value>& args) {
14061412
// Objects containing v14 or later modules will have registered themselves
14071413
// on the pending list. Activate all of them now. At present, only one
14081414
// module per object is supported.
1409-
node_module* const mp = modpending;
1410-
modpending = nullptr;
1415+
node_module* const mp = static_cast<node_module*>(
1416+
uv_key_get(&thread_local_modpending));
1417+
uv_key_set(&thread_local_modpending, nullptr);
14111418

14121419
if (!is_opened) {
14131420
Local<String> errmsg = OneByteString(env->isolate(), dlib.errmsg_.c_str());

0 commit comments

Comments
 (0)