diff --git a/CHANGELOG.md b/CHANGELOG.md index b96ceb6c765a..1230300850fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,12 +2,10 @@ ## Unreleased -- Keep cause-free Error serialization on its terminal fast path with byte-identical v14 output; use a distinct v16 Error cause tag and capability negotiation with older IPC peers. +- Back out Error.cause serialization (#192, #194) pending a performance-neutral design. - Avoid an extra payload copy when structured cloning or messaging a Buffer or ArrayBuffer inside a container, without changing serialized bytes. -- Preserve Error cause graphs in structured cloning and worker messages, while retaining v14 bytes for cause-free values and negotiating cause support for advanced IPC with older Bun processes; thanks fuller-stack-dev. - - Sync oven-sh/bun through `ad4089bf49d9f4c3ab7c8d95a58f3e0f0f186054`, including lint, format, binding, WebSocket and SQL updates, while retaining the fork runtime and CI contracts. - Share identical `node:vm` script and compiled-function source buffers and source-map URI strings through a bounded per-VM weak index, including after compilation-cache eviction. diff --git a/docs/guides/process/ipc.mdx b/docs/guides/process/ipc.mdx index f55db9c160f1..96e2ec236f0c 100644 --- a/docs/guides/process/ipc.mdx +++ b/docs/guides/process/ipc.mdx @@ -56,8 +56,6 @@ process.on("message", message => { By default, Bun serializes messages with the JSC `serialize` API. This API supports everything [`structuredClone` supports](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), including strings, typed arrays, and objects. The API does not support transferring ownership of objects. -Advanced IPC preserves `Error.cause` once the peer has advertised v16 cause-format support on that channel. Messages sent before that advertisement, or to an older Bun process, omit causes and retain the v14 format used by older builds. The unreleased intermediate v15 capability does not enable v16 causes. Cause-free messages always retain v14 bytes. This allows an already-running process to communicate with a child started from an updated Bun executable. In-process `structuredClone`, Worker, MessagePort, and BroadcastChannel messages preserve causes without IPC negotiation. - ```ts child.ts icon="/icons/typescript.svg" // send a string process.send("Hello from child as string"); diff --git a/docs/runtime/nodejs-compat.mdx b/docs/runtime/nodejs-compat.mdx index 3b8f37106a02..ed7196aeace2 100644 --- a/docs/runtime/nodejs-compat.mdx +++ b/docs/runtime/nodejs-compat.mdx @@ -315,7 +315,7 @@ Destroying an HTTP/2 session releases its TLS transport without waiting for the Map and Set serialization copies entries and ignores custom own properties, like `structuredClone`. Existing Bun records with own-property sections remain readable. -🟡 `writeHeapSnapshot`, `getHeapSnapshot`, `getHeapStatistics`, `getHeapSpaceStatistics`, `queryObjects`, `GCProfiler` and `startupSnapshot` are implemented. `queryObjects()` collects garbage and returns a count or shallow summaries of objects matching the constructor's prototype chain in the current context. The heap statistics describe JavaScriptCore's single heap, and `setFlagsFromString` ignores the flags it is given. `serialize` and `deserialize` use JavaScriptCore's wire format instead of V8's. Cause-free values retain the v14 format; Error cause graphs use v16, which older Bun builds cannot deserialize. Readers reject v15, an unreleased intermediate format. These bytes are not interchangeable with Node.js serialization. Missing `startCpuProfile`, `startHeapProfile`, `Serializer`/`Deserializer`, `takeCoverage`/`stopCoverage` and `promiseHooks`. For profiling, use [`bun:jsc`](/project/benchmarking#javascript-heap-stats) instead. +🟡 `writeHeapSnapshot`, `getHeapSnapshot`, `getHeapStatistics`, `getHeapSpaceStatistics`, `queryObjects`, `GCProfiler` and `startupSnapshot` are implemented. `queryObjects()` collects garbage and returns a count or shallow summaries of objects matching the constructor's prototype chain in the current context. The heap statistics describe JavaScriptCore's single heap, and `setFlagsFromString` ignores the flags it is given. `serialize` and `deserialize` use JavaScriptCore's wire format instead of V8's. Missing `startCpuProfile`, `startHeapProfile`, `Serializer`/`Deserializer`, `takeCoverage`/`stopCoverage` and `promiseHooks`. For profiling, use [`bun:jsc`](/project/benchmarking#javascript-heap-stats) instead. ### [`node:vm`](https://nodejs.org/api/vm.html) diff --git a/src/js/node/v8.ts b/src/js/node/v8.ts index d33e01742f56..7907365abbfc 100644 --- a/src/js/node/v8.ts +++ b/src/js/node/v8.ts @@ -298,7 +298,7 @@ function getCppHeapStatistics(type = "detailed") { } // Buffer-bearing payloads are framed as MAGIC + version + SSV([value, buffers]) so deserialize // can restore Buffer prototypes (see internal/serialization_buffers). Leading 0xFF cannot collide -// with bare SSV output; Buffer-free payloads retain the current bare SSV framing. +// with bare SSV output; Buffer-free payloads stay bare SSV so older readers keep working. function hasBufferEnvelopeMagic(view) { // In-bounds integer-indexed reads on a typed array never consult the @@ -345,7 +345,8 @@ function stopCoverage() { notimpl("stopCoverage"); } function serialize(arg1) { - return serializeNative(arg1); + const tagged = require("internal/serialization_buffers").tagBuffers(arg1); + return serializeNative(tagged === null ? arg1 : tagged, tagged !== null); } function getDefaultHeapSnapshotPath() { diff --git a/src/jsc/JSValue.rs b/src/jsc/JSValue.rs index 5e000f33363d..cef5bd5a4e98 100644 --- a/src/jsc/JSValue.rs +++ b/src/jsc/JSValue.rs @@ -2192,8 +2192,6 @@ pub enum TemporalType { pub struct SerializedFlags { pub for_cross_process_transfer: bool, pub for_storage: bool, - pub preserve_node_buffers: bool, - pub omit_error_cause: bool, } /// `JSValue.SerializedScriptValue` — owned view over a @@ -2202,13 +2200,8 @@ pub struct SerializedScriptValue { bytes: *const u8, size: usize, handle: *mut c_void, - has_buffer_envelope: bool, } impl SerializedScriptValue { - pub fn has_buffer_envelope(&self) -> bool { - self.has_buffer_envelope - } - /// Borrow the serialized bytes. Valid only while `self` is alive (the /// backing buffer is freed on drop); the lifetime is tied to `&self`. #[inline] @@ -2231,7 +2224,6 @@ struct SerializedScriptValueExternal { bytes: *const u8, size: usize, handle: *mut c_void, - has_buffer_envelope: bool, } /// Callback signature for [`JSValue::for_each`] / [`JSValue::for_each_with_context`]. @@ -2700,12 +2692,6 @@ impl JSValue { if flags.for_storage { bits |= 1 << 1; } - if flags.preserve_node_buffers { - bits |= 1 << 2; - } - if flags.omit_error_cause { - bits |= 1 << 3; - } let ext = host_fn::from_js_host_call_generic(global, || { Bun__serializeJSValue(global, self, bits) })?; @@ -2716,7 +2702,6 @@ impl JSValue { bytes: ext.bytes, size: ext.size, handle: ext.handle, - has_buffer_envelope: ext.has_buffer_envelope, }) } } diff --git a/src/jsc/bindings/IPC.cpp b/src/jsc/bindings/IPC.cpp index 1fb42b22f110..ae5b0898b15a 100644 --- a/src/jsc/bindings/IPC.cpp +++ b/src/jsc/bindings/IPC.cpp @@ -38,6 +38,21 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue IPCParse(Zig::Globa return JSC::JSValue::encode(result); } +extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue IPCTagAdvancedBuffers(Zig::GlobalObject* global, JSC::EncodedJSValue message) +{ + auto& vm = JSC::getVM(global); + auto scope = DECLARE_THROW_SCOPE(vm); + JSC::JSFunction* tagFunction = global->m_ipcTagAdvancedBuffersFunction.getInitializedOnMainThread(global); + JSC::CallData callData = JSC::getCallData(tagFunction); + + JSC::MarkedArgumentBuffer args; + args.append(JSC::JSValue::decode(message)); + + auto result = JSC::call(global, tagFunction, callData, JSC::jsUndefined(), args); + RETURN_IF_EXCEPTION(scope, {}); + return JSC::JSValue::encode(result); +} + extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue IPCRestoreAdvancedBuffers(Zig::GlobalObject* global, JSC::EncodedJSValue envelope) { auto& vm = JSC::getVM(global); diff --git a/src/jsc/bindings/NodeV8.cpp b/src/jsc/bindings/NodeV8.cpp index 04fa924451ca..5f34379064e4 100644 --- a/src/jsc/bindings/NodeV8.cpp +++ b/src/jsc/bindings/NodeV8.cpp @@ -5,6 +5,7 @@ #include "ErrorCode.h" #include "BunClientData.h" #include "NodeV8.h" +#include "MessagePort.h" #include "SerializedScriptValue.h" #include "ZigGlobalObject.h" @@ -45,15 +46,16 @@ JSC_DEFINE_HOST_FUNCTION(functionSerializeForNode, (JSGlobalObject * globalObjec auto& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); auto* domGlobal = uncheckedDowncast(globalObject); - bool hasBufferEnvelope = false; - auto result = WebCore::SerializedScriptValue::createForNode(*domGlobal, callFrame->argument(0), WebCore::SerializationForStorage::Yes, WebCore::SerializationForCrossProcessTransfer::No, hasBufferEnvelope); + Vector> transfers; + Vector> ports; + auto result = WebCore::SerializedScriptValue::create(*domGlobal, callFrame->argument(0), WTF::move(transfers), ports, WebCore::SerializationForStorage::Yes); EXCEPTION_ASSERT(result.hasException() == !!scope.exception()); if (result.hasException()) { WebCore::propagateException(*domGlobal, scope, result.releaseException()); RELEASE_AND_RETURN(scope, {}); } auto serialized = result.releaseReturnValue(); - auto prefix = hasBufferEnvelope ? std::span(bufferEnvelopeMagic) : std::span(); + auto prefix = callFrame->argument(1).asBoolean() ? std::span(bufferEnvelopeMagic) : std::span(); auto buffer = serialized->toArrayBuffer(ArrayBufferSharingMode::Default, prefix); size_t length = buffer->byteLength(); RELEASE_AND_RETURN(scope, JSValue::encode(JSUint8Array::create(globalObject, domGlobal->JSBufferSubclassStructure(), WTF::move(buffer), 0, length))); @@ -202,7 +204,7 @@ JSC::JSObject* createNodeV8Binding(JSC::JSGlobalObject* globalObject) RETURN_IF_EXCEPTION(scope, nullptr); } object->putDirect(vm, Identifier::fromString(vm, "bufferEnvelopeMagic"_s), magic); - object->putDirectNativeFunction(vm, globalObject, Identifier::fromString(vm, "serialize"_s), 1, functionSerializeForNode, ImplementationVisibility::Public, NoIntrinsic, 0); + object->putDirectNativeFunction(vm, globalObject, Identifier::fromString(vm, "serialize"_s), 2, functionSerializeForNode, ImplementationVisibility::Public, NoIntrinsic, 0); object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "queryObjects"_s), 1, functionQueryObjects, ImplementationVisibility::Public, JSC::NoIntrinsic, 0); object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "getHeapUsage"_s), 0, functionGetHeapUsage, ImplementationVisibility::Public, JSC::NoIntrinsic, 0); object->putDirectNativeFunction(vm, globalObject, JSC::Identifier::fromString(vm, "isStringOneByteRepresentation"_s), 1, functionIsStringOneByteRepresentation, ImplementationVisibility::Public, JSC::NoIntrinsic, 0); diff --git a/src/jsc/bindings/Serialization.cpp b/src/jsc/bindings/Serialization.cpp index 41eda970b1f6..1919a91d2a35 100644 --- a/src/jsc/bindings/Serialization.cpp +++ b/src/jsc/bindings/Serialization.cpp @@ -13,15 +13,12 @@ struct SerializedValueSlice { const uint8_t* bytes; size_t size; WebCore::SerializedScriptValue* value; // NOLINT - bool hasBufferEnvelope; }; enum class SerializedFlags : uint8_t { None = 0, ForCrossProcessTransfer = 1 << 0, ForStorage = 1 << 1, - PreserveNodeBuffers = 1 << 2, - OmitErrorCause = 1 << 3, }; /// Returns a "slice" that also contains a pointer to the SerializedScriptValue. Must be freed by the caller @@ -34,13 +31,9 @@ extern "C" SerializedValueSlice Bun__serializeJSValue(JSGlobalObject* globalObje Vector> transferList; Vector> dummyPorts; auto forStorage = (static_cast(flags) & static_cast(SerializedFlags::ForStorage)) ? SerializationForStorage::Yes : SerializationForStorage::No; - auto context = (static_cast(flags) & static_cast(SerializedFlags::OmitErrorCause)) ? SerializationContext::LegacyIPC : SerializationContext::Default; + auto context = SerializationContext::Default; auto forTransferEnum = (static_cast(flags) & static_cast(SerializedFlags::ForCrossProcessTransfer)) ? SerializationForCrossProcessTransfer::Yes : SerializationForCrossProcessTransfer::No; - bool hasBufferEnvelope = false; - bool preserveNodeBuffers = static_cast(flags) & static_cast(SerializedFlags::PreserveNodeBuffers); - ExceptionOr> serialized = preserveNodeBuffers - ? SerializedScriptValue::createForNode(*globalObject, value, forStorage, forTransferEnum, hasBufferEnvelope, context) - : SerializedScriptValue::create(*globalObject, value, WTF::move(transferList), dummyPorts, forStorage, context, forTransferEnum); + ExceptionOr> serialized = SerializedScriptValue::create(*globalObject, value, WTF::move(transferList), dummyPorts, forStorage, context, forTransferEnum); EXCEPTION_ASSERT(!!scope.exception() == serialized.hasException()); if (serialized.hasException()) { @@ -56,7 +49,6 @@ extern "C" SerializedValueSlice Bun__serializeJSValue(JSGlobalObject* globalObje bytes.begin(), bytes.size(), &serializedValue.leakRef(), - hasBufferEnvelope, }; } diff --git a/src/jsc/bindings/webcore/SerializedScriptValue.cpp b/src/jsc/bindings/webcore/SerializedScriptValue.cpp index 7646271daf42..cfd2b3ff01ef 100644 --- a/src/jsc/bindings/webcore/SerializedScriptValue.cpp +++ b/src/jsc/bindings/webcore/SerializedScriptValue.cpp @@ -141,8 +141,7 @@ enum WalkerState { StateUnknown, MapDataEndVisitKey, MapDataEndVisitValue, SetDataStartVisitEntry, - SetDataEndVisitKey, - ErrorEndVisitCause }; + SetDataEndVisitKey }; // These can't be reordered, and any new types must be added to the end of the list // When making changes to these lists please cover your new type(s) in the API test "IndexedDB.StructuredCloneBackwardCompatibility" @@ -190,7 +189,6 @@ enum SerializationTag { DOMExceptionTag = 51, ResizableArrayBufferTag = 54, ErrorInstanceTag = 55, - ErrorInstanceWithCauseTag = 56, Bun__BlobTag = 254, // bun types start at 254 and decrease with each addition @@ -418,12 +416,8 @@ const uint8_t cryptoKeyOKPOpNameTagMaximumValue = 1; * Version 13. added support for ErrorInstance objects. * Version 14. Date, RegExp, Error, DOMException, CryptoKey, KeyObject, X509Certificate, * and Bun cloneable types are recorded in the object reference pool on both sides. - * Version 15. Unreleased intermediate format with inline Error cause-presence bytes; rejected. - * Version 16. A distinct ErrorInstanceWithCauseTag carries an own data cause. */ -[[maybe_unused]] static constexpr unsigned CurrentVersion = 16; -static constexpr unsigned DefaultVersion = 14; -static constexpr unsigned FirstVersionWithErrorCause = 16; +[[maybe_unused]] static constexpr unsigned CurrentVersion = 14; // Deserializers must not pool the version 14 terminal types for older payloads, // whose writers never counted them, or the pool indices stop matching the writer's. [[maybe_unused]] static constexpr unsigned FirstVersionWithPooledTerminals = 14; @@ -442,8 +436,8 @@ static constexpr unsigned StringDataIs8BitFlag = 0x80000000; * minimum sized unsigned integer type required to represent the maximum index * in the constant pool. * - * SerializedValue :- Value - * Value :- Array | Object | Map | Set | Error | Terminal + * SerializedValue :- Value + * Value :- Array | Object | Map | Set | Terminal * * Array :- * ArrayTag ()* TerminatorTag @@ -458,10 +452,6 @@ static constexpr unsigned StringDataIs8BitFlag = 0x80000000; * MapData :- ()* NonMapPropertiesTag ()* TerminatorTag * SetData :- ()* NonSetPropertiesTag ()* TerminatorTag * - * Error :- ErrorInstanceWithCauseTag ErrorMetadata Value (version 16 only) - * ErrorMetadata :- - * - * * Terminal :- * UndefinedTag * | NullTag @@ -488,7 +478,6 @@ static constexpr unsigned StringDataIs8BitFlag = 0x80000000; * | ArrayBuffer * | ArrayBufferViewTag ArrayBufferViewSubtag (ArrayBuffer | ObjectReference) * | CryptoKeyTag - * | ErrorInstanceTag ErrorMetadata * | DOMPoint * | DOMRect * | DOMMatrix @@ -735,20 +724,15 @@ class CloneSerializer : public CloneBase { #endif Vector& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers, Vector& serializedBlockListRefs, - SerializationForStorage forStorage, SerializationForCrossProcessTransfer forTransfer, bool* hasBufferEnvelope, JSArray* legacyNodeBuffers) + SerializationForStorage forStorage, SerializationForCrossProcessTransfer forTransfer) { CloneSerializer serializer(lexicalGlobalObject, messagePorts, arrayBuffers, #if ENABLE(WEBASSEMBLY) wasmModules, wasmMemoryHandles, #endif - out, context, sharedBuffers, forStorage, forTransfer, hasBufferEnvelope != nullptr, legacyNodeBuffers); + out, context, sharedBuffers, forStorage, forTransfer); auto code = serializer.serialize(value); - if (code == SerializationReturnCode::SuccessfullyCompleted && hasBufferEnvelope) { - *hasBufferEnvelope = serializer.finishBufferEnvelope(); - if (serializer.m_failed) - code = SerializationReturnCode::UnspecifiedError; - } serializedBlockListRefs = WTF::move(serializer.m_serializedBlockListRefs); return code; } @@ -761,7 +745,7 @@ class CloneSerializer : public CloneBase { WasmModuleArray& wasmModules, WasmMemoryHandleArray& wasmMemoryHandles, #endif - Vector& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers, SerializationForStorage forStorage, SerializationForCrossProcessTransfer forTransfer, bool preserveNodeBuffers, JSArray* legacyNodeBuffers) + Vector& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers, SerializationForStorage forStorage, SerializationForCrossProcessTransfer forTransfer) : CloneBase(lexicalGlobalObject) , m_buffer(out) , m_emptyIdentifier(Identifier::fromString(lexicalGlobalObject->vm(), emptyString())) @@ -773,12 +757,8 @@ class CloneSerializer : public CloneBase { #endif , m_forStorage(forStorage) , m_forTransfer(forTransfer) - , m_preserveNodeBuffers(preserveNodeBuffers) - , m_legacyNodeBuffers(legacyNodeBuffers) { - write(DefaultVersion); - if (legacyNodeBuffers) - m_gcBuffer.appendWithCrashOnOverflow(legacyNodeBuffers); + write(CurrentVersion); fillTransferMap(messagePorts, m_transferredMessagePorts); fillTransferMap(arrayBuffers, m_transferredArrayBuffers); } @@ -1046,22 +1026,6 @@ class CloneSerializer : public CloneBase { return JSC::JSArrayBuffer::create(vm, globalObject->arrayBufferStructure(arrayBuffer.sharingMode()), &arrayBuffer); } - bool isNodeBuffer(JSObject* object) - { - if (!object->inherits()) - return false; - auto prototype = defaultGlobalObject(m_lexicalGlobalObject)->JSBufferSubclassStructure()->storedPrototype(); - // Inspect engine-stored prototypes, as queryObjects does. [[GetPrototypeOf]] - // would execute Proxy traps while serializing an otherwise ordinary view. - // Direct traversal retains Buffer subclasses and intermediate prototypes - // without following an exotic object's user-defined prototype chain. - for (JSValue current = object->getPrototypeDirect(); current.isObject(); current = asObject(current)->getPrototypeDirect()) { - if (current == prototype) - return true; - } - return false; - } - bool dumpArrayBufferView(JSObject* obj, SerializationReturnCode& code) { VM& vm = m_lexicalGlobalObject->vm(); @@ -1137,105 +1101,6 @@ class CloneSerializer : public CloneBase { code = SerializationReturnCode::DataCloneError; } - JSValue errorCause(ErrorInstance* errorInstance) - { - auto& vm = m_lexicalGlobalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - if (m_context == SerializationContext::WorkerError || m_context == SerializationContext::LegacyIPC) - return {}; - - // Unlike stack/line/column, cause has no lazy Error metadata slot. - unsigned attributes = 0; - JSValue cause = errorInstance->getDirect(vm, vm.propertyNames->cause, attributes); - if (errorInstance->classInfo() != ErrorInstance::info() || (attributes & PropertyAttribute::CustomAccessorOrValue)) [[unlikely]] { - JSC::PropertyDescriptor descriptor; - bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->cause, descriptor); - RETURN_IF_EXCEPTION(scope, JSValue()); - cause = found && descriptor.isDataDescriptor() ? descriptor.value() : JSValue(); - } else if (attributes & PropertyAttribute::Accessor) - return {}; - - // Root the own data value before any Error metadata can run user code. - if (cause) - m_gcBuffer.appendWithCrashOnOverflow(cause); - return cause; - } - - bool dumpError(ErrorInstance* errorInstance, SerializationTag tag) - { - auto& vm = m_lexicalGlobalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - auto errorTypeValue = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->name); - RETURN_IF_EXCEPTION(scope, false); - auto errorTypeString = errorTypeValue.toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - - // .message/.line/.column/.sourceURL: HTML spec + Node/WebKit read - // OWN data descriptors only (an inherited or accessor .message is - // NOT serialized). .stack: Node reads via [[Get]] to materialize - // V8's lazy accessor. Any getter/coercion/prepareStackTrace throw - // propagates out of postMessage/structuredClone (Node parity). - String message, sourceURL, stack; - unsigned line = 0, column = 0; - { - // .message is ToString'd rather than gated on isString (node clones - // `e.message = 42` as "42"). Reading it before .line also keeps a - // Symbol message from reaching ErrorInstance's lazy materialization. - JSC::PropertyDescriptor d; - bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->message, d); - RETURN_IF_EXCEPTION(scope, false); - if (found && d.isDataDescriptor() && d.value()) { - message = d.value().toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - } - } - // Trigger ErrorInstance's lazy materialization up front so a throwing - // prepareStackTrace propagates here instead of tripping the exception - // assertion inside JSObject::getOwnPropertyDescriptor. - errorInstance->materializeErrorInfoIfNeeded(vm); - RETURN_IF_EXCEPTION(scope, false); - { - JSC::PropertyDescriptor d; - bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->line, d); - RETURN_IF_EXCEPTION(scope, false); - if (found && d.isDataDescriptor() && d.value().isNumber()) - line = d.value().toNumber(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - } - { - JSC::PropertyDescriptor d; - bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->column, d); - RETURN_IF_EXCEPTION(scope, false); - if (found && d.isDataDescriptor() && d.value().isNumber()) - column = d.value().toNumber(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - } - { - JSC::PropertyDescriptor d; - bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->sourceURL, d); - RETURN_IF_EXCEPTION(scope, false); - if (found && d.isDataDescriptor() && d.value().isString()) - sourceURL = d.value().toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - } - { - JSValue v = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->stack); - RETURN_IF_EXCEPTION(scope, false); - if (v.isString()) - stack = v.toWTFString(m_lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - } - - write(tag); - write(errorNameToSerializableErrorType(errorTypeString)); - writeNullableString(message); - write(line); - write(column); - writeNullableString(sourceURL); - writeNullableString(stack); - return true; - } - bool dumpIfTerminal(JSValue value, SerializationReturnCode& code) { if (!value.isCell()) { @@ -1329,20 +1194,78 @@ class CloneSerializer : public CloneBase { write(String(JSC::Yarr::flagsString(regExp->regExp()->flags()).span())); return true; } - if (auto* error = dynamicDowncast(obj)) { - if (m_pendingError == error) - return false; - if (!startObjectInternal(error)) + if (auto* errorInstance = dynamicDowncast(obj)) { + if (!startObjectInternal(errorInstance)) // handle duplicates return true; - JSValue cause = errorCause(error); + auto& vm = m_lexicalGlobalObject->vm(); + auto errorTypeValue = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->name); RETURN_IF_EXCEPTION(scope, false); - if (cause) { - m_pendingError = error; - m_pendingErrorCause = cause; - return false; + auto errorTypeString = errorTypeValue.toWTFString(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + + // .message/.line/.column/.sourceURL: HTML spec + Node/WebKit read + // OWN data descriptors only (an inherited or accessor .message is + // NOT serialized). .stack: Node reads via [[Get]] to materialize + // V8's lazy accessor. Any getter/coercion/prepareStackTrace throw + // propagates out of postMessage/structuredClone (Node parity). + String message, sourceURL, stack; + unsigned line = 0, column = 0; + { + // .message is ToString'd rather than gated on isString (node clones + // `e.message = 42` as "42"). Reading it before .line also keeps a + // Symbol message from reaching ErrorInstance's lazy materialization. + JSC::PropertyDescriptor d; + bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->message, d); + RETURN_IF_EXCEPTION(scope, false); + if (found && d.isDataDescriptor() && d.value()) { + message = d.value().toWTFString(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + } } - dumpError(error, ErrorInstanceTag); + // Trigger ErrorInstance's lazy materialization up front so a throwing + // prepareStackTrace propagates here instead of tripping the exception + // assertion inside JSObject::getOwnPropertyDescriptor. + errorInstance->materializeErrorInfoIfNeeded(vm); RETURN_IF_EXCEPTION(scope, false); + { + JSC::PropertyDescriptor d; + bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->line, d); + RETURN_IF_EXCEPTION(scope, false); + if (found && d.isDataDescriptor() && d.value().isNumber()) + line = d.value().toNumber(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + } + { + JSC::PropertyDescriptor d; + bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->column, d); + RETURN_IF_EXCEPTION(scope, false); + if (found && d.isDataDescriptor() && d.value().isNumber()) + column = d.value().toNumber(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + } + { + JSC::PropertyDescriptor d; + bool found = errorInstance->getOwnPropertyDescriptor(m_lexicalGlobalObject, vm.propertyNames->sourceURL, d); + RETURN_IF_EXCEPTION(scope, false); + if (found && d.isDataDescriptor() && d.value().isString()) + sourceURL = d.value().toWTFString(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + } + { + JSValue v = errorInstance->get(m_lexicalGlobalObject, vm.propertyNames->stack); + RETURN_IF_EXCEPTION(scope, false); + if (v.isString()) + stack = v.toWTFString(m_lexicalGlobalObject); + RETURN_IF_EXCEPTION(scope, false); + } + + write(ErrorInstanceTag); + write(errorNameToSerializableErrorType(errorTypeString)); + writeNullableString(message); + write(line); + write(column); + writeNullableString(sourceURL); + writeNullableString(stack); return true; } if (obj->inherits()) { @@ -1422,12 +1345,6 @@ class CloneSerializer : public CloneBase { bool success = dumpArrayBufferView(obj, code); RETURN_IF_EXCEPTION(scope, false); recordObject(obj); - if (m_preserveNodeBuffers && success && code == SerializationReturnCode::SuccessfullyCompleted) { - bool isBuffer = isNodeBuffer(obj); - RETURN_IF_EXCEPTION(scope, false); - if (isBuffer) - m_nodeBuffers.append(obj); - } return success; } #if ENABLE(WEB_CRYPTO) @@ -1452,7 +1369,7 @@ class CloneSerializer : public CloneBase { dummyModules, dummyMemoryHandles, #endif - serializedKey, SerializationContext::Default, dummySharedBuffers, m_forStorage, m_forTransfer, false, nullptr); + serializedKey, SerializationContext::Default, dummySharedBuffers, m_forStorage, m_forTransfer); rawKeySerializer.write(key); write(serializedKey); return true; @@ -1720,79 +1637,9 @@ class CloneSerializer : public CloneBase { void writeObjectIndex(unsigned i) { - if (m_preserveNodeBuffers) - m_objectReferences.append({ m_buffer.size(), i, static_cast(m_objectPool.size()) }); writeConstantPoolIndex(m_objectPool, i); } - // Retain the v14 pre-scan's Buffer order and framing. Only cause-bearing - // graphs add identities discovered by the native walk. - bool finishBufferEnvelope() - { - auto& vm = m_lexicalGlobalObject->vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - JSArray* buffers = m_legacyNodeBuffers; - if (m_hasErrorCause && !m_nodeBuffers.isEmpty()) { - if (!buffers) { - buffers = constructEmptyArray(m_lexicalGlobalObject, static_cast(nullptr)); - RETURN_IF_EXCEPTION(scope, false); - m_gcBuffer.appendWithCrashOnOverflow(buffers); - } - HashSet seen; - for (unsigned i = 0; i < buffers->length(); ++i) - seen.add(buffers->getDirectIndex(m_lexicalGlobalObject, i).getObject()); - RETURN_IF_EXCEPTION(scope, false); - for (auto* buffer : m_nodeBuffers) { - if (seen.add(buffer).isNewEntry) - buffers->putDirectIndex(m_lexicalGlobalObject, buffers->length(), buffer); - RETURN_IF_EXCEPTION(scope, false); - } - } - if (!buffers) - return false; - if (m_objectPool.size() > std::numeric_limits::max() - 2) { - fail(); - return false; - } - write(static_cast(1)); - if (serialize(buffers) != SerializationReturnCode::SuccessfullyCompleted) { - fail(); - return false; - } - Vector valueBytes = WTF::move(m_buffer); - m_buffer = {}; - write(m_hasErrorCause ? CurrentVersion : DefaultVersion); - write(ArrayTag); - write(static_cast(2)); - write(static_cast(0)); - size_t cursor = sizeof(CurrentVersion); - auto indexWidth = [](uint32_t count) -> size_t { - return count <= 0xFF ? 1 : count <= 0xFFFF ? 2 - : 4; - }; - auto writeIndex = [&](uint32_t count, uint32_t index) { - if (count <= 0xFF) - write(static_cast(index)); - else if (count <= 0xFFFF) - write(static_cast(index)); - else - write(index); - }; - for (const auto& reference : m_objectReferences) { - write(valueBytes.span().data() + cursor, reference.offset - cursor); - if (m_failed) - return false; - writeIndex(reference.poolSize + 1, reference.index + 1); - cursor = reference.offset + indexWidth(reference.poolSize); - } - write(valueBytes.span().data() + cursor, valueBytes.size() - cursor); - if (m_failed) - return false; - write(TerminatorTag); - m_objectReferences.clear(); - return true; - } - template void writeConstantPoolIndex(const T& constantPool, unsigned i) { ASSERT(i < constantPool.size()); @@ -2141,17 +1988,6 @@ class CloneSerializer : public CloneBase { } } #endif - struct ObjectReference { - size_t offset; - uint32_t index; - uint32_t poolSize; - }; - Vector m_objectReferences; - Vector m_nodeBuffers; - // The dispatcher can check a nonterminal Error twice before visiting its cause. - ErrorInstance* m_pendingError { nullptr }; - JSValue m_pendingErrorCause; - bool m_hasErrorCause { false }; unsigned m_pendingContainerBytes { 0 }; ObjectPool m_objectPool; ObjectPool m_transferredMessagePorts; @@ -2168,8 +2004,6 @@ class CloneSerializer : public CloneBase { #endif SerializationForStorage m_forStorage; SerializationForCrossProcessTransfer m_forTransfer; - bool m_preserveNodeBuffers; - JSArray* m_legacyNodeBuffers; }; SYSV_ABI void SerializedScriptValue::writeBytesForBun(CloneSerializer* ctx, const uint8_t* data, uint32_t size) @@ -2400,29 +2234,6 @@ SerializationReturnCode CloneSerializer::serialize(JSValue in) goto setDataStartVisitEntry; } - errorStartState: - { - if (inputObjectStack.size() > maximumFilterRecursion) - return SerializationReturnCode::StackOverflowError; - auto* error = uncheckedDowncast(inValue); - ASSERT(m_pendingError == error); - JSValue cause = std::exchange(m_pendingErrorCause, JSValue()); - m_pendingError = nullptr; - m_hasErrorCause = true; - m_buffer[0] = CurrentVersion; - dumpError(error, ErrorInstanceWithCauseTag); - RETURN_IF_EXCEPTION(scope, SerializationReturnCode::ExistingExceptionError); - ASSERT(cause); - // Keep the Error in the same pool before traversing its cause, including self references. - inputObjectStack.append(error); - inValue = cause; - stateStack.append(ErrorEndVisitCause); - goto stateUnknown; - } - case ErrorEndVisitCause: - inputObjectStack.removeLast(); - break; - stateUnknown: case StateUnknown: { auto terminalCode = SerializationReturnCode::SuccessfullyCompleted; @@ -2440,8 +2251,6 @@ SerializationReturnCode CloneSerializer::serialize(JSValue in) goto mapStartState; if (isSet(inValue)) goto setStartState; - if (inValue.inherits()) - goto errorStartState; goto objectStartState; } } @@ -2595,7 +2404,7 @@ class CloneDeserializer : public CloneBase { DeserializationResult deserialize(); - bool isValid() const { return m_version <= DefaultVersion || m_version == CurrentVersion; } + bool isValid() const { return m_version <= CurrentVersion; } template bool readLittleEndian(T& value) { @@ -3774,43 +3583,6 @@ class CloneDeserializer : public CloneBase { return tryConvertToBigInt32(bigInt); } - ErrorInstance* readError() - { - SerializableErrorType serializedErrorType; - if (!read(serializedErrorType)) { - fail(); - return nullptr; - } - String message; - if (!readNullableString(message)) { - fail(); - return nullptr; - } - uint32_t line; - if (!read(line)) { - fail(); - return nullptr; - } - uint32_t column; - if (!read(column)) { - fail(); - return nullptr; - } - String sourceURL; - if (!readNullableString(sourceURL)) { - fail(); - return nullptr; - } - String stackString; - if (!readNullableString(stackString)) { - fail(); - return nullptr; - } - auto* obj = ErrorInstance::create(m_lexicalGlobalObject, WTF::move(message), toErrorType(serializedErrorType), { line, column }, WTF::move(sourceURL), WTF::move(stackString)); - addTerminalToObjectPool(obj); - return obj; - } - JSValue readTerminal() { const uint8_t* preTagPtr = m_ptr; @@ -3939,12 +3711,40 @@ class CloneDeserializer : public CloneBase { return obj; } case ErrorInstanceTag: { - auto* error = readError(); - return error ? JSValue(error) : JSValue(); + SerializableErrorType serializedErrorType; + if (!read(serializedErrorType)) { + fail(); + return JSValue(); + } + String message; + if (!readNullableString(message)) { + fail(); + return JSValue(); + } + uint32_t line; + if (!read(line)) { + fail(); + return JSValue(); + } + uint32_t column; + if (!read(column)) { + fail(); + return JSValue(); + } + String sourceURL; + if (!readNullableString(sourceURL)) { + fail(); + return JSValue(); + } + String stackString; + if (!readNullableString(stackString)) { + fail(); + return JSValue(); + } + auto* obj = ErrorInstance::create(m_lexicalGlobalObject, WTF::move(message), toErrorType(serializedErrorType), { line, column }, WTF::move(sourceURL), WTF::move(stackString)); + addTerminalToObjectPool(obj); + return obj; } - case ErrorInstanceWithCauseTag: - m_ptr = preTagPtr; - return JSValue(); case ObjectReferenceTag: { auto index = readConstantPoolIndex(m_objectPool); if (!index || *index >= static_cast(m_objectPool.size())) { @@ -4352,27 +4152,6 @@ DeserializationResult CloneDeserializer::deserialize() goto setDataStartVisitEntry; } - errorStartState: - { - if (outputObjectStack.size() > maximumFilterRecursion) - return std::make_pair(JSValue(), SerializationReturnCode::StackOverflowError); - auto* error = readError(); - if (scope.exception() || !error) - goto error; - outputObjectStack.append(error); - stateStack.append(ErrorEndVisitCause); - goto stateUnknown; - } - case ErrorEndVisitCause: { - auto* error = outputObjectStack.last(); - error->putDirect(vm, vm.propertyNames->cause, outValue, static_cast(PropertyAttribute::DontEnum)); - if (scope.exception()) - goto error; - outValue = error; - outputObjectStack.removeLast(); - break; - } - stateUnknown: case StateUnknown: JSValue terminal = readTerminal(); @@ -4393,8 +4172,6 @@ DeserializationResult CloneDeserializer::deserialize() goto mapObjectStartState; if (tag == SetObjectTag) goto setObjectStartState; - if (tag == ErrorInstanceWithCauseTag && m_version >= FirstVersionWithErrorCause) - goto errorStartState; goto error; } if (stateStack.isEmpty()) @@ -4707,24 +4484,6 @@ static bool isObjectFastPathCandidate(Structure* structure) return true; } -ExceptionOr> SerializedScriptValue::createForNode(JSGlobalObject& globalObject, JSValue value, SerializationForStorage forStorage, SerializationForCrossProcessTransfer forTransfer, bool& hasBufferEnvelope, SerializationContext context) -{ - auto& vm = globalObject.vm(); - auto scope = DECLARE_THROW_SCOPE(vm); - auto* global = uncheckedDowncast(&globalObject); - auto* tagFunction = global->m_ipcTagAdvancedBuffersFunction.getInitializedOnMainThread(global); - MarkedArgumentBuffer args; - args.append(value); - auto tagged = JSC::call(global, tagFunction, JSC::getCallData(tagFunction), jsUndefined(), args); - RETURN_IF_EXCEPTION(scope, Exception { ExistingExceptionError }); - Strong taggedRoot(vm, tagged.getObject()); - auto* legacyBuffers = tagged.isNull() ? nullptr : asArray(asArray(tagged)->getDirectIndex(global, 1)); - RETURN_IF_EXCEPTION(scope, Exception { ExistingExceptionError }); - Vector> ports; - hasBufferEnvelope = false; - RELEASE_AND_RETURN(scope, create(globalObject, value, {}, ports, forStorage, SerializationErrorMode::Throwing, context, forTransfer, &hasBufferEnvelope, legacyBuffers)); -} - RefPtr SerializedScriptValue::create(JSC::JSGlobalObject& globalObject, JSC::JSValue value, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext serializationContext, SerializationForCrossProcessTransfer forTransfer) { Vector> dummyPorts; @@ -4739,13 +4498,13 @@ ExceptionOr> SerializedScriptValue::create(JSGlobalOb return create(globalObject, value, WTF::move(transferList), messagePorts, forStorage, SerializationErrorMode::Throwing, serializationContext, forTransfer); } -ExceptionOr> SerializedScriptValue::create(JSGlobalObject& lexicalGlobalObject, JSValue value, Vector>&& transferList, Vector>& messagePorts, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext context, SerializationForCrossProcessTransfer forTransfer, bool* hasBufferEnvelope, JSArray* legacyNodeBuffers) +ExceptionOr> SerializedScriptValue::create(JSGlobalObject& lexicalGlobalObject, JSValue value, Vector>&& transferList, Vector>& messagePorts, SerializationForStorage forStorage, SerializationErrorMode throwExceptions, SerializationContext context, SerializationForCrossProcessTransfer forTransfer) { VM& vm = lexicalGlobalObject.vm(); auto scope = DECLARE_THROW_SCOPE(vm); // Fast path optimization: for postMessage/structuredClone with pure strings and no transfers - const bool canUseFastPath = !hasBufferEnvelope && (context == SerializationContext::WorkerPostMessage || context == SerializationContext::WindowPostMessage || context == SerializationContext::Default) + const bool canUseFastPath = (context == SerializationContext::WorkerPostMessage || context == SerializationContext::WindowPostMessage || context == SerializationContext::Default) && forStorage == SerializationForStorage::No && forTransfer == SerializationForCrossProcessTransfer::No && transferList.isEmpty() @@ -5027,7 +4786,7 @@ ExceptionOr> SerializedScriptValue::create(JSGlobalOb wasmModules, wasmMemoryHandles, #endif - buffer, context, *sharedBuffers, serializedBlockListRefs, forStorage, forTransfer, hasBufferEnvelope, legacyNodeBuffers); + buffer, context, *sharedBuffers, serializedBlockListRefs, forStorage, forTransfer); auto releaseSerializedBlockListRefs = [&] { for (auto* ptr : serializedBlockListRefs) diff --git a/src/jsc/bindings/webcore/SerializedScriptValue.h b/src/jsc/bindings/webcore/SerializedScriptValue.h index b57ac26892db..38a38b9cc6c2 100644 --- a/src/jsc/bindings/webcore/SerializedScriptValue.h +++ b/src/jsc/bindings/webcore/SerializedScriptValue.h @@ -88,9 +88,7 @@ enum class SerializationErrorMode { NonThrowing, Throwing }; enum class SerializationContext { Default, WorkerPostMessage, - WindowPostMessage, - WorkerError, - LegacyIPC }; + WindowPostMessage }; enum class SerializationForStorage : bool { No, Yes }; enum class SerializationForCrossProcessTransfer : bool { No, @@ -120,9 +118,6 @@ class SerializedScriptValue : public ThreadSafeRefCounted static RefPtr convert(JSC::JSGlobalObject& globalObject, JSC::JSValue value) { return create(globalObject, value, SerializationForStorage::Yes); } - // Node transports retain Buffer identities from the actual serialization walk. - WEBCORE_EXPORT static ExceptionOr> createForNode(JSC::JSGlobalObject&, JSC::JSValue, SerializationForStorage, SerializationForCrossProcessTransfer, bool& hasBufferEnvelope, SerializationContext = SerializationContext::Default); - // Fast path for postMessage with pure strings static Ref createStringFastPath(const String& string); @@ -158,7 +153,7 @@ class SerializedScriptValue : public ThreadSafeRefCounted WEBCORE_EXPORT ~SerializedScriptValue(); private: - static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, Vector>&, SerializationForStorage, SerializationErrorMode, SerializationContext, SerializationForCrossProcessTransfer, bool* hasBufferEnvelope = nullptr, JSC::JSArray* legacyNodeBuffers = nullptr); + static ExceptionOr> create(JSC::JSGlobalObject&, JSC::JSValue, Vector>&& transfer, Vector>&, SerializationForStorage, SerializationErrorMode, SerializationContext, SerializationForCrossProcessTransfer); WEBCORE_EXPORT SerializedScriptValue(Vector&&, std::unique_ptr&& = nullptr); SerializedScriptValue(Vector&&, std::unique_ptr, std::unique_ptr sharedBuffers diff --git a/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp b/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp index 3ef9f8867fe0..202fac234c16 100644 --- a/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp +++ b/src/jsc/bindings/webcore/WorkerMessagingProxy.cpp @@ -685,7 +685,7 @@ static RefPtr serializeWorkerErrorMetadata(Zig::G scope.clearException(); } } - metadata->properties = SerializedScriptValue::create(globalObject, propertiesObject, SerializationForStorage::No, SerializationErrorMode::NonThrowing, SerializationContext::WorkerError); + metadata->properties = SerializedScriptValue::create(globalObject, propertiesObject, SerializationForStorage::No, SerializationErrorMode::NonThrowing); } CLEAR_IF_EXCEPTION(scope); @@ -706,7 +706,7 @@ static RefPtr serializeWorkerErrorMetadata(Zig::G if (cause.isCallable() || cause.isSymbol()) return metadata; - metadata->cause = SerializedScriptValue::create(globalObject, cause, SerializationForStorage::No, SerializationErrorMode::NonThrowing, SerializationContext::WorkerError); + metadata->cause = SerializedScriptValue::create(globalObject, cause, SerializationForStorage::No, SerializationErrorMode::NonThrowing); CLEAR_IF_EXCEPTION(scope); if (!metadata->cause) return metadata; @@ -776,7 +776,7 @@ bool WorkerMessagingProxy::postSerializedErrorToWorkerObject(Zig::GlobalObject& auto& vm = JSC::getVM(&workerGlobalObject); auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm); - auto serialized = SerializedScriptValue::create(workerGlobalObject, value, SerializationForStorage::No, SerializationErrorMode::NonThrowing, SerializationContext::WorkerError); + auto serialized = SerializedScriptValue::create(workerGlobalObject, value, SerializationForStorage::No, SerializationErrorMode::NonThrowing); CLEAR_IF_EXCEPTION(scope); // Cloning an Error reads `stack`; when that getter throws (a throwing Error.prepareStackTrace), // Node drops only `stack` (lib/internal/error_serdes.js TryGetAllProperties) rather than the @@ -790,7 +790,7 @@ bool WorkerMessagingProxy::postSerializedErrorToWorkerObject(Zig::GlobalObject& CLEAR_IF_EXCEPTION(scope); errorInstance->putDirect(vm, vm.propertyNames->stack, JSC::jsUndefined(), static_cast(JSC::PropertyAttribute::DontEnum)); if (!vm.hasPendingTerminationException()) - serialized = SerializedScriptValue::create(workerGlobalObject, value, SerializationForStorage::No, SerializationErrorMode::NonThrowing, SerializationContext::WorkerError); + serialized = SerializedScriptValue::create(workerGlobalObject, value, SerializationForStorage::No, SerializationErrorMode::NonThrowing); CLEAR_IF_EXCEPTION(scope); } } @@ -801,8 +801,9 @@ bool WorkerMessagingProxy::postSerializedErrorToWorkerObject(Zig::GlobalObject& // preserves a string `error.code` (lib/internal/error_serdes.js). String errorCode = errorCodeOf(workerGlobalObject, value); - // WorkerError omits causes from the general clone so this bounded, best-effort - // metadata owner alone handles them, including uncloneable causes and enumerable fields. + // Node's worker error serializer preserves an Error's own enumerable metadata and recursively + // serializes `cause`. The ordinary structured-clone Error path intentionally keeps only + // standard Error fields, so carry these worker-only additions separately. RefPtr serializedMetadata; if (auto* errorInstance = dynamicDowncast(value)) { HashSet seen; diff --git a/src/runtime/ipc.rs b/src/runtime/ipc.rs index 781fa4ee0ac4..50e5c17086b5 100644 --- a/src/runtime/ipc.rs +++ b/src/runtime/ipc.rs @@ -262,16 +262,10 @@ mod advanced { const HEADER_LENGTH: usize = size_of::() + size_of::(); // HEADER_LENGTH is a 5-byte compile-time constant; narrowing to u32 is provably safe. const HEADER_LENGTH_U32: u32 = HEADER_LENGTH as u32; - // The low 16 bits remain protocol v2; old readers consume and ignore the - // entire hello word, so its high bits can advertise serializer capabilities. + // v2 added `SerializedMessageWithBuffers`. The peer's advertised version is + // debug-logged, never consulted, so mixed-version pairs only break when a + // Buffer-bearing message actually crosses to a v1 peer. const VERSION: u32 = 2; - const VERSION_MASK: u32 = 0xFFFF; - // Bit 16 identified the incompatible, intermediate v15 Error layout. - const ERROR_CAUSE_CAPABILITY: u32 = 1 << 17; - - pub(super) fn supports_error_cause(hello: u32) -> bool { - hello & VERSION_MASK == VERSION && hello & ERROR_CAUSE_CAPABILITY != 0 - } #[repr(u8)] #[derive(Copy, Clone, Eq, PartialEq)] @@ -301,7 +295,7 @@ mod advanced { } static VERSION_PACKET_BYTES: [u8; HEADER_LENGTH] = { - let v = (VERSION | ERROR_CAUSE_CAPABILITY).to_le_bytes(); + let v = VERSION.to_ne_bytes(); [IPCMessageType::Version as u8, v[0], v[1], v[2], v[3]] }; @@ -392,27 +386,29 @@ mod advanced { global: &JSGlobalObject, value: JSValue, is_internal: IsInternal, - peer_supports_error_cause: bool, ) -> Result { // Internal (control) messages never carry user Buffers, and the // hardcoded ack/nack packets depend on their bare wire shape. + let (value, message_type) = match is_internal { + IsInternal::Internal => (value, IPCMessageType::SerializedInternalMessage), + IsInternal::External => { + let tagged = ipc_tag_advanced_buffers(global, value)?; + if tagged.is_null() { + (value, IPCMessageType::SerializedMessage) + } else { + (tagged, IPCMessageType::SerializedMessageWithBuffers) + } + } + }; + let serialized = value.serialize( global, SerializedFlags { - // IPC sends across process. Internal ACK/NACK messages stay bare. + // IPC sends across process. for_cross_process_transfer: true, for_storage: false, - preserve_node_buffers: matches!(is_internal, IsInternal::External), - omit_error_cause: !peer_supports_error_cause, }, )?; - let message_type = match is_internal { - IsInternal::Internal => IPCMessageType::SerializedInternalMessage, - IsInternal::External if serialized.has_buffer_envelope() => { - IPCMessageType::SerializedMessageWithBuffers - } - IsInternal::External => IPCMessageType::SerializedMessage, - }; // `serialized` Drops at scope exit (defer serialized.deinit()). let size: u32 = u32::try_from(serialized.data().len()).expect("int cast"); @@ -626,16 +622,9 @@ pub(crate) fn serialize( global: &JSGlobalObject, value: JSValue, is_internal: IsInternal, - peer_supports_error_cause: bool, ) -> Result { match mode { - Mode::Advanced => advanced::serialize( - writer, - global, - value, - is_internal, - peer_supports_error_cause, - ), + Mode::Advanced => advanced::serialize(writer, global, value, is_internal), Mode::Json => json::serialize(writer, global, value, is_internal), } } @@ -917,7 +906,6 @@ pub(crate) struct SendQueue { #[cfg(debug_assertions)] pub(crate) has_written_version: Cell, pub(crate) mode: Mode, - peer_supports_error_cause: Cell, pub internal_msg_queue: JsCell, incoming: JsCell, pub(crate) incoming_fd: Cell>, @@ -1046,7 +1034,6 @@ impl SendQueue { #[cfg(debug_assertions)] has_written_version: Cell::new(0), mode, - peer_supports_error_cause: Cell::new(false), internal_msg_queue: JsCell::new(InternalMsgHolder::default()), incoming: JsCell::new(IncomingBuffer::init(mode)), incoming_fd: Cell::new(None), @@ -1660,20 +1647,7 @@ impl SendQueue { let immediate = self.queue.get().is_empty() && self.waiting_for_ack.get().is_none(); let mode = self.mode; let mut payload = StreamBuffer::default(); - let supports_error_cause = self.peer_supports_error_cause.get(); - if mode == Mode::Advanced && !supports_error_cause { - log!( - "Peer has not advertised Error.cause support; serializing legacy v14 without causes" - ); - } - let payload_length = match serialize( - mode, - &mut payload, - global, - value, - is_internal, - supports_error_cause, - ) { + let payload_length = match serialize(mode, &mut payload, global, value, is_internal) { Ok(n) => n, Err(_) => return SerializeAndSendResult::Failure, }; @@ -2131,11 +2105,6 @@ fn handle_ipc_message( message: DecodedIPCMessage, global_this: &JSGlobalObject, ) -> JsResult<()> { - if let DecodedIPCMessage::Version(hello) = message { - send_queue - .peer_supports_error_cause - .set(advanced::supports_error_cause(hello)); - } #[cfg(debug_assertions)] { // The `Formatter` runs its deinit in `Drop`. @@ -2659,6 +2628,16 @@ pub(crate) fn ipc_serialize( bun_jsc::cpp::IPCSerialize(global_object, message, handle, options) } +#[track_caller] +pub(crate) fn ipc_tag_advanced_buffers( + global_object: &JSGlobalObject, + message: JSValue, +) -> JsResult { + // `[[ZIG_EXPORT(zero_is_throw)]]`; returns null when the message holds no + // Buffers, else the `[message, buffers]` envelope (see Ipc.ts). + bun_jsc::cpp::IPCTagAdvancedBuffers(global_object, message) +} + #[track_caller] pub(crate) fn ipc_restore_advanced_buffers( global_object: &JSGlobalObject, diff --git a/test/js/bun/spawn/spawn.ipc.test.ts b/test/js/bun/spawn/spawn.ipc.test.ts index 281a7317e536..67a4f313bf38 100644 --- a/test/js/bun/spawn/spawn.ipc.test.ts +++ b/test/js/bun/spawn/spawn.ipc.test.ts @@ -355,9 +355,9 @@ it("child with unusable NODE_CHANNEL_FD tears down IPC without crashing", async expect(exitCode).toBe(0); }); -it.skipIf(isWindows)("advanced serialization advertises protocol 2 and Error.cause support", async () => { +it.skipIf(isWindows)("advanced serialization advertises wire format version 2", async () => { // The version packet is the first frame on the channel: - // [type=Version(1), u16 LE protocol=2, u16 LE capabilities=2]. Read it raw off fd 3 before the + // [type=Version(1), u32 LE version]. Read it raw off fd 3 before the // child's own channel machinery starts consuming the socket. await using child = Bun.spawn({ cmd: [ @@ -381,7 +381,7 @@ it.skipIf(isWindows)("advanced serialization advertises protocol 2 and Error.cau ipc() {}, }); const [stdout, exitCode] = await Promise.all([child.stdout.text(), child.exited]); - expect(JSON.parse(stdout.trim())).toEqual([1, 2, 0, 2, 0]); + expect(JSON.parse(stdout.trim())).toEqual([1, 2, 0, 0, 0]); expect(exitCode).toBe(0); }); diff --git a/test/js/node/child_process/child_process_ipc.test.js b/test/js/node/child_process/child_process_ipc.test.js index 39d472385b96..e803886fff1e 100644 --- a/test/js/node/child_process/child_process_ipc.test.js +++ b/test/js/node/child_process/child_process_ipc.test.js @@ -1,27 +1,6 @@ import { $ } from "bun"; import { bunEnv, bunExe, tempDir } from "harness"; -for (const kind of ["object", "error", "cause"]) { - for (const direction of ["parent", "child"]) { - test.concurrent(`advanced IPC negotiates Error.cause: ${kind} from ${direction}`, async () => { - await using child = Bun.spawn({ - cmd: [bunExe(), `${import.meta.dir}/fixtures/error-cause-ipc.cjs`, bunExe(), kind, direction, "true"], - env: bunEnv, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([child.stdout.text(), child.stderr.text(), child.exited]); - expect(stderr).toBe(""); - expect(JSON.parse(stdout)).toEqual( - kind === "object" - ? { answer: 42, error: false } - : { error: true, message: "outer", ...(kind === "cause" ? { cause: "inner" } : {}) }, - ); - expect(exitCode).toBe(0); - }); - } -} - test("child_process ipc", async () => { const output = await $`${bunExe()} ${import.meta.dir}/fixtures/ipc_fixture.js`.text(); // node (v23.4.0) has identical output diff --git a/test/js/node/child_process/fixtures/error-cause-ipc.cjs b/test/js/node/child_process/fixtures/error-cause-ipc.cjs deleted file mode 100644 index 24ed90ae9125..000000000000 --- a/test/js/node/child_process/fixtures/error-cause-ipc.cjs +++ /dev/null @@ -1,51 +0,0 @@ -const { fork } = require("node:child_process"); -const { once } = require("node:events"); -const assert = require("node:assert/strict"); - -function payload(kind) { - if (kind === "object") return { answer: 42 }; - const error = new Error("outer"); - error.stack = "stable"; - if (kind === "cause") error.cause = new Error("inner"); - return error; -} - -function summarize(value) { - return { answer: value.answer, error: value instanceof Error, message: value.message, cause: value.cause?.message }; -} - -if (process.argv[2] === "child") { - process.on("message", ({ kind, direction }) => { - if (direction === "child") process.send(payload(kind)); - else process.send(summarize(kind)); - }); - process.send("ready"); -} else { - (async () => { - const [childExecutable, kind, direction, expectedCause] = process.argv.slice(2); - const child = fork(__filename, ["child"], { - execPath: childExecutable, - serialization: "advanced", - stdio: ["ignore", "inherit", "inherit", "ipc"], - }); - try { - assert.equal((await once(child, "message"))[0], "ready"); - const reply = once(child, "message"); - child.send(direction === "child" ? { kind, direction } : { kind: payload(kind), direction }); - const value = (await reply)[0]; - const result = direction === "child" ? summarize(value) : value; - assert.equal(result.error, kind !== "object"); - if (kind === "object") assert.equal(result.answer, 42); - else assert.equal(result.message, "outer"); - assert.equal(result.cause, expectedCause === "true" && kind === "cause" ? "inner" : undefined); - console.log(JSON.stringify(result)); - } finally { - const exit = once(child, "exit"); - child.kill(); - await exit; - } - })().catch(error => { - console.error(error); - process.exitCode = 1; - }); -} diff --git a/test/js/node/v8/legacy-clone-golden.fixture.json b/test/js/node/v8/legacy-clone-golden.fixture.json deleted file mode 100644 index 139e3fef0f48..000000000000 --- a/test/js/node/v8/legacy-clone-golden.fixture.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "primitives": "9fe335d551e8ef71bcd30b72040071246f36e15f62210596bdd7205cdf3f7c82", - "object": "59dc238949a0de68350f462a46ed0591d56b030e70bcd5bce7843b8a22aa1e6b", - "holes": "35170162854c1245c5c4bd0bc11b51aee211198d571bb66917320f5f3678273a", - "terminals": "df955f577f604cd42d84b3a712fd2a2d380061e737bf1c6a939e187762d0b78c", - "collections": "d9934e3552e683119b08ad27abfa455d74d5647e433f62d62164e5bf6f26c7c8", - "views": "15d483ea50c87db40152dcf380a2da69496e4c4f6b886faa1db5198f1c9a861c", - "buffers": "2163e5cf52ff0a40dafaf8a314b89fd6077eb18bfe5445e0d4a149caee1aa6ee", - "nestedBuffers": "a3749c9b64624b37e12736c0737da4a95572420a8aa5c747ae822412a9d304b5", - "getterBuffer": "1e48d3b90c9539431743aafe57db130e88c28d0affb97d5839cc857cadf567a4", - "bufferPoolBoundary": "661534cf720ff7273df10ddb432d79662d255c27c241e00634389b316cf537a0" -} diff --git a/test/js/node/v8/legacy-clone-graphs.fixture.mjs b/test/js/node/v8/legacy-clone-graphs.fixture.mjs deleted file mode 100644 index d372351034ac..000000000000 --- a/test/js/node/v8/legacy-clone-graphs.fixture.mjs +++ /dev/null @@ -1,29 +0,0 @@ -export function legacyGraphs() { - const error = new TypeError("stable"); - error.stack = "stable"; - error.line = 0; - error.column = 0; - error.sourceURL = ""; - const a = Buffer.alloc(3, 1); - const b = Buffer.alloc(2, 2); - const shared = { n: 1 }; - const cycle = { shared, again: shared }; - cycle.self = cycle; - const slots = Array.from({ length: 254 }, (_, n) => ({ n })); - return { - primitives: [undefined, null, false, true, 0, -1, 1.5, "hello", "é", 123n], - object: { answer: 42, nested: ["x", { ok: true }] }, - holes: [1, , undefined, , 4], - terminals: [new Date(42), /abc/gi, error, error], - collections: [new Map([[shared, [1, 2]]]), new Set([shared]), cycle], - views: [new Uint8Array([1, 2]), new Uint16Array([3, 4]), new ArrayBuffer(2)], - buffers: { a, b, again: a }, - nestedBuffers: new Map([[a, { b, a }]]), - getterBuffer: { - get value() { - return a; - }, - }, - bufferPoolBoundary: { slots, a, again: a, first: slots[0], last: slots.at(-1) }, - }; -} diff --git a/test/js/node/v8/v8-serdes-buffer.test.ts b/test/js/node/v8/v8-serdes-buffer.test.ts index 903926c3cc7f..6ab422212b20 100644 --- a/test/js/node/v8/v8-serdes-buffer.test.ts +++ b/test/js/node/v8/v8-serdes-buffer.test.ts @@ -1,28 +1,11 @@ import { describe, expect, test } from "bun:test"; import { bunEnv, bunExe } from "harness"; -import { createHash } from "node:crypto"; import v8 from "node:v8"; -import legacyGolden from "./legacy-clone-golden.fixture.json"; -import { legacyGraphs } from "./legacy-clone-graphs.fixture.mjs"; // Buffer identity through v8.serialize/deserialize, matching node v26.3.0's // serializer delegate behavior (DefaultSerializer host objects). Non-Buffer -// payloads keep bare JSC framing instead of the Buffer envelope. +// payloads keep the bare JSC-serialized format for backward compatibility. describe("v8 serialize/deserialize Buffer identity", () => { - test("cause-free graphs retain the pre-cause v14 bytes", () => { - for (const [name, value] of Object.entries(legacyGraphs())) { - const bytes = v8.serialize(value); - expect(createHash("sha256").update(bytes).digest("hex")).toBe(legacyGolden[name]); - } - }); - - test("only a graph with a cause edge requires v16", () => { - const error = new Error("empty"); - error.stack = "stable"; - expect(v8.serialize([error, error]).readUInt32LE(0)).toBe(14); - error.cause = undefined; - expect(v8.serialize([new Error("first"), error]).readUInt32LE(0)).toBe(16); - }); test.each([new Uint8Array([1, 2]), Buffer.from([1, 2])])("serialized output is transferable: %p", input => { const serialized = v8.serialize(input); expect(serialized.buffer).toBeInstanceOf(ArrayBuffer); @@ -67,163 +50,14 @@ describe("v8 serialize/deserialize Buffer identity", () => { expect(Buffer.isBuffer(value.v)).toBe(true); }); - test("Error.cause-only Buffers retain their type and graph identity", () => { - const buffer = Buffer.from("cause").subarray(1, 4); - const error = new Error("outer", { cause: new Map([[buffer, buffer]]) }); - const out = v8.deserialize(v8.serialize(error)); - expect(out).toBeInstanceOf(Error); - expect(out.cause).toBeInstanceOf(Map); - const [[key, value]] = [...out.cause]; - expect(Buffer.isBuffer(key)).toBe(true); - expect(key).toBe(value); - expect(key.toString()).toBe("aus"); - }); - - test.each(["name", "message", "stack"])("cause snapshot retains Buffer brand and bytes before %s effects", field => { - const source = new Error("outer", { cause: Buffer.from("original").subarray(1, 5) }); - source.stack = ""; - let calls = 0; - const effect = () => { - calls++; - source.cause = Buffer.from("replacement"); - return field === "name" ? "Error" : "metadata"; - }; - Object.defineProperty(source, field, field === "message" ? { value: { toString: effect } } : { get: effect }); - const out = v8.deserialize(v8.serialize(source)); - expect(calls).toBe(1); - expect(Buffer.isBuffer(out.cause)).toBe(true); - expect(out.cause.toString()).toBe("rigi"); - expect(out.cause.length).toBe(4); - }); - - for (const initial of ["buffer", "absent"]) { - test.each(["name", "message", "stack"])( - `later Error with ${initial} cause retains a Buffer introduced by %s effects`, - field => { - const later = initial === "buffer" ? new Error("later", { cause: Buffer.from("old") }) : new Error("later"); - const first = new Error("first"); - first.stack = ""; - let calls = 0; - const effect = () => { - calls++; - const buffer = Buffer.from("!new!").subarray(1, 4); - later.cause = new Map([[buffer, [buffer, buffer]]]); - return field === "name" ? "Error" : "metadata"; - }; - Object.defineProperty(first, field, field === "message" ? { value: { toString: effect } } : { get: effect }); - const out = v8.deserialize(v8.serialize([first, later, later])); - expect(calls).toBe(1); - expect(out[1]).toBe(out[2]); - expect(out[1].cause).toBeInstanceOf(Map); - const [[key, values]] = [...out[1].cause]; - expect(Array.from(key)).toEqual([110, 101, 119]); - expect(Buffer.isBuffer(key)).toBe(true); - expect(key.toString()).toBe("new"); - expect(values[0]).toBe(key); - expect(values[1]).toBe(key); - }, - ); - } - - test("Error.cause Buffer serialization terminates on Error cycles without invoking accessors", () => { - const error = new Error("outer"); - const nested = new Error("inner", { cause: error }); - const accessor = new Error("accessor"); - let reads = 0; - Object.defineProperty(accessor, "cause", { - get() { - reads++; - throw new Error("must not read accessor"); - }, - }); - error.cause = [nested, Buffer.from("cycle"), accessor]; - const out = v8.deserialize(v8.serialize(error)); - expect(out.cause[0].cause).toBe(out); - expect(Buffer.isBuffer(out.cause[1])).toBe(true); - expect(out.cause[1].toString()).toBe("cycle"); - expect(Object.hasOwn(out.cause[2], "cause")).toBe(false); - expect(reads).toBe(0); - }); - - test("Buffer-free payloads keep bare JSC framing in the current runtime", () => { + test("Buffer-free payloads keep the bare format (old readers still work)", () => { const jsc = require("bun:jsc"); const bytes = v8.serialize({ n: 1, s: "x" }); // Bare JSC bytes deserialize directly — no envelope framing present. expect(jsc.deserialize(bytes)).toEqual({ n: 1, s: "x" }); - // deserialize also accepts current bare output from jsc.serialize. - const bare = jsc.serialize({ buf: new Uint8Array([7]) }, { binaryType: "nodebuffer" }); - expect(v8.deserialize(bare)).toEqual({ buf: new Uint8Array([7]) }); - }); - - test.each([249, 250, 251, 252, 65529, 65530, 65531, 65532])( - "Buffer envelope retains aliases across %i values", - count => { - const buffer = Buffer.from("slots"); - const values = Array.from({ length: count }, (_, index) => ({ index })); - const input: any = { values, buffer, again: buffer, first: values[0], last: values.at(-1) }; - input.self = input; - const out = v8.deserialize(v8.serialize(input)); - expect(out.self).toBe(out); - expect(out.first).toBe(out.values[0]); - expect(out.last).toBe(out.values.at(-1)); - expect(out.buffer).toBe(out.again); - expect(Buffer.isBuffer(out.buffer)).toBe(true); - expect(out.buffer.toString()).toBe("slots"); - }, - ); - - test("Buffer-free Error graphs retain byte-for-byte bare framing", () => { - const jsc = require("bun:jsc"); - const error = new Error("bare", { cause: new Map([["cause", { n: 1 }]]) }); - error.stack = "stable"; - const input = [error, error]; - expect(v8.serialize(input)).toEqual(jsc.serialize(input, { binaryType: "nodebuffer" })); - }); - - test("advanced IPC tags Buffers introduced by earlier Error metadata", async () => { - const source = [ - 'process.once("message", () => {', - "let calls = 0;", - 'for (const initial of ["buffer", "absent"]) for (const field of ["name", "message", "stack"]) {', - ' const later = initial === "buffer" ? new Error("later", { cause: Buffer.from("old") }) : new Error("later");', - ' const first = new Error("first"); first.stack = "";', - ' const effect = () => { calls++; const b = Buffer.from("new"); later.cause = new Map([[b, b]]); return field === "name" ? "Error" : "metadata"; };', - ' Object.defineProperty(first, field, field === "message" ? { value: { toString: effect } } : { get: effect });', - " process.send([first, later, later]);", - "}", - "process.send({ done: true, calls });", - "});", - ].join("\n"); - const { promise, resolve, reject } = Promise.withResolvers(); - const messages: any[] = []; - let calls; - await using child = Bun.spawn({ - cmd: [bunExe(), "-e", source], - env: bunEnv, - stdout: "ignore", - stderr: "inherit", - serialization: "advanced", - ipc(message) { - if (message?.done) { - calls = message.calls; - resolve(); - } else messages.push(message); - }, - onExit(_child, code, signal) { - reject(new Error("IPC child exited before completion: " + code + "/" + signal)); - }, - }); - child.send("ready"); - await promise; - expect(calls).toBe(6); - expect(messages).toHaveLength(6); - for (const out of messages) { - expect(out[1]).toBe(out[2]); - const [[key, value]] = [...out[1].cause]; - expect(key).toBe(value); - expect(Buffer.isBuffer(key)).toBe(true); - expect(key.toString()).toBe("new"); - } + // And deserialize accepts pre-envelope output produced by jsc.serialize. + const legacy = jsc.serialize({ buf: new Uint8Array([7]) }, { binaryType: "nodebuffer" }); + expect(v8.deserialize(legacy)).toEqual({ buf: new Uint8Array([7]) }); }); test("rejects an envelope whose buffer list holds a non-Uint8Array view", () => { diff --git a/test/js/web/structured-clone-shared-array-buffer.test.ts b/test/js/web/structured-clone-shared-array-buffer.test.ts index 9070f059764e..0fe1e595957c 100644 --- a/test/js/web/structured-clone-shared-array-buffer.test.ts +++ b/test/js/web/structured-clone-shared-array-buffer.test.ts @@ -1,6 +1,4 @@ -import { deserialize as jscDeserialize, serialize as jscSerialize } from "bun:jsc"; import { describe, expect, test } from "bun:test"; -import { deserialize as v8Deserialize, serialize as v8Serialize } from "node:v8"; // structuredClone stays inside the agent cluster, so SharedArrayBuffers share // their backing store like node and the HTML spec's StructuredSerialize. @@ -51,97 +49,3 @@ describe("structuredClone(SharedArrayBuffer)", () => { } }); }); - -describe("Error.cause SharedArrayBuffer graph", () => { - test("an ArrayBuffer cause transfers once and retains view aliases", () => { - const buffer = new ArrayBuffer(4); - const view = new Uint8Array(buffer); - view[0] = 42; - const result = structuredClone(new Error("transfer", { cause: { buffer, view } }), { transfer: [buffer] }); - expect(buffer.byteLength).toBe(0); - expect(result.cause.buffer).toBeInstanceOf(ArrayBuffer); - expect(result.cause.view.buffer).toBe(result.cause.buffer); - expect([...result.cause.view]).toEqual([42, 0, 0, 0]); - }); - - test("a failing cause leaves transferred buffers attached", () => { - const buffer = new ArrayBuffer(4); - new Uint8Array(buffer)[0] = 42; - const source = new Error("invalid", { cause: { buffer, invalid: () => {} } }); - expect(() => structuredClone(source, { transfer: [buffer] })).toThrow( - expect.objectContaining({ name: "DataCloneError" }), - ); - expect(buffer.byteLength).toBe(4); - expect([...new Uint8Array(buffer)]).toEqual([42, 0, 0, 0]); - }); - - for (const [name, serialize, deserialize] of [ - ["bun:jsc", jscSerialize, jscDeserialize], - ["node:v8", v8Serialize, v8Deserialize], - ] as const) { - test("storage serialization copies shared causes into private buffers: " + name, () => { - const buffer = new SharedArrayBuffer(4); - const view = new Uint8Array(buffer); - view[0] = 42; - const result = deserialize(serialize(new Error("storage", { cause: { buffer, view } }))); - expect(result.cause.buffer).toBeInstanceOf(ArrayBuffer); - expect(result.cause.buffer).not.toBeInstanceOf(SharedArrayBuffer); - expect(result.cause.view.buffer).toBe(result.cause.buffer); - expect([...result.cause.view]).toEqual([42, 0, 0, 0]); - view[0] = 7; - expect(result.cause.view[0]).toBe(42); - result.cause.view[1] = 9; - expect(view[1]).toBe(0); - }); - } - - test("nested views retain aliases and shared backing memory", () => { - const buffer = new SharedArrayBuffer(4); - const view = new Uint8Array(buffer); - const error = new Error("outer", { cause: new Map([["view", view]]) }); - const result = structuredClone({ error, view, buffer }); - expect(result.error).toBeInstanceOf(Error); - expect(result.error.message).toBe("outer"); - const cause = result.error.cause; - expect(cause).toBeInstanceOf(Map); - if (!(cause instanceof Map)) throw new Error("Expected cloned Map cause"); - expect(cause.get("view")).toBe(result.view); - expect(result.view.buffer).toBe(result.buffer); - view[0] = 42; - expect(result.view[0]).toBe(42); - result.view[1] = 7; - expect(view[1]).toBe(7); - }); - - test("worker postMessage preserves cause aliases and shared memory", async () => { - const buffer = new SharedArrayBuffer(4); - const view = new Uint8Array(buffer); - const url = URL.createObjectURL( - new Blob( - [ - "self.onmessage = ({data}) => { data.error.cause[0] = 42; postMessage({error: data.error, same: data.error.cause === data.view}); };", - ], - { type: "application/javascript" }, - ), - ); - const worker = new Worker(url); - try { - const { promise, resolve, reject } = Promise.withResolvers(); - worker.onmessage = resolve; - worker.onerror = reject; - worker.postMessage({ error: new Error("worker", { cause: view }), view }); - const { data } = await promise; - expect(data.same).toBe(true); - expect(data.error).toBeInstanceOf(Error); - expect(data.error.message).toBe("worker"); - expect(data.error.cause).toBeInstanceOf(Uint8Array); - expect(data.error.cause[0]).toBe(42); - expect(view[0]).toBe(42); - data.error.cause[1] = 7; - expect(view[1]).toBe(7); - } finally { - worker.terminate(); - URL.revokeObjectURL(url); - } - }); -}); diff --git a/test/js/web/workers/error-cause-node-parity.test.mjs b/test/js/web/workers/error-cause-node-parity.test.mjs deleted file mode 100644 index dc748dd208b9..000000000000 --- a/test/js/web/workers/error-cause-node-parity.test.mjs +++ /dev/null @@ -1,94 +0,0 @@ -import assert from "node:assert/strict"; -import { once } from "node:events"; -import { test } from "node:test"; -import { deserialize, serialize } from "node:v8"; -import { MessageChannel, Worker } from "node:worker_threads"; - -function graph() { - const shared = { answer: 42 }; - const first = new Error("outer", { cause: shared }); - const second = new TypeError("inner", { cause: first }); - shared.second = second; - return [first, shared, first, new Error("absent"), new Error("undefined", { cause: undefined })]; -} - -function check(value) { - assert(value[0] instanceof Error); - assert.equal(value[0].cause, value[1]); - assert.equal(value[1].second.cause, value[0]); - assert.equal(value[0], value[2]); - assert.equal(Object.hasOwn(value[3], "cause"), false); - assert.deepEqual(Object.getOwnPropertyDescriptor(value[4], "cause"), { - value: undefined, - writable: true, - enumerable: false, - configurable: true, - }); -} - -for (const [name, clone] of [ - ["structuredClone", structuredClone], - ["node:v8", value => deserialize(serialize(value))], -]) { - test(`${name} retains cause cycles, aliases and descriptors`, () => check(clone(graph()))); - test(`${name} omits accessor causes without invoking them`, () => { - const error = new Error("accessor"); - Object.defineProperty(error, "cause", { - get() { - throw new Error("must not run"); - }, - }); - assert.equal(Object.hasOwn(clone(error), "cause"), false); - }); -} - -test("structuredClone preserves the four cause value kinds", () => { - const shared = new Uint8Array(new SharedArrayBuffer(4)); - shared[0] = 42; - for (const cause of [new Error("inner"), 42, shared, { answer: 42 }]) { - const result = structuredClone(new Error("outer", { cause })); - assert(Object.hasOwn(result, "cause")); - if (cause instanceof Error) assert.equal(result.cause.message, cause.message); - else assert.deepEqual(result.cause, cause); - } -}); - -test("Worker postMessage retains cause graphs", async () => { - const worker = new Worker( - 'require("node:worker_threads").parentPort.once("message", value => require("node:worker_threads").parentPort.postMessage(value))', - { eval: true }, - ); - try { - const reply = once(worker, "message"); - worker.postMessage(graph()); - check((await reply)[0]); - } finally { - await worker.terminate(); - } -}); - -test("MessagePort retains cause graphs", async () => { - const { port1, port2 } = new MessageChannel(); - try { - const reply = once(port2, "message"); - port1.postMessage(graph()); - check((await reply)[0]); - } finally { - port1.close(); - port2.close(); - } -}); - -test("BroadcastChannel retains cause graphs", async () => { - const name = `error-cause-${process.pid}`; - const sender = new BroadcastChannel(name); - const receiver = new BroadcastChannel(name); - try { - const reply = once(receiver, "message"); - sender.postMessage(graph()); - check((await reply)[0].data); - } finally { - sender.close(); - receiver.close(); - } -}); diff --git a/test/js/web/workers/structured-clone.test.ts b/test/js/web/workers/structured-clone.test.ts index df58e54efb9e..95f6d9ecc3a1 100644 --- a/test/js/web/workers/structured-clone.test.ts +++ b/test/js/web/workers/structured-clone.test.ts @@ -179,6 +179,7 @@ for (const structuredCloneFn of [structuredClone, jscSerializeRoundtrip, jscSeri { description: "primitive number, 9007199254740994", value: 9007199254740994 }, { description: "primitive number, -9007199254740994", value: -9007199254740994 }, { description: "primitive BigInt, 0n", value: 0n }, + { description: "primitive BigInt, -0n", value: -0n }, { description: "primitive BigInt, -9007199254740994000n", value: -9007199254740994000n }, { description: "primitive BigInt, -9007199254740994000900719925474099400090071992547409940009007199254740994000n", @@ -214,6 +215,7 @@ for (const structuredCloneFn of [structuredClone, jscSerializeRoundtrip, jscSeri 9007199254740994, -9007199254740994, -12n, + -0n, 0n, ]; const cloned = await structuredCloneFn(input); @@ -246,6 +248,7 @@ for (const structuredCloneFn of [structuredClone, jscSerializeRoundtrip, jscSeri "9007199254740994": 9007199254740994, "-9007199254740994": -9007199254740994, "-12n": -12n, + "-0n": -0n, "0n": 0n, }; const cloned = await structuredCloneFn(input); @@ -310,7 +313,7 @@ for (const structuredCloneFn of [structuredClone, jscSerializeRoundtrip, jscSeri expect([...cloned.input.values()]).toEqual([{ payload: 42 }]); expect([...cloned.input.values()][0]).toBe(cloned.entry); expect(cloned.entry).not.toBe(entry); - if (property === "getter") expect(getterCalls).toBe(0); + expect(getterCalls).toBe(0); }); } } @@ -1255,7 +1258,9 @@ describe("X509Certificate records whose DER does not decode are rejected", () => bunExe(), "-e", `import { deserialize } from "bun:jsc"; - import { deserialize as v8Deserialize } from "node:v8"; + import { deserialize as v8Deserialize, serialize as v8Serialize } from "node:v8"; +import { once } from "node:events"; +import { MessageChannel, Worker as NodeWorker } from "node:worker_threads"; for (const [name, fn] of [["bun:jsc", deserialize], ["node:v8", v8Deserialize]]) { try { const key = fn(new Uint8Array(${JSON.stringify([...record(Buffer.alloc(0))])})).publicKey; @@ -1399,277 +1404,3 @@ describe("Map/Set own properties across message and storage boundaries", () => { expect(await proc.stderr.text()).toBe(""); }); }); - -function v8SerializeRoundtrip(value: any) { - return v8Deserialize(v8Serialize(value)); -} - -for (const clone of [structuredClone, jscSerializeRoundtrip, v8SerializeRoundtrip]) { - describe("Error.cause graph serialization: " + clone.name, () => { - test.each([undefined, null, false, 0, -0, NaN, Infinity, "", "cause", 42n])("own data cause %p", cause => { - const result = clone(new Error("outer", { cause })); - expect(result).toBeInstanceOf(Error); - expect(result.message).toBe("outer"); - expect(Object.getOwnPropertyDescriptor(result, "cause")).toEqual({ - value: cause, - writable: true, - enumerable: false, - configurable: true, - }); - }); - - test("nested errors preserve their type, message and cause", () => { - const result = clone(new TypeError("outer", { cause: new RangeError("inner", { cause: { code: 42 } }) })); - expect(result).toBeInstanceOf(TypeError); - expect(result.message).toBe("outer"); - expect(result.cause).toBeInstanceOf(RangeError); - expect(result.cause.message).toBe("inner"); - expect(result.cause.cause).toEqual({ code: 42 }); - }); - - test("mixed Error tags preserve snapshots, terminal records, and aliases", () => { - const early = new Error("early"); - const late = new Error("late", { cause: early }); - const last = new Error("last"); - let calls = 0; - Object.defineProperty(early, "name", { - get() { - calls++; - early.cause = "added after snapshot"; - return "Error"; - }, - }); - const result = clone([early, late, last, early, late, { sentinel: 42 }]); - expect(calls).toBe(1); - expect(Object.hasOwn(result[0], "cause")).toBe(false); - expect(result[1].cause).toBe(result[0]); - expect(Object.hasOwn(result[2], "cause")).toBe(false); - expect(result[3]).toBe(result[0]); - expect(result[4]).toBe(result[1]); - expect(result[5]).toEqual({ sentinel: 42 }); - }); - - test("dictionary Error properties retain an own data cause before metadata effects", () => { - const source = new Error("dictionary"); - for (let i = 0; i < 100; i++) source[`property${i}`] = i; - for (let i = 0; i < 100; i++) delete source[`property${i}`]; - const cause = { original: true }; - Object.defineProperty(source, "cause", { value: cause, writable: true }); - Object.defineProperty(source, "name", { - get() { - source.cause = "replacement"; - return "Error"; - }, - }); - expect(clone(source).cause).toEqual({ original: true }); - }); - - for (const field of ["name", "message", "stack"]) { - test.each(["replace", "delete", "uncloneable"])( - "cause snapshot precedes " + field + " metadata effects: %s", - mutation => { - const source = new Error("outer", { cause: { marker: "original" } }); - source.stack = ""; - let calls = 0; - const effect = () => { - calls++; - if (mutation === "delete") delete source.cause; - else source.cause = mutation === "replace" ? { marker: "replacement" } : () => {}; - return field === "name" ? "Error" : "metadata"; - }; - Object.defineProperty(source, field, field === "message" ? { value: { toString: effect } } : { get: effect }); - const result = clone(source); - expect(calls).toBe(1); - expect(result.cause).toEqual({ marker: "original" }); - }, - ); - } - - test("cause snapshot stays rooted across metadata deletion and early collection", () => { - const source = new Error("outer"); - source.cause = { error: source, bytes: new Uint8Array([17, 42]) }; - Object.defineProperty(source, "stack", { - get() { - delete source.cause; - Bun.gc(true); - return ""; - }, - }); - const result = clone(source); - expect(Object.hasOwn(source, "cause")).toBe(false); - expect(result.cause.error).toBe(result); - expect(result.cause.bytes).toEqual(new Uint8Array([17, 42])); - }); - - test("cause snapshot rejects an original uncloneable value removed by metadata", () => { - const source = new Error("outer", { cause: () => {} }); - Object.defineProperty(source, "stack", { - get() { - source.cause = "replacement"; - return ""; - }, - }); - expect(() => clone(source)).toThrow(expect.objectContaining({ name: "DataCloneError" })); - expect(source.cause).toBe("replacement"); - }); - - test("self, mutual and container cycles preserve object identity", () => { - const self = new Error("self"); - self.cause = self; - const first = new Error("first"); - const second = new Error("second", { cause: first }); - first.cause = second; - const container = new Error("container"); - container.cause = { error: container }; - const result = clone([self, first, second, container]); - expect(result[0].cause).toBe(result[0]); - expect(result[1].cause).toBe(result[2]); - expect(result[2].cause).toBe(result[1]); - expect(result[3].cause.error).toBe(result[3]); - }); - - test("cause aliases survive reference-pool index width changes", () => { - const shared = { marker: "shared" }; - const errors = Array.from({ length: 300 }, (_, i) => new Error(String(i), { cause: shared })); - const result = clone([shared, ...errors, errors[0], shared]); - for (let i = 1; i <= errors.length; i++) { - expect(result[i]).toBeInstanceOf(Error); - expect(result[i].message).toBe(String(i - 1)); - expect(result[i].cause).toBe(result[0]); - } - expect(result[301]).toBe(result[1]); - expect(result[302]).toBe(result[0]); - }); - - test("deep causes use the shared iterative graph traversal", () => { - let source: Error = new Error("leaf"); - for (let i = 0; i < 1500; i++) source = new Error(String(i), { cause: source }); - let result = clone(source); - for (let i = 1499; i >= 0; i--) { - expect(result.message).toBe(String(i)); - result = result.cause; - } - expect(result.message).toBe("leaf"); - expect(Object.hasOwn(result, "cause")).toBe(false); - }); - - test("cause traversal stays rooted when a nested getter mutates the source and collects", () => { - const source = new Error("outer"); - source.cause = { - get child() { - source.cause = undefined; - Bun.gc(true); - return source; - }, - }; - const result = clone(source); - expect(result.cause.child).toBe(result); - }); - - test("absent, inherited and accessor causes are omitted without calling getters", () => { - const absent = new Error("absent"); - const inherited = new Error("inherited"); - const accessor = new Error("accessor"); - let calls = 0; - Object.setPrototypeOf( - inherited, - Object.create(Error.prototype, { - cause: { - get() { - calls++; - throw new Error("inherited getter"); - }, - }, - }), - ); - Object.defineProperty(accessor, "cause", { - get() { - calls++; - throw new Error("own getter"); - }, - }); - const result = clone([absent, inherited, accessor]); - expect(result.map((value: Error) => Object.hasOwn(value, "cause"))).toEqual([false, false, false]); - expect(calls).toBe(0); - }); - - test.each([() => {}, Symbol("uncloneable"), new WeakMap()])("rejects uncloneable cause %p", cause => { - expect(() => clone(new Error("outer", { cause }))).toThrow(expect.objectContaining({ name: "DataCloneError" })); - }); - - test("a getter inside a cause propagates the original thrown value", () => { - const thrown = new Error("nested getter"); - const cause = { - get value() { - throw thrown; - }, - }; - let caught: unknown; - try { - clone(new Error("outer", { cause })); - } catch (error) { - caught = error; - } - expect(caught).toBe(thrown); - }); - }); -} - -test("Error.cause graph serialization survives a fresh process", () => { - const error = new TypeError("outer"); - const shared = { error }; - error.cause = shared; - const result = jscSerializeRoundtripCrossProcessCold([error, shared, error]); - expect(result[0]).toBeInstanceOf(TypeError); - expect(result[0].message).toBe("outer"); - expect(result[0].cause).toBe(result[1]); - expect(result[1].error).toBe(result[0]); - expect(result[2]).toBe(result[0]); -}); - -// Captured with format version 14, before Error.cause was part of the wire format. -const legacyErrorGraph = Buffer.from( - "DgAAAAEEAAAAAAAAADcFAAAAAAYAAIBsZWdhY3kBAAAALAAAAAAAAAA5AACAL3ByaXZhdGUvdG1wL3BsdWdpbi1uYXRpdmUtYnVuLXJlcGFpci0yMDI2MTAxOC9idW4vW2V2YWxdAAAAAAAAAIABAAAAEwECAAAAAgEAAIBuBSoAAAD/////AwAAABMC/////w==", - "base64", -); - -for (const [name, read] of [ - ["bun:jsc", deserialize], - ["node:v8", v8Deserialize], -] as const) { - test("Error.cause format accepts legacy pooled Error records: " + name, () => { - const result = read(legacyErrorGraph); - expect(result[0]).toBeInstanceOf(TypeError); - expect(result[0].message).toBe("legacy"); - expect(Object.hasOwn(result[0], "cause")).toBe(false); - expect(result[1]).toBe(result[0]); - expect(result[2]).toEqual({ n: 42 }); - expect(result[3]).toBe(result[2]); - }); - - test("Error.cause format rejects truncated and malformed records: " + name, () => { - const error = new Error("wire", { cause: 1 }); - error.stack = ""; - const bytes = Buffer.from(serialize(error)); - expect(bytes.readUInt32LE(0)).toBe(16); - expect(read(bytes).cause).toBe(1); - for (let end = 4; end < bytes.length; end++) { - expect(() => read(bytes.subarray(0, end))).toThrow("Unable to deserialize data."); - } - expect(bytes[4]).toBe(56); - expect(bytes.at(-1)).toBe(7); // OneTag, directly after Error metadata. - for (const version of [14, 15]) { - const invalidVersion = Buffer.from(bytes); - invalidVersion.writeUInt32LE(version, 0); - expect(() => read(invalidVersion)).toThrow("Unable to deserialize data."); - } - const invalidTag = Buffer.from(bytes); - invalidTag[invalidTag.length - 1] = 255; - expect(() => read(invalidTag)).toThrow("Unable to deserialize data."); - const invalidReference = Buffer.concat([bytes.subarray(0, -1), Buffer.from([19, 255])]); - expect(() => read(invalidReference)).toThrow("Unable to deserialize data."); - const future = Buffer.from(bytes); - future.writeUInt32LE(17, 0); - expect(() => read(future)).toThrow("Unable to deserialize data."); - }); -}