Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions scripts/verify-baseline-static/allowlist-x64.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1354,13 +1354,17 @@ jsimd_ycc_rgb_convert_avx2.return [AVX, AVX2]
# so every LLInt opcode handler starts with a raw 4-byte ".int <opcode_id>"
# (LowLevelInterpreter.cpp: EMBED_OPCODE_ID_IF_NEEDED). The linear-sweep
# decoder desyncs on those embedded ints and, depending on how preceding .text
# code aligns, can decode a stray VEX-encoded instruction out of the garbage.
# offlineasm's x86 backend emits SSE2 (not VEX), and the Intel SDE Nehalem
# emulation step in this same job exercises the LLInt and passes, so any
# single-digit hit here is decode noise. Ceiling [AVX] so a multi-feature leak
# still fails. On ELF each opcode handler has its own symbol, so layout shifts
# can move the desync between llint_op_* siblings; add them here as they trip.
# (2 symbols)
# code aligns, can decode a stray VEX-encoded instruction (or an RDPMC, 0F 33)
# out of the garbage. offlineasm's x86 backend emits SSE2 (not VEX), and the
# Intel SDE Nehalem emulation step in this same job exercises the LLInt and
# passes, so any single-digit hit here is decode noise. Blanket pass, as for
# any data-in-.text misdecode: the handlers are offlineasm output, not compiler
# output, and the decoded feature moves with link layout (the same desync has
# decoded as AVX and as RDPMC), so a ceiling has nothing to bound. On ELF each
# opcode handler has its own symbol, so layout shifts can move the desync
# between llint_op_* siblings; add them here as they trip.
# (3 symbols)
# ----------------------------------------------------------------------------
llint_op_enter_wide32 [AVX]
llint_op_wide16_wide16 [AVX]
llint_op_enter_wide32
llint_op_jmp_wide32
llint_op_wide16_wide16
4 changes: 3 additions & 1 deletion src/jsc/bindings/BunString.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,9 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue BunString__toJSON(
const BunString* bunString)
{
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
JSC::JSValue result = JSC::JSONParse(globalObject, bunString->toWTFString());
// toWTFString() is null for an empty string, and JSONParseWithException throws nothing for null.
WTF::String string = !bunString->isDead() && bunString->isEmpty() ? emptyString() : bunString->toWTFString();
JSC::JSValue result = JSC::JSONParseWithException(globalObject, string);

if (!result && !scope.exception()) {
scope.throwException(globalObject, createSyntaxError(globalObject, "Failed to parse JSON"_s));
Expand Down
8 changes: 4 additions & 4 deletions src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2732,20 +2732,20 @@ extern "C" JSC::EncodedJSValue JSC__JSValue__unwrapBoxedPrimitive(JSGlobalObject
extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue EncodedSlice__toJSONObject(const EncodedSlice* strPtr, JSC::JSGlobalObject* globalObject)
{
ASSERT_NO_PENDING_EXCEPTION(globalObject);
auto str = Zig::toString(*strPtr);
// Zig::toString() is null for an empty slice, and JSONParseWithException throws nothing for null.
auto str = strPtr->len ? Zig::toString(*strPtr) : emptyString();
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());

if (str.isNull()) {
// isNull() will be true for empty strings and for strings which are too long.
// isNull() will be true for strings which are too long, and when an allocation fails.
// So we need to check the length is plausibly due to a long string.
if (strPtr->len > Bun__stringSyntheticAllocationLimit || strPtr->len > WTF::String::MaxLength) {
scope.throwException(globalObject, Bun::createError(globalObject, Bun::ErrorCode::ERR_STRING_TOO_LONG, "Cannot parse a JSON string longer than 2147483647 characters"_s));
return {};
}
}

// JSONParseWithException does not propagate exceptions as expected. See #5859
JSValue result = JSONParse(globalObject, str);
JSValue result = JSONParseWithException(globalObject, str);
RETURN_IF_EXCEPTION(scope, {});
if (!result) {
scope.throwException(globalObject, createSyntaxError(globalObject, "Failed to parse JSON"_s));
Expand Down
3 changes: 2 additions & 1 deletion test/js/bun/http/serve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2530,7 +2530,8 @@ it("#5859 json", async () => {
body: new Uint8Array([0xfd]),
});

expect(await response.text()).toBe("Failed to parse JSON");
// The body decodes to U+FFFD, so req.json() rejects with the error of JSON.parse("\uFFFD").
expect(await response.text()).toBe("JSON Parse error: Unrecognized token '\uFFFD'");
expect(response.ok).toBeFalse();
});

Expand Down
35 changes: 33 additions & 2 deletions test/js/bun/spawn/readablestream-helpers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,43 @@ describe("ReadableStream conversion methods", () => {
// Check it doesn't throw synchronously.
expect(result).toBeInstanceOf(Promise);

// TODO: why is the error message different here??
expect(async () => await result).toThrowErrorMatchingInlineSnapshot(`"Failed to parse JSON"`);
expect(async () => await result).toThrowErrorMatchingInlineSnapshot(`"JSON Parse error: Expected '}'"`);

expect(process.exitCode).toBe(0);
});

test.each([
["invalid JSON", "{ invalid json content }", "JSON Parse error: Expected '}'"],
// The text of a body is the UTF-8 decode of its bytes, and the decode drops a byte order mark.
["only a byte order mark", "\uFEFF", "JSON Parse error: Unexpected EOF"],
])(
"ReadableStream.prototype.json() of %s rejects with the JSON.parse error for a buffered and a streamed source",
async (_label, body, message) => {
const bytes = new TextEncoder().encode(body);
expect(() => JSON.parse(new TextDecoder().decode(bytes))).toThrow(message);

// A Response body holds all of its bytes, so json() parses them in native code.
const buffered = new Response(bytes.slice()).body!;
// A stream with a JavaScript source delivers chunks, so json() reads the text first.
const streamed = new ReadableStream({
start(controller) {
controller.enqueue(bytes.slice());
controller.close();
},
});

const settle = (promise: Promise<unknown>) =>
promise.then(
() => "resolved",
(error: Error) => `${error.name}: ${error.message}`,
);
expect([await settle(buffered.json()), await settle(streamed.json())]).toEqual([
`SyntaxError: ${message}`,
`SyntaxError: ${message}`,
]);
},
);

test("Bun.spawn() process.stdout.blob() should convert stream to Blob", async () => {
// Generate random binary data
const randomBytes = new Uint8Array(256);
Expand Down
16 changes: 16 additions & 0 deletions test/js/web/fetch/body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ function randomFilled(bufferType: (typeof bufferTypes)[number], length: number)
return buffer;
}

function jsonParseError(text: string): SyntaxError {
try {
JSON.parse(text);
} catch (error) {
return error as SyntaxError;
}
throw new Error(`JSON.parse accepted ${JSON.stringify(text)}`);
}

const utf8 = [
{
string: "",
Expand Down Expand Up @@ -920,6 +929,13 @@ for (const { body, fn } of bodyTypes) {
for (const actual of invalidTests) {
test(actual || "<empty>", async () => {
expect(async () => await fn(actual).json()).toThrow(SyntaxError);
// An empty body is rejected before the parser runs, with its own message.
if (actual !== "") {
const error = await fn(actual)
.json()
.catch(error => error);
expect(error.message).toBe(jsonParseError(actual).message);
}
});
}
});
Expand Down