Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 21 additions & 41 deletions Source/JavaScriptCore/runtime/AbstractModuleRecord.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1144,7 +1144,11 @@ JS_EXPORT_PRIVATE JSValue AbstractModuleRecord::evaluate(JSGlobalObject* globalO
return jsUndefined();
}

#if USE(BUN_JSC_ADDITIONS)
JSPromise* AbstractModuleRecord::evaluate(JSGlobalObject* globalObject, int64_t referrerAsyncOrder)
#else
JSPromise* AbstractModuleRecord::evaluate(JSGlobalObject* globalObject)
#endif
{
VM& vm = globalObject->vm();

Expand All @@ -1159,7 +1163,11 @@ JSPromise* AbstractModuleRecord::evaluate(JSGlobalObject* globalObject)
};

if (auto* cyclicRecord = dynamicDowncast<CyclicModuleRecord>(this))
#if USE(BUN_JSC_ADDITIONS)
return wrap(cyclicRecord->evaluate(globalObject, referrerAsyncOrder));
#else
return wrap(cyclicRecord->evaluate(globalObject));
#endif
if (auto* syntheticRecord = dynamicDowncast<SyntheticModuleRecord>(this))
return wrap(syntheticRecord->evaluate(globalObject));
RELEASE_ASSERT_NOT_REACHED();
Expand Down Expand Up @@ -1188,7 +1196,7 @@ static void checkSafeToRecurse(JSGlobalObject* globalObject, ThrowScope& scope)
}

#if USE(BUN_JSC_ADDITIONS)
unsigned AbstractModuleRecord::innerModuleEvaluation(JSGlobalObject* globalObject, Vector<AbstractModuleRecord*, 8>& stack, unsigned index, int64_t asyncOrderWatermark)
unsigned AbstractModuleRecord::innerModuleEvaluation(JSGlobalObject* globalObject, Vector<AbstractModuleRecord*, 8>& stack, unsigned index, int64_t referrerAsyncOrder)
#else
unsigned AbstractModuleRecord::innerModuleEvaluation(JSGlobalObject* globalObject, Vector<AbstractModuleRecord*, 8>& stack, unsigned index)
#endif
Expand Down Expand Up @@ -1262,37 +1270,10 @@ unsigned AbstractModuleRecord::innerModuleEvaluation(JSGlobalObject* globalObjec
for (AbstractModuleRecord* requiredModule : evaluationList) {
checkSafeToRecurse(globalObject, scope);
RETURN_IF_EXCEPTION(scope, invalid);
#if USE(BUN_JSC_ADDITIONS)
// Record whether this dep was already mid-TLA before our recursive
// visit. The spec (12.b.v) makes us wait on it, which is a guaranteed
// deadlock when we're running inside that very dep's TLA continuation
// (e.g. Nitro: index.mjs top-level `await fetch()` -> handler ->
// `import("./chunk")` -> chunk statically imports index.mjs). The
// pre-rewrite JS loader did not track async parents across dynamic
// imports, so it evaluated the chunk immediately with the parent's
// already-initialised bindings. Preserve that for back-compat.
//
// "Already EvaluatingAsync" alone is too broad: it also matches a
// sibling static import in the *same* Evaluate() pass that popped an
// SCC to EvaluatingAsync earlier in the walk. In that case the dep's
// body has not run yet (its bindings are TDZ) and skipping the wait
// executes the importer too early. We narrow at 12.b.v below: only
// skip when the cycle root's pendingAsyncDependencies is 0, i.e. its
// ExecuteModule/ExecuteAsyncModule has already been called and the
// bindings before its first await are initialised. For an SCC still
// queued behind an async dep the root's count is > 0. That alone is
// still insufficient: a TLA dep with no async deps of its own has
// count 0 yet may have only run to its first await within this same
// DFS, leaving post-await bindings TDZ (#30259). We additionally
// require asyncEvaluationOrder() < asyncOrderWatermark, i.e. the
// dep entered EvaluatingAsync in a *prior* Evaluate() call.
bool depWasAlreadyEvaluatingAsync = false;
if (auto* depCyclic = dynamicDowncast<CyclicModuleRecord>(requiredModule))
depWasAlreadyEvaluatingAsync = depCyclic->status() == Status::EvaluatingAsync;
// 12.a. Set index to ? InnerModuleEvaluation(requiredModule, stack, index).
unsigned result = requiredModule->innerModuleEvaluation(globalObject, stack, index, asyncOrderWatermark);
#if USE(BUN_JSC_ADDITIONS)
unsigned result = requiredModule->innerModuleEvaluation(globalObject, stack, index, referrerAsyncOrder);
#else
// 12.a. Set index to ? InnerModuleEvaluation(requiredModule, stack, index).
unsigned result = requiredModule->innerModuleEvaluation(globalObject, stack, index);
#endif
RETURN_IF_EXCEPTION(scope, invalid);
Expand Down Expand Up @@ -1339,17 +1320,16 @@ unsigned AbstractModuleRecord::innerModuleEvaluation(JSGlobalObject* globalObjec
// 12.b.v. If requiredModule.[[AsyncEvaluationOrder]] is an integer, then
if (cyclic->asyncEvaluationOrder().hasOrder()) {
#if USE(BUN_JSC_ADDITIONS)
// See note above the recursive call: skip the spec-mandated
// wait to avoid self-deadlock and match old-loader behaviour.
// Only skip when the cycle root entered EvaluatingAsync in a
// *prior* Evaluate() (order < asyncOrderWatermark) — a dep
// that became EvaluatingAsync earlier in *this* DFS is a
// sibling whose post-await bindings are still TDZ (#30259) —
// and its body has already been entered
// (pendingAsyncDependencies == 0).
if (!depWasAlreadyEvaluatingAsync
|| cyclic->asyncEvaluationOrder().order() >= asyncOrderWatermark
|| cyclic->pendingAsyncDependencies().value_or(1)) {
// Spec says wait on this dep. That's a guaranteed deadlock when
// the dep is the very module whose TLA continuation called the
// dynamic import() that started this Evaluate(): the dep can
// only finish after the import() promise settles, which is
// waiting on us. referrerAsyncOrder is that module's
// asyncEvaluationOrder(), captured at the import() call site
// (-1 when the referrer was not EvaluatingAsync). It is a
// VM-unique identity, so equality is exact — siblings that
// happen to be EvaluatingAsync (#30259, #30634) never match.
if (cyclic->asyncEvaluationOrder().order() != referrerAsyncOrder) {
#endif
// 12.b.v.1. Set module.[[PendingAsyncDependencies]] to module.[[PendingAsyncDependencies]] + 1.
module->setPendingAsyncDependencies(module->pendingAsyncDependencies().value() + 1);
Expand Down
6 changes: 5 additions & 1 deletion Source/JavaScriptCore/runtime/AbstractModuleRecord.h
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,19 @@ class AbstractModuleRecord : public JSInternalFieldObjectImpl<2> {

void evaluateModuleSync(JSGlobalObject*);
#if USE(BUN_JSC_ADDITIONS)
unsigned innerModuleEvaluation(JSGlobalObject*, Vector<AbstractModuleRecord*, 8>& stack, unsigned index, int64_t asyncOrderWatermark);
unsigned innerModuleEvaluation(JSGlobalObject*, Vector<AbstractModuleRecord*, 8>& stack, unsigned index, int64_t referrerAsyncOrder);
#else
unsigned innerModuleEvaluation(JSGlobalObject*, Vector<AbstractModuleRecord*, 8>& stack, unsigned index);
#endif
unsigned innerModuleLinking(JSGlobalObject*, Vector<CyclicModuleRecord*, 8>& stack, unsigned index, RefPtr<ScriptFetcher>);

DECLARE_VISIT_CHILDREN;

#if USE(BUN_JSC_ADDITIONS)
JSPromise* evaluate(JSGlobalObject*, int64_t referrerAsyncOrder = -1);
#else
JSPromise* evaluate(JSGlobalObject*);
#endif

#if USE(BUN_JSC_ADDITIONS)
bool m_isTypeScript = false;
Expand Down
4 changes: 2 additions & 2 deletions Source/JavaScriptCore/runtime/Completion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -280,14 +280,14 @@ JSPromise* linkAndEvaluateModule(JSGlobalObject* globalObject, const Identifier&
return globalObject->moduleLoader()->linkAndEvaluateModule(globalObject, moduleKey, nullptr, WTF::move(scriptFetcher));
}

JSPromise* importModule(JSGlobalObject* globalObject, const Identifier& moduleName, const Identifier& referrer, RefPtr<ScriptFetchParameters> parameters, RefPtr<ScriptFetcher> scriptFetcher, bool deferred)
JSPromise* importModule(JSGlobalObject* globalObject, const Identifier& moduleName, const Identifier& referrer, RefPtr<ScriptFetchParameters> parameters, RefPtr<ScriptFetcher> scriptFetcher, bool deferred, int64_t referrerAsyncOrder)
{
VM& vm = globalObject->vm();
JSLockHolder lock(vm);
RELEASE_ASSERT(vm.atomStringTable() == Thread::currentSingleton().atomStringTable());
RELEASE_ASSERT(!vm.isCollectorBusyOnCurrentThread());

return globalObject->moduleLoader()->requestImportModule(globalObject, moduleName, referrer, WTF::move(parameters), WTF::move(scriptFetcher), deferred);
return globalObject->moduleLoader()->requestImportModule(globalObject, moduleName, referrer, WTF::move(parameters), WTF::move(scriptFetcher), deferred, referrerAsyncOrder);
Comment on lines +283 to +290

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Keep the Bun-only async-order parameter behind the Bun flag.

referrerAsyncOrder is only consumed by the Bun-gated evaluation path, but this public JSC::importModule wrapper now exposes and forwards it for every build. Please keep the extra parameter/overload under USE(BUN_JSC_ADDITIONS) consistently through the loader API so non-Bun JSC API/ABI does not carry Bun-specific state.

As per coding guidelines, "Source/JavaScriptCore/**/*.{cpp,h}: Guard Bun-specific features with USE(BUN_JSC_ADDITIONS) and event-loop integration with USE(BUN_EVENT_LOOP)."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Source/JavaScriptCore/runtime/Completion.cpp` around lines 283 - 290, The
importModule function currently exposes the referrerAsyncOrder parameter
publicly without any Bun-specific guards, even though this parameter is only
consumed by Bun-gated evaluation paths. Guard the function declaration or create
separate overloads using USE(BUN_JSC_ADDITIONS) preprocessor conditionals to
ensure the version with the referrerAsyncOrder parameter is only exposed in Bun
builds, preventing non-Bun JSC API/ABI from carrying Bun-specific state. This
ensures consistency with the coding guideline that Bun-specific features in
Source/JavaScriptCore must be guarded with USE(BUN_JSC_ADDITIONS).

Source: Coding guidelines

}

UncheckedKeyHashMap<RefPtr<UniquedStringImpl>, String> retrieveImportAttributesFromDynamicImportOptions(JSGlobalObject* globalObject, JSValue options, const Vector<RefPtr<UniquedStringImpl>>& supportedImportAttributes)
Expand Down
2 changes: 1 addition & 1 deletion Source/JavaScriptCore/runtime/Completion.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ JS_EXPORT_PRIVATE JSPromise* loadModule(JSGlobalObject*, SourceCode&&, RefPtr<Sc
// Link and evaluate the already linked module. This function is called in an async manner.
JS_EXPORT_PRIVATE JSPromise* linkAndEvaluateModule(JSGlobalObject*, const Identifier& moduleKey, RefPtr<ScriptFetcher>);

JS_EXPORT_PRIVATE JSPromise* importModule(JSGlobalObject*, const Identifier& moduleName, const Identifier& referrer, RefPtr<ScriptFetchParameters>, RefPtr<ScriptFetcher>, bool deferred = false);
JS_EXPORT_PRIVATE JSPromise* importModule(JSGlobalObject*, const Identifier& moduleName, const Identifier& referrer, RefPtr<ScriptFetchParameters>, RefPtr<ScriptFetcher>, bool deferred = false, int64_t referrerAsyncOrder = -1);

JS_EXPORT_PRIVATE UncheckedKeyHashMap<RefPtr<UniquedStringImpl>, String> retrieveImportAttributesFromDynamicImportOptions(JSGlobalObject*, JSValue, const Vector<RefPtr<UniquedStringImpl>>& supportedAssertions);
JS_EXPORT_PRIVATE std::optional<ScriptFetchParameters::Type> retrieveTypeImportAttribute(JSGlobalObject*, const UncheckedKeyHashMap<RefPtr<UniquedStringImpl>, String>&);
Expand Down
9 changes: 5 additions & 4 deletions Source/JavaScriptCore/runtime/CyclicModuleRecord.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,11 @@ void CyclicModuleRecord::link(JSGlobalObject* globalObject, RefPtr<ScriptFetcher
// 7. Return UNUSED.
}

#if USE(BUN_JSC_ADDITIONS)
JSPromise* CyclicModuleRecord::evaluate(JSGlobalObject* globalObject, int64_t referrerAsyncOrder)
#else
JSPromise* CyclicModuleRecord::evaluate(JSGlobalObject* globalObject)
#endif
{
// https://tc39.es/ecma262/#sec-moduleevaluation

Expand Down Expand Up @@ -447,10 +451,7 @@ JSPromise* CyclicModuleRecord::evaluate(JSGlobalObject* globalObject)
module->setTopLevelCapability(vm, capability);
// 8. Let result be Completion(InnerModuleEvaluation(module, stack, 0)).
#if USE(BUN_JSC_ADDITIONS)
// Snapshot the async-order counter so the DFS can tell deps that were
// already EvaluatingAsync before this Evaluate() (re-entrant deadlock
// case, see note at 11.c.v) from siblings that transition during it.
module->innerModuleEvaluation(globalObject, stack, 0, vm.moduleAsyncEvaluationCount());
module->innerModuleEvaluation(globalObject, stack, 0, referrerAsyncOrder);
#else
module->innerModuleEvaluation(globalObject, stack, 0);
#endif
Expand Down
4 changes: 4 additions & 0 deletions Source/JavaScriptCore/runtime/CyclicModuleRecord.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ class CyclicModuleRecord : public AbstractModuleRecord {

void initializeEnvironment(JSGlobalObject*, RefPtr<ScriptFetcher>);
void link(JSGlobalObject*, RefPtr<ScriptFetcher>);
#if USE(BUN_JSC_ADDITIONS)
JSPromise* evaluate(JSGlobalObject*, int64_t referrerAsyncOrder = -1);
#else
JSPromise* evaluate(JSGlobalObject*);
#endif
void execute(JSGlobalObject*, JSPromise* = nullptr);
void executeAsync(JSGlobalObject*);
void asyncExecutionFulfilled(JSGlobalObject*);
Expand Down
21 changes: 17 additions & 4 deletions Source/JavaScriptCore/runtime/JSMicrotask.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1074,7 +1074,11 @@ static void moduleLoadTopSettled(JSGlobalObject* globalObject, VM& vm, ThrowScop
if (context->useImportMap())
innerLoadFlags.add(ModuleLoadFlag::UseImportMap);
if (context->dynamic()) {
#if USE(BUN_JSC_ADDITIONS)
combinedCell = ModuleLoaderPayload::create(vm, statePromise, context->deferred(), context->referrerAsyncOrder());
#else
combinedCell = ModuleLoaderPayload::create(vm, statePromise, context->deferred());
#endif
loadPromise = globalObject->moduleLoader()->loadModule(globalObject, globalObject, request, combinedCell, scriptFetcher, innerLoadFlags);
} else {
combinedCell = ModuleGraphLoadingState::create(vm, statePromise, scriptFetcher);
Expand Down Expand Up @@ -1346,11 +1350,12 @@ static void dynamicImportLoadSettled(JSGlobalObject* globalObject, VM& vm, Throw
// Step-4 rejectedClosure or Step-6 linkAndEvaluateClosure
//
// continueDynamicImport: loadPromise settled
// arguments[0] = capabilityPromise
// arguments[0] = AbstractModuleRecord*
// arguments[1] = resolution or error
// arguments[2] = AbstractModuleRecord*
auto* capabilityPromise = uncheckedDowncast<JSPromise>(arguments[0]);
auto* module = uncheckedDowncast<AbstractModuleRecord>(arguments[2]);
// arguments[2] = ModuleLoaderPayload*
auto* module = uncheckedDowncast<AbstractModuleRecord>(arguments[0]);
auto* dynamicPayload = uncheckedDowncast<ModuleLoaderPayload>(arguments[2]);
auto* capabilityPromise = dynamicPayload->promise();
auto status = static_cast<JSPromise::Status>(payload);
if (status != JSPromise::Status::Fulfilled) {
// Step-4 rejectedClosure
Expand All @@ -1373,7 +1378,11 @@ static void dynamicImportLoadSettled(JSGlobalObject* globalObject, VM& vm, Throw

if (!deferred) {
// 6.c. Let evaluatePromise be module.Evaluate().
#if USE(BUN_JSC_ADDITIONS)
JSPromise* evaluatePromise = module->evaluate(globalObject, dynamicPayload->referrerAsyncOrder());
#else
JSPromise* evaluatePromise = module->evaluate(globalObject);
#endif
if (scope.exception()) [[unlikely]] {
capabilityPromise->rejectWithCaughtException(vm, scope);
return;
Expand Down Expand Up @@ -1402,7 +1411,11 @@ static void dynamicImportLoadSettled(JSGlobalObject* globalObject, VM& vm, Throw
// For each Module Record dep of evaluationList, append dep.Evaluate() to asyncDepsEvaluationPromises.
MarkedArgumentBuffer asyncDepsEvaluationPromises;
for (AbstractModuleRecord* dep : evaluationList) {
#if USE(BUN_JSC_ADDITIONS)
JSPromise* depPromise = dep->evaluate(globalObject, dynamicPayload->referrerAsyncOrder());
#else
JSPromise* depPromise = dep->evaluate(globalObject);
#endif
if (scope.exception()) [[unlikely]] {
capabilityPromise->rejectWithCaughtException(vm, scope);
return;
Expand Down
Loading
Loading