From d63cb26a6fc4a44e91e70abc96091c96406dd385 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 08:39:38 +0000 Subject: [PATCH 1/8] Resolve runtime-provided globals in builtin modules to the intrinsic, not globalThis Builtin JS modules read constructors like MessagePort, Blob, URL and objects like crypto from the mutable global, so user code that replaced or deleted one before a builtin loaded (happy-dom's GlobalRegistrator does) could break or hijack it. `new Worker()` from node:worker_threads threw "port.on is not a function" once globalThis.MessagePort was replaced (#40268). Node's lib/ takes these from internalBinding() and derives the globals from them, so a replaced global never reaches its internals. Do the same: - The builtin bundler rewrites every global in ZigGlobalObject.lut.txt whose value is a runtime-created object (constructors, process, crypto, ...) to @Name, the way it already did for a hand-picked list of stream classes. - Zig::GlobalObject::getOwnPropertySlot resolves a private @Name that misses to the same static-table entry globalThis.Name was initialized from and reifies it under the private name, so steady-state access is a direct property load. This replaces the per-name custom getters that were installed at startup for the old list. - worker_threads, worker messaging, node:crypto and node:inspector stop reading globalThis.* explicitly. Build: BunBuiltinNames+extras.h is now a declared codegen output and codegen headers are implicit (not order-only) PCH inputs, so a regenerated header rebuilds the PCH in the same run instead of one build later. --- scripts/build/bun.ts | 27 ++++--- scripts/build/codegen.ts | 12 ++-- scripts/build/compile.ts | 24 +++---- src/codegen/bundle-functions.ts | 8 +-- src/codegen/bundle-modules.ts | 3 +- src/codegen/replacements.ts | 43 ++++++------ src/js/builtins.d.ts | 4 ++ src/js/builtins/BunBuiltinNames.h | 12 ---- src/js/internal/worker/messaging.ts | 2 +- src/js/node/crypto.ts | 3 - src/js/node/inspector.ts | 2 +- src/js/node/worker_threads.ts | 23 +++--- src/jsc/bindings/ZigGlobalObject.cpp | 70 ++++++++++--------- src/jsc/bindings/ZigGlobalObject.h | 1 + .../bun/builtin-intrinsic-globals-fixture.js | 46 ++++++++++++ test/js/bun/globals.test.js | 16 +++++ test/regression/issue/40268.test.ts | 28 ++++++++ 17 files changed, 200 insertions(+), 124 deletions(-) create mode 100644 test/js/bun/builtin-intrinsic-globals-fixture.js create mode 100644 test/regression/issue/40268.test.ts diff --git a/scripts/build/bun.ts b/scripts/build/bun.ts index d83626605249..00ddf4cb8db5 100644 --- a/scripts/build/bun.ts +++ b/scripts/build/bun.ts @@ -279,23 +279,22 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput { if (usePch) { n.comment("─── PCH ───"); n.blank(); - // Dep outputs are IMPLICIT inputs (not order-only). The crucial case is - // local WebKit: headers live in buildDir and get REGENERATED by dep_build - // mid-run. At startup, ninja sees old headers via PCH's depfile → thinks - // PCH is fresh. dep_build then regenerates them. cxx fails with "file - // modified since PCH was built". As implicit inputs, restat sees the .a - // changed → PCH rebuilds → one-build convergence. See the pch() docstring. + // Dep outputs and codegen headers are IMPLICIT inputs (not order-only): + // both are regenerated mid-run (local WebKit headers by dep_build, codegen + // headers by their step), and the PCH's depfile records them by absolute + // path, which is not the node the producing edge declares. At startup ninja + // sees the old header → thinks the PCH is fresh → cxx compiles against a + // stale PCH (or fails with "file modified since PCH was built"). As + // implicit inputs, restat sees the regenerated file → PCH rebuilds in the + // same run. See the pch() docstring. // - // Codegen stays order-only: those outputs only change if inputs change, - // and inputs don't change mid-build. cppAll (not all) — bake/.rs outputs - // are rust-only; pulling them here would run bake-codegen in cpp-only CI - // mode where it fails on the pinned bun version (see cppAll docstring). - // Scripts that emit undeclared .h also emit a .cpp/.h in cppAll, so they - // still run. cxx transitively waits: cxx → PCH → deps+cppAll. + // cppAll (not all) — bake/.rs outputs are rust-only; pulling them here + // would run bake-codegen in cpp-only CI mode where it fails on the pinned + // bun version (see cppAll docstring). cxx transitively waits: cxx → PCH → + // deps+cppAll. pchOut = pch(n, cfg, "src/jsc/bindings/root-pch.h", { flags: cxxFlagsFull, - implicitInputs: depHeaderSignal, - orderOnlyInputs: codegen.cppAll, + implicitInputs: [...depHeaderSignal, ...codegen.cppAll], }); } diff --git a/scripts/build/codegen.ts b/scripts/build/codegen.ts index ab631c95be34..38801a6fd802 100644 --- a/scripts/build/codegen.ts +++ b/scripts/build/codegen.ts @@ -26,9 +26,7 @@ * the per-file Generated*.h headers and not just the .cpp that gets compiled. * * Files nothing compiles may stay undeclared (.d.ts twins, bundle-modules' - * eval/ dir, JSSink.lut.txt consumed within its own step). The remaining - * #included exception is BunBuiltinNames+extras.h from bundle-functions.ts, - * reached through the PCH. + * eval/ dir, JSSink.lut.txt consumed within its own step). */ import { spawnSync } from "node:child_process"; @@ -759,10 +757,16 @@ function emitJsModules({ n, cfg, sources, o, dirStamp }: Ctx): void { // ($makeErrorWithCode(N, ...)); without this dep an ErrorCode.ts edit leaves // stale error numbers in the JS bundles while the C++ enum regenerates. const errorCodeInput = resolve(cfg.cwd, "src", "jsc", "bindings", "ErrorCode.ts"); + // replacements.ts derives the @Name intrinsic globals from this table, and + // bundle-functions.ts emits BunBuiltinNames+extras.h as the ones missing from + // BunBuiltinNames.h. + const globalObjectTableInput = resolve(cfg.cwd, "src", "jsc", "bindings", "ZigGlobalObject.lut.txt"); + const builtinNamesInput = resolve(cfg.cwd, "src", "js", "builtins", "BunBuiltinNames.h"); const outputs = [ resolve(cfg.codegenDir, "WebCoreJSBuiltins.cpp"), resolve(cfg.codegenDir, "WebCoreJSBuiltins.h"), + resolve(cfg.codegenDir, "BunBuiltinNames+extras.h"), resolve(cfg.codegenDir, "InternalModuleRegistryConstants.h"), resolve(cfg.codegenDir, "InternalModuleRegistry+createInternalModuleById.h"), resolve(cfg.codegenDir, "InternalModuleRegistry+enum.h"), @@ -785,7 +789,7 @@ function emitJsModules({ n, cfg, sources, o, dirStamp }: Ctx): void { n.build({ outputs, rule: "codegen", - inputs: [script, ...sources.js, ...sources.jsCodegen, extraInput, errorCodeInput], + inputs: [script, ...sources.js, ...sources.jsCodegen, extraInput, errorCodeInput, globalObjectTableInput, builtinNamesInput], orderOnlyInputs: [dirStamp], vars: { cwd: cfg.cwd, diff --git a/scripts/build/compile.ts b/scripts/build/compile.ts index fc6cbe776170..bf160243ce7a 100644 --- a/scripts/build/compile.ts +++ b/scripts/build/compile.ts @@ -358,25 +358,23 @@ export function pch( opts: { flags: string[]; /** - * Files whose change must invalidate the PCH. Typically: dep output - * libs (libJavaScriptCore.a etc.). + * Files whose change must invalidate the PCH: dep output libs + * (libJavaScriptCore.a etc.) and generated headers. * - * Can't be order-only: the depfile tracks headers, but ninja stats at - * startup. Local WebKit headers live in buildDir and get regenerated - * by dep_build MID-RUN. At startup ninja sees old headers → thinks - * PCH is fresh → cxx fails with "file modified since PCH was built" - * → needs a second build. With these implicit, restat propagates the - * lib change to PCH and it rebuilds in the same run. + * Can't be order-only: the depfile tracks headers, but ninja stats them + * at startup and records them by absolute path (a different node from + * the producing edge's declared output). Anything regenerated MID-RUN — + * local WebKit headers by dep_build, codegen headers by their step — + * leaves the PCH looking fresh → cxx builds against a stale PCH or fails + * with "file modified since PCH was built" → needs a second build. With + * these implicit, restat propagates the change to the PCH and it + * rebuilds in the same run. * * Cost: PCH also rebuilds on unrelated dep bumps (brotli etc.). Rare * enough to accept for correctness. */ implicitInputs?: string[]; - /** - * Must exist before PCH compiles; changes don't invalidate it. - * Codegen outputs go here — they only change when inputs change, - * and inputs don't change mid-build. - */ + /** Must exist before PCH compiles; changes don't invalidate it. */ orderOnlyInputs?: string[]; }, ): { pch: string; wrapperHeader: string } { diff --git a/src/codegen/bundle-functions.ts b/src/codegen/bundle-functions.ts index b98c60532043..b2add47251ad 100644 --- a/src/codegen/bundle-functions.ts +++ b/src/codegen/bundle-functions.ts @@ -49,7 +49,7 @@ import { sliceSourceCode } from "./builtin-parser"; import { createAssertClientJS, createLogClientJS } from "./client-js"; import { getJS2NativeDTS } from "./generate-js2native"; import { cap, checkAscii, low, writeIfNotChanged } from "./helpers"; -import { applyGlobalReplacements, define } from "./replacements"; +import { applyGlobalReplacements, define, intrinsicGlobals } from "./replacements"; const PARALLEL = false; const KEEP_TMP = true; @@ -329,8 +329,7 @@ $$capture_start$$(${fn.async ? "async " : ""}${ (usesAssert ? createAssertClientJS(fn.name) : ""), ) .replace(/^\((async )?function\(/, "($1function (") - .replace(/__intrinsic__/g, "@") - .replace(/__no_intrinsic__/g, "") + "\n"; + .replace(/__intrinsic__/g, "@") + "\n"; const errors = [...finalReplacement.matchAll(/@bundleError\((.*)\)/g)]; if (errors.length) { @@ -415,7 +414,8 @@ export async function bundleBuiltinFunctions({ requireTransformer }: BundleBuilt } const combinedSourceCodeLength = combinedSourceCode.length; - let additionalPrivateNames = new Set(); + // Every @Name a builtin can reference must exist as a private symbol. + let additionalPrivateNames = new Set(intrinsicGlobals); function privateName(name) { additionalPrivateNames.add(name); diff --git a/src/codegen/bundle-modules.ts b/src/codegen/bundle-modules.ts index 6f5f9909faf8..71df5431b9a2 100644 --- a/src/codegen/bundle-modules.ts +++ b/src/codegen/bundle-modules.ts @@ -261,8 +261,7 @@ for (const entrypoint of bundledEntryPoints) { throw new Error(`Builtin Bundler: do not use import.meta.require() (in ${file_path}))`); }) .replace(/return \$\nexport /, "return") - .replace(/__intrinsic__/g, "@") - .replace(/__no_intrinsic__/g, "") + "\n"; + .replace(/__intrinsic__/g, "@") + "\n"; captured = captured.replace( /function\s*\(.*?\)\s*{/, '$&"use strict";' + diff --git a/src/codegen/replacements.ts b/src/codegen/replacements.ts index 3aaf4f3132c0..d8159ed34dee 100644 --- a/src/codegen/replacements.ts +++ b/src/codegen/replacements.ts @@ -1,3 +1,5 @@ +import { readFileSync } from "node:fs"; +import path from "node:path"; import NodeErrors from "../jsc/bindings/ErrorCode.ts"; import jsclasses from "./../jsc/bindings/js_classes"; import { sliceSourceCode } from "./builtin-parser"; @@ -51,40 +53,39 @@ export const globalReplacements: ReplacementRule[] = [ }, ]; -// This is a list of globals we should access using @ notation -// This prevents a global override attacks. -// Note that the public `Bun` global is immutable. +// Globals from ZigGlobalObject.lut.txt whose value is an object the runtime +// creates (constructors, `process`, `crypto`, ...). Builtins reference these as +// @Name, which Zig::GlobalObject::getOwnPropertySlot resolves to the original +// value even if user code replaced or deleted globalThis.Name — the same +// guarantee Node's lib/ gets from taking them off internalBinding(). +export const intrinsicGlobals = [ + ...readFileSync(path.join(import.meta.dir, "../jsc/bindings/ZigGlobalObject.lut.txt"), "utf8").matchAll( + /^\s+([A-Za-z]\w*)\s+(\S+)\s+(\S+)\s*$/gm, + ), +] + .filter( + ([, , value, attributes]) => + /\b(CellProperty|ClassStructure)\b/.test(attributes) || + (/\bPropertyCallback\b/.test(attributes) && value.endsWith("ConstructorCallback")), + ) + .map(([, name]) => name); + +// Globals builtins access as @Name so user code replacing globalThis.Name cannot +// reach them. The rest are provided by JSC. // undefined -> __intrinsic__undefined -> @undefined export const globalsToPrefix = [ - "AbortSignal", + ...intrinsicGlobals, "Array", "ArrayBuffer", - "Buffer", "Infinity", "Promise", - "ReadableByteStreamController", - "ReadableStream", - "ReadableStreamBYOBReader", - "ReadableStreamBYOBRequest", - "ReadableStreamDefaultController", - "ReadableStreamDefaultReader", - "TransformStream", - "TransformStreamDefaultController", "Uint8Array", "String", "RegExp", - "WritableStream", - "WritableStreamDefaultController", - "WritableStreamDefaultWriter", "isFinite", "undefined", ]; -replacements.push({ - from: new RegExp(`\\bextends\\s+(${globalsToPrefix.join("|")})`, "g"), - to: "extends __no_intrinsic__%1", -}); - // These enums map to $IdToLabel and $LabelToId (ids start at 1) // Make sure to define in ./builtins.d.ts export const enums = { diff --git a/src/js/builtins.d.ts b/src/js/builtins.d.ts index 6a79984312ae..eacde1786eb9 100644 --- a/src/js/builtins.d.ts +++ b/src/js/builtins.d.ts @@ -341,6 +341,10 @@ declare class ReadableStreamBYOBReader { constructor(stream: ReadableStream); } +// Globals the runtime creates (see intrinsicGlobals in codegen/replacements.ts) +// are rewritten to $Name automatically; spell $Name only where a local shadows it. +declare const $Worker: typeof Worker; + // Inlining our enum types declare const $ImportKindIdToLabel: Array; declare const $ImportKindLabelToId: Record; diff --git a/src/js/builtins/BunBuiltinNames.h b/src/js/builtins/BunBuiltinNames.h index e02f8edeb4cf..f80fd1dccf87 100644 --- a/src/js/builtins/BunBuiltinNames.h +++ b/src/js/builtins/BunBuiltinNames.h @@ -23,20 +23,8 @@ using namespace JSC; // Keep this list sorted. #define BUN_COMMON_PRIVATE_IDENTIFIERS_EACH_PROPERTY_NAME(macro) \ macro($$typeof) \ - macro(AbortSignal) \ macro(Buffer) \ - macro(ReadableByteStreamController) \ - macro(ReadableStream) \ - macro(ReadableStreamBYOBReader) \ - macro(ReadableStreamBYOBRequest) \ - macro(ReadableStreamDefaultController) \ - macro(ReadableStreamDefaultReader) \ macro(SQL) \ - macro(TransformStream) \ - macro(TransformStreamDefaultController) \ - macro(WritableStream) \ - macro(WritableStreamDefaultController) \ - macro(WritableStreamDefaultWriter) \ macro(_debugInfo) \ macro(_debugStack) \ macro(_debugTask) \ diff --git a/src/js/internal/worker/messaging.ts b/src/js/internal/worker/messaging.ts index 7b56cb37bd21..2a3bc0ae1f45 100644 --- a/src/js/internal/worker/messaging.ts +++ b/src/js/internal/worker/messaging.ts @@ -159,7 +159,7 @@ function receiveMessageFromWorker(source, value, memory) { // Bun half of Node's createMainThreadPort: create the channel linking a (future) // thread to the main thread. Called before `new Worker`. function createMessagingChannel() { - const { port1, port2 } = new globalThis.MessageChannel(); + const { port1, port2 } = new MessageChannel(); // port1 (portToMain) stays with the hub; port2 (portToWorker) is transferred to // the new thread where it becomes that thread's mainThreadPort. return { portToMain: port1, portToWorker: port2 }; diff --git a/src/js/node/crypto.ts b/src/js/node/crypto.ts index 4590f1cd35e5..220e188b131f 100644 --- a/src/js/node/crypto.ts +++ b/src/js/node/crypto.ts @@ -108,7 +108,6 @@ Certificate.verifySpkac = verifySpkac; Certificate.exportPublicKey = exportPublicKey; Certificate.exportChallenge = exportChallenge; -var Buffer = globalThis.Buffer; const { isAnyArrayBuffer, isArrayBufferView } = require("node:util/types"); function getArrayBufferOrView(buffer, name, encoding?) { @@ -123,8 +122,6 @@ function getArrayBufferOrView(buffer, name, encoding?) { return buffer; } -const crypto = globalThis.crypto; - var crypto_exports: any = {}; crypto_exports.getRandomValues = value => crypto.getRandomValues(value); diff --git a/src/js/node/inspector.ts b/src/js/node/inspector.ts index a785edc54bea..118e0d9ae606 100644 --- a/src/js/node/inspector.ts +++ b/src/js/node/inspector.ts @@ -57,7 +57,7 @@ function open(port?: number, host?: string, wait?: boolean) { const hostname = typeof host === "string" && host.length > 0 ? host : "127.0.0.1"; // Bracket bare IPv6 hosts so they survive URL parsing. const hostPart = hostname.includes(":") && !hostname.startsWith("[") ? `[${hostname}]` : hostname; - const requestedUrl = `ws://${hostPart}:${portNumber}/${globalThis.crypto.randomUUID()}`; + const requestedUrl = `ws://${hostPart}:${portNumber}/${crypto.randomUUID()}`; const disposable = { __proto__: null, diff --git a/src/js/node/worker_threads.ts b/src/js/node/worker_threads.ts index f60d8cd3d2cd..8d924a3e989e 100644 --- a/src/js/node/worker_threads.ts +++ b/src/js/node/worker_threads.ts @@ -52,16 +52,12 @@ function validateWorkerFilename(filename) { throw $ERR_WORKER_PATH(message); } -const { - MessageChannel, - BroadcastChannel, - Worker: WebWorker, -} = globalThis as typeof globalThis & { - // The Worker constructor secretly takes an extra parameter to provide the node:worker_threads - // instance. This is so that it can emit the `worker` event on the process with the - // node:worker_threads instance instead of the Web Worker instance. - Worker: new (...args: [...ConstructorParameters, nodeWorker: Worker]) => WebWorker; -}; +// The Worker constructor secretly takes an extra parameter to provide the node:worker_threads +// instance. This is so that it can emit the `worker` event on the process with the +// node:worker_threads instance instead of the Web Worker instance. +const WebWorker = $Worker as unknown as new ( + ...args: [...ConstructorParameters, nodeWorker: Worker] +) => WebWorker; const SHARE_ENV = Symbol.for("nodejs.worker_threads.SHARE_ENV"); const isMainThread = Bun.isMainThread; @@ -281,10 +277,7 @@ function injectFakeEmitter(Class) { Object.setPrototypeOf(proto, inherited); } -const _MessagePort = globalThis.MessagePort; -injectFakeEmitter(_MessagePort); - -const MessagePort = _MessagePort; +injectFakeEmitter(MessagePort); // node's close(cb) registers cb as a one-time "close" listener before the native close. // closedMessagePorts lets moveMessagePortToContext report ERR_CLOSED_MESSAGE_PORT. @@ -442,7 +435,7 @@ function packJSTransferables(options: NodeWorkerOptions): NodeWorkerOptions { item !== null && typeof item === "object" && !(item instanceof ArrayBuffer) && - !(item instanceof _MessagePort) && + !(item instanceof MessagePort) && !$isTypedArrayView(item) ) { hasCandidate = true; diff --git a/src/jsc/bindings/ZigGlobalObject.cpp b/src/jsc/bindings/ZigGlobalObject.cpp index 63b7abb9fd65..06d5b9a60105 100644 --- a/src/jsc/bindings/ZigGlobalObject.cpp +++ b/src/jsc/bindings/ZigGlobalObject.cpp @@ -866,16 +866,10 @@ JSC_DEFINE_HOST_FUNCTION(functionEsmLoadSync, (JSC::JSGlobalObject * lexicalGlob return JSValue::encode(ns); } -#define WEBCORE_GENERATED_CONSTRUCTOR_GETTER(ConstructorName) \ - JSValue ConstructorName##ConstructorCallback(VM& vm, JSObject* lexicalGlobalObject) \ - { \ - return WebCore::JS##ConstructorName::getConstructor(vm, uncheckedDowncast(lexicalGlobalObject)); \ - } \ - JSC_DEFINE_CUSTOM_GETTER(ConstructorName##_getter, \ - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, \ - JSC::PropertyName)) \ - { \ - return JSC::JSValue::encode(WebCore::JS##ConstructorName::getConstructor(lexicalGlobalObject->vm(), uncheckedDowncast(lexicalGlobalObject))); \ +#define WEBCORE_GENERATED_CONSTRUCTOR_GETTER(ConstructorName) \ + JSValue ConstructorName##ConstructorCallback(VM& vm, JSObject* lexicalGlobalObject) \ + { \ + return WebCore::JS##ConstructorName::getConstructor(vm, uncheckedDowncast(lexicalGlobalObject)); \ } String GlobalObject::defaultAgentClusterID() @@ -1161,16 +1155,7 @@ WebCore::EventTarget& GlobalObject::eventTarget() return globalEventScope; } -JSC_DEFINE_CUSTOM_GETTER(JSBuffer_getter, - (JSC::JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, - JSC::PropertyName)) -{ - return JSC::JSValue::encode(uncheckedDowncast(lexicalGlobalObject)->JSBufferConstructor()); -} - -// This macro defines the getter needed for ZigGlobalObject.lut.h -// "ConstructorCallback" is a PropertyCallback -// it also defines "_getter" which is the getter for a JSC::CustomGetterSetter +// Defines the "ConstructorCallback" PropertyCallback for ZigGlobalObject.lut.h WEBCORE_GENERATED_CONSTRUCTOR_GETTER(AbortController); WEBCORE_GENERATED_CONSTRUCTOR_GETTER(AbortSignal); WEBCORE_GENERATED_CONSTRUCTOR_GETTER(BroadcastChannel); @@ -2877,20 +2862,6 @@ void GlobalObject::addBuiltinGlobals(JSC::VM& vm) NoIntrinsic, PropertyAttribute::ReadOnly | PropertyAttribute::DontDelete | 0); - putDirectCustomAccessor(vm, static_cast(vm.clientData)->builtinNames().BufferPrivateName(), JSC::CustomGetterSetter::create(vm, JSBuffer_getter, nullptr), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.TransformStreamPrivateName(), CustomGetterSetter::create(vm, TransformStream_getter, nullptr), attributesForStructure(static_cast(PropertyAttribute::DontEnum)) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.TransformStreamDefaultControllerPrivateName(), CustomGetterSetter::create(vm, TransformStreamDefaultController_getter, nullptr), attributesForStructure(static_cast(PropertyAttribute::DontEnum)) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.ReadableByteStreamControllerPrivateName(), CustomGetterSetter::create(vm, ReadableByteStreamController_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.ReadableStreamPrivateName(), CustomGetterSetter::create(vm, ReadableStream_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.ReadableStreamBYOBReaderPrivateName(), CustomGetterSetter::create(vm, ReadableStreamBYOBReader_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.ReadableStreamBYOBRequestPrivateName(), CustomGetterSetter::create(vm, ReadableStreamBYOBRequest_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.ReadableStreamDefaultControllerPrivateName(), CustomGetterSetter::create(vm, ReadableStreamDefaultController_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.ReadableStreamDefaultReaderPrivateName(), CustomGetterSetter::create(vm, ReadableStreamDefaultReader_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.WritableStreamPrivateName(), CustomGetterSetter::create(vm, WritableStream_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.WritableStreamDefaultControllerPrivateName(), CustomGetterSetter::create(vm, WritableStreamDefaultController_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.WritableStreamDefaultWriterPrivateName(), CustomGetterSetter::create(vm, WritableStreamDefaultWriter_getter, nullptr), attributesForStructure(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly) | PropertyAttribute::CustomValue); - putDirectCustomAccessor(vm, builtinNames.AbortSignalPrivateName(), CustomGetterSetter::create(vm, AbortSignal_getter, nullptr), PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly | PropertyAttribute::CustomValue); - // ----- Public Properties ----- // a direct accessor (uses js functions for get and set) cannot be on the lookup table. i think. @@ -4097,4 +4068,35 @@ extern "C" void WebWorker__teardownJSCVM(Zig::GlobalObject* globalObject) const JSC::ClassInfo GlobalObject::s_info = { "GlobalObject"_s, &Base::s_info, &bunGlobalObjectTable, nullptr, CREATE_METHOD_TABLE(GlobalObject) }; +// Builtin modules reference the globals in bunGlobalObjectTable as @Name (see +// intrinsicGlobals in src/codegen/replacements.ts). @Name resolves here to the +// table entry that globalThis.Name was initialized from, reified under the +// private name, so a replaced or deleted globalThis.Name never reaches builtins. +bool GlobalObject::getOwnPropertySlot(JSObject* object, JSGlobalObject* lexicalGlobalObject, PropertyName propertyName, PropertySlot& slot) +{ + if (Base::getOwnPropertySlot(object, lexicalGlobalObject, propertyName, slot)) + return true; + if (!propertyName.isPrivateName()) + return false; + + VM& vm = lexicalGlobalObject->vm(); + auto* uid = propertyName.uid(); + auto* entry = bunGlobalObjectTable.entry(uid->is8Bit() ? Identifier::fromString(vm, uid->span8()) : Identifier::fromString(vm, uid->span16())); + if (!entry || !(entry->attributes() & (PropertyAttribute::CellProperty | PropertyAttribute::ClassStructure | PropertyAttribute::PropertyCallback))) + return false; + + { + DeferTerminationForAWhile deferScope(vm); + reifyStaticProperty(vm, info(), propertyName, *entry, *object); + } + if (vm.exceptionForInspection()) [[unlikely]] + return false; + + unsigned attributes; + PropertyOffset offset = object->getDirectOffset(vm, propertyName, attributes); + ASSERT(isValidOffset(offset)); + slot.setValue(object, attributes, object->getDirect(offset), offset); + return true; +} + } // namespace Zig diff --git a/src/jsc/bindings/ZigGlobalObject.h b/src/jsc/bindings/ZigGlobalObject.h index 496ced5fd142..0001ca5faa64 100644 --- a/src/jsc/bindings/ZigGlobalObject.h +++ b/src/jsc/bindings/ZigGlobalObject.h @@ -128,6 +128,7 @@ class GlobalObject : public Bun::GlobalScope { ~GlobalObject(); static void destroy(JSC::JSCell*); + static bool getOwnPropertySlot(JSC::JSObject*, JSC::JSGlobalObject*, JSC::PropertyName, JSC::PropertySlot&); static constexpr const JSC::ClassInfo* info() { return &s_info; } diff --git a/test/js/bun/builtin-intrinsic-globals-fixture.js b/test/js/bun/builtin-intrinsic-globals-fixture.js new file mode 100644 index 000000000000..7a14576b6663 --- /dev/null +++ b/test/js/bun/builtin-intrinsic-globals-fixture.js @@ -0,0 +1,46 @@ +class Fake extends EventTarget { + constructor() { + super(); + throw new Error("builtin used a replaced global"); + } +} +for (const name of ["MessagePort", "MessageChannel", "BroadcastChannel", "Worker", "Blob", "AbortController", "TextDecoder", "Headers"]) { + globalThis[name] = Fake; +} +// Deleting a global reifies the whole static table; intrinsics must still resolve after that. +delete globalThis.URL; +delete globalThis.Event; +globalThis.crypto = { randomUUID: () => "fake" }; + +const wt = require("node:worker_threads"); +if (wt.MessagePort === Fake || wt.MessageChannel === Fake || wt.BroadcastChannel === Fake) throw new Error("worker_threads exported a replaced global"); +if (typeof wt.MessagePort.prototype.on !== "function") throw new Error("MessagePort.prototype.on missing"); +const { port1, port2 } = new wt.MessageChannel(); +port1.close(); +port2.close(); +const worker = new wt.Worker("require('node:worker_threads').parentPort.postMessage('hi')", { eval: true }); +const [message] = await require("node:events").once(worker, "message"); +if (message !== "hi") throw new Error("worker message: " + message); +await worker.terminate(); + +if (require("node:crypto").randomUUID() === "fake") throw new Error("node:crypto used a replaced globalThis.crypto"); + +const { Readable } = require("node:stream"); +const text = await require("node:stream/consumers").text(Readable.from([Buffer.from("abc")])); +if (text !== "abc") throw new Error("stream/consumers text: " + text); + +const http = require("node:http"); +const server = http.createServer((req, res) => res.end("ok")).listen(0); +await require("node:events").once(server, "listening"); +const body = await new Promise((resolve, reject) => { + http.get(`http://127.0.0.1:${server.address().port}/`, res => { + let data = ""; + res.setEncoding("utf8"); + res.on("data", chunk => (data += chunk)); + res.on("end", () => resolve(data)); + }).on("error", reject); +}); +server.close(); +if (body !== "ok") throw new Error("http body: " + body); + +console.log("ok"); diff --git a/test/js/bun/globals.test.js b/test/js/bun/globals.test.js index e4d50b8bccb4..08493f84abe1 100644 --- a/test/js/bun/globals.test.js +++ b/test/js/bun/globals.test.js @@ -206,6 +206,22 @@ it("globals are deletable", () => { expect(exitCode).toBe(0); }); +// Builtin modules take runtime-created globals (MessagePort, Blob, URL, crypto, ...) +// from the intrinsic, like Node's lib/ takes them from internalBinding(), so user +// code that replaces or deletes the global (e.g. happy-dom's registrator) cannot +// break or hijack them. https://github.com/oven-sh/bun/issues/40268 +it("builtin modules do not read replaceable globals", () => { + const { stdout, stderr, exitCode } = Bun.spawnSync({ + cmd: [bunExe(), path.join(import.meta.dir, "builtin-intrinsic-globals-fixture.js")], + env: bunEnv, + stderr: "pipe", + }); + + expect(stderr.toString()).toBe(""); + expect(stdout.toString()).toBe("ok\n"); + expect(exitCode).toBe(0); +}); + it("self is a getter", () => { const descriptor = Object.getOwnPropertyDescriptor(globalThis, "self"); expect(descriptor.get).toBeInstanceOf(Function); diff --git a/test/regression/issue/40268.test.ts b/test/regression/issue/40268.test.ts new file mode 100644 index 000000000000..d28cbcf0c7d3 --- /dev/null +++ b/test/regression/issue/40268.test.ts @@ -0,0 +1,28 @@ +import { expect, test } from "bun:test"; +import { bunEnv, bunExe } from "harness"; + +// https://github.com/oven-sh/bun/issues/40268 +// happy-dom's GlobalRegistrator replaces globalThis.MessagePort with its own +// EventTarget subclass before node:worker_threads loads; `new Worker()` then +// threw "port.on is not a function". +test("new Worker works after globalThis.MessagePort is replaced", async () => { + await using proc = Bun.spawn({ + cmd: [ + bunExe(), + "-e", + `globalThis.MessagePort = class MessagePort extends EventTarget {}; + const { Worker } = require("node:worker_threads"); + const worker = new Worker("require('node:worker_threads').parentPort.postMessage('hi')", { eval: true }); + worker.on("message", message => { + console.log(message); + worker.terminate(); + });`, + ], + env: bunEnv, + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stderr).toBe(""); + expect(stdout).toBe("hi\n"); + expect(exitCode).toBe(0); +}); From 0fb1063b4b24b183e97840c69d8ee33605f1e160 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 08:59:35 +0000 Subject: [PATCH 2/8] [autofix.ci] apply automated fixes --- scripts/build/codegen.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/scripts/build/codegen.ts b/scripts/build/codegen.ts index 38801a6fd802..8f5682824244 100644 --- a/scripts/build/codegen.ts +++ b/scripts/build/codegen.ts @@ -789,7 +789,15 @@ function emitJsModules({ n, cfg, sources, o, dirStamp }: Ctx): void { n.build({ outputs, rule: "codegen", - inputs: [script, ...sources.js, ...sources.jsCodegen, extraInput, errorCodeInput, globalObjectTableInput, builtinNamesInput], + inputs: [ + script, + ...sources.js, + ...sources.jsCodegen, + extraInput, + errorCodeInput, + globalObjectTableInput, + builtinNamesInput, + ], orderOnlyInputs: [dirStamp], vars: { cwd: cfg.cwd, From b0c349cdd310d83a3b701f318b2011a42e0069cf Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 09:03:49 +0000 Subject: [PATCH 3/8] test: assert subprocess stdout/stderr/exitCode together No-Verification-Needed: test-only change --- test/js/bun/globals.test.js | 4 +--- test/regression/issue/40268.test.ts | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/test/js/bun/globals.test.js b/test/js/bun/globals.test.js index 08493f84abe1..4d7b4577d23a 100644 --- a/test/js/bun/globals.test.js +++ b/test/js/bun/globals.test.js @@ -217,9 +217,7 @@ it("builtin modules do not read replaceable globals", () => { stderr: "pipe", }); - expect(stderr.toString()).toBe(""); - expect(stdout.toString()).toBe("ok\n"); - expect(exitCode).toBe(0); + expect({ stdout: stdout.toString(), stderr: stderr.toString(), exitCode }).toEqual({ stdout: "ok\n", stderr: "", exitCode: 0 }); }); it("self is a getter", () => { diff --git a/test/regression/issue/40268.test.ts b/test/regression/issue/40268.test.ts index d28cbcf0c7d3..dbd5697bca9a 100644 --- a/test/regression/issue/40268.test.ts +++ b/test/regression/issue/40268.test.ts @@ -22,7 +22,5 @@ test("new Worker works after globalThis.MessagePort is replaced", async () => { stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - expect(stderr).toBe(""); - expect(stdout).toBe("hi\n"); - expect(exitCode).toBe(0); + expect({ stdout, stderr, exitCode }).toEqual({ stdout: "hi\n", stderr: "", exitCode: 0 }); }); From 510e1205eaefc4fe6b6a489394c09a640fe075d2 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 09:06:39 +0000 Subject: [PATCH 4/8] [autofix.ci] apply automated fixes --- test/js/bun/globals.test.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/js/bun/globals.test.js b/test/js/bun/globals.test.js index 4d7b4577d23a..6224b3351a71 100644 --- a/test/js/bun/globals.test.js +++ b/test/js/bun/globals.test.js @@ -217,7 +217,11 @@ it("builtin modules do not read replaceable globals", () => { stderr: "pipe", }); - expect({ stdout: stdout.toString(), stderr: stderr.toString(), exitCode }).toEqual({ stdout: "ok\n", stderr: "", exitCode: 0 }); + expect({ stdout: stdout.toString(), stderr: stderr.toString(), exitCode }).toEqual({ + stdout: "ok\n", + stderr: "", + exitCode: 0, + }); }); it("self is a getter", () => { From 3b447fee12a5b4644e5bf8b0826fc8a93b04334c Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 09:21:13 +0000 Subject: [PATCH 5/8] process.nextTick: use the process object it was initialized with initializeNextTickQueue shadowed its `process` parameter and re-read globalThis.process on the first tick, so `process.stdin` (which constructs a stream that calls nextTick) threw once user code replaced the global. The stdio accessors now work after `process = null`, matching Node; update the test that expected them to throw. --- src/js/builtins/ProcessObjectInternals.ts | 6 +----- test/js/node/process/process.test.js | 13 ++++--------- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/src/js/builtins/ProcessObjectInternals.ts b/src/js/builtins/ProcessObjectInternals.ts index 37501f664d0b..3a485036a41e 100644 --- a/src/js/builtins/ProcessObjectInternals.ts +++ b/src/js/builtins/ProcessObjectInternals.ts @@ -348,7 +348,6 @@ export function initializeNextTickQueue( ) { var queue; var tickInitHooks; - var process; var nextTickQueue = nextTickQueue; var drainMicrotasks = drainMicrotasksFn; var reportUncaughtException = reportUncaughtExceptionFn; @@ -411,10 +410,7 @@ export function initializeNextTickQueue( function nextTick(cb, ...args) { validateFunction(cb, "callback"); - if (setup) { - setup(); - process = globalThis.process; - } + if (setup) setup(); if (process._exiting) return; const tock = { diff --git a/test/js/node/process/process.test.js b/test/js/node/process/process.test.js index d07989e2b719..f802fc0d4f11 100644 --- a/test/js/node/process/process.test.js +++ b/test/js/node/process/process.test.js @@ -2062,20 +2062,15 @@ it("should handle user assigned `default` properties", async () => { await promise; }); -it.each(["stdin", "stdout", "stderr"])("%s stream accessor should handle exceptions without crashing", async stream => { +it.each(["stdin", "stdout", "stderr"])("%s stream accessor works after globalThis.process is replaced", async stream => { await runInlineFixture( /* js */ ` const old = process; process = null; - try { - old.${stream}; - } catch {} - if (typeof old.${stream} !== "undefined") { - console.log("wrong"); - } + const stream = old.${stream}; + old.stdout.write(typeof stream + " " + stream.fd + "\\n"); `, - "", - 1, + `object ${{ stdin: 0, stdout: 1, stderr: 2 }[stream]}\n`, ); }); From 5851f6aa191b97595c1f3835399e664cd44171d2 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 09:23:53 +0000 Subject: [PATCH 6/8] [autofix.ci] apply automated fixes --- test/js/node/process/process.test.js | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/js/node/process/process.test.js b/test/js/node/process/process.test.js index f802fc0d4f11..bc871c878bb3 100644 --- a/test/js/node/process/process.test.js +++ b/test/js/node/process/process.test.js @@ -2062,17 +2062,20 @@ it("should handle user assigned `default` properties", async () => { await promise; }); -it.each(["stdin", "stdout", "stderr"])("%s stream accessor works after globalThis.process is replaced", async stream => { - await runInlineFixture( - /* js */ ` +it.each(["stdin", "stdout", "stderr"])( + "%s stream accessor works after globalThis.process is replaced", + async stream => { + await runInlineFixture( + /* js */ ` const old = process; process = null; const stream = old.${stream}; old.stdout.write(typeof stream + " " + stream.fd + "\\n"); `, - `object ${{ stdin: 0, stdout: 1, stderr: 2 }[stream]}\n`, - ); -}); + `object ${{ stdin: 0, stdout: 1, stderr: 2 }[stream]}\n`, + ); + }, +); it("process.versions", () => { expect(process.versions.node).toEqual("26.3.0"); From 2ee48446ffc6694ffdf41220f613ca81e2546a74 Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 09:57:03 +0000 Subject: [PATCH 7/8] node:url, node:http, node:perf_hooks: stop destructuring constructors off globalThis `const { URL } = globalThis` declares a local that shadows the intrinsic, so these modules still exported whatever user code had put on the global. Use the bare names (rewritten to @Name) and drop perf_hooks' guards for a deleted global, which can no longer happen. --- src/js/bun/ffi.ts | 2 +- src/js/node/http.ts | 2 - src/js/node/perf_hooks.ts | 77 ++++++++----------- src/js/node/url.ts | 1 - .../bun/builtin-intrinsic-globals-fixture.js | 19 ++++- 5 files changed, 49 insertions(+), 52 deletions(-) diff --git a/src/js/bun/ffi.ts b/src/js/bun/ffi.ts index 569d3a109b1e..eddd90ae35a7 100644 --- a/src/js/bun/ffi.ts +++ b/src/js/bun/ffi.ts @@ -64,7 +64,7 @@ const FFIType = { const suffix = process.platform === "win32" ? "dll" : process.platform === "darwin" ? "dylib" : "so"; -var ffi = globalThis.Bun.FFI; +var ffi = Bun.FFI; const ptr = (arg1, arg2) => (typeof arg2 === "undefined" ? ffi.ptr(arg1) : ffi.ptr(arg1, arg2)); const toBuffer = ffi.toBuffer; const toArrayBuffer = ffi.toArrayBuffer; diff --git a/src/js/node/http.ts b/src/js/node/http.ts index aeb42fb6aa23..cf91d076d212 100644 --- a/src/js/node/http.ts +++ b/src/js/node/http.ts @@ -11,8 +11,6 @@ const { METHODS, STATUS_CODES, setMaxHTTPHeaderSize, getMaxHTTPHeaderSize } = re if (process.env.NODE_DEBUG) require("node:util").debuglog("http"); -const { WebSocket, CloseEvent, MessageEvent } = globalThis; - function createServer(options, callback) { return new Server(options, callback); } diff --git a/src/js/node/perf_hooks.ts b/src/js/node/perf_hooks.ts index 60b54f817404..e8dd9b444e4e 100644 --- a/src/js/node/perf_hooks.ts +++ b/src/js/node/perf_hooks.ts @@ -15,22 +15,10 @@ const cppCreateHistogram = $newCppFunction("JSNodePerformanceHooksHistogram.cpp" figures: number, ) => import("node:perf_hooks").RecordableHistogram; -var { - Performance, - PerformanceEntry, - PerformanceMark, - PerformanceMeasure, - PerformanceObserver: NodePerformanceObserver, - PerformanceObserverEntryList, -} = globalThis; - -// `extends PerformanceEntry` can't work (WebCore ctor throws); link here via -// the captured global. Construction is gated by hasObserver() so this module -// has loaded first. Guarded so a pre-require delete degrades, not throws. -if (PerformanceEntry) { - Object.setPrototypeOf(PerformanceNodeEntry.prototype, PerformanceEntry.prototype); - Object.setPrototypeOf(PerformanceNodeEntry, PerformanceEntry); -} +// `extends PerformanceEntry` can't work (WebCore ctor throws); link here. +// Construction is gated by hasObserver() so this module has loaded first. +Object.setPrototypeOf(PerformanceNodeEntry.prototype, PerformanceEntry.prototype); +Object.setPrototypeOf(PerformanceNodeEntry, PerformanceEntry); var constants = { NODE_PERFORMANCE_ENTRY_TYPE_DNS: 4, @@ -124,8 +112,6 @@ function eventLoopUtilization(_utilization1, _utilization2) { }; } -const { PerformanceResourceTiming } = globalThis; - const kNodeObserver = Symbol("kNodeObserver"); const kObserverCallback = Symbol("kObserverCallback"); @@ -133,10 +119,9 @@ const kObserverCallback = Symbol("kObserverCallback"); * The native (WebCore) observer only understands mark/measure/resource. * Node-only entry types ('net', 'dns', ...) are routed to the JS-side * registry in internal/shared; everything else is delegated to the native - * observer unchanged. (`NodePerformanceObserver` is the existing alias for - * the native class destructured from globalThis above.) + * observer unchanged. */ -class PerformanceObserverForNodeTypes extends NodePerformanceObserver { +class PerformanceObserverForNodeTypes extends PerformanceObserver { constructor(callback) { super(callback); this[kObserverCallback] = callback; @@ -144,7 +129,7 @@ class PerformanceObserverForNodeTypes extends NodePerformanceObserver { /** The native list plus the Node-only types routed through the JS registry. */ static get supportedEntryTypes() { - return [...new Set([...(NodePerformanceObserver.supportedEntryTypes ?? []), ...kNodeEntryTypes])].sort(); + return [...new Set([...(PerformanceObserver.supportedEntryTypes ?? []), ...kNodeEntryTypes])].sort(); } observe(options) { @@ -275,31 +260,29 @@ const nodeTiming = createPerformanceNodeTiming(); // Node augments the real `performance` object (not a forwarding shim), so // timerify/eventLoopUtilization/nodeTiming go on Performance.prototype, // non-enumerable, per lib/internal/perf/performance.js. -if (Performance) { - Object.defineProperties(Performance.prototype, { - nodeTiming: { - __proto__: null, - configurable: true, - enumerable: false, - writable: true, - value: nodeTiming, - }, - timerify: { - __proto__: null, - configurable: true, - enumerable: false, - writable: true, - value: timerify, - }, - eventLoopUtilization: { - __proto__: null, - configurable: true, - enumerable: false, - writable: true, - value: eventLoopUtilization, - }, - }); -} +Object.defineProperties(Performance.prototype, { + nodeTiming: { + __proto__: null, + configurable: true, + enumerable: false, + writable: true, + value: nodeTiming, + }, + timerify: { + __proto__: null, + configurable: true, + enumerable: false, + writable: true, + value: timerify, + }, + eventLoopUtilization: { + __proto__: null, + configurable: true, + enumerable: false, + writable: true, + value: eventLoopUtilization, + }, +}); export default { timerify, diff --git a/src/js/node/url.ts b/src/js/node/url.ts index 8b82062b6364..a77a174fd77c 100644 --- a/src/js/node/url.ts +++ b/src/js/node/url.ts @@ -25,7 +25,6 @@ "use strict"; -const { URL, URLSearchParams, URLPattern } = globalThis; const [domainToASCII, domainToUnicode, idnaToASCII] = $cpp("NodeURL.cpp", "Bun::createNodeURLBinding"); const { urlToHttpOptions } = require("internal/url"); const { validateString, validateObject } = require("internal/validators"); diff --git a/test/js/bun/builtin-intrinsic-globals-fixture.js b/test/js/bun/builtin-intrinsic-globals-fixture.js index 7a14576b6663..3038c4c61cbb 100644 --- a/test/js/bun/builtin-intrinsic-globals-fixture.js +++ b/test/js/bun/builtin-intrinsic-globals-fixture.js @@ -7,13 +7,30 @@ class Fake extends EventTarget { for (const name of ["MessagePort", "MessageChannel", "BroadcastChannel", "Worker", "Blob", "AbortController", "TextDecoder", "Headers"]) { globalThis[name] = Fake; } +for (const name of ["URLSearchParams", "WebSocket", "Performance", "PerformanceEntry", "PerformanceObserver", "PerformanceResourceTiming"]) { + globalThis[name] = Fake; +} // Deleting a global reifies the whole static table; intrinsics must still resolve after that. delete globalThis.URL; delete globalThis.Event; globalThis.crypto = { randomUUID: () => "fake" }; +for (const [mod, names] of Object.entries({ + "node:url": ["URL", "URLSearchParams"], + "node:http": ["WebSocket"], + "node:perf_hooks": ["Performance", "PerformanceEntry", "PerformanceResourceTiming"], + "node:worker_threads": ["MessagePort", "MessageChannel", "BroadcastChannel"], +})) { + for (const name of names) { + const value = require(mod)[name]; + if (typeof value !== "function" || value === Fake) throw new Error(mod + " exported a replaced " + name); + } +} +if (!(require("node:perf_hooks").performance instanceof require("node:perf_hooks").Performance)) throw new Error("perf_hooks.Performance is not the intrinsic"); +new (require("node:perf_hooks").PerformanceObserver)(() => {}).disconnect(); +if (new (require("node:url").URL)("http://a/b").pathname !== "/b") throw new Error("url.URL is not the intrinsic"); + const wt = require("node:worker_threads"); -if (wt.MessagePort === Fake || wt.MessageChannel === Fake || wt.BroadcastChannel === Fake) throw new Error("worker_threads exported a replaced global"); if (typeof wt.MessagePort.prototype.on !== "function") throw new Error("MessagePort.prototype.on missing"); const { port1, port2 } = new wt.MessageChannel(); port1.close(); From 01db4ce673201f66c7c62643cfbb3dd0a48547ea Mon Sep 17 00:00:00 2001 From: Dylan Conway Date: Mon, 24 Aug 2026 10:43:47 +0000 Subject: [PATCH 8/8] build: track generated headers in the PCH through its depfile, not implicit inputs Spell -I dirs under buildDir relative so depfile entries for generated headers name the nodes their codegen edge declares. The PCH then rebuilds in the same run exactly when a header it includes was regenerated, and codegen outputs go back to order-only so a JS-only edit doesn't rebuild it. Also drop the last `if (PerformanceEntry)` guard in perf_hooks. --- scripts/build/bun.ts | 38 +++++++++++++++++++++++--------------- scripts/build/compile.ts | 25 ++++++++++++++----------- src/js/node/perf_hooks.ts | 6 ++---- 3 files changed, 39 insertions(+), 30 deletions(-) diff --git a/scripts/build/bun.ts b/scripts/build/bun.ts index 00ddf4cb8db5..8428be63c5e2 100644 --- a/scripts/build/bun.ts +++ b/scripts/build/bun.ts @@ -262,9 +262,15 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput { const flags = computeFlags(cfg); // Full include set: bun's own + all dep includes + buildDir (for the - // generated versions header). + // generated versions header). Dirs under buildDir are spelled relative so + // the compiler's depfile names generated headers the way their codegen + // edge declares them (`codegen/X.h`); an absolute spelling is a different + // ninja node, and a header regenerated mid-run would then only invalidate + // its includers (notably the PCH) one build later. const allIncludes = [...bunIncludes(cfg), cfg.buildDir, ...depIncludes]; - const includeFlags = allIncludes.map(inc => `-I${inc}`); + const includeFlags = allIncludes.map( + inc => `-I${inc === cfg.buildDir || inc.startsWith(cfg.buildDir + sep) ? n.rel(inc) || "." : inc}`, + ); const defineFlags = flags.defines.map(d => `-D${d}`); // Final flag arrays for compile. @@ -279,22 +285,24 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput { if (usePch) { n.comment("─── PCH ───"); n.blank(); - // Dep outputs and codegen headers are IMPLICIT inputs (not order-only): - // both are regenerated mid-run (local WebKit headers by dep_build, codegen - // headers by their step), and the PCH's depfile records them by absolute - // path, which is not the node the producing edge declares. At startup ninja - // sees the old header → thinks the PCH is fresh → cxx compiles against a - // stale PCH (or fails with "file modified since PCH was built"). As - // implicit inputs, restat sees the regenerated file → PCH rebuilds in the - // same run. See the pch() docstring. + // Dep outputs are IMPLICIT inputs (not order-only). The crucial case is + // local WebKit: headers live in buildDir and get REGENERATED by dep_build + // mid-run. At startup, ninja sees old headers via PCH's depfile → thinks + // PCH is fresh. dep_build then regenerates them. cxx fails with "file + // modified since PCH was built". As implicit inputs, restat sees the .a + // changed → PCH rebuilds → one-build convergence. See the pch() docstring. // - // cppAll (not all) — bake/.rs outputs are rust-only; pulling them here - // would run bake-codegen in cpp-only CI mode where it fails on the pinned - // bun version (see cppAll docstring). cxx transitively waits: cxx → PCH → - // deps+cppAll. + // Codegen stays order-only: the depfile names exactly the generated + // headers the PCH reaches, as the nodes their codegen edge declares (see + // includeFlags), so a regenerated one rebuilds the PCH in the same run and + // an unrelated one doesn't. cppAll (not all) — bake/.rs outputs are + // rust-only; pulling them here would run bake-codegen in cpp-only CI mode + // where it fails on the pinned bun version (see cppAll docstring). cxx + // transitively waits: cxx → PCH → deps+cppAll. pchOut = pch(n, cfg, "src/jsc/bindings/root-pch.h", { flags: cxxFlagsFull, - implicitInputs: [...depHeaderSignal, ...codegen.cppAll], + implicitInputs: depHeaderSignal, + orderOnlyInputs: codegen.cppAll, }); } diff --git a/scripts/build/compile.ts b/scripts/build/compile.ts index bf160243ce7a..7f4ea2a854fb 100644 --- a/scripts/build/compile.ts +++ b/scripts/build/compile.ts @@ -358,23 +358,26 @@ export function pch( opts: { flags: string[]; /** - * Files whose change must invalidate the PCH: dep output libs - * (libJavaScriptCore.a etc.) and generated headers. + * Files whose change must invalidate the PCH. Typically: dep output + * libs (libJavaScriptCore.a etc.). * - * Can't be order-only: the depfile tracks headers, but ninja stats them - * at startup and records them by absolute path (a different node from - * the producing edge's declared output). Anything regenerated MID-RUN — - * local WebKit headers by dep_build, codegen headers by their step — - * leaves the PCH looking fresh → cxx builds against a stale PCH or fails - * with "file modified since PCH was built" → needs a second build. With - * these implicit, restat propagates the change to the PCH and it - * rebuilds in the same run. + * Can't be order-only: the depfile tracks headers, but ninja stats at + * startup. Local WebKit headers live in buildDir and get regenerated + * by dep_build MID-RUN. At startup ninja sees old headers → thinks + * PCH is fresh → cxx fails with "file modified since PCH was built" + * → needs a second build. With these implicit, restat propagates the + * lib change to PCH and it rebuilds in the same run. * * Cost: PCH also rebuilds on unrelated dep bumps (brotli etc.). Rare * enough to accept for correctness. */ implicitInputs?: string[]; - /** Must exist before PCH compiles; changes don't invalidate it. */ + /** + * Must exist before PCH compiles; the depfile decides which of them + * invalidate it. Codegen outputs go here — that only works because their + * -I dir is buildDir-relative, so depfile entries name the declared + * output nodes. + */ orderOnlyInputs?: string[]; }, ): { pch: string; wrapperHeader: string } { diff --git a/src/js/node/perf_hooks.ts b/src/js/node/perf_hooks.ts index e8dd9b444e4e..0e4dfda80d4b 100644 --- a/src/js/node/perf_hooks.ts +++ b/src/js/node/perf_hooks.ts @@ -90,10 +90,8 @@ class PerformanceNodeTiming { }; } } -if (PerformanceEntry) { - Object.setPrototypeOf(PerformanceNodeTiming.prototype, PerformanceEntry.prototype); - Object.setPrototypeOf(PerformanceNodeTiming, PerformanceEntry); -} +Object.setPrototypeOf(PerformanceNodeTiming.prototype, PerformanceEntry.prototype); +Object.setPrototypeOf(PerformanceNodeTiming, PerformanceEntry); function createPerformanceNodeTiming() { const object = Object.create(PerformanceNodeTiming.prototype);