#include "root.h" #include "JavaScriptCore/PropertySlot.h" #include "JavaScriptCore/ExecutableInfo.h" #include "JavaScriptCore/WriteBarrierInlines.h" #include "ErrorCode.h" #include #include #include "BunClientData.h" #include "NodeVM.h" #include "CodeGenerationFromStrings.h" #include "NodeVMScript.h" #include "NodeVMModule.h" #include "NodeVMSourceTextModule.h" #include "NodeVMSyntheticModule.h" #include "JavaScriptCore/JSObjectInlines.h" #include "JavaScriptCore/JSWebAssemblyCompileError.h" #include "JavaScriptCore/JSWebAssemblyModule.h" #include "wtf/text/ExternalStringImpl.h" #include "JavaScriptCore/FunctionPrototype.h" #include "JavaScriptCore/FunctionConstructor.h" #include "JavaScriptCore/HeapAnalyzer.h" #include "JavaScriptCore/JSDestructibleObjectHeapCellType.h" #include "JavaScriptCore/SlotVisitorMacros.h" #include "JavaScriptCore/ObjectConstructor.h" #include "JavaScriptCore/SubspaceInlines.h" #include "wtf/GetPtr.h" #include "wtf/NoTailCalls.h" #include "wtf/PointerPreparations.h" #include "wtf/URL.h" #include "JavaScriptCore/TypedArrayInlines.h" #include "JavaScriptCore/PropertyNameArray.h" #include "JavaScriptCore/JSWeakMap.h" #include "JavaScriptCore/JSWeakMapInlines.h" #include "JavaScriptCore/JSWithScope.h" #include "JavaScriptCore/JSGlobalProxyInlines.h" #include "GCDefferalContext.h" #include "JSBuffer.h" #include "xxhash3.h" #include #include #include #include "JavaScriptCore/LazyClassStructureInlines.h" #include "JavaScriptCore/Parser.h" #include "JavaScriptCore/SourceCodeKey.h" #include "JavaScriptCore/UnlinkedFunctionExecutable.h" #include "NodeValidator.h" #include "AsyncContextFrame.h" #include "JavaScriptCore/JSCInlines.h" #include "JavaScriptCore/JSPromise.h" #include "JavaScriptCore/JSNativeStdFunction.h" #include "JavaScriptCore/BytecodeCacheError.h" #include "JavaScriptCore/CodeCache.h" #include "JavaScriptCore/FunctionCodeBlock.h" #include "JavaScriptCore/JIT.h" #include "JavaScriptCore/ProgramCodeBlock.h" #include "JavaScriptCore/GlobalObjectMethodTable.h" #include "NodeVMScriptFetcher.h" #include "ZigSourceProvider.h" #include "wtf/FileHandle.h" #include "JavaScriptCore/GetterSetter.h" #include "JavaScriptCore/MicrotaskQueue.h" #include "JavaScriptCore/MicrotaskQueueInlines.h" #include "JavaScriptCore/AOTModuleHost.h" #include "JavaScriptCore/AOTPropertyWalk.h" #include "BunCompiledModules.h" namespace Bun { using namespace WebCore; static JSPromise* moduleLoaderImportModuleInner(NodeVMGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSString* moduleName, RefPtr parameters, const JSC::SourceOrigin& sourceOrigin); namespace NodeVM { static JSPromise* importModuleInner(JSGlobalObject* globalObject, JSString* moduleName, RefPtr parameters, const SourceOrigin& sourceOrigin, JSValue dynamicImportCallback, JSValue owner); static JSValue scriptFetchParametersToImportAttributes(JSGlobalObject* globalObject, JSC::ScriptFetchParameters* params) { auto& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); auto* obj = constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure()); if (!params) return obj; if (!params->attributes().isEmpty()) { // An attribute key can be an array index, e.g. `import(x, { with: { "0": "a" } })`. for (auto& [key, value] : params->attributes()) { obj->putDirectMayBeIndex(globalObject, JSC::Identifier::fromUid(vm, key.get()), jsString(vm, value)); RETURN_IF_EXCEPTION(scope, {}); } return obj; } switch (params->type()) { case JSC::ScriptFetchParameters::Type::JSON: obj->putDirect(vm, vm.propertyNames->type, jsNontrivialString(vm, "json"_s)); break; case JSC::ScriptFetchParameters::Type::WebAssembly: obj->putDirect(vm, vm.propertyNames->type, jsNontrivialString(vm, "webassembly"_s)); break; case JSC::ScriptFetchParameters::Type::JavaScript: obj->putDirect(vm, vm.propertyNames->type, jsNontrivialString(vm, "javascript"_s)); break; case JSC::ScriptFetchParameters::Type::Text: // Unreachable with BUN_JSC_ADDITIONS (`type: "text"` parses as HostDefined); kept so the switch stays exhaustive. obj->putDirect(vm, vm.propertyNames->type, jsNontrivialString(vm, "text"_s)); break; case JSC::ScriptFetchParameters::Type::CSS: // Unreachable for the same reason. obj->putDirect(vm, vm.propertyNames->type, jsNontrivialString(vm, "css"_s)); break; case JSC::ScriptFetchParameters::Type::HostDefined: obj->putDirect(vm, vm.propertyNames->type, jsString(vm, params->hostDefinedImportType())); break; case JSC::ScriptFetchParameters::Type::None: break; } return obj; } bool extractCachedData(JSValue cachedDataValue, WTF::Vector& outCachedData) { if (!cachedDataValue.isCell()) { return false; } std::span bytes; if (auto* arrayBufferView = dynamicDowncast(cachedDataValue)) { if (arrayBufferView->isDetached()) { return false; } bytes = arrayBufferView->span(); } else if (auto* arrayBuffer = dynamicDowncast(cachedDataValue); arrayBuffer && arrayBuffer->impl()) { bytes = arrayBuffer->impl()->span(); } else { return false; } // Don't copy a buffer that's too big for a Vector. The caller rejects empty cachedData. if (WTF::isValidCapacityForVector(bytes.size())) { outCachedData = bytes; } return true; } static Ref createOwnedCachedBytecode(std::span bytes) { // UnlinkedFunctionExecutable's Decoder constructor (CachedTypes.cpp) keeps the Decoder and a // payload offset, and decodes the body on the function's first call, borrowed payload or not. auto payload = WTF::MallocSpan::malloc(bytes.size()); WTF::memcpySpan(payload.mutableSpan(), bytes); return JSC::CachedBytecode::create(WTF::move(payload), {}); } // cachedData is the bytecode prefixed with its XXH3-64 hash. JSC's decoder trusts its input, so corrupt bytes must never reach it. JSC::JSUint8Array* createCachedDataBuffer(JSGlobalObject* globalObject, std::span bytecode) { JSC::JSUint8Array* buffer = WebCore::createUninitializedBuffer(globalObject, sizeof(uint64_t) + bytecode.size()); if (!buffer) [[unlikely]] { return nullptr; } const uint64_t hash = highway_xxhash3_64(bytecode.data(), bytecode.size(), 0); auto bytes = buffer->typedSpan(); WTF::memcpySpan(bytes, WTF::asByteSpan(hash)); WTF::memcpySpan(bytes.subspan(sizeof(hash)), bytecode); return buffer; } RefPtr unwrapCachedData(std::span cachedData) { uint64_t hash; if (cachedData.size() <= sizeof(hash)) { return nullptr; } memcpy(&hash, cachedData.data(), sizeof(hash)); auto bytecode = cachedData.subspan(sizeof(hash)); if (hash != highway_xxhash3_64(bytecode.data(), bytecode.size(), 0)) { return nullptr; } return createOwnedCachedBytecode(bytecode); } JSC::JSFunction* constructAnonymousFunction(JSC::JSGlobalObject* globalObject, const ArgList& args, const SourceOrigin& sourceOrigin, CompileFunctionOptions&& options, JSC::SourceTaintedOrigin sourceTaintOrigin, JSC::JSScope* scope) { ASSERT(scope); VM& vm = globalObject->vm(); auto throwScope = DECLARE_THROW_SCOPE(vm); // wrap the arguments in an anonymous function expression int startOffset = 0; String program = stringifyAnonymousFunction(globalObject, args, throwScope, &startOffset); EXCEPTION_ASSERT(!!throwScope.exception() == program.isNull()); RETURN_IF_EXCEPTION(throwScope, nullptr); // The wrapper is the longest text parsed below (the body alone is parsed first). options.lineOffset = clampOffsetForSource(options.lineOffset, program.length()); options.columnOffset = clampOffsetForSource(options.columnOffset, program.length()); TextPosition position = providerStartPosition(options.lineOffset, options.columnOffset); LexicallyScopedFeatures lexicallyScopedFeatures = globalObject->globalScopeExtension() ? TaintedByWithScopeLexicallyScopedFeature : NoLexicallyScopedFeatures; // First try parsing the code as is without wrapping it in an anonymous function expression. // This is to reject cases where the user passes in a string like "});(function() {". if (!args.isEmpty() && args.at(0).isString()) { ParserError error; String code = args.at(0).toWTFString(globalObject); RETURN_IF_EXCEPTION(throwScope, nullptr); SourceCode sourceCode(JSC::StringSourceProvider::create(code, sourceOrigin, options.filename, sourceTaintOrigin, position, SourceProviderSourceType::Program)); if (!checkSyntax(vm, sourceCode, error)) { ASSERT(error.isValid()); bool actuallyValid = true; if (error.type() == ParserError::ErrorType::SyntaxError && error.syntaxErrorType() == ParserError::SyntaxErrorIrrecoverable) { String message = error.message(); if (message == "Return statements are only valid inside functions.") { actuallyValid = false; } else { const JSToken& token = error.token(); int start = token.m_startPosition.offset; int end = token.m_endPosition.offset; if (start >= 0 && start < end) { StringView tokenView = sourceCode.view().substring(start, end - start); error = ParserError(ParserError::SyntaxError, ParserError::SyntaxErrorIrrecoverable, token, makeString("Unexpected token '"_s, tokenView, '\''), error.line()); } } } if (actuallyValid) { auto exception = error.toErrorObject(globalObject, sourceCode, -1); // Building the error materializes its stack, running a user // Error.prepareStackTrace that may throw; Node throws the // SyntaxError anyway. Terminations survive tryClearException. if (exception) (void)throwScope.tryClearException(); RETURN_IF_EXCEPTION(throwScope, nullptr); // Node always attaches the arrow header to compile-time SyntaxErrors // (node_contextify.cc DecorateErrorStack), independent of displayErrors. decorateParseErrorStack(globalObject, vm, exception, code, options.filename, error, options.lineOffset); RETURN_IF_EXCEPTION(throwScope, nullptr); throwException(globalObject, throwScope, exception); return nullptr; } } } // The body starts on line 2 of the wrapped program. V8's CompileFunction reports body line 1 as lineOffset + 1. TextPosition wrappedPosition(OrdinalNumber::fromZeroBasedInt(std::max(position.m_line.zeroBasedInt() - 1, 0)), position.m_column); SourceCode sourceCode(JSC::StringSourceProvider::create(program, sourceOrigin, WTF::move(options.filename), sourceTaintOrigin, wrappedPosition, SourceProviderSourceType::Program)); CodeCache* cache = vm.codeCache(); ProgramExecutable* programExecutable = ProgramExecutable::create(globalObject, sourceCode); UnlinkedProgramCodeBlock* unlinkedProgramCodeBlock = nullptr; RefPtr cachedBytecode; TriState bytecodeAccepted = TriState::Indeterminate; // Like Node, reject an empty cachedData. if (options.cachedDataProvided) { cachedBytecode = unwrapCachedData(options.cachedData.span()); if (cachedBytecode) { SourceCodeKey key(sourceCode, {}, JSC::SourceCodeType::ProgramType, lexicallyScopedFeatures, JSC::JSParserScriptMode::Classic, JSC::DerivedContextType::None, JSC::EvalContextType::None, false, {}, std::nullopt); unlinkedProgramCodeBlock = JSC::decodeCodeBlock(vm, key, *cachedBytecode); } if (unlinkedProgramCodeBlock == nullptr) { bytecodeAccepted = TriState::False; } else { bytecodeAccepted = TriState::True; } } ParserError error; if (unlinkedProgramCodeBlock == nullptr) { unlinkedProgramCodeBlock = cache->getUnlinkedProgramCodeBlock(vm, programExecutable, sourceCode, {}, error); } if (!unlinkedProgramCodeBlock || error.isValid()) { return nullptr; } ProgramCodeBlock* programCodeBlock = nullptr; { DeferGC deferGC(vm); programCodeBlock = ProgramCodeBlock::create(vm, programExecutable, unlinkedProgramCodeBlock, scope); RETURN_IF_EXCEPTION(throwScope, nullptr); } if (!programCodeBlock || programCodeBlock->numberOfFunctionExprs() == 0) { return nullptr; } FunctionExecutable* functionExecutable = programCodeBlock->functionExpr(0); if (!functionExecutable) { return nullptr; } Structure* structure = JSFunction::selectStructureForNewFuncExp(globalObject, functionExecutable); JSFunction* function = JSFunction::create(vm, globalObject, functionExecutable, scope, structure); if (bytecodeAccepted == TriState::Indeterminate) { if (options.produceCachedData) { RefPtr producedBytecode = getBytecode(globalObject, JSC::SourceCodeType::ProgramType, sourceCode); if (producedBytecode) { JSC::JSUint8Array* buffer = createCachedDataBuffer(globalObject, producedBytecode->span()); RETURN_IF_EXCEPTION(throwScope, nullptr); Bun::putDirectNamed(vm, function, "cachedData"_s, buffer); Bun::putDirectNamed(vm, function, "cachedDataProduced"_s, jsBoolean(true)); } else { Bun::putDirectNamed(vm, function, "cachedDataProduced"_s, jsBoolean(false)); } } } else { Bun::putDirectNamed(vm, function, "cachedDataRejected"_s, jsBoolean(bytecodeAccepted == TriState::False)); RETURN_IF_EXCEPTION(throwScope, nullptr); } return function; } JSPromise* importModule(JSGlobalObject* globalObject, JSString* moduleName, RefPtr parameters, const SourceOrigin& sourceOrigin) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (auto* fetcher = sourceOrigin.fetcher(); !fetcher || fetcher->fetcherType() != ScriptFetcher::Type::NodeVM) { if (!sourceOrigin.url().isEmpty()) { if (auto* nodeVmGlobalObject = dynamicDowncast(globalObject)) { if (nodeVmGlobalObject->dynamicImportCallback()) { RELEASE_AND_RETURN(scope, moduleLoaderImportModuleInner(nodeVmGlobalObject, globalObject->moduleLoader(), moduleName, WTF::move(parameters), sourceOrigin)); } } } return nullptr; } auto* fetcher = static_cast(sourceOrigin.fetcher()); if (fetcher->isUsingDefaultLoader()) { return nullptr; } JSValue dynamicImportCallback = fetcher->dynamicImportCallback(); if (isUseMainContextDefaultLoaderConstant(globalObject, dynamicImportCallback)) { auto defer = fetcher->temporarilyUseDefaultLoader(); Zig::GlobalObject* zigGlobalObject = defaultGlobalObject(globalObject); RELEASE_AND_RETURN(scope, zigGlobalObject->moduleLoaderImportModule(zigGlobalObject, zigGlobalObject->moduleLoader(), moduleName, WTF::move(parameters), sourceOrigin, false)); } else if (!dynamicImportCallback || !dynamicImportCallback.isCallable()) { throwException(globalObject, scope, createError(globalObject, ErrorCode::ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, "A dynamic import callback was not specified."_s)); return nullptr; } RELEASE_AND_RETURN(scope, importModuleInner(globalObject, moduleName, WTF::move(parameters), sourceOrigin, dynamicImportCallback, fetcher->owner())); } static JSPromise* importModuleInner(JSGlobalObject* globalObject, JSString* moduleName, RefPtr parameters, const SourceOrigin& sourceOrigin, JSValue dynamicImportCallback, JSValue owner) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue importAttributes = scriptFetchParametersToImportAttributes(globalObject, parameters.get()); RETURN_IF_EXCEPTION(scope, nullptr); MarkedArgumentBuffer args; args.append(moduleName); if (owner) { args.append(owner); } else if (auto* nodeVmGlobalObject = dynamicDowncast(globalObject)) { args.append(nodeVmGlobalObject->contextObject()); } else { args.append(jsUndefined()); } args.append(importAttributes); // Node passes the import phase name as the 4th argument; JSC has no // source-phase imports, so it is always the evaluation phase. args.append(jsString(vm, String("evaluation"_s))); JSValue result = AsyncContextFrame::call(globalObject, dynamicImportCallback, jsUndefined(), args); RETURN_IF_EXCEPTION(scope, nullptr); if (result.isUndefinedOrNull()) { throwException(globalObject, scope, createError(globalObject, ErrorCode::ERR_VM_MODULE_NOT_MODULE, "Provided module is not an instance of Module"_s)); return nullptr; } if (auto* promise = dynamicDowncast(result)) { return promise; } auto* promise = JSPromise::create(vm, globalObject->promiseStructure()); RETURN_IF_EXCEPTION(scope, nullptr); auto* transformer = JSNativeStdFunction::create(vm, globalObject, 1, {}, [](JSGlobalObject* globalObject, CallFrame* callFrame) -> JSC::EncodedJSValue { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue argument = callFrame->argument(0); if (JSObject* object = argument.getObject()) { JSValue result = object->get(globalObject, JSC::Identifier::fromString(vm, "namespace"_s)); RETURN_IF_EXCEPTION(scope, {}); if (!result.isUndefinedOrNull()) { return JSValue::encode(result); } } return JSValue::encode(argument); }); RETURN_IF_EXCEPTION(scope, nullptr); promise->fulfill(vm, result); RETURN_IF_EXCEPTION(scope, nullptr); JSObject* thenResult = promise->then(globalObject, transformer, jsUndefined()); RETURN_IF_EXCEPTION(scope, nullptr); // JSPromise::then() may return a non-JSPromise when Promise[Symbol.species] // is overridden in the vm context — don't uncheckedDowncast (release-mode // static_cast) on a user-influenced shape. if (auto* thenPromise = dynamicDowncast(thenResult)) RELEASE_AND_RETURN(scope, thenPromise); RELEASE_AND_RETURN(scope, JSPromise::resolvedPromise(globalObject, thenResult)); } // Helper function to create an anonymous function expression with parameters String stringifyAnonymousFunction(JSGlobalObject* globalObject, const ArgList& args, ThrowScope& scope, int* outOffset) { // How we stringify functions is important for creating anonymous function expressions String program; if (args.isEmpty()) { // No arguments, just an empty function body program = "(function () {\n\n})"_s; } else if (args.size() == 1) { // Just the function body auto body = args.at(0).toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, {}); program = tryMakeString("(function () {\n"_s, body, "\n})"_s); *outOffset = "(function () {\n"_s.length(); if (!program) [[unlikely]] { throwOutOfMemoryError(globalObject, scope); return {}; } } else { // Process parameters and body unsigned parameterCount = args.size() - 1; // The params come from JS. Past `String::MaxLength` a default `StringBuilder` calls `CRASH()`. StringBuilder paramString { OverflowPolicy::RecordOverflow }; for (unsigned i = 0; i < parameterCount; ++i) { auto param = args.at(i).toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, {}); if (i > 0) { paramString.append(", "_s); } paramString.append(param); } if (paramString.hasOverflowed()) [[unlikely]] { throwOutOfMemoryError(globalObject, scope); return {}; } auto body = args.at(parameterCount).toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, {}); program = tryMakeString("(function ("_s, paramString.toString(), ") {\n"_s, body, "\n})"_s); *outOffset = "(function ("_s.length() + paramString.length() + ") {\n"_s.length(); if (!program) [[unlikely]] { throwOutOfMemoryError(globalObject, scope); return {}; } } return program; } // cachedData is a function of the source alone: every nested function is generated now (not whichever ones this // process happens to have run), with the default code-generation mode (no debugger/profiler opcodes), independently of // what the VM's CodeCache holds. RefPtr getBytecode(JSGlobalObject* globalObject, JSC::SourceCodeType type, const JSC::SourceCode& source) { VM& vm = JSC::getVM(globalObject); JSC::ParserError parserError; JSC::BytecodeCacheError bytecodeCacheError; FileSystem::FileHandle fileHandle; if (type == JSC::SourceCodeType::ModuleType) { // What JSC itself keys module code with: always strict, never tainted by a global scope extension. JSC::LexicallyScopedFeatures lexicallyScopedFeatures = StrictModeLexicallyScopedFeature; JSC::UnlinkedModuleProgramCodeBlock* unlinked = JSC::recursivelyGenerateUnlinkedCodeBlockForModuleProgram(vm, source, lexicallyScopedFeatures, JSParserScriptMode::Module, {}, parserError, EvalContextType::None); if (!unlinked || parserError.isValid() || hasStringTooLongForBytecodeCache(vm, source)) return nullptr; return JSC::serializeBytecode(vm, unlinked, source, JSC::SourceCodeType::ModuleType, lexicallyScopedFeatures, JSParserScriptMode::Module, fileHandle, bytecodeCacheError, {}); } ASSERT(type == JSC::SourceCodeType::ProgramType); JSC::LexicallyScopedFeatures lexicallyScopedFeatures = globalObject->globalScopeExtension() ? TaintedByWithScopeLexicallyScopedFeature : NoLexicallyScopedFeatures; JSC::UnlinkedProgramCodeBlock* unlinked = JSC::recursivelyGenerateUnlinkedCodeBlockForProgram(vm, source, lexicallyScopedFeatures, JSParserScriptMode::Classic, {}, parserError, EvalContextType::None); if (!unlinked || parserError.isValid() || hasStringTooLongForBytecodeCache(vm, source)) return nullptr; return JSC::serializeBytecode(vm, unlinked, source, JSC::SourceCodeType::ProgramType, lexicallyScopedFeatures, JSParserScriptMode::Classic, fileHandle, bytecodeCacheError, {}); } JSC::EncodedJSValue createCachedData(JSGlobalObject* globalObject, const JSC::SourceCode& source) { VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); RefPtr bytecode = getBytecode(globalObject, JSC::SourceCodeType::ProgramType, source); if (!bytecode) [[unlikely]] { return throwVMError(globalObject, scope, "createCachedData failed"_s); } JSC::JSUint8Array* buffer = createCachedDataBuffer(globalObject, bytecode->span()); RETURN_IF_EXCEPTION(scope, {}); if (!buffer) { return throwVMError(globalObject, scope, "Failed to create buffer"_s); } return JSValue::encode(buffer); } // AppendExceptionLine helpers shared by the runtime (handleException) and // compile-time (decorateParseErrorStack) paths — a single implementation of // Node's arrow-header format so the two call sites cannot drift. static String nthSourceLineForArrowHeader(StringView source, int64_t physicalLine1Based) { if (physicalLine1Based < 1 || physicalLine1Based > static_cast(source.length()) + 1) return {}; size_t lineStart = 0; for (int64_t currentLine = 1; currentLine < physicalLine1Based && lineStart != WTF::notFound; currentLine++) { size_t newline = source.find('\n', lineStart); lineStart = newline == WTF::notFound ? WTF::notFound : newline + 1; } if (lineStart == WTF::notFound) return {}; size_t lineEnd = source.find('\n', lineStart); if (lineEnd == WTF::notFound) lineEnd = source.length(); StringView lineView = source.substring(lineStart, lineEnd - lineStart); if (lineView.endsWith('\r')) lineView = lineView.left(lineView.length() - 1); // Like Node, skip the decoration for excessively long lines. if (lineView.length() > 1024) return {}; return lineView.toString(); } static void writeArrowHeaderStack(VM& vm, ErrorInstance* errorInstance, const String& url, int reportedLine, const String& sourceLineText, unsigned caretColumn1Based, const String& stack) { String prepend; if (!sourceLineText.isNull() && caretColumn1Based >= 1 && caretColumn1Based <= sourceLineText.length() + 1) { StringBuilder caretLine; for (unsigned i = 1; i < caretColumn1Based; i++) caretLine.append(i <= sourceLineText.length() && sourceLineText[i - 1] == '\t' ? '\t' : ' '); caretLine.append('^'); prepend = tryMakeString(url, ':', reportedLine, '\n', sourceLineText, '\n', caretLine.toString(), "\n\n"_s, stack); } else { prepend = tryMakeString(url, ':', reportedLine, '\n', stack); } // The URL and the stack come from JS. Past `String::MaxLength` `makeString` calls `CRASH()`. The error keeps its stack, without the header. if (prepend.isNull()) [[unlikely]] return; const auto& decoratedName = WebCore::builtinNames(vm).vmErrorDecoratedPrivateName(); errorInstance->putDirect(vm, vm.propertyNames->stack, jsString(vm, prepend), JSC::PropertyAttribute::DontEnum | 0); errorInstance->putDirect(vm, decoratedName, jsBoolean(true), JSC::PropertyAttribute::DontEnum | JSC::PropertyAttribute::ReadOnly); } bool handleException(JSGlobalObject* globalObject, VM& vm, NakedPtr exception, ThrowScope& throwScope) { if (auto* errorInstance = dynamicDowncast(exception->value())) { // No stack is captured for a throw that a `catch` clause further up is certain to handle. The error's own is // taken then, and that one is gone once the `stack` property is materialized. auto& e_stack = exception->stackForReporting(vm); errorInstance->materializeErrorInfoIfNeeded(vm, vm.propertyNames->stack); RETURN_IF_EXCEPTION(throwScope, {}); JSValue stack_jsval = errorInstance->get(globalObject, vm.propertyNames->stack); RETURN_IF_EXCEPTION(throwScope, {}); if (!stack_jsval.isString()) { return false; } String stack = stack_jsval.toWTFString(globalObject); RETURN_IF_EXCEPTION(throwScope, {}); size_t stack_size = e_stack.size(); if (stack_size == 0) { return false; } // Decoration must be idempotent: an error crossing several nested vm // boundaries passes through here once per layer (Node guards with a // hidden "decorated" marker too). const auto& decoratedName = WebCore::builtinNames(vm).vmErrorDecoratedPrivateName(); if (errorInstance->getDirect(vm, decoratedName)) { JSC::throwException(globalObject, throwScope, exception.get()); return true; } auto& stack_frame = e_stack[0]; auto source_url = stack_frame.sourceURL(vm); // Treat empty, [unknown], and [source:*] placeholders as missing source URLs if (source_url.isEmpty() || source_url == "[unknown]"_s || source_url.startsWith("[source:"_s)) { // copy what Node does: https://github.com/nodejs/node/blob/afe3909483a2d5ae6b847055f544da40571fb28d/lib/vm.js#L94 source_url = "evalmachine."_s; } auto line_and_column = stack_frame.computeLineAndColumn(); // Node decorates vm script errors with the offending source line and a // caret marker (AppendExceptionLine): // :\n\n\n\n String sourceLineText; unsigned caretColumn = 0; if (JSC::CodeBlock* codeBlock = stack_frame.codeBlock()) { if (JSC::SourceProvider* provider = codeBlock->source().provider()) { int64_t startLineZeroBased = provider->startPosition().m_line.zeroBasedInt(); int64_t physicalLine = static_cast(line_and_column.line) - startLineZeroBased; sourceLineText = nthSourceLineForArrowHeader(provider->source(), physicalLine); if (!sourceLineText.isNull()) { caretColumn = line_and_column.column; unsigned startColumnZeroBased = static_cast(provider->startPosition().m_column.zeroBasedInt()); if (physicalLine == 1 && caretColumn > startColumnZeroBased) caretColumn -= startColumnZeroBased; } } } writeArrowHeaderStack(vm, errorInstance, source_url, static_cast(line_and_column.line), sourceLineText, caretColumn, stack); JSC::throwException(globalObject, throwScope, exception.get()); return true; } return false; } // Compile-time counterpart of handleException: prepends Node's arrow header // (`:\n\n^\n\n`) using ParserError since there is no CodeBlock // yet. Node applies this unconditionally at compile time (not displayErrors). void decorateParseErrorStack(JSGlobalObject* globalObject, VM& vm, JSObject* error, StringView sourceString, const String& url, const JSC::ParserError& parseError, OrdinalNumber lineOffset) { UNUSED_PARAM(globalObject); auto* errorInstance = dynamicDowncast(error); // Stack overflow and out-of-memory ParserErrors have no position to point at. if (!errorInstance || parseError.line() < 0) return; // The caller's toErrorObject() already materialized the stack (running any // user Error.prepareStackTrace), so this cannot re-enter JS or throw. errorInstance->materializeErrorInfoIfNeeded(vm, vm.propertyNames->stack); JSValue stackValue = errorInstance->getDirect(vm, vm.propertyNames->stack); if (!stackValue || !stackValue.isString()) return; auto stackHolder = asString(stackValue)->tryGetValue(); const String& stack = stackHolder.data; if (stack.isNull()) return; // `url` is resolved by the caller: `new Script` substitutes // evalmachine. only when no filename was provided, while // compileFunction has no such default. An explicit "" renders as ":". // parseError.line() is the provider's start line (providerStartPosition) plus the physical line. int lineOff = lineOffset.zeroBasedInt(); int64_t physicalLine = static_cast(parseError.line()) - std::max(lineOff, 0); int reportedLine = static_cast(physicalLine) + lineOff; String sourceLineText = nthSourceLineForArrowHeader(sourceString, physicalLine); unsigned caretColumn = 0; if (!sourceLineText.isNull()) { caretColumn = 1; // The token offset is physical, so columnOffset needs no adjustment. int offset = parseError.token().m_startPosition.offset; if (offset >= 0 && static_cast(offset) <= sourceString.length()) { size_t newline = offset ? sourceString.reverseFind('\n', offset - 1) : WTF::notFound; caretColumn = offset - (newline == WTF::notFound ? 0 : newline + 1) + 1; } } writeArrowHeaderStack(vm, errorInstance, url, reportedLine, sourceLineText, caretColumn, stack); } const WTF::URL& sourceOriginURL(JSC::VM& vm, const String& filename) { auto& cache = WebCore::clientData(vm)->nodeVMSourceOriginCache(); if (cache.url.isNull() || cache.filename != filename) { cache.url = WTF::URL::fileURLWithFileSystemPath(filename); // A copy: `filename` can be a slice of a large string, and that StringImpl keeps the whole string alive. cache.filename = filename.isolatedCopy(); } return cache.url; } OrdinalNumber clampOffsetForSource(OrdinalNumber offset, unsigned sourceLength) { int64_t maxOffset = std::max(static_cast(std::numeric_limits::max()) - 1 - sourceLength, 0); if (offset.zeroBasedInt() <= maxOffset) return offset; return OrdinalNumber::fromZeroBasedInt(static_cast(maxOffset)); } TextPosition providerStartPosition(OrdinalNumber lineOffset, OrdinalNumber columnOffset) { return TextPosition( OrdinalNumber::fromZeroBasedInt(std::max(lineOffset.zeroBasedInt(), 0)), OrdinalNumber::fromZeroBasedInt(std::max(columnOffset.zeroBasedInt(), 0))); } void getNodeVMContextOptions(JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSValue optionsArg, NodeVMContextOptions& outOptions, const JSC::Identifier& codeGenerationKey, JSValue* importer) { if (importer) { *importer = jsUndefined(); } outOptions = {}; // If options is provided, validate name and origin properties if (!optionsArg.isObject()) { return; } JSObject* options = asObject(optionsArg); // Check name property auto nameValue = options->getIfPropertyExists(globalObject, vm.propertyNames->name); RETURN_IF_EXCEPTION(scope, ); if (nameValue) { if (!nameValue.isUndefined() && !nameValue.isString()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.name"_s, "string"_s, nameValue); return; } } // Check origin property auto originValue = options->getIfPropertyExists(globalObject, vm.propertyNames->origin); RETURN_IF_EXCEPTION(scope, ); if (originValue) { if (!originValue.isUndefined() && !originValue.isString()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.origin"_s, "string"_s, originValue); return; } } JSValue importModuleDynamicallyValue = options->getIfPropertyExists(globalObject, optionNames(vm).importModuleDynamically(vm)); RETURN_IF_EXCEPTION(scope, ); if (importModuleDynamicallyValue) { if (importer && importModuleDynamicallyValue && (importModuleDynamicallyValue.isCallable() || isUseMainContextDefaultLoaderConstant(globalObject, importModuleDynamicallyValue))) { *importer = importModuleDynamicallyValue; } } // microtaskMode: "afterEvaluate" gives the context its own microtask // queue. Validated here (not only in vm.ts) so native entry points like // script.runInNewContext reject invalid values the way Node does. JSValue microtaskModeValue = options->getIfPropertyExists(globalObject, optionNames(vm).microtaskMode(vm)); RETURN_IF_EXCEPTION(scope, ); if (microtaskModeValue && !microtaskModeValue.isUndefined()) { bool isAfterEvaluate = false; if (microtaskModeValue.isString()) { String microtaskMode = microtaskModeValue.toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, ); isAfterEvaluate = microtaskMode == "afterEvaluate"_s; } if (!isAfterEvaluate) { static constexpr ASCIILiteral oneOf[] = { "afterEvaluate"_s, "undefined"_s }; ERR::INVALID_ARG_VALUE(scope, globalObject, "options.microtaskMode"_s, "must be one of: "_s, microtaskModeValue, oneOf); return; } outOptions.ownMicrotaskQueue = true; } JSValue codeGenerationValue = options->getIfPropertyExists(globalObject, codeGenerationKey); RETURN_IF_EXCEPTION(scope, ); if (codeGenerationValue) { if (codeGenerationValue.isUndefined()) { return; } if (!codeGenerationValue.isObject()) { ERR::INVALID_ARG_TYPE(scope, globalObject, WTF::makeString("options."_s, codeGenerationKey.string()), "object"_s, codeGenerationValue); return; } JSObject* codeGenerationObject = asObject(codeGenerationValue); auto allowStringsValue = codeGenerationObject->getIfPropertyExists(globalObject, optionNames(vm).strings(vm)); RETURN_IF_EXCEPTION(scope, ); if (allowStringsValue && !allowStringsValue.isUndefined()) { if (!allowStringsValue.isBoolean()) { ERR::INVALID_ARG_TYPE(scope, globalObject, WTF::makeString("options."_s, codeGenerationKey.string(), ".strings"_s), "boolean"_s, allowStringsValue); return; } outOptions.allowStrings = allowStringsValue.asBoolean(); } auto allowWasmValue = codeGenerationObject->getIfPropertyExists(globalObject, optionNames(vm).wasm(vm)); RETURN_IF_EXCEPTION(scope, ); if (allowWasmValue && !allowWasmValue.isUndefined()) { if (!allowWasmValue.isBoolean()) { ERR::INVALID_ARG_TYPE(scope, globalObject, WTF::makeString("options."_s, codeGenerationKey.string(), ".wasm"_s), "boolean"_s, allowWasmValue); return; } outOptions.allowWasm = allowWasmValue.asBoolean(); } } } static NodeVMGlobalObject* globalObjectOfContextObject(JSGlobalObject* globalObject, JSObject* context) { if (auto* nodeVmGlobalObject = dynamicDowncast(defaultGlobalObject(globalObject)->vmModuleContextMap()->get(context))) return nodeVmGlobalObject; if (auto* proxy = dynamicDowncast(context)) { if (auto* nodeVmGlobalObject = dynamicDowncast(proxy->target()); nodeVmGlobalObject && nodeVmGlobalObject->contextObject() == proxy) return nodeVmGlobalObject; } return nullptr; } NodeVMGlobalObject* getGlobalObjectFromContext(JSGlobalObject* globalObject, JSValue contextValue, bool canThrow) { auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); if (!contextValue.isObject()) { if (canThrow) { ERR::INVALID_ARG_TYPE(scope, globalObject, "context"_s, "object"_s, contextValue); } return nullptr; } JSObject* context = asObject(contextValue); auto* nodeVmGlobalObject = globalObjectOfContextObject(globalObject, context); if (!nodeVmGlobalObject && canThrow) { INVALID_ARG_VALUE_VM_VARIATION(scope, globalObject, "contextifiedObject"_s, context); } return nodeVmGlobalObject; } /// For some reason Node has this error message with a grammatical error and we have to match it so the tests pass: /// `The "" argument must be an vm.Context` JSC::EncodedJSValue INVALID_ARG_VALUE_VM_VARIATION(JSC::ThrowScope& throwScope, JSC::JSGlobalObject* globalObject, WTF::ASCIILiteral name, JSC::JSValue value) { throwScope.throwException(globalObject, createError(globalObject, ErrorCode::ERR_INVALID_ARG_TYPE, makeString("The \""_s, name, "\" argument must be an vm.Context"_s))); throwScope.release(); return {}; } bool isContext(JSGlobalObject* globalObject, JSValue value) { return globalObjectOfContextObject(globalObject, asObject(value)); } bool getContextArg(JSGlobalObject* globalObject, JSValue contextArg, JSObject*& contextifiedObject) { contextifiedObject = nullptr; if (contextArg.isUndefined()) { contextifiedObject = JSC::constructEmptyObject(globalObject); } else if (contextArg.isObject()) { contextifiedObject = asObject(contextArg); } else { Zig::GlobalObject* zigGlobalObject = defaultGlobalObject(globalObject); return contextArg == zigGlobalObject->m_nodeVMDontContextify.get(zigGlobalObject); } return true; } bool isUseMainContextDefaultLoaderConstant(JSGlobalObject* globalObject, JSValue value) { if (value.isSymbol()) { Zig::GlobalObject* zigGlobalObject = defaultGlobalObject(globalObject); if (value == zigGlobalObject->m_nodeVMUseMainContextDefaultLoader.get(zigGlobalObject)) { return true; } } return false; } } // namespace NodeVM using namespace NodeVM; // V8's --expose-gc. As there, it is for the whole process and for the contexts made after it is set. static std::atomic newContextsHaveGC { false }; extern "C" void JSC__JSGlobalObject__addGc(JSC::JSGlobalObject*); extern "C" void Bun__NodeVM__setNewContextsHaveGC(bool value) { newContextsHaveGC.store(value, std::memory_order_relaxed); } JSC_DEFINE_HOST_FUNCTION(jsFunctionSetNewContextsHaveGC, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame)) { Bun__NodeVM__setNewContextsHaveGC(callFrame->argument(0).toBoolean(globalObject)); return JSValue::encode(jsUndefined()); } NodeVMGlobalObject::NodeVMGlobalObject(JSC::VM& vm, JSC::Structure* structure, NodeVMContextOptions contextOptions, JSValue importer) : Base(vm, structure, &globalObjectMethodTable()) , m_dynamicImportCallback(vm, this, importer) , m_contextOptions(contextOptions) { } template JSC::GCClient::IsoSubspace* NodeVMGlobalObject::subspaceFor(JSC::VM& vm) { if constexpr (mode == JSC::SubspaceAccess::Concurrently) return nullptr; return WebCore::subspaceForImpl(vm, BUN_SUBSPACE_SLOTS(m_clientSubspaceForNodeVMGlobalObject, m_subspaceForNodeVMGlobalObject), [](auto& server) -> JSC::HeapCellType& { return server.m_heapCellTypeForNodeVMGlobalObject; }); } NodeVMGlobalObject* NodeVMGlobalObject::create(JSC::VM& vm, NodeVMContextOptions options, JSValue importer, JSObject* contextifiedObject) { // A Structure points at its realm, so sharing one across contexts would keep the last context alive. auto* structure = createStructure(vm); auto* cell = new (NotNull, JSC::allocateCell(vm)) NodeVMGlobalObject(vm, structure, options, importer); cell->finishCreation(vm); // Must be set after finishCreation(), which reads and deletes the bare global's properties. cell->m_sandbox.setMayBeNull(vm, cell, contextifiedObject); defaultGlobalObject(vm)->addDerivedRealm(cell); return cell; } Structure* NodeVMGlobalObject::createStructure(JSC::VM& vm) { // ~IsImmutablePrototypeExoticObject is necessary for JSDOM to work (it relies on __proto__ = on the GlobalObject). return JSC::Structure::create(vm, nullptr, jsNull(), JSC::TypeInfo(JSC::GlobalObjectType, StructureFlags & ~IsImmutablePrototypeExoticObject), info()); } void unsafeEvalNoop(JSGlobalObject*, const WTF::String&) {} static void promiseRejectionTrackerForNodeVM(JSGlobalObject* globalObject, JSC::JSPromise* promise, JSC::JSPromiseRejectionOperation operation) { // Delegate to the parent global object so that unhandled rejections // in VM contexts are reported to the main process (matching Node.js behavior) if (Bun::isRetiredTestIsolationRealm(globalObject)) [[unlikely]] return; auto* zigGlobalObject = defaultGlobalObject(globalObject); Zig::GlobalObject::promiseRejectionTracker(zigGlobalObject, promise, operation); } const JSC::GlobalObjectMethodTable& NodeVMGlobalObject::globalObjectMethodTable() { static const JSC::GlobalObjectMethodTable table { &supportsRichSourceInfo, &shouldInterruptScript, &javaScriptRuntimeFlags, nullptr, // shouldInterruptScriptBeforeTimeout, nullptr, // moduleTypeIsAllowed &moduleLoaderImportModule, nullptr, // moduleLoaderResolve nullptr, // moduleLoaderFetch nullptr, // moduleLoaderCreateImportMetaProperties nullptr, // moduleLoaderEvaluate &promiseRejectionTrackerForNodeVM, &reportUncaughtExceptionAtEventLoop, ¤tScriptExecutionOwner, &scriptExecutionStatus, &unsafeEvalNoop, // reportViolationForUnsafeEval nullptr, // defaultLanguage nullptr, // compileStreaming nullptr, // instantiateStreaming #if defined(BUN_DISABLE_SHADOW_REALM) nullptr, // deriveShadowRealmGlobalObject #else &Zig::GlobalObject::deriveShadowRealmGlobalObject, #endif &codeForEval, &canCompileStrings, &trustedScriptStructure, nullptr, // requireBuiltinModule nullptr, // nativeBinding }; return table; } #if ENABLE(WEBASSEMBLY) JSC_DEFINE_HOST_FUNCTION(jsNodeVmWasmDisallowed, (JSC::JSGlobalObject * globalObject, JSC::CallFrame*)) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* error = JSC::createJSWebAssemblyCompileError(globalObject, vm, "Wasm code generation disallowed by embedder"_s); RETURN_IF_EXCEPTION(scope, {}); scope.throwException(globalObject, error); return {}; } // Async compile entry points reject (rather than throw) with the embedder // CompileError, like V8's code-generation callback. JSC_DEFINE_HOST_FUNCTION(jsNodeVmWasmCompileDisallowed, (JSC::JSGlobalObject * globalObject, JSC::CallFrame*)) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* error = JSC::createJSWebAssemblyCompileError(globalObject, vm, "Wasm code generation disallowed by embedder"_s); RETURN_IF_EXCEPTION(scope, {}); RELEASE_AND_RETURN(scope, JSValue::encode(JSC::JSPromise::rejectedPromise(globalObject, error))); } #endif // ENABLE(WEBASSEMBLY) void NodeVMGlobalObject::finishCreation(JSC::VM& vm) { auto scope = DECLARE_THROW_SCOPE(vm); Base::finishCreation(vm); RETURN_IF_EXCEPTION(scope, ); // microtaskMode: "afterEvaluate" — give this context its own microtask // queue, like Node's contextify own_microtask_queue. Microtasks enqueued // for this global no longer land on the VM's default queue (which the // event loop drains); they only run when drainOwnMicrotasks() is called // after a script/module evaluation in this context. if (m_contextOptions.ownMicrotaskQueue) { setMicrotaskQueue(JSC::MicrotaskQueue::create(vm)); // Defeat JSC's cross-realm promise fast paths for promises created in // this context. With the fast paths active, awaiting/resolving one of // this context's (settled) promises from another realm enqueues the // reaction job directly on the *lexical* realm's queue. V8 routes // promise jobs through the promise's own context: the generic // thenable route calls this realm's `then`, which enqueues the // reaction on this context's own queue — so the outer event loop // cannot make progress on inner promises until the next afterEvaluate // checkpoint (see test-vm-{script,module}-after-evaluate.js). promiseThenWatchpointSet().fireAll(vm, "node:vm microtaskMode afterEvaluate context"); promiseSpeciesWatchpointSet().fireAll(vm, "node:vm microtaskMode afterEvaluate context"); } // A context decides for itself, as in Node.js, unless nothing in the process may. setEvalEnabled(m_contextOptions.allowStrings && !Bun::isCodeGenerationFromStringsStrict(), Bun::codeGenerationFromStringsDisallowedMessage()); setWebAssemblyEnabled(m_contextOptions.allowWasm, "Wasm code generation disallowed by embedder"_s); #if ENABLE(WEBASSEMBLY) if (!m_contextOptions.allowWasm) { // JSC's setWebAssemblyEnabled only gates the streaming entry points; // `new WebAssembly.Module(bytes)`, WebAssembly.compile(bytes), and // WebAssembly.instantiate(bytes) would still compile. Gate them like // V8's embedder callback: code *generation* throws/rejects // CompileError, while introspection (Module.imports/exports/ // customSections) and instantiating an already-compiled module stay // available. JSValue webAssembly = get(this, Identifier::fromString(vm, "WebAssembly"_s)); RETURN_IF_EXCEPTION(scope, ); if (webAssembly.isObject()) { JSObject* webAssemblyObject = asObject(webAssembly); JSC::JSFunction* moduleDisallowed = JSC::JSFunction::create(vm, this, 1, "Module"_s, jsNodeVmWasmDisallowed, ImplementationVisibility::Public, NoIntrinsic, jsNodeVmWasmDisallowed); JSValue originalModule = webAssemblyObject->get(this, Identifier::fromString(vm, "Module"_s)); RETURN_IF_EXCEPTION(scope, ); if (originalModule.isObject()) { JSObject* originalModuleObject = asObject(originalModule); // Preserve the introspection statics and the prototype so // existing Module instances keep working inside the context. for (auto staticName : { "imports"_s, "exports"_s, "customSections"_s }) { Identifier identifier = Identifier::fromString(vm, staticName); JSValue staticValue = originalModuleObject->get(this, identifier); RETURN_IF_EXCEPTION(scope, ); moduleDisallowed->putDirect(vm, identifier, staticValue, static_cast(PropertyAttribute::DontEnum)); } JSValue prototypeValue = originalModuleObject->get(this, vm.propertyNames->prototype); RETURN_IF_EXCEPTION(scope, ); moduleDisallowed->putDirect(vm, vm.propertyNames->prototype, prototypeValue, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); // Without this, prototype.constructor would hand back the // original compiling constructor. if (prototypeValue.isObject()) { asObject(prototypeValue)->putDirect(vm, vm.propertyNames->constructor, moduleDisallowed, static_cast(PropertyAttribute::DontEnum)); } } webAssemblyObject->putDirect(vm, Identifier::fromString(vm, "Module"_s), moduleDisallowed, static_cast(PropertyAttribute::DontEnum)); // WebAssembly.compile bypasses JSC's webAssemblyEnabled gate, so // replace it with a rejecting version. WebAssembly.instantiate is // already gated by setWebAssemblyEnabled and rejects with the // embedder CompileError on its own. JSC::JSFunction* compileDisallowed = JSC::JSFunction::create(vm, this, 1, "compile"_s, jsNodeVmWasmCompileDisallowed, ImplementationVisibility::Public); webAssemblyObject->putDirect(vm, Identifier::fromString(vm, "compile"_s), compileDisallowed, static_cast(PropertyAttribute::DontEnum)); } } #endif // ENABLE(WEBASSEMBLY) // Delete the internal Loader property from the VM global object. // This is exposed by JSC when exposeInternalModuleLoader() is true, // but it should not be visible in node:vm contexts. JSC::DeletePropertySlot slot; JSC::JSObject::deleteProperty(this, this, vm.propertyNames->Loader, slot); RETURN_IF_EXCEPTION(scope, ); vm.ensureTerminationException(); // Share the async context data with the parent global object. // This is necessary because AsyncLocalStorage methods (run, getStore, etc.) are defined // in the parent realm and reference the parent's $asyncContext. However, microtask // processing (JSMicrotask.cpp) operates on this NodeVMGlobalObject's m_asyncContextData. // By sharing the same InternalFieldTuple, both the JS code and C++ microtask handling // will operate on the same async context, ensuring proper AsyncLocalStorage behavior // across await boundaries in VM contexts. auto* parentGlobalObject = defaultGlobalObject(this); if (parentGlobalObject && parentGlobalObject->m_asyncContextData) { m_asyncContextData.set(vm, this, parentGlobalObject->m_asyncContextData.get()); if (parentGlobalObject->isAsyncContextTrackingEnabled()) setAsyncContextTrackingEnabled(true); } if (newContextsHaveGC.load(std::memory_order_relaxed)) JSC__JSGlobalObject__addGc(this); } void NodeVMGlobalObject::destroy(JSCell* cell) { static_cast(cell)->~NodeVMGlobalObject(); } NodeVMGlobalObject::~NodeVMGlobalObject() = default; void NodeVMGlobalObject::drainOwnMicrotasks() { if (!m_contextOptions.ownMicrotaskQueue) return; VM& vm = this->vm(); // Same drain mode as VM::drainMicrotasks so process.nextTick interop // (onEachMicrotaskTick) keeps working inside the checkpoint. microtaskQueue().performMicrotaskCheckpoint(vm, [](JSGlobalObject*, JSGlobalObject*) {}); } // The contextified object can itself be another context's global, so forwarding can recurse arbitrarily deep. static bool isSafeToForwardToContextifiedObject(JSGlobalObject* globalObject, ThrowScope& scope) { if (scope.vm().isSafeToRecurseSoft()) [[likely]] return true; throwStackOverflowError(globalObject, scope); return false; } // V8's GetRealNamedPropertyAttributes(): [[GetOwnProperty]] up the prototype chain, which runs no getter and no `get` trap. // The two loops are those of JSObject::getPropertySlot() and JSObject::getNonIndexPropertySlot(), which never end when a Proxy is on its own prototype chain. // Here a Proxy ends the walk and declares every name, as in V8. So does the global of another context. The store or the definition then goes to the contextified object. static ALWAYS_INLINE bool getDeclaredPropertySlotOfContextifiedObject(JSGlobalObject* globalObject, JSObject* contextifiedObject, PropertyName propertyName, PropertySlot& slot) { VM& vm = JSC::getVM(globalObject); JSObject* object = contextifiedObject; while (!TypeInfo::overridesGetOwnPropertySlot(object->inlineTypeFlags())) { Structure* structure = object->structureID().decode(); if (object->getOwnNonIndexPropertySlot(vm, structure, propertyName, slot)) return true; JSValue prototype = structure->storedPrototype(object); if (!prototype.isObject()) { object = nullptr; break; } object = asObject(prototype); } // getOwnNonIndexPropertySlot() finds no index, so an index starts again and asks every object through its method table. std::optional index = parseIndex(propertyName); if (index) object = contextifiedObject; else if (!object) return false; auto scope = DECLARE_THROW_SCOPE(vm); JSObject* first = object; while (true) { Structure* structure = object->structureID().decode(); if (!index && !TypeInfo::overridesGetOwnPropertySlot(object->inlineTypeFlags())) { if (object->getOwnNonIndexPropertySlot(vm, structure, propertyName, slot)) return true; } else { if (auto* proxy = dynamicDowncast(object)) { if (auto* context = dynamicDowncast(proxy->target()); context && context->contextifiedObject()) return true; } auto& methodTable = structure->classInfoForCells()->methodTable; bool found = index ? methodTable.getOwnPropertySlotByIndex(object, globalObject, *index, slot) : methodTable.getOwnPropertySlot(object, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, false); if (found || object->type() == ProxyObjectType) return true; if (isTypedArrayType(object->type()) && isCanonicalNumericIndexString(propertyName.uid())) return false; } JSValue prototype; if (!structure->typeInfo().overridesGetPrototype()) [[likely]] prototype = object->getPrototypeDirect(); #if ENABLE(AOT) else if (!index && vm.hasCompiledCode() && JSC::AOT::PropertyWalk::isOrdinaryPrototypeChain(first, object)) prototype = object->getPrototypeDirect(); #endif else { prototype = object->getPrototype(globalObject); RETURN_IF_EXCEPTION(scope, false); } if (!prototype.isObject()) return false; object = asObject(prototype); } } bool NodeVMGlobalObject::put(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot) { auto* thisObject = uncheckedDowncast(cell); // JSC passes the scope as the receiver when storing to a bare identifier. Setters and Proxy traps must see globalThis. if (slot.thisValue() == thisObject) slot.setThisValue(thisObject->globalThis()); if (!thisObject->m_sandbox) { return Base::put(cell, globalObject, propertyName, value, slot); } auto* sandbox = thisObject->m_sandbox.get(); VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); if (!isSafeToForwardToContextifiedObject(globalObject, scope)) [[unlikely]] return false; JSValue thisValue = slot.thisValue(); bool isContextualStore = thisValue != JSValue(globalObject); if (auto* proxy = dynamicDowncast(thisValue); proxy && proxy->target() == globalObject) { isContextualStore = false; } bool isDeclaredOnGlobalObject = slot.type() == JSC::PutPropertySlot::NewProperty; PropertySlot getter(sandbox, PropertySlot::InternalMethodType::GetOwnProperty, nullptr); bool isDeclaredOnSandbox = getDeclaredPropertySlotOfContextifiedObject(globalObject, sandbox, propertyName, getter); RETURN_IF_EXCEPTION(scope, false); bool isDeclared = isDeclaredOnGlobalObject || isDeclaredOnSandbox; bool isFunction = value.isCallable(); if (slot.isStrictMode() && !isDeclared && isContextualStore && !isFunction) { RELEASE_AND_RETURN(scope, Base::put(cell, globalObject, propertyName, value, slot)); } if (!isDeclared && value.isSymbol()) { RELEASE_AND_RETURN(scope, Base::put(cell, globalObject, propertyName, value, slot)); } slot.setThisValue(sandbox); bool result = sandbox->methodTable()->put(sandbox, globalObject, propertyName, value, slot); RETURN_IF_EXCEPTION(scope, false); if (!result) return false; // An accessor that a Proxy reports does not end the store. The value on the global keeps a later `var` of that name from hiding the accessor. if (isDeclaredOnSandbox && getter.isAccessor() and (getter.attributes() & PropertyAttribute::DontEnum) == 0 && !getter.isTaintedByOpaqueObject()) { return true; } slot.setThisValue(thisValue); RELEASE_AND_RETURN(scope, Base::put(cell, globalObject, propertyName, value, slot)); } // [[Get]] that reports whether the property exists. A JSC Proxy always says yes, so without a `get` trap ask its target, like V8. static bool getPropertySlotOfContextifiedObject(JSGlobalObject* globalObject, JSObject* object, PropertyName propertyName, PropertySlot& slot) { NO_TAIL_CALLS(); VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); // A Proxy can be on its own target's prototype chain. if (!vm.isSafeToRecurseSoft()) [[unlikely]] { throwStackOverflowError(globalObject, scope); return false; } while (true) { if (auto* proxy = dynamicDowncast(object); proxy && !proxy->isRevoked() && !propertyName.isPrivateName()) { JSObject* target = proxy->target(); JSObject* handler = asObject(proxy->handler()); CallData callData; JSObject* getTrap = proxy->getHandlerTrap(globalObject, handler, callData, vm.propertyNames->get, ProxyObject::HandlerTrap::Get); RETURN_IF_EXCEPTION(scope, false); if (!getTrap) RELEASE_AND_RETURN(scope, getPropertySlotOfContextifiedObject(globalObject, target, propertyName, slot)); // Copied from performProxyGet() in JSC's ProxyObject.cpp. Calling it would read the trap from the handler twice. MarkedArgumentBuffer arguments; arguments.append(target); arguments.append(identifierToSafePublicJSValue(vm, Identifier::fromUid(vm, propertyName.uid()))); arguments.append(slot.thisValue()); ASSERT(!arguments.hasOverflowed()); JSValue trapResult = call(globalObject, getTrap, callData, handler, arguments); RETURN_IF_EXCEPTION(scope, false); if (target->structure()->hasNonConfigurableReadOnlyOrGetterSetterProperties()) { ProxyObject::validateGetTrapResult(globalObject, trapResult, target, propertyName); RETURN_IF_EXCEPTION(scope, false); } unsigned ignoredAttributes = 0; slot.setValue(proxy, ignoredAttributes, trapResult); return true; } bool found = object->getOwnPropertySlotInline(globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, false); if (found) return true; if (isTypedArrayType(object->type()) && isCanonicalNumericIndexString(propertyName.uid())) return false; JSValue prototype = object->getPrototype(globalObject); RETURN_IF_EXCEPTION(scope, false); if (!prototype.isObject()) return false; object = asObject(prototype); } } bool NodeVMGlobalObject::getOwnPropertySlot(JSObject* cell, JSGlobalObject* globalObject, PropertyName propertyName, PropertySlot& slot) { VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); auto* thisObject = uncheckedDowncast(cell); // As in put(), getters and Proxy traps must see globalThis as the receiver, not the scope. JSValue thisValue = slot.thisValue() == thisObject ? thisObject->globalThis() : slot.thisValue(); if (JSObject* contextifiedObject = thisObject->contextifiedObject()) { if (slot.internalMethodType() == JSC::PropertySlot::InternalMethodType::Get) { PropertySlot contextifiedSlot(contextifiedObject, PropertySlot::InternalMethodType::Get); bool result = getPropertySlotOfContextifiedObject(globalObject, contextifiedObject, propertyName, contextifiedSlot); RETURN_IF_EXCEPTION(scope, false); if (result) { // Materialize the value (like V8's contextify GetterCallback) so that, // when a lookup on the sandbox yields the sandbox object itself, we can // substitute the context's global proxy to keep identities consistent. JSValue value = contextifiedSlot.getValue(globalObject, propertyName); RETURN_IF_EXCEPTION(scope, false); if (value == contextifiedObject) value = thisObject->globalThis(); unsigned ignoredAttributes = 0; slot.disableCaching(); slot.setValue(contextifiedObject, ignoredAttributes, value); return true; } } else { // For [[GetOwnProperty]] and [[HasProperty]], only own properties of the // sandbox may be reported on the context's global object. Properties from // the sandbox's prototype chain remain readable through normal lookup // (InternalMethodType::Get above) but must not appear as own properties, // matching Node's contextify Query/Descriptor callbacks. if (!isSafeToForwardToContextifiedObject(globalObject, scope)) [[unlikely]] return false; slot.setThisValue(contextifiedObject); bool result = contextifiedObject->methodTable()->getOwnPropertySlot(contextifiedObject, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, false); if (result) return true; } } slot.setThisValue(thisValue); RELEASE_AND_RETURN(scope, Base::getOwnPropertySlot(cell, globalObject, propertyName, slot)); } bool NodeVMGlobalObject::getOwnPropertySlotByIndex(JSObject* cell, JSGlobalObject* globalObject, unsigned index, PropertySlot& slot) { VM& vm = JSC::getVM(globalObject); return getOwnPropertySlot(cell, globalObject, Identifier::from(vm, index), slot); } bool NodeVMGlobalObject::defineOwnProperty(JSObject* cell, JSGlobalObject* globalObject, PropertyName propertyName, const PropertyDescriptor& descriptor, bool shouldThrow) { VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); auto* thisObject = uncheckedDowncast(cell); if (!thisObject->m_sandbox) [[likely]] { RELEASE_AND_RETURN(scope, Base::defineOwnProperty(cell, globalObject, propertyName, descriptor, shouldThrow)); } auto* contextifiedObject = thisObject->m_sandbox.get(); if (!isSafeToForwardToContextifiedObject(globalObject, scope)) [[unlikely]] return false; PropertySlot slot(globalObject, PropertySlot::InternalMethodType::GetOwnProperty, nullptr); bool isDeclaredOnGlobalProxy = globalObject->JSC::JSGlobalObject::getOwnPropertySlot(globalObject, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, false); // If the property is set on the global as neither writable nor // configurable, don't change it on the global or sandbox. if (isDeclaredOnGlobalProxy && (slot.attributes() & PropertyAttribute::ReadOnly) != 0 && (slot.attributes() & PropertyAttribute::DontDelete) != 0) { RELEASE_AND_RETURN(scope, Base::defineOwnProperty(cell, globalObject, propertyName, descriptor, shouldThrow)); } // Dispatch through the method table so exotic sandboxes (e.g. Proxy objects) // observe the [[DefineOwnProperty]] exactly once, like V8's contextify // PropertyDefinerCallback. if (descriptor.isAccessorDescriptor()) { RELEASE_AND_RETURN(scope, contextifiedObject->methodTable()->defineOwnProperty(contextifiedObject, globalObject, propertyName, descriptor, shouldThrow)); } // The lookup above may have filled `slot` as cacheable (e.g. a lazy global // stored as a CustomGetterSetter on a non-dictionary structure). Reusing it // here would trip PropertySlot's CachingDisallowed asserts if the sandbox // resolves the same name via setGetterSlot/setCustom/setValue(3-arg), which // happens once the sandbox has transitioned to an uncacheable dictionary. PropertySlot sandboxSlot(globalObject, PropertySlot::InternalMethodType::GetOwnProperty, nullptr); bool isDeclaredOnSandbox = getDeclaredPropertySlotOfContextifiedObject(globalObject, contextifiedObject, propertyName, sandboxSlot); RETURN_IF_EXCEPTION(scope, false); if (isDeclaredOnSandbox && !isDeclaredOnGlobalProxy) { RELEASE_AND_RETURN(scope, contextifiedObject->methodTable()->defineOwnProperty(contextifiedObject, globalObject, propertyName, descriptor, shouldThrow)); } auto did = contextifiedObject->methodTable()->defineOwnProperty(contextifiedObject, globalObject, propertyName, descriptor, shouldThrow); RETURN_IF_EXCEPTION(scope, false); if (!did) return false; RELEASE_AND_RETURN(scope, Base::defineOwnProperty(cell, globalObject, propertyName, descriptor, shouldThrow)); } DEFINE_VISIT_CHILDREN(NodeVMGlobalObject); template void NodeVMGlobalObject::visitChildrenImpl(JSCell* cell, Visitor& visitor) { Base::visitChildren(cell, visitor); auto* thisObject = uncheckedDowncast(cell); visitor.append(thisObject->m_sandbox); visitor.append(thisObject->m_dynamicImportCallback); } JSC_DEFINE_HOST_FUNCTION(vmModuleCompileFunction, (JSGlobalObject * globalObject, CallFrame* callFrame)) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); THROW_AND_RETURN_IF_CODE_GENERATION_FROM_STRINGS_IS_STRICT(globalObject, scope, {}); // Step 1: Argument validation // Get code argument (required) JSValue codeArg = callFrame->argument(0); if (!codeArg || !codeArg.isString()) return ERR::INVALID_ARG_TYPE(scope, globalObject, "code"_s, "string"_s, codeArg); // Get params argument (optional array of strings) MarkedArgumentBuffer parameters; JSValue paramsArg = callFrame->argument(1); if (paramsArg && !paramsArg.isUndefined()) { bool paramsIsArray = paramsArg.isObject() && isArray(globalObject, paramsArg); RETURN_IF_EXCEPTION(scope, {}); if (!paramsIsArray) { return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "params"_s, "Array"_s, paramsArg); } auto* paramsArray = dynamicDowncast(paramsArg); if (!paramsArray) [[unlikely]] { // isArray() accepts Proxy->Array, but jsDynamicCast returns null. return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "params"_s, "Array"_s, paramsArg); } unsigned length = paramsArray->length(); for (unsigned i = 0; i < length; i++) { JSValue param = paramsArray->getIndex(globalObject, i); RETURN_IF_EXCEPTION(scope, {}); if (!param.isString()) { return ERR::INVALID_ARG_TYPE(scope, globalObject, "params"_s, "Array"_s, paramsArg); } parameters.append(param); } } // Get options argument JSValue optionsArg = callFrame->argument(2); CompileFunctionOptions options; JSValue importer; if (!options.fromJS(globalObject, vm, scope, optionsArg, &importer)) { RETURN_IF_EXCEPTION(scope, {}); options = {}; options.parsingContext = globalObject; } // Step 3: Create a new function // Prepare the function code by combining the parameters and body String sourceString = codeArg.toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, {}); // Create an ArgList with the parameters and function body for constructFunction MarkedArgumentBuffer constructFunctionArgs; // Add all parameters for (unsigned i = 0; i < parameters.size(); i++) { constructFunctionArgs.append(parameters.at(i)); } // Add the function body constructFunctionArgs.append(jsString(vm, sourceString)); RefPtr fetcher(NodeVMScriptFetcher::create(vm, importer, jsUndefined())); // Create the source origin SourceOrigin sourceOrigin { sourceOriginURL(vm, options.filename), *fetcher }; // Process contextExtensions if they exist JSScope* functionScope = options.parsingContext ? options.parsingContext : globalObject; bool hasContextExtensions = !options.contextExtensions.isUndefinedOrNull() && !options.contextExtensions.isEmpty() && options.contextExtensions.isObject() && isArray(globalObject, options.contextExtensions); RETURN_IF_EXCEPTION(scope, {}); if (hasContextExtensions) { auto* contextExtensionsArray = dynamicDowncast(options.contextExtensions); unsigned length = contextExtensionsArray ? contextExtensionsArray->length() : 0; if (length > 0) { // Get the global scope from the parsing context JSScope* currentScope = options.parsingContext->globalScope(); // Create JSWithScope objects for each context extension for (unsigned i = 0; i < length; i++) { JSValue extension = contextExtensionsArray->getIndex(globalObject, i); RETURN_IF_EXCEPTION(scope, {}); if (extension.isObject()) { JSObject* extensionObject = asObject(extension); currentScope = JSWithScope::create(vm, options.parsingContext, currentScope, extensionObject); } } // Use the outermost JSWithScope as our function scope functionScope = currentScope; } } options.parsingContext->setGlobalScopeExtension(functionScope); // Create the function using constructAnonymousFunction with the appropriate scope chain JSFunction* function = constructAnonymousFunction(globalObject, ArgList(constructFunctionArgs), sourceOrigin, WTF::move(options), JSC::SourceTaintedOrigin::Untainted, functionScope); RETURN_IF_EXCEPTION(scope, {}); if (!function) { return throwVMError(globalObject, scope, "Failed to compile function"_s); } fetcher->owner(vm, function); ensureStillAliveHere(importer); if (!function) { return throwVMError(globalObject, scope, "Failed to compile function"_s); } return JSValue::encode(function); } JSC_DEFINE_HOST_FUNCTION(vmModule_createContext, (JSGlobalObject * globalObject, CallFrame* callFrame)) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); NodeVMContextOptions contextOptions {}; JSValue contextArg = callFrame->argument(0); JSObject* sandbox; if (!getContextArg(globalObject, contextArg, sandbox)) { return ERR::INVALID_ARG_TYPE(scope, globalObject, "context"_s, "object"_s, contextArg); } JSValue optionsArg = callFrame->argument(1); if (!optionsArg.isUndefined()) { V::validateObject(scope, globalObject, optionsArg, "options"_s); RETURN_IF_EXCEPTION(scope, {}); } JSValue importer; getNodeVMContextOptions(globalObject, vm, scope, optionsArg, contextOptions, optionNames(vm).codeGeneration(vm), &importer); RETURN_IF_EXCEPTION(scope, {}); if (sandbox && isContext(globalObject, sandbox)) { return JSValue::encode(sandbox); } auto* zigGlobalObject = defaultGlobalObject(globalObject); auto* targetContext = NodeVMGlobalObject::create(vm, contextOptions, importer, sandbox); RETURN_IF_EXCEPTION(scope, {}); if (sandbox) { // Store context in WeakMap for isContext checks zigGlobalObject->vmModuleContextMap()->set(vm, sandbox, targetContext); } return JSValue::encode(targetContext->contextObject()); } JSC_DEFINE_HOST_FUNCTION(vmModule_isContext, (JSGlobalObject * globalObject, CallFrame* callFrame)) { ArgList args(callFrame); JSValue contextArg = callFrame->argument(0); VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!contextArg || !contextArg.isObject()) { return ERR::INVALID_ARG_TYPE(scope, globalObject, "object"_s, "object"_s, contextArg); } return JSValue::encode(jsBoolean(isContext(globalObject, contextArg))); } const ClassInfo NodeVMGlobalObject::s_info = { "NodeVMGlobalObject"_s, &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(NodeVMGlobalObject) }; bool NodeVMGlobalObject::deleteProperty(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, JSC::DeletePropertySlot& slot) { auto* thisObject = uncheckedDowncast(cell); if (!thisObject->m_sandbox) [[unlikely]] { return Base::deleteProperty(cell, globalObject, propertyName, slot); } VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); if (!isSafeToForwardToContextifiedObject(globalObject, scope)) [[unlikely]] return false; auto* sandbox = thisObject->m_sandbox.get(); bool deleted = sandbox->methodTable()->deleteProperty(sandbox, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, false); if (!deleted) { return false; } RELEASE_AND_RETURN(scope, Base::deleteProperty(cell, globalObject, propertyName, slot)); } bool NodeVMGlobalObject::setPrototype(JSObject* object, JSGlobalObject* globalObject, JSValue prototype, bool shouldThrowIfCantSet) { VM& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* globalThis = uncheckedDowncast(object)->globalThis(); // JSC's cycle check looks for `object` in the chain, but user code can only put its JSGlobalProxy (globalThis) there. for (JSValue next = prototype; next.isObject() && asObject(next)->type() != ProxyObjectType; next = asObject(next)->getPrototypeDirect()) { if (next == globalThis) return typeError(globalObject, scope, shouldThrowIfCantSet, "cyclic __proto__ value"_s); } bool didSet = Base::setPrototype(object, globalObject, prototype, shouldThrowIfCantSet); RETURN_IF_EXCEPTION(scope, false); // Keep the proxy's stored prototype in sync, since JSC's cycle check walks through it. if (didSet && globalThis->getPrototypeDirect() != prototype) globalThis->setPrototypeDirect(vm, prototype); return didSet; } static JSPromise* moduleLoaderImportModuleInner(NodeVMGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSString* moduleName, RefPtr parameters, const JSC::SourceOrigin& sourceOrigin) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); auto* promise = JSPromise::create(vm, globalObject->promiseStructure()); if (sourceOrigin.fetcher() == nullptr && sourceOrigin.url().isEmpty()) { if (globalObject->dynamicImportCallback().isCallable()) { RELEASE_AND_RETURN(scope, NodeVM::importModuleInner(globalObject, moduleName, WTF::move(parameters), sourceOrigin, globalObject->dynamicImportCallback(), JSValue {})); } promise->reject(vm, createError(globalObject, ErrorCode::ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING, "A dynamic import callback was not specified."_s)); return promise; } // Default behavior copied from JSModuleLoader::importModule auto moduleNameString = moduleName->value(globalObject); RETURN_IF_EXCEPTION(scope, promise->rejectWithCaughtException(vm, scope)); scope.release(); // The specifier comes from JS. Past `String::MaxLength`, `makeString` calls `CRASH()` and `tryMakeString` returns null. auto message = tryMakeString("Could not import the module '"_s, moduleNameString.data, "'."_s); if (!message) [[unlikely]] promise->reject(vm, createOutOfMemoryError(globalObject)); else promise->reject(vm, createError(globalObject, message)); return promise; } JSPromise* NodeVMGlobalObject::moduleLoaderImportModule(JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSString* moduleName, RefPtr parameters, const JSC::SourceOrigin& sourceOrigin, bool deferred) { UNUSED_PARAM(deferred); auto* nodeVmGlobalObject = static_cast(globalObject); VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSPromise* result = NodeVM::importModule(nodeVmGlobalObject, moduleName, parameters, sourceOrigin); // importModule runs the user's dynamic-import callback, which can throw // and leave a null result; surface that as a rejected promise instead of // falling through with the exception pending. if (scope.exception()) [[unlikely]] { auto* promise = JSPromise::create(vm, globalObject->promiseStructure()); return promise->rejectWithCaughtException(vm, scope); } if (result) { return result; } RELEASE_AND_RETURN(scope, moduleLoaderImportModuleInner(nodeVmGlobalObject, moduleLoader, moduleName, WTF::move(parameters), sourceOrigin)); } void NodeVMGlobalObject::getOwnPropertyNames(JSObject* cell, JSGlobalObject* globalObject, JSC::PropertyNameArrayBuilder& propertyNames, JSC::DontEnumPropertiesMode mode) { auto& vm = JSC::getVM(globalObject); auto scope = DECLARE_THROW_SCOPE(vm); auto* thisObject = uncheckedDowncast(cell); if (thisObject->m_sandbox) { if (!isSafeToForwardToContextifiedObject(globalObject, scope)) [[unlikely]] return; thisObject->m_sandbox->methodTable()->getOwnPropertyNames(thisObject->m_sandbox.get(), globalObject, propertyNames, mode); RETURN_IF_EXCEPTION(scope, ); } RELEASE_AND_RETURN(scope, Base::getOwnPropertyNames(cell, globalObject, propertyNames, mode)); } JSC_DEFINE_HOST_FUNCTION(vmIsModuleNamespaceObject, (JSGlobalObject * globalObject, CallFrame* callFrame)) { JSValue argument = callFrame->argument(0); return JSValue::encode(jsBoolean(argument.inherits(JSModuleNamespaceObject::info()) || (argument.isCell() && JSC::AOT::isModuleNamespace(argument.asCell())))); } JSC::JSValue createNodeVMBinding(Zig::GlobalObject* globalObject) { VM& vm = globalObject->vm(); auto* obj = constructEmptyObject(globalObject); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "Script"_s)), defaultGlobalObject(globalObject)->NodeVMScript(), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "Module"_s)), defaultGlobalObject(globalObject)->NodeVMSourceTextModule(), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "createContext"_s)), JSC::JSFunction::create(vm, globalObject, 0, "createContext"_s, vmModule_createContext, ImplementationVisibility::Public, Intrinsic::NoIntrinsic, vmModule_createContext), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "isContext"_s)), JSC::JSFunction::create(vm, globalObject, 0, "isContext"_s, vmModule_isContext, ImplementationVisibility::Public), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "compileFunction"_s)), JSC::JSFunction::create(vm, globalObject, 0, "compileFunction"_s, vmModuleCompileFunction, ImplementationVisibility::Public), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "isModuleNamespaceObject"_s)), JSC::JSFunction::create(vm, globalObject, 0, "isModuleNamespaceObject"_s, vmIsModuleNamespaceObject, ImplementationVisibility::Public), 1); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "kLinked"_s)), JSC::jsNumber(static_cast(NodeVMSourceTextModule::Status::Linked)), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "kEvaluated"_s)), JSC::jsNumber(static_cast(NodeVMSourceTextModule::Status::Evaluated)), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "kErrored"_s)), JSC::jsNumber(static_cast(NodeVMSourceTextModule::Status::Errored)), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "DONT_CONTEXTIFY"_s)), globalObject->m_nodeVMDontContextify.get(globalObject), 0); obj->putDirect( vm, JSC::PropertyName(JSC::Identifier::fromString(vm, "USE_MAIN_CONTEXT_DEFAULT_LOADER"_s)), globalObject->m_nodeVMUseMainContextDefaultLoader.get(globalObject), 0); return obj; } void configureNodeVM(JSC::VM& vm, Zig::GlobalObject* globalObject) { globalObject->m_nodeVMDontContextify.initLater([](const LazyProperty::Initializer& init) { init.set(JSC::Symbol::createWithDescription(init.vm, "vm_dont_contextify"_s)); }); globalObject->m_nodeVMUseMainContextDefaultLoader.initLater([](const LazyProperty::Initializer& init) { init.set(JSC::Symbol::createWithDescription(init.vm, "vm_use_main_context_default_loader"_s)); }); globalObject->m_NodeVMScriptClassStructure.initLater( [](LazyClassStructure::Initializer& init) { auto prototype = NodeVMScript::createPrototype(init.vm, init.global); auto* structure = NodeVMScript::createStructure(init.vm, init.global, prototype); auto* constructorStructure = NodeVMScriptConstructor::createStructure( init.vm, init.global, init.global->m_functionPrototype.get()); auto* constructor = NodeVMScriptConstructor::create( init.vm, init.global, constructorStructure, prototype); init.setPrototype(prototype); init.setStructure(structure); init.setConstructor(constructor); }); globalObject->m_NodeVMSourceTextModuleClassStructure.initLater( [](LazyClassStructure::Initializer& init) { auto prototype = NodeVMSourceTextModule::createPrototype(init.vm, init.global); auto* structure = NodeVMSourceTextModule::createStructure(init.vm, init.global, prototype); auto* constructorStructure = NodeVMModuleConstructor::createStructure( init.vm, init.global, init.global->m_functionPrototype.get()); auto* constructor = NodeVMModuleConstructor::create( init.vm, init.global, constructorStructure, prototype); init.setPrototype(prototype); init.setStructure(structure); init.setConstructor(constructor); }); globalObject->m_NodeVMSyntheticModuleClassStructure.initLater( [](LazyClassStructure::Initializer& init) { auto prototype = NodeVMSyntheticModule::createPrototype(init.vm, init.global); auto* structure = NodeVMSyntheticModule::createStructure(init.vm, init.global, prototype); auto* constructorStructure = NodeVMModuleConstructor::createStructure( init.vm, init.global, init.global->m_functionPrototype.get()); auto* constructor = NodeVMModuleConstructor::create( init.vm, init.global, constructorStructure, prototype); init.setPrototype(prototype); init.setStructure(structure); init.setConstructor(constructor); }); } BaseVMOptions::BaseVMOptions(String filename) : filename(WTF::move(filename)) { } bool BaseVMOptions::fromJS(JSC::JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSC::JSValue optionsArg) { JSObject* options = nullptr; bool any = false; if (!optionsArg.isUndefined()) { V::validateObject(scope, globalObject, optionsArg, "options"_s); RETURN_IF_EXCEPTION(scope, false); options = asObject(optionsArg); auto filenameOpt = options->getIfPropertyExists(globalObject, builtinNames(vm).filenamePublicName()); RETURN_IF_EXCEPTION(scope, false); if (filenameOpt) { if (filenameOpt.isString()) { this->filename = filenameOpt.toWTFString(globalObject); RETURN_IF_EXCEPTION(scope, false); this->filenameProvided = true; any = true; } else if (!filenameOpt.isUndefined()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.filename"_s, "string"_s, filenameOpt); return false; } } else { this->filename = "evalmachine."_s; } auto lineOffsetOpt = options->getIfPropertyExists(globalObject, optionNames(vm).lineOffset(vm)); RETURN_IF_EXCEPTION(scope, false); if (lineOffsetOpt) { if (lineOffsetOpt.isAnyInt()) { if (!lineOffsetOpt.isInt32()) { ERR::OUT_OF_RANGE(scope, globalObject, "options.lineOffset"_s, std::numeric_limits().min(), std::numeric_limits().max(), lineOffsetOpt); return false; } this->lineOffset = OrdinalNumber::fromZeroBasedInt(lineOffsetOpt.asInt32()); any = true; } else if (lineOffsetOpt.isNumber()) { ERR::OUT_OF_RANGE(scope, globalObject, "options.lineOffset"_s, "an integer"_s, lineOffsetOpt); return false; } else if (!lineOffsetOpt.isUndefined()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.lineOffset"_s, "number"_s, lineOffsetOpt); return false; } } auto columnOffsetOpt = options->getIfPropertyExists(globalObject, optionNames(vm).columnOffset(vm)); RETURN_IF_EXCEPTION(scope, false); if (columnOffsetOpt) { if (columnOffsetOpt.isAnyInt()) { if (!columnOffsetOpt.isInt32()) { ERR::OUT_OF_RANGE(scope, globalObject, "options.columnOffset"_s, std::numeric_limits().min(), std::numeric_limits().max(), columnOffsetOpt); return false; } int columnOffsetValue = columnOffsetOpt.asInt32(); this->columnOffset = OrdinalNumber::fromZeroBasedInt(columnOffsetValue); any = true; } else if (columnOffsetOpt.isNumber()) { ERR::OUT_OF_RANGE(scope, globalObject, "options.columnOffset"_s, "an integer"_s, columnOffsetOpt); return false; } else if (!columnOffsetOpt.isUndefined()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.columnOffset"_s, "number"_s, columnOffsetOpt); return false; } } } return any; } bool BaseVMOptions::validateProduceCachedData(JSC::JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSObject* options, bool& outProduceCachedData) { JSValue produceCachedDataOpt = options->getIfPropertyExists(globalObject, optionNames(vm).produceCachedData(vm)); RETURN_IF_EXCEPTION(scope, false); if (produceCachedDataOpt && !produceCachedDataOpt.isUndefined()) { if (!produceCachedDataOpt.isBoolean()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.produceCachedData"_s, "boolean"_s, produceCachedDataOpt); return false; } outProduceCachedData = produceCachedDataOpt.asBoolean(); return true; } return false; } bool BaseVMOptions::validateCachedData(JSC::JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSObject* options, WTF::Vector& outCachedData) { JSValue cachedDataOpt = options->getIfPropertyExists(globalObject, optionNames(vm).cachedData(vm)); RETURN_IF_EXCEPTION(scope, {}); if (cachedDataOpt && !cachedDataOpt.isUndefined()) { // Verify it's a Buffer, TypedArray or DataView and extract the data if it is. if (extractCachedData(cachedDataOpt, outCachedData)) { return true; } ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.cachedData"_s, "Buffer, TypedArray, or DataView"_s, cachedDataOpt); } return false; } bool BaseVMOptions::validateTimeout(JSC::JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSObject* options, std::optional& outTimeout) { JSValue timeoutOpt = options->getIfPropertyExists(globalObject, optionNames(vm).timeout(vm)); RETURN_IF_EXCEPTION(scope, false); if (timeoutOpt && !timeoutOpt.isUndefined()) { if (!timeoutOpt.isNumber()) { ERR::INVALID_ARG_TYPE(scope, globalObject, "options.timeout"_s, "number"_s, timeoutOpt); return false; } ssize_t timeoutValue; V::validateInteger(scope, globalObject, timeoutOpt, "options.timeout"_s, jsNumber(1), jsNumber(std::numeric_limits().max()), &timeoutValue); RETURN_IF_EXCEPTION(scope, {}); outTimeout = timeoutValue; return true; } return false; } bool CompileFunctionOptions::fromJS(JSC::JSGlobalObject* globalObject, JSC::VM& vm, JSC::ThrowScope& scope, JSC::JSValue optionsArg, JSValue* importer) { if (importer) { *importer = jsUndefined(); } this->parsingContext = globalObject; bool any = BaseVMOptions::fromJS(globalObject, vm, scope, optionsArg); RETURN_IF_EXCEPTION(scope, false); // Node's compileFunction defaults filename to the empty string, unlike // `new Script` which defaults to "evalmachine." (the default // BaseVMOptions::fromJS applies). Reset so both compileFunction call // shapes (with and without an options object) render the same origin. if (!this->filenameProvided) this->filename = String(); if (!optionsArg.isUndefined() && !optionsArg.isString()) { JSObject* options = asObject(optionsArg); if (validateProduceCachedData(globalObject, vm, scope, options, this->produceCachedData)) any = true; // The validators return false both for "absent" and for "threw". RETURN_IF_EXCEPTION(scope, false); if (validateCachedData(globalObject, vm, scope, options, this->cachedData)) { this->cachedDataProvided = true; any = true; } RETURN_IF_EXCEPTION(scope, false); JSValue parsingContextValue = options->getIfPropertyExists(globalObject, optionNames(vm).parsingContext(vm)); RETURN_IF_EXCEPTION(scope, {}); if (!parsingContextValue.isEmpty() && !parsingContextValue.isUndefined()) { if (parsingContextValue.isNull() || !parsingContextValue.isObject()) return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.parsingContext"_s, "Context"_s, parsingContextValue); parsingContext = globalObjectOfContextObject(globalObject, asObject(parsingContextValue)); if (!parsingContext) return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.parsingContext"_s, "Context"_s, parsingContextValue); any = true; } // Handle contextExtensions option JSValue contextExtensionsValue = options->getIfPropertyExists(globalObject, optionNames(vm).contextExtensions(vm)); RETURN_IF_EXCEPTION(scope, {}); if (!contextExtensionsValue.isEmpty() && !contextExtensionsValue.isUndefined()) { if (contextExtensionsValue.isNull() || !contextExtensionsValue.isObject()) return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.contextExtensions"_s, "Array"_s, contextExtensionsValue); if (auto* contextExtensionsObject = asObject(contextExtensionsValue)) { bool contextExtensionsIsArray = isArray(globalObject, contextExtensionsObject); RETURN_IF_EXCEPTION(scope, {}); if (!contextExtensionsIsArray) return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.contextExtensions"_s, "Array"_s, contextExtensionsValue); // Validate that all items in the array are objects auto* contextExtensionsArray = dynamicDowncast(contextExtensionsValue); if (!contextExtensionsArray) [[unlikely]] { // isArray() accepts Proxy->Array, but jsDynamicCast returns null. return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.contextExtensions"_s, "Array"_s, contextExtensionsValue); } unsigned length = contextExtensionsArray->length(); for (unsigned i = 0; i < length; i++) { JSValue extension = contextExtensionsArray->getIndex(globalObject, i); RETURN_IF_EXCEPTION(scope, {}); if (!extension.isObject()) return ERR::INVALID_ARG_TYPE(scope, globalObject, "options.contextExtensions[0]"_s, "object"_s, extension); } } else { return ERR::INVALID_ARG_INSTANCE(scope, globalObject, "options.contextExtensions"_s, "Array"_s, contextExtensionsValue); } this->contextExtensions = contextExtensionsValue; any = true; } // Handle importModuleDynamically option JSValue importModuleDynamicallyValue = options->getIfPropertyExists(globalObject, optionNames(vm).importModuleDynamically(vm)); RETURN_IF_EXCEPTION(scope, {}); if (importModuleDynamicallyValue && (importModuleDynamicallyValue.isCallable() || isUseMainContextDefaultLoaderConstant(globalObject, importModuleDynamicallyValue))) { if (importer) { *importer = importModuleDynamicallyValue; } any = true; } } return any; } } // namespace Bun