From 5905eab994aa328c3069c8861d263afbecb7b271 Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Wed, 2 Sep 2026 13:26:04 +0000 Subject: [PATCH 1/3] Annotate an impossible 'X is not defined' with why module resolution missed When get_from_scope is about to throw ReferenceError for a name and a JSModuleEnvironment on the function's scope chain imports or declares a binding with the same text, the error should not have been possible. In that case append a short, fixed-vocabulary suffix to the message that says which invariant is broken: whether the record resolves the name now, whether the import entry is present by pointer but missed by the hash lookup (damaged table or hash word), whether an entry with equal text but a different StringImpl exists (two atoms), whether the identifier is the atom the table holds for its text, and the same for the exporter's export entries and the environment's symbol table. Only the throw path is touched and only when a module environment is on the chain and one of those checks fires, so ordinary undefined-global errors are unchanged. Every field is a small enum so telemetry that only keeps a hash of the message can still recover it. --- Source/JavaScriptCore/dfg/DFGOperations.cpp | 7 +- Source/JavaScriptCore/jit/JITOperations.cpp | 7 +- .../JavaScriptCore/llint/LLIntSlowPaths.cpp | 7 +- .../runtime/ExceptionHelpers.cpp | 14 ++ .../JavaScriptCore/runtime/ExceptionHelpers.h | 7 + Source/JavaScriptCore/runtime/JSScope.cpp | 123 ++++++++++++++++++ Source/JavaScriptCore/runtime/JSScope.h | 5 + 7 files changed, 167 insertions(+), 3 deletions(-) diff --git a/Source/JavaScriptCore/dfg/DFGOperations.cpp b/Source/JavaScriptCore/dfg/DFGOperations.cpp index 592e999cff13e..79ff2ade1f677 100644 --- a/Source/JavaScriptCore/dfg/DFGOperations.cpp +++ b/Source/JavaScriptCore/dfg/DFGOperations.cpp @@ -5972,8 +5972,13 @@ JSC_DEFINE_JIT_OPERATION(operationGetDynamicVar, EncodedJSValue, (JSGlobalObject OPERATION_RETURN(scope, JSValue::encode(jsScope->getPropertySlot(globalObject, ident, [&] (bool found, PropertySlot& slot) -> JSValue { if (!found) { GetPutInfo getPutInfo(getPutInfoBits); - if (getPutInfo.resolveMode() == ThrowIfNotFound) + if (getPutInfo.resolveMode() == ThrowIfNotFound) { +#if USE(BUN_JSC_ADDITIONS) + throwException(globalObject, scope, createUndefinedVariableError(globalObject, ident, callFrame->jsCallee() && callFrame->jsCallee()->inherits() ? uncheckedDowncast(callFrame->jsCallee())->scope() : dynamicDowncast(jsScope), static_cast(getPutInfo.resolveType()) | 0x100u, callFrame->codeBlock())); +#else throwException(globalObject, scope, createUndefinedVariableError(globalObject, ident)); +#endif + } return jsUndefined(); } diff --git a/Source/JavaScriptCore/jit/JITOperations.cpp b/Source/JavaScriptCore/jit/JITOperations.cpp index 094443ecfe81e..e56ef48c57e63 100644 --- a/Source/JavaScriptCore/jit/JITOperations.cpp +++ b/Source/JavaScriptCore/jit/JITOperations.cpp @@ -4652,8 +4652,13 @@ JSC_DEFINE_JIT_OPERATION(operationGetFromScope, EncodedJSValue, (JSGlobalObject* OPERATION_RETURN(scope, JSValue::encode(environment->getPropertySlot(globalObject, ident, [&] (bool found, PropertySlot& slot) -> JSValue { if (!found) { - if (getPutInfo.resolveMode() == ThrowIfNotFound) + if (getPutInfo.resolveMode() == ThrowIfNotFound) { +#if USE(BUN_JSC_ADDITIONS) + throwException(globalObject, scope, createUndefinedVariableError(globalObject, ident, callFrame->uncheckedR(codeBlock->scopeRegister()).Register::scope(), static_cast(getPutInfo.resolveType()), codeBlock)); +#else throwException(globalObject, scope, createUndefinedVariableError(globalObject, ident)); +#endif + } return jsUndefined(); } diff --git a/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp b/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp index 7b5d9d829b8a2..5c52e6a97b65b 100644 --- a/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp +++ b/Source/JavaScriptCore/llint/LLIntSlowPaths.cpp @@ -2354,8 +2354,13 @@ LLINT_SLOW_PATH_DECL(slow_path_get_from_scope) LLINT_RETURN(scope->getPropertySlot(globalObject, ident, [&] (bool found, PropertySlot& slot) -> JSValue { if (!found) { - if (metadata.m_getPutInfo.resolveMode() == ThrowIfNotFound) + if (metadata.m_getPutInfo.resolveMode() == ThrowIfNotFound) { +#if USE(BUN_JSC_ADDITIONS) + return throwException(globalObject, throwScope, createUndefinedVariableError(globalObject, ident, callFrame->uncheckedR(codeBlock->scopeRegister()).Register::scope(), static_cast(metadata.m_getPutInfo.resolveType()), codeBlock)); +#else return throwException(globalObject, throwScope, createUndefinedVariableError(globalObject, ident)); +#endif + } return jsUndefined(); } diff --git a/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp b/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp index 766b17bac36c2..c9e0b62b7a3bd 100644 --- a/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp +++ b/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp @@ -28,6 +28,7 @@ #include "config.h" #include "ExceptionHelpers.h" +#include "JSScope.h" #include "ErrorHandlingScope.h" #include "Exception.h" @@ -68,6 +69,19 @@ JSObject* createUndefinedVariableError(JSGlobalObject* globalObject, const Ident return createReferenceError(globalObject, message); } +#if USE(BUN_JSC_ADDITIONS) +JSObject* createUndefinedVariableError(JSGlobalObject* globalObject, const Identifier& ident, JSScope* start, unsigned resolveType, CodeBlock* codeBlock) +{ + String diagnosis = JSScope::diagnoseImpossibleUndefinedVariable(globalObject, start, ident, resolveType, codeBlock); + if (diagnosis.isNull()) + return createUndefinedVariableError(globalObject, ident); + String message = tryMakeString(ident.string(), " is not defined"_s, diagnosis); + if (!message) [[unlikely]] + return createUndefinedVariableError(globalObject, ident); + return createReferenceError(globalObject, message); +} +#endif + String errorDescriptionForValue(JSGlobalObject* globalObject, JSValue v) { if (v.isString()) { diff --git a/Source/JavaScriptCore/runtime/ExceptionHelpers.h b/Source/JavaScriptCore/runtime/ExceptionHelpers.h index f2f8ff2ac9ad5..bce25e3c4cd33 100644 --- a/Source/JavaScriptCore/runtime/ExceptionHelpers.h +++ b/Source/JavaScriptCore/runtime/ExceptionHelpers.h @@ -47,6 +47,13 @@ String constructErrorMessage(JSGlobalObject*, JSValue, const String&); JS_EXPORT_PRIVATE JSObject* createError(JSGlobalObject*, JSValue, const String&, ErrorInstance::SourceAppender); JS_EXPORT_PRIVATE JSObject* createStackOverflowError(JSGlobalObject*); JSObject* createUndefinedVariableError(JSGlobalObject*, const Identifier&); +#if USE(BUN_JSC_ADDITIONS) +class JSScope; +class CodeBlock; +// As above, but if a module environment reachable from `start` declares or imports `ident` (so the error should have been +// impossible) the message says which resolution invariant is broken. `resolveType` is the op's linked ResolveType. +JSObject* createUndefinedVariableError(JSGlobalObject*, const Identifier&, JSScope* start, unsigned resolveType, CodeBlock*); +#endif JSObject* createTDZError(JSGlobalObject*, StringView); JSObject* createTDZError(JSGlobalObject*); JSObject* createTDZError(JSGlobalObject*, const Identifier&); diff --git a/Source/JavaScriptCore/runtime/JSScope.cpp b/Source/JavaScriptCore/runtime/JSScope.cpp index 2963f80fa70ea..04afc97bad118 100644 --- a/Source/JavaScriptCore/runtime/JSScope.cpp +++ b/Source/JavaScriptCore/runtime/JSScope.cpp @@ -29,6 +29,9 @@ #include "AbstractModuleRecord.h" #include "DeferTermination.h" #include "JSCInlines.h" +#include "CodeBlock.h" +#include +#include #include "JSLexicalEnvironment.h" #include "JSModuleEnvironment.h" #include "JSScopeInlines.h" @@ -305,6 +308,126 @@ JSObject* JSScope::resolve(JSGlobalObject* globalObject, JSScope* scope, const I return resolve(globalObject, scope, ident, predicate1, predicate2); } +#if USE(BUN_JSC_ADDITIONS) +static unsigned computedHashOf(const StringImpl* impl) +{ + return impl->is8Bit() ? StringHasher::computeHashAndMaskTop8Bits(impl->span8()) : StringHasher::computeHashAndMaskTop8Bits(impl->span16()); +} + +String JSScope::diagnoseImpossibleUndefinedVariable(JSGlobalObject* globalObject, JSScope* start, const Identifier& ident, unsigned resolveType, CodeBlock* codeBlock) +{ + if (!start || ident.isNull() || ident.isSymbol()) + return { }; + VM& vm = globalObject->vm(); + DeferTerminationForAWhile deferScope(vm); + auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm); + if (catchScope.exception()) + return { }; + + StringBuilder out; + unsigned depth = 0; + for (JSScope* scope = start; scope; scope = scope->next(), ++depth) { + if (scope->type() != ModuleEnvironmentType) + continue; + auto* environment = uncheckedDowncast(scope); + AbstractModuleRecord* record = environment->moduleRecord(); + if (!record) + continue; + + // Does the record resolve the name right now (by pointer, as the engine does)? + AbstractModuleRecord::Resolution resolution = record->resolveImport(globalObject, ident); + if (catchScope.exception()) { + catchScope.clearException(); + resolution = AbstractModuleRecord::Resolution::error(); + } + // Is there an import entry / symbol table entry whose key has the same text but is a different StringImpl? + const UniquedStringImpl* textEqualImportKey = nullptr; + bool pointerEqualImportKey = false; // found by linear scan: if the hash lookup then misses, the table or the key's hash word is damaged + unsigned iteratedImportEntries = 0; // != importEntries().size() means the map's inline header (in the record cell) is damaged + for (auto& pair : record->importEntries()) { + ++iteratedImportEntries; + if (pair.key.get() == ident.impl()) + pointerEqualImportKey = true; + else if (pair.key && WTF::equal(pair.key.get(), ident.impl())) + textEqualImportKey = pair.key.get(); + } + bool hashLookupFindsImportKey = !!record->tryGetImportEntry(ident.impl()); + bool symbolTableHasPointer = false; + const UniquedStringImpl* textEqualSymbolKey = nullptr; + { + SymbolTable* symbolTable = environment->symbolTable(); + ConcurrentJSLocker locker(symbolTable->m_lock); + symbolTableHasPointer = symbolTable->contains(locker, ident.impl()); + if (!symbolTableHasPointer) { + for (auto iter = symbolTable->begin(locker), end = symbolTable->end(locker); iter != end; ++iter) { + if (iter->key && WTF::equal(iter->key.get(), ident.impl())) { + textEqualSymbolKey = iter->key.get(); + break; + } + } + } + } + + bool impossible = resolution.type == AbstractModuleRecord::Resolution::Type::Resolved || textEqualImportKey || pointerEqualImportKey || hashLookupFindsImportKey || symbolTableHasPointer || textEqualSymbolKey; + if (!impossible) + continue; + + if (out.isEmpty()) { + SUPPRESS_UNCOUNTED_LOCAL auto* impl = ident.impl(); + RefPtr tableAtom = impl->is8Bit() ? AtomStringImpl::lookUp(impl->span8()) : AtomStringImpl::lookUp(impl->span16()); + unsigned computedHash = computedHashOf(impl); + // Telemetry that only carries a hash of the message has to brute-force it back, so every field is a small + // enum: no counts, pointers or hashes. + out.append(" [bun-diag rt="_s, resolveType, + " jt="_s, codeBlock ? static_cast(codeBlock->jitType()) : 9u, + " atom="_s, impl->isAtom() ? 1 : 0, + " intable="_s, !tableAtom ? 0 : (tableAtom.get() == impl ? 1 : 2), + " rc="_s, impl->refCount() < 3 ? 0 : impl->refCount() < 20 ? 1 : 2, + " heq="_s, impl->isSymbol() || !impl->hasHash() ? 9 : (impl->existingHash() == computedHash ? 1 : 0), + " len="_s, std::min(impl->length(), 9u)); + } + out.append(" env"_s, std::min(depth, 9u), ":imp="_s, static_cast(resolution.type), + ",hdr="_s, iteratedImportEntries == record->importEntries().size() ? 1 : 0, + ",ptrimp="_s, pointerEqualImportKey ? 1 : 0, + ",hashimp="_s, hashLookupFindsImportKey ? 1 : 0, + ",txtimp="_s, textEqualImportKey ? 1 : 0, + ",sym="_s, symbolTableHasPointer ? 1 : 0, + ",txtsym="_s, textEqualSymbolKey ? 1 : 0); + if (textEqualImportKey) + out.append(",ik_atom="_s, textEqualImportKey->isAtom() ? 1 : 0, ",ik_rc="_s, textEqualImportKey->refCount() < 3 ? 0 : textEqualImportKey->refCount() < 20 ? 1 : 2, ",ik_heq="_s, textEqualImportKey->isSymbol() || !textEqualImportKey->hasHash() ? 9 : (textEqualImportKey->existingHash() == computedHashOf(textEqualImportKey) ? 1 : 0)); + if (auto entry = record->tryGetImportEntry(ident.impl()); entry && resolution.type != AbstractModuleRecord::Resolution::Type::Resolved) { + AbstractModuleRecord* exporter = record->hostResolveImportedModule(globalObject, entry->moduleRequest, entry->moduleRequestType); + out.append(",exp="_s, exporter ? 1 : 0); + if (exporter) { + SUPPRESS_UNCOUNTED_LOCAL auto* importName = entry->importName.impl(); + bool exportPtr = false; + bool exportTxt = false; + for (auto& pair : exporter->exportEntries()) { + if (pair.key.get() == importName) + exportPtr = true; + else if (pair.key && importName && WTF::equal(pair.key.get(), importName)) + exportTxt = true; + } + out.append(",xptr="_s, exportPtr ? 1 : 0, ",xhash="_s, exporter->tryGetExportEntry(importName) ? 1 : 0, ",xtxt="_s, exportTxt ? 1 : 0, ",xenv="_s, exporter->moduleEnvironmentMayBeNull() ? 1 : 0); + } + } + if (resolution.type == AbstractModuleRecord::Resolution::Type::Resolved && resolution.moduleRecord) { + JSModuleEnvironment* importedEnvironment = resolution.moduleRecord->moduleEnvironmentMayBeNull(); + out.append(",xenv="_s, importedEnvironment ? 1 : 0); + if (importedEnvironment) { + SymbolTable* symbolTable = importedEnvironment->symbolTable(); + ConcurrentJSLocker locker(symbolTable->m_lock); + out.append(",xsym="_s, symbolTable->contains(locker, resolution.localName.impl()) ? 1 : 0); + } + } + } + if (out.isEmpty()) + return { }; + out.append(']'); + return out.toString(); +} +#endif + ResolveOp JSScope::abstractResolve(JSGlobalObject* globalObject, size_t depthOffset, JSScope* scope, const Identifier& ident, GetOrPut getOrPut, ResolveType unlinkedType, InitializationMode initializationMode) { ResolveOp op(Dynamic, 0, nullptr, nullptr, nullptr, 0); diff --git a/Source/JavaScriptCore/runtime/JSScope.h b/Source/JavaScriptCore/runtime/JSScope.h index be8fd8d57b6da..c30d9766dbeb6 100644 --- a/Source/JavaScriptCore/runtime/JSScope.h +++ b/Source/JavaScriptCore/runtime/JSScope.h @@ -56,6 +56,11 @@ class JSScope : public JSNonFinalObject { static JSObject* NODELETE objectAtScope(JSScope*); static JSObject* resolve(JSGlobalObject*, JSScope*, const Identifier&); +#if USE(BUN_JSC_ADDITIONS) + // Empty unless `ident` is unresolvable from `start` while a module environment on the chain declares or imports a + // binding with the same text: then a short description of which invariant is broken, for the ReferenceError's message. + static String diagnoseImpossibleUndefinedVariable(JSGlobalObject*, JSScope* start, const Identifier&, unsigned resolveType, CodeBlock*); +#endif static JSValue resolveScopeForHoistingFuncDeclInEval(JSGlobalObject*, JSScope*, const Identifier&); static ResolveOp abstractResolve(JSGlobalObject*, size_t depthOffset, JSScope*, const Identifier&, GetOrPut, ResolveType, InitializationMode); From ad86a94b7531dd2adf1b0cea92ab74fe3f3cbedf Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Wed, 2 Sep 2026 13:45:41 +0000 Subject: [PATCH 2/3] Don't let a damaged [[LoadedModules]] turn the diagnostic into a null dereference --- Source/JavaScriptCore/runtime/JSScope.cpp | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/Source/JavaScriptCore/runtime/JSScope.cpp b/Source/JavaScriptCore/runtime/JSScope.cpp index 04afc97bad118..50c9072b744ca 100644 --- a/Source/JavaScriptCore/runtime/JSScope.cpp +++ b/Source/JavaScriptCore/runtime/JSScope.cpp @@ -334,11 +334,17 @@ String JSScope::diagnoseImpossibleUndefinedVariable(JSGlobalObject* globalObject if (!record) continue; - // Does the record resolve the name right now (by pointer, as the engine does)? - AbstractModuleRecord::Resolution resolution = record->resolveImport(globalObject, ident); - if (catchScope.exception()) { - catchScope.clearException(); - resolution = AbstractModuleRecord::Resolution::error(); + // Does the record resolve the name right now (by pointer, as the engine does)? resolveImport() assumes the + // exporter is in [[LoadedModules]]; don't let a damaged record turn the diagnostic into a null dereference. + AbstractModuleRecord::Resolution resolution = AbstractModuleRecord::Resolution::notFound(); + std::optional importEntry = record->tryGetImportEntry(ident.impl()); + AbstractModuleRecord* exporter = importEntry ? record->hostResolveImportedModule(globalObject, importEntry->moduleRequest, importEntry->moduleRequestType) : nullptr; + if (!importEntry || exporter) { + resolution = record->resolveImport(globalObject, ident); + if (catchScope.exception()) { + catchScope.clearException(); + resolution = AbstractModuleRecord::Resolution::error(); + } } // Is there an import entry / symbol table entry whose key has the same text but is a different StringImpl? const UniquedStringImpl* textEqualImportKey = nullptr; @@ -351,7 +357,7 @@ String JSScope::diagnoseImpossibleUndefinedVariable(JSGlobalObject* globalObject else if (pair.key && WTF::equal(pair.key.get(), ident.impl())) textEqualImportKey = pair.key.get(); } - bool hashLookupFindsImportKey = !!record->tryGetImportEntry(ident.impl()); + bool hashLookupFindsImportKey = !!importEntry; bool symbolTableHasPointer = false; const UniquedStringImpl* textEqualSymbolKey = nullptr; { @@ -395,11 +401,10 @@ String JSScope::diagnoseImpossibleUndefinedVariable(JSGlobalObject* globalObject ",txtsym="_s, textEqualSymbolKey ? 1 : 0); if (textEqualImportKey) out.append(",ik_atom="_s, textEqualImportKey->isAtom() ? 1 : 0, ",ik_rc="_s, textEqualImportKey->refCount() < 3 ? 0 : textEqualImportKey->refCount() < 20 ? 1 : 2, ",ik_heq="_s, textEqualImportKey->isSymbol() || !textEqualImportKey->hasHash() ? 9 : (textEqualImportKey->existingHash() == computedHashOf(textEqualImportKey) ? 1 : 0)); - if (auto entry = record->tryGetImportEntry(ident.impl()); entry && resolution.type != AbstractModuleRecord::Resolution::Type::Resolved) { - AbstractModuleRecord* exporter = record->hostResolveImportedModule(globalObject, entry->moduleRequest, entry->moduleRequestType); + if (importEntry && resolution.type != AbstractModuleRecord::Resolution::Type::Resolved) { out.append(",exp="_s, exporter ? 1 : 0); if (exporter) { - SUPPRESS_UNCOUNTED_LOCAL auto* importName = entry->importName.impl(); + SUPPRESS_UNCOUNTED_LOCAL auto* importName = importEntry->importName.impl(); bool exportPtr = false; bool exportTxt = false; for (auto& pair : exporter->exportEntries()) { From 0fa29e162813348f8718940f99313d583aba82ed Mon Sep 17 00:00:00 2001 From: Jarred Sumner Date: Wed, 2 Sep 2026 15:52:36 +0000 Subject: [PATCH 3/3] Annotate an impossible TDZ error on a module binding the same way op_check_tdz names the binding by its source text. If that text is an import or module-scope binding of a module environment on the function's scope chain, look at the slot it resolves to now: a non-empty slot means the read that fed the check produced a wrong value, and an empty slot in a module that finished evaluating without error means the environment was damaged. Ordinary TDZ (a lexical binding read before its declaration ran, a binding of a module still evaluating in a cycle) is unchanged. --- .../runtime/CommonSlowPaths.cpp | 9 ++ .../runtime/ExceptionHelpers.cpp | 2 +- Source/JavaScriptCore/runtime/JSScope.cpp | 109 ++++++++++++++++++ Source/JavaScriptCore/runtime/JSScope.h | 3 + 4 files changed, 122 insertions(+), 1 deletion(-) diff --git a/Source/JavaScriptCore/runtime/CommonSlowPaths.cpp b/Source/JavaScriptCore/runtime/CommonSlowPaths.cpp index 3557e2387c8f5..1b59238504b80 100644 --- a/Source/JavaScriptCore/runtime/CommonSlowPaths.cpp +++ b/Source/JavaScriptCore/runtime/CommonSlowPaths.cpp @@ -25,6 +25,7 @@ #include "config.h" #include "CommonSlowPaths.h" +#include "JSScope.h" #include "ArithProfile.h" #include "ArrayPrototypeInlines.h" @@ -323,6 +324,14 @@ JSC_DEFINE_COMMON_SLOW_PATH(slow_path_check_tdz) RefPtr provider = codeBlock->source().provider(); auto ident = provider->getRange(expressionStart, expressionStop); +#if USE(BUN_JSC_ADDITIONS) + String diagnosis = JSScope::diagnoseImpossibleTDZ(globalObject, callFrame->uncheckedR(codeBlock->scopeRegister()).Register::scope(), ident, codeBlock); + if (!diagnosis.isNull()) { + String message = tryMakeString("Cannot access '"_s, ident, "' before initialization."_s, diagnosis); + if (!message.isNull()) + THROW(createReferenceError(globalObject, message)); + } +#endif THROW(createTDZError(globalObject, ident)); } } diff --git a/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp b/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp index c9e0b62b7a3bd..bdcffcd1a9fa5 100644 --- a/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp +++ b/Source/JavaScriptCore/runtime/ExceptionHelpers.cpp @@ -76,7 +76,7 @@ JSObject* createUndefinedVariableError(JSGlobalObject* globalObject, const Ident if (diagnosis.isNull()) return createUndefinedVariableError(globalObject, ident); String message = tryMakeString(ident.string(), " is not defined"_s, diagnosis); - if (!message) [[unlikely]] + if (message.isNull()) [[unlikely]] return createUndefinedVariableError(globalObject, ident); return createReferenceError(globalObject, message); } diff --git a/Source/JavaScriptCore/runtime/JSScope.cpp b/Source/JavaScriptCore/runtime/JSScope.cpp index 50c9072b744ca..2fad0329fea6d 100644 --- a/Source/JavaScriptCore/runtime/JSScope.cpp +++ b/Source/JavaScriptCore/runtime/JSScope.cpp @@ -30,6 +30,7 @@ #include "DeferTermination.h" #include "JSCInlines.h" #include "CodeBlock.h" +#include "CyclicModuleRecord.h" #include #include #include "JSLexicalEnvironment.h" @@ -431,6 +432,114 @@ String JSScope::diagnoseImpossibleUndefinedVariable(JSGlobalObject* globalObject out.append(']'); return out.toString(); } + +// The value a TDZ check saw was empty. If the text it read is an import (or a module-scope binding) of a module environment on +// the chain, look at the slot the binding resolves to now: a non-empty slot means the read produced a wrong value; an empty slot in +// a module that finished evaluating without error means the environment was damaged. Ordinary TDZ (a `let` read before its +// declaration ran, a binding of a module still evaluating in a cycle) prints nothing. +String JSScope::diagnoseImpossibleTDZ(JSGlobalObject* globalObject, JSScope* start, StringView name, CodeBlock* codeBlock) +{ + if (!start || name.isEmpty() || name.length() > 64) + return { }; + VM& vm = globalObject->vm(); + DeferTerminationForAWhile deferScope(vm); + auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm); + if (catchScope.exception()) + return { }; + + // What the slot of `key` in `environment` holds now: 0 empty, 1 a value, 8 no such symbol table entry, 9 no environment. + auto slotState = [&](JSModuleEnvironment* environment, UniquedStringImpl* key) -> unsigned { + if (!environment) + return 9; + SymbolTable* symbolTable = environment->symbolTable(); + ScopeOffset offset; + { + ConcurrentJSLocker locker(symbolTable->m_lock); + auto iter = symbolTable->find(locker, key); + if (iter == symbolTable->end(locker)) + return 8; + offset = iter->value.scopeOffset(); + } + if (!environment->isValidScopeOffset(offset)) + return 8; + return environment->variableAt(offset).get() ? 1 : 0; + }; + auto recordState = [&](AbstractModuleRecord* record) -> unsigned { + auto* cyclic = dynamicDowncast(record); + if (!cyclic) + return 9; + unsigned status = static_cast(cyclic->status()); + return cyclic->evaluationError() ? 10 + status : status; + }; + constexpr unsigned evaluated = static_cast(CyclicModuleRecord::Status::Evaluated); + + StringBuilder out; + unsigned depth = 0; + for (JSScope* scope = start; scope; scope = scope->next(), ++depth) { + if (scope->type() != ModuleEnvironmentType) + continue; + auto* environment = uncheckedDowncast(scope); + AbstractModuleRecord* record = environment->moduleRecord(); + if (!record) + continue; + + // An import whose local name has this text. + for (auto& pair : record->importEntries()) { + if (!pair.key || StringView(pair.key.get()) != name) + continue; + const auto& entry = pair.value; + AbstractModuleRecord* exporter = record->hostResolveImportedModule(globalObject, entry.moduleRequest, entry.moduleRequestType); + unsigned exporterState = exporter ? recordState(exporter) : 99; + AbstractModuleRecord::Resolution resolution = AbstractModuleRecord::Resolution::notFound(); + if (exporter) { + resolution = record->resolveImport(globalObject, Identifier::fromUid(vm, pair.key.get())); + if (catchScope.exception()) { + catchScope.clearException(); + resolution = AbstractModuleRecord::Resolution::error(); + } + } + unsigned slot = 9; + unsigned targetState = 99; + if (resolution.type == AbstractModuleRecord::Resolution::Type::Resolved && resolution.moduleRecord) { + slot = slotState(resolution.moduleRecord->moduleEnvironmentMayBeNull(), resolution.localName.impl()); + targetState = recordState(resolution.moduleRecord); + } + bool impossible = slot == 1 || (slot == 0 && targetState == evaluated); + if (!impossible) + continue; + if (out.isEmpty()) + out.append(" [bun-diag tdz jt="_s, codeBlock ? static_cast(codeBlock->jitType()) : 9u); + out.append(" env"_s, std::min(depth, 9u), ":imp res="_s, static_cast(resolution.type), " slot="_s, slot, " xst="_s, std::min(exporterState, 99u), " tst="_s, std::min(targetState, 99u), " self="_s, resolution.moduleRecord == record ? 1 : 0); + } + // A module-scope binding of this module with this text. + { + RefPtr key; + { + SymbolTable* symbolTable = environment->symbolTable(); + ConcurrentJSLocker locker(symbolTable->m_lock); + for (auto iter = symbolTable->begin(locker), end = symbolTable->end(locker); iter != end; ++iter) { + if (iter->key && StringView(iter->key.get()) == name) { + key = iter->key; + break; + } + } + } + if (key) { + unsigned slot = slotState(environment, key.get()); + unsigned state = recordState(record); + if (slot == 1 || (slot == 0 && state == evaluated)) { + if (out.isEmpty()) + out.append(" [bun-diag tdz jt="_s, codeBlock ? static_cast(codeBlock->jitType()) : 9u); + out.append(" env"_s, std::min(depth, 9u), ":own slot="_s, slot, " st="_s, std::min(state, 99u), " atom="_s, key->isAtom() ? 1 : 0); + } + } + } + } + if (out.isEmpty()) + return { }; + out.append(']'); + return out.toString(); +} #endif ResolveOp JSScope::abstractResolve(JSGlobalObject* globalObject, size_t depthOffset, JSScope* scope, const Identifier& ident, GetOrPut getOrPut, ResolveType unlinkedType, InitializationMode initializationMode) diff --git a/Source/JavaScriptCore/runtime/JSScope.h b/Source/JavaScriptCore/runtime/JSScope.h index c30d9766dbeb6..4a4457b6bfaa3 100644 --- a/Source/JavaScriptCore/runtime/JSScope.h +++ b/Source/JavaScriptCore/runtime/JSScope.h @@ -60,6 +60,9 @@ class JSScope : public JSNonFinalObject { // Empty unless `ident` is unresolvable from `start` while a module environment on the chain declares or imports a // binding with the same text: then a short description of which invariant is broken, for the ReferenceError's message. static String diagnoseImpossibleUndefinedVariable(JSGlobalObject*, JSScope* start, const Identifier&, unsigned resolveType, CodeBlock*); + // Empty unless `name` (the source text of a TDZ-checked read) is an import or module-scope binding of a module environment on the + // chain whose slot is not empty now, or is empty although its module finished evaluating without error. + static String diagnoseImpossibleTDZ(JSGlobalObject*, JSScope* start, StringView name, CodeBlock*); #endif static JSValue resolveScopeForHoistingFuncDeclInEval(JSGlobalObject*, JSScope*, const Identifier&); static ResolveOp abstractResolve(JSGlobalObject*, size_t depthOffset, JSScope*, const Identifier&, GetOrPut, ResolveType, InitializationMode);