diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index 1f3c485bee94..f71f8463ee30 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -8,6 +8,7 @@ // Include the CMake-generated dependency versions header #include "bun_dependency_versions.h" +#include #include #include #include @@ -583,6 +584,14 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( // iterator dangling. auto pendingNapiModules = std::exchange(globalObject->m_pendingNapiModules, {}); auto pendingV8Modules = std::exchange(globalObject->m_pendingV8Modules, {}); + // Whatever happens below, no registration state may leak into the next dlopen(). + auto resetPendingRegistrations = WTF::makeScopeExit([&] { + globalObject->m_pendingV8Modules.clear(); + globalObject->m_pendingNapiModules.clear(); + globalObject->napiModuleRegisterCallCount = 0; + globalObject->m_pendingNapiModuleAndExports[0].clear(); + globalObject->m_pendingNapiModuleAndExports[1].clear(); + }); if (handle) { // Save all NAPI module registrations @@ -597,6 +606,10 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( } } + // A V8-style module's nm_register_func already ran inside dlopen() (node_module_register) + // and may have thrown. + RETURN_IF_EXCEPTION(scope, {}); + // Execute all NAPI modules. If an nm_register_func registers more // modules re-entrantly, they accumulate back in m_pendingNapiModules; // drain those too once the current batch is done. @@ -608,22 +621,14 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( globalObject->m_pendingNapiModule = mod; Napi::executePendingNapiModule(globalObject); globalObject->m_pendingNapiModule = {}; + RETURN_IF_EXCEPTION(scope, {}); } if (globalObject->m_pendingNapiModules.isEmpty()) break; pendingNapiModules = std::exchange(globalObject->m_pendingNapiModules, {}); } - // Clear any re-entrant V8 registrations (not executed here). - globalObject->m_pendingV8Modules.clear(); - JSValue resultValue = globalObject->m_pendingNapiModuleAndExports[0].get(); - globalObject->napiModuleRegisterCallCount = 0; - globalObject->m_pendingNapiModuleAndExports[0].clear(); - globalObject->m_pendingNapiModuleAndExports[1].clear(); - - RETURN_IF_EXCEPTION(scope, {}); - if (resultValue && resultValue != strongModule.get()) { if (resultValue.isCell() && resultValue.getObject()->isErrorInstance()) { JSC::throwException(globalObject, scope, resultValue); @@ -636,18 +641,24 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( // Module didn't self-register on this load. Check if we have cached registrations. if (auto cachedModules = Bun::DLHandleMap::singleton().get(handle)) { - // Replay all registrations from this handle - // This will populate the vectors again via register functions + // (The V8 registrations are already in DLHandleMap; nothing here re-saves them.) + auto resetPendingRegistrations = WTF::makeScopeExit([&] { + globalObject->m_pendingV8Modules.clear(); + globalObject->m_pendingNapiModules.clear(); + globalObject->napiModuleRegisterCallCount = 0; + globalObject->m_pendingNapiModuleAndExports[0].clear(); + globalObject->m_pendingNapiModuleAndExports[1].clear(); + }); + + // Replay all registrations from this handle. napi ones only queue into + // m_pendingNapiModules; a V8 one runs its nm_register_func right here. for (auto& registration : *cachedModules) { - std::visit([](auto&& mod) { - using T = std::decay_t; - if constexpr (std::is_same_v) { - node::node_module_register(mod); - } else if constexpr (std::is_same_v) { - napi_module_register(mod); - } - }, - registration); + if (auto* const* nodeModule = std::get_if(®istration)) { + node::node_module_register(*nodeModule); + RETURN_IF_EXCEPTION(scope, {}); + } else { + napi_module_register(std::get(registration)); + } } // Execute all NAPI modules that were just registered. Move to a @@ -662,19 +673,11 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( globalObject->m_pendingNapiModule = mod; Napi::executePendingNapiModule(globalObject); globalObject->m_pendingNapiModule = {}; + RETURN_IF_EXCEPTION(scope, {}); } } - // Clear the V8 vector (no need to save again since already in DLHandleMap) - globalObject->m_pendingV8Modules.clear(); - JSValue resultValue = globalObject->m_pendingNapiModuleAndExports[0].get(); - globalObject->napiModuleRegisterCallCount = 0; - globalObject->m_pendingNapiModuleAndExports[0].clear(); - globalObject->m_pendingNapiModuleAndExports[1].clear(); - - RETURN_IF_EXCEPTION(scope, {}); - if (resultValue && resultValue != strongModule.get()) { if (resultValue.isCell() && resultValue.getObject()->isErrorInstance()) { JSC::throwException(globalObject, scope, resultValue); @@ -771,9 +774,10 @@ JSC_DEFINE_HOST_FUNCTION_WITH_ATTRIBUTES(Process_functionDlopen, __attribute__(( // https://github.com/nodejs/node/blob/2eff28fb7a93d3f672f80b582f664a7c701569fb/src/node_api.cc#L734-L742 // https://github.com/oven-sh/bun/issues/1288 - if (!resultValue.isEmpty() && !scope.exception() && (!strongExports || resultValue != strongExports.get())) { + if (!resultValue.isEmpty() && (!strongExports || resultValue != strongExports.get())) { PutPropertySlot slot(strongModule.get(), false); strongModule->put(strongModule.get(), globalObject, builtinNames(vm).exportsPublicName(), resultValue, slot); + RETURN_IF_EXCEPTION(scope, {}); } return JSValue::encode(resultValue); diff --git a/src/jsc/bindings/ImportMetaObject.cpp b/src/jsc/bindings/ImportMetaObject.cpp index 970e8dc461c7..cef4eab4c4bc 100644 --- a/src/jsc/bindings/ImportMetaObject.cpp +++ b/src/jsc/bindings/ImportMetaObject.cpp @@ -175,7 +175,10 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSync(JSC::JSGlobalObje if (globalObject->onLoadPlugins.hasVirtualModules()) { if (moduleName.isString()) { auto moduleString = moduleName.toWTFString(globalObject); - if (auto resolvedString = globalObject->onLoadPlugins.resolveVirtualModule(moduleString, JSValue::decode(from).toWTFString(globalObject))) { + RETURN_IF_EXCEPTION(scope, {}); + auto fromString = JSValue::decode(from).toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); + if (auto resolvedString = globalObject->onLoadPlugins.resolveVirtualModule(moduleString, fromString)) { if (moduleString == resolvedString.value()) return JSC::JSValue::encode(moduleName); return JSC::JSValue::encode(jsString(vm, resolvedString.value())); @@ -214,7 +217,10 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo if (globalObject->onLoadPlugins.hasVirtualModules()) { if (moduleName.isString()) { auto moduleString = moduleName.toWTFString(globalObject); - if (auto resolvedString = globalObject->onLoadPlugins.resolveVirtualModule(moduleString, from.toWTFString(globalObject))) { + RETURN_IF_EXCEPTION(scope, {}); + auto fromString = from.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); + if (auto resolvedString = globalObject->onLoadPlugins.resolveVirtualModule(moduleString, fromString)) { if (moduleString == resolvedString.value()) return JSC::JSValue::encode(moduleName); return JSC::JSValue::encode(jsString(vm, resolvedString.value())); @@ -229,6 +235,7 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo if (overrideHandler) [[likely]] { ASSERT(overrideHandler->isCallable()); JSValue parentModuleObject = globalObject->requireMap()->get(globalObject, from); + RETURN_IF_EXCEPTION(scope, {}); JSValue parentID = jsUndefined(); if (auto* parent = dynamicDowncast(parentModuleObject)) { @@ -241,12 +248,14 @@ extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlo args.append(moduleName); args.append(parentModuleObject); auto parentIdStr = parentID.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); auto bunStr = Bun::toString(parentIdStr); args.append(jsBoolean(Bun__isBunMain(lexicalGlobalObject, &bunStr))); // Pass options object with paths if provided if (!userPathList.isUndefinedOrNull()) { JSObject* options = JSC::constructEmptyObject(globalObject); + RETURN_IF_EXCEPTION(scope, {}); options->putDirect(vm, JSC::Identifier::fromString(vm, "paths"_s), userPathList); args.append(options); } @@ -441,6 +450,7 @@ JSC_DEFINE_HOST_FUNCTION(functionImportMeta__resolve, } auto resultString = result.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); if (isAbsolutePath(resultString)) { // file path -> url RELEASE_AND_RETURN(scope, JSValue::encode(jsString(vm, WTF::URL::fileURLWithFileSystemPath(resultString).string()))); diff --git a/src/jsc/bindings/JSCommonJSModule.cpp b/src/jsc/bindings/JSCommonJSModule.cpp index faf6f4207e87..aba39cc90f82 100644 --- a/src/jsc/bindings/JSCommonJSModule.cpp +++ b/src/jsc/bindings/JSCommonJSModule.cpp @@ -523,8 +523,10 @@ JSC_DEFINE_CUSTOM_SETTER(setterPath, JSCommonJSModule* thisObject = dynamicDowncast(JSValue::decode(thisValue)); if (!thisObject) return false; - - thisObject->m_dirname.set(globalObject->vm(), thisObject, JSValue::decode(value).toString(globalObject)); + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSString* string = JSValue::decode(value).toString(globalObject); + RETURN_IF_EXCEPTION(scope, false); + thisObject->m_dirname.set(globalObject->vm(), thisObject, string); return true; } @@ -648,8 +650,10 @@ JSC_DEFINE_CUSTOM_SETTER(setterFilename, JSCommonJSModule* thisObject = dynamicDowncast(JSValue::decode(thisValue)); if (!thisObject) return false; - - thisObject->m_filename.set(globalObject->vm(), thisObject, JSValue::decode(value).toString(globalObject)); + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSString* string = JSValue::decode(value).toString(globalObject); + RETURN_IF_EXCEPTION(scope, false); + thisObject->m_filename.set(globalObject->vm(), thisObject, string); return true; } @@ -660,8 +664,10 @@ JSC_DEFINE_CUSTOM_SETTER(setterId, JSCommonJSModule* thisObject = dynamicDowncast(JSValue::decode(thisValue)); if (!thisObject) return false; - - thisObject->m_id.set(globalObject->vm(), thisObject, JSValue::decode(value).toString(globalObject)); + auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); + JSString* string = JSValue::decode(value).toString(globalObject); + RETURN_IF_EXCEPTION(scope, false); + thisObject->m_id.set(globalObject->vm(), thisObject, string); return true; } JSC_DEFINE_CUSTOM_SETTER(setterParent, @@ -886,14 +892,16 @@ JSCommonJSModule* JSCommonJSModule::create( JSC_DEFINE_HOST_FUNCTION(jsFunctionCreateCommonJSModule, (JSGlobalObject * globalObject, CallFrame* callframe)) { RELEASE_ASSERT(callframe->argumentCount() == 4); + auto scope = DECLARE_THROW_SCOPE(JSC::getVM(globalObject)); auto id = callframe->uncheckedArgument(0).toString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); JSValue object = callframe->uncheckedArgument(1); JSValue hasEvaluated = callframe->uncheckedArgument(2); ASSERT(hasEvaluated.isBoolean()); JSValue parent = callframe->uncheckedArgument(3); - return JSValue::encode(JSCommonJSModule::create(uncheckedDowncast(globalObject), id, object, hasEvaluated.isTrue(), parent)); + RELEASE_AND_RETURN(scope, JSValue::encode(JSCommonJSModule::create(uncheckedDowncast(globalObject), id, object, hasEvaluated.isTrue(), parent))); } JSCommonJSModule* JSCommonJSModule::create( @@ -904,12 +912,15 @@ JSCommonJSModule* JSCommonJSModule::create( JSValue parent) { auto& vm = JSC::getVM(globalObject); + auto scope = DECLARE_THROW_SCOPE(vm); auto key = requireMapKey->value(globalObject); + RETURN_IF_EXCEPTION(scope, nullptr); auto index = key->reverseFind(PLATFORM_SEP, key->length()); JSString* dirname; if (index != WTF::notFound) { dirname = JSC::jsSubstring(globalObject, requireMapKey, 0, index); + RETURN_IF_EXCEPTION(scope, nullptr); } else { dirname = jsEmptyString(vm); } diff --git a/src/jsc/bindings/ModuleLoader.cpp b/src/jsc/bindings/ModuleLoader.cpp index bc097917d1d4..b68327d1f900 100644 --- a/src/jsc/bindings/ModuleLoader.cpp +++ b/src/jsc/bindings/ModuleLoader.cpp @@ -386,7 +386,7 @@ static JSValue handleVirtualModuleResult( const auto rejectOrResolve = [&](JSValue code) -> JSValue { if (auto* exception = scope.exception()) { if constexpr (allowPromise) { - (void)scope.tryClearException(); + TRY_CLEAR_EXCEPTION(scope, {}); RELEASE_AND_RETURN(scope, rejectedInternalPromise(globalObject, exception)); } else { return exception; @@ -423,12 +423,12 @@ static JSValue handleVirtualModuleResult( const auto& __esModuleIdentifier = vm.propertyNames->__esModule; auto esModuleValue = object->getIfPropertyExists(globalObject, __esModuleIdentifier); if (scope.exception()) [[unlikely]] { - RELEASE_AND_RETURN(scope, reject(scope.exception())); + return rejectOrResolve({}); } if (esModuleValue && esModuleValue.toBoolean(globalObject)) { auto defaultValue = object->getIfPropertyExists(globalObject, vm.propertyNames->defaultKeyword); if (scope.exception()) [[unlikely]] { - RELEASE_AND_RETURN(scope, reject(scope.exception())); + return rejectOrResolve({}); } if (defaultValue && !defaultValue.isUndefined()) { commonJSModule->setExportsObject(defaultValue); diff --git a/src/jsc/bindings/napi.cpp b/src/jsc/bindings/napi.cpp index fa4b51887e57..3819852cda0f 100644 --- a/src/jsc/bindings/napi.cpp +++ b/src/jsc/bindings/napi.cpp @@ -746,6 +746,7 @@ void Napi::executePendingNapiModule(Zig::GlobalObject* globalObject) RETURN_IF_EXCEPTION(scope, void()); object = Bun::JSCommonJSModule::create(globalObject, keyStr, exportsObject, false, jsUndefined()); + RETURN_IF_EXCEPTION(scope, void()); strongExportsObject = { vm, exportsObject }; } else { JSValue exportsObject = object->get(globalObject, WebCore::builtinNames(vm).exportsPublicName()); diff --git a/src/jsc/bindings/v8/node.cpp b/src/jsc/bindings/v8/node.cpp index 28b510bb7ebf..7389e978c201 100644 --- a/src/jsc/bindings/v8/node.cpp +++ b/src/jsc/bindings/v8/node.cpp @@ -145,6 +145,7 @@ void node_module_register(void* opaque_mod) RETURN_IF_EXCEPTION(scope, void()); object = Bun::JSCommonJSModule::create(globalObject, keyStr, exportsObject, false, jsUndefined()); + RETURN_IF_EXCEPTION(scope, void()); strongExportsObject = { vm, exportsObject }; } else { JSValue exportsObject = object->get(globalObject, WebCore::builtinNames(vm).exportsPublicName()); diff --git a/src/jsc/modules/BunJSCModule.h b/src/jsc/modules/BunJSCModule.h index f8e994d886dd..02ae3334d2b7 100644 --- a/src/jsc/modules/BunJSCModule.h +++ b/src/jsc/modules/BunJSCModule.h @@ -372,10 +372,12 @@ JSC_DEFINE_HOST_FUNCTION(functionMemoryUsageStatistics, #endif #endif + auto scope = DECLARE_THROW_SCOPE(vm); mi_collect(false); if (char* json = mi_stats_get_json(0, nullptr)) { JSValue parsed = JSONParse(globalObject, String::fromUTF8(json)); mi_free(json); + RETURN_IF_EXCEPTION(scope, {}); object->putDirect(vm, Identifier::fromString(vm, "mimalloc"_s), parsed.isEmpty() ? jsNull() : parsed); } @@ -384,8 +386,14 @@ JSC_DEFINE_HOST_FUNCTION(functionMemoryUsageStatistics, JSValue arg0 = callFrame->argument(0); if (arg0.isObject()) { JSValue dump = arg0.getObject()->get(globalObject, Identifier::fromString(vm, "dump"_s)); + RETURN_IF_EXCEPTION(scope, {}); if (dump.toBoolean(globalObject)) { - const bool includeBlocks = dump.isString() && dump.toWTFString(globalObject) == "blocks"_s; + bool includeBlocks = false; + if (dump.isString()) { + auto dumpString = dump.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); + includeBlocks = dumpString == "blocks"_s; + } #if BUN_DEBUG const bool hashAddresses = false; #else @@ -394,6 +402,7 @@ JSC_DEFINE_HOST_FUNCTION(functionMemoryUsageStatistics, if (char* json = mi_heap_dump_json(includeBlocks, hashAddresses)) { JSValue parsed = JSONParse(globalObject, String::fromUTF8(json)); mi_free(json); + RETURN_IF_EXCEPTION(scope, {}); object->putDirect(vm, Identifier::fromString(vm, "mimallocDump"_s), parsed.isEmpty() ? jsNull() : parsed); } diff --git a/src/jsc/modules/NodeModuleModule.cpp b/src/jsc/modules/NodeModuleModule.cpp index db5021be0940..983978fd0b54 100644 --- a/src/jsc/modules/NodeModuleModule.cpp +++ b/src/jsc/modules/NodeModuleModule.cpp @@ -789,7 +789,8 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionRunMain, (JSGlobalObject * globalObject, JSC: auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); auto arg1 = callFrame->argument(0); - auto name = makeAtomString(arg1.toWTFString(globalObject)); + auto name = arg1.toWTFString(globalObject); + RETURN_IF_EXCEPTION(scope, {}); auto* promise = JSC::loadAndEvaluateModule(globalObject, name, nullptr, nullptr); RETURN_IF_EXCEPTION(scope, {}); diff --git a/test/js/bun/plugin/plugins.test.ts b/test/js/bun/plugin/plugins.test.ts index 780013d38717..ebd753cc4636 100644 --- a/test/js/bun/plugin/plugins.test.ts +++ b/test/js/bun/plugin/plugins.test.ts @@ -1017,3 +1017,22 @@ describe.concurrent("Bun.plugin.clearAll()", () => { }); }); }); + +it("object loader: an error thrown by a getter on the exports object rejects the require()", () => { + const boom = new Error("boom"); + plugin({ + name: "object loader with throwing __esModule", + setup(build) { + build.module("object-loader-throwing-esmodule", () => ({ + exports: { + get __esModule() { + throw boom; + }, + a: 1, + }, + loader: "object", + })); + }, + }); + expect(() => require("object-loader-throwing-esmodule")).toThrow(boom); +}); diff --git a/test/js/node/module/node-module-module.test.js b/test/js/node/module/node-module-module.test.js index 350c559d56f6..ebde35001db9 100644 --- a/test/js/node/module/node-module-module.test.js +++ b/test/js/node/module/node-module-module.test.js @@ -405,6 +405,26 @@ console.log("survived", require("./late.js"));`, expect(Module._resolveFilename("fs")).toBe("fs"); }); + test("Module.runMain propagates an error from stringifying its argument", () => { + const boom = new Error("boom"); + expect(() => + Module.runMain({ + toString() { + throw boom; + }, + }), + ).toThrow(boom); + }); + + test("module.filename/id/path setters propagate a failed string conversion", () => { + const m = new Module("x"); + for (const key of ["filename", "id", "path"]) { + expect(() => { + m[key] = Symbol("s"); + }).toThrow(TypeError); + } + }); + test("Module._resolveFilename accepts an options object without paths", () => { // An options object without .paths used to segfault on the isArray() check. expect(Module._resolveFilename("fs", null, false, {})).toBe("fs");