Skip to content
Merged
64 changes: 34 additions & 30 deletions src/jsc/bindings/BunProcess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

// Include the CMake-generated dependency versions header
#include "bun_dependency_versions.h"
#include <wtf/Scope.h>
#include <JavaScriptCore/InternalFieldTuple.h>
#include <JavaScriptCore/JSMicrotask.h>
#include <JavaScriptCore/ObjectConstructor.h>
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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();
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
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);
Expand All @@ -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<decltype(mod)>;
if constexpr (std::is_same_v<T, node::node_module*>) {
node::node_module_register(mod);
} else if constexpr (std::is_same_v<T, napi_module*>) {
napi_module_register(mod);
}
},
registration);
if (auto* const* nodeModule = std::get_if<node::node_module*>(&registration)) {
node::node_module_register(*nodeModule);
RETURN_IF_EXCEPTION(scope, {});
} else {
napi_module_register(std::get<napi_module*>(registration));
}
}

// Execute all NAPI modules that were just registered. Move to a
Expand All @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
14 changes: 12 additions & 2 deletions src/jsc/bindings/ImportMetaObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -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()));
Expand All @@ -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<Bun::JSCommonJSModule>(parentModuleObject)) {
Expand All @@ -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);
}
Expand Down Expand Up @@ -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())));
Expand Down
25 changes: 18 additions & 7 deletions src/jsc/bindings/JSCommonJSModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -523,8 +523,10 @@ JSC_DEFINE_CUSTOM_SETTER(setterPath,
JSCommonJSModule* thisObject = dynamicDowncast<JSCommonJSModule>(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;
}

Expand Down Expand Up @@ -648,8 +650,10 @@ JSC_DEFINE_CUSTOM_SETTER(setterFilename,
JSCommonJSModule* thisObject = dynamicDowncast<JSCommonJSModule>(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;
}

Expand All @@ -660,8 +664,10 @@ JSC_DEFINE_CUSTOM_SETTER(setterId,
JSCommonJSModule* thisObject = dynamicDowncast<JSCommonJSModule>(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,
Expand Down Expand Up @@ -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<Zig::GlobalObject>(globalObject), id, object, hasEvaluated.isTrue(), parent));
RELEASE_AND_RETURN(scope, JSValue::encode(JSCommonJSModule::create(uncheckedDowncast<Zig::GlobalObject>(globalObject), id, object, hasEvaluated.isTrue(), parent)));
}

JSCommonJSModule* JSCommonJSModule::create(
Expand All @@ -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);
}
Expand Down
6 changes: 3 additions & 3 deletions src/jsc/bindings/ModuleLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/napi.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
strongExportsObject = { vm, exportsObject };
} else {
JSValue exportsObject = object->get(globalObject, WebCore::builtinNames(vm).exportsPublicName());
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/v8/node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
11 changes: 10 additions & 1 deletion src/jsc/modules/BunJSCModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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
Expand All @@ -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);
}
Expand Down
3 changes: 2 additions & 1 deletion src/jsc/modules/NodeModuleModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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, {});
Expand Down
19 changes: 19 additions & 0 deletions test/js/bun/plugin/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
20 changes: 20 additions & 0 deletions test/js/node/module/node-module-module.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down