diff --git a/scripts/build/bun.ts b/scripts/build/bun.ts index d83626605249..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. @@ -286,12 +292,13 @@ export function emitBun(n: Ninja, cfg: Config, sources: Sources): BunOutput { // modified since PCH was built". As implicit inputs, restat sees the .a // changed → PCH rebuilds → one-build convergence. 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. + // 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, diff --git a/scripts/build/codegen.ts b/scripts/build/codegen.ts index ab631c95be34..8f5682824244 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,15 @@ 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..7f4ea2a854fb 100644 --- a/scripts/build/compile.ts +++ b/scripts/build/compile.ts @@ -373,9 +373,10 @@ export function pch( */ 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; 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[]; }, 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 9c56858b3b29..090240f0ab09 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 46e0108344c9..a48530e75012 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/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/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/internal/worker/messaging.ts b/src/js/internal/worker/messaging.ts index 370ceeaea417..2a3bc0ae1f45 100644 --- a/src/js/internal/worker/messaging.ts +++ b/src/js/internal/worker/messaging.ts @@ -22,9 +22,6 @@ const messageTypes = { // Set once via initThreadInfo() when worker_threads.ts loads. let currentThreadId = 0; let isMainThread = true; -// The intrinsic constructor from worker_threads' native binding, not -// globalThis.MessageChannel, which user code can replace (#40268). -let MessageChannel: typeof globalThis.MessageChannel; // Only populated on the main thread (the hub); always empty elsewhere. // SafeMap: its prototype is a frozen null-proto snapshot taken at bootstrap, so the @@ -45,10 +42,9 @@ const WORKER_MESSAGING_RESULT_DELIVERED = 0; const WORKER_MESSAGING_RESULT_NO_LISTENERS = 1; const WORKER_MESSAGING_RESULT_LISTENER_ERROR = 2; -function initThreadInfo(threadId: number, mainThread: boolean, MessageChannelCtor: typeof globalThis.MessageChannel) { +function initThreadInfo(threadId: number, mainThread: boolean) { currentThreadId = threadId; isMainThread = mainThread; - MessageChannel = MessageChannelCtor; } // This event handler is always executed on the main thread only. 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/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/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/perf_hooks.ts b/src/js/node/perf_hooks.ts index 60b54f817404..0e4dfda80d4b 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, @@ -102,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); @@ -124,8 +110,6 @@ function eventLoopUtilization(_utilization1, _utilization2) { }; } -const { PerformanceResourceTiming } = globalThis; - const kNodeObserver = Symbol("kNodeObserver"); const kObserverCallback = Symbol("kObserverCallback"); @@ -133,10 +117,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 +127,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 +258,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/src/js/node/worker_threads.ts b/src/js/node/worker_threads.ts index 1658bd7cb4eb..8d924a3e989e 100644 --- a/src/js/node/worker_threads.ts +++ b/src/js/node/worker_threads.ts @@ -52,6 +52,12 @@ function validateWorkerFilename(filename) { throw $ERR_WORKER_PATH(message); } +// 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; @@ -69,13 +75,6 @@ const { 10: _isNodeWorker, 11: _setParentPort, 12: _setStdioPorts, - // The intrinsic web constructors, captured natively so user code replacing the - // globals (e.g. happy-dom's registrator) before this module loads cannot break - // worker_threads (#40268). - 13: _MessagePort, - 14: MessageChannel, - 15: BroadcastChannel, - 16: WebWorker, } = $cpp("Worker.cpp", "createNodeWorkerThreadsBinding") as [ unknown, number, @@ -90,13 +89,6 @@ const { boolean, (port: MessagePort) => void, (ports: object) => void, - typeof globalThis.MessagePort, - typeof globalThis.MessageChannel, - typeof globalThis.BroadcastChannel, - // 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. - new (...args: [...ConstructorParameters, nodeWorker: Worker]) => WebWorker, ]; type NodeWorkerOptions = import("node:worker_threads").WorkerOptions; @@ -285,9 +277,7 @@ function injectFakeEmitter(Class) { Object.setPrototypeOf(proto, inherited); } -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. @@ -445,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; @@ -594,7 +584,7 @@ let parentPort: MessagePort | null = null; // postMessageToThread (Node 22+): the Worker ctor always smuggles a control // MessagePort to the worker by wrapping workerData; unwrap it here. const messaging = require("internal/worker/messaging"); -messaging.initThreadInfo(threadId, isMainThread, MessageChannel); +messaging.initThreadInfo(threadId, isMainThread); // Captured stdio + the messaging control port ride inside workerData (wrapped; // ports transferred). Unwrap and bind the worker's stdio / messaging hub. // Gate on _isNodeWorker so a raw `new globalThis.Worker` that loads this module 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/src/jsc/bindings/webcore/Worker.cpp b/src/jsc/bindings/webcore/Worker.cpp index a3e4f756c57a..4f8174b8354e 100644 --- a/src/jsc/bindings/webcore/Worker.cpp +++ b/src/jsc/bindings/webcore/Worker.cpp @@ -47,8 +47,6 @@ #include "JSDOMConvertObject.h" #include "JSDOMConvertSequences.h" #include "JSMessagePort.h" -#include "JSMessageChannel.h" -#include "JSWorker.h" #include "MessagePortPipe.h" #include "JSBroadcastChannel.h" #include "JSStructuredSerializeOptions.h" @@ -337,7 +335,7 @@ JSValue createNodeWorkerThreadsBinding(Zig::GlobalObject* globalObject) bool isNodeWorker = proxy && proxy->options().kind == WorkerOptions::Kind::Node; - JSObject* array = constructEmptyArray(globalObject, nullptr, 17); + JSObject* array = constructEmptyArray(globalObject, nullptr, 13); RETURN_IF_EXCEPTION(scope, {}); array->putDirectIndex(globalObject, 0, workerData); array->putDirectIndex(globalObject, 1, threadId); @@ -352,12 +350,6 @@ JSValue createNodeWorkerThreadsBinding(Zig::GlobalObject* globalObject) array->putDirectIndex(globalObject, 10, jsBoolean(isNodeWorker)); array->putDirectIndex(globalObject, 11, JSFunction::create(vm, globalObject, 1, "setParentPort"_s, jsFunctionSetParentPort, ImplementationVisibility::Public, NoIntrinsic)); array->putDirectIndex(globalObject, 12, JSFunction::create(vm, globalObject, 1, "setStdioPorts"_s, jsFunctionSetNodeWorkerStdioPorts, ImplementationVisibility::Public, NoIntrinsic)); - // The intrinsic constructors, so worker_threads keeps working when user code - // replaces globalThis.MessagePort etc. before the module loads (#40268). - array->putDirectIndex(globalObject, 13, JSMessagePort::getConstructor(vm, globalObject)); - array->putDirectIndex(globalObject, 14, JSMessageChannel::getConstructor(vm, globalObject)); - array->putDirectIndex(globalObject, 15, JSBroadcastChannel::getConstructor(vm, globalObject)); - array->putDirectIndex(globalObject, 16, JSWorker::getConstructor(vm, globalObject)); return array; } 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..3038c4c61cbb --- /dev/null +++ b/test/js/bun/builtin-intrinsic-globals-fixture.js @@ -0,0 +1,63 @@ +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; +} +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 (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..6224b3351a71 100644 --- a/test/js/bun/globals.test.js +++ b/test/js/bun/globals.test.js @@ -206,6 +206,24 @@ 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({ stdout: stdout.toString(), stderr: stderr.toString(), exitCode }).toEqual({ + stdout: "ok\n", + stderr: "", + exitCode: 0, + }); +}); + it("self is a getter", () => { const descriptor = Object.getOwnPropertyDescriptor(globalThis, "self"); expect(descriptor.get).toBeInstanceOf(Function); diff --git a/test/js/node/process/process.test.js b/test/js/node/process/process.test.js index c1a07c118f92..ae0eb3c678ce 100644 --- a/test/js/node/process/process.test.js +++ b/test/js/node/process/process.test.js @@ -2062,22 +2062,20 @@ 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 => { - 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; - 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`, + ); + }, +); it("process.versions", () => { expect(process.versions.node).toEqual("26.3.0");