Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 9 additions & 7 deletions scripts/verify-baseline-static/allowlist-x64.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1354,13 +1354,15 @@ 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. Each ceiling is the one
# feature that the scan reported, 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.
# (3 symbols)
# ----------------------------------------------------------------------------
llint_op_enter_wide32 [AVX]
llint_op_jmp_wide32 [RDPMC]
Comment thread
robobun marked this conversation as resolved.
Resolved
llint_op_wide16_wide16 [AVX]
7 changes: 6 additions & 1 deletion src/jsc/bindings/BunString.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -519,7 +519,12 @@ 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());
WTF::String string = bunString->toWTFString();
// An empty input converts to a null string, and JSONParseWithException does not throw for a
// null string. Parse "" instead, so the error is the one that JSON.parse("") throws.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (string.isNull() && bunString->isEmpty() && !bunString->isDead())
string = emptyString();
JSC::JSValue result = JSC::JSONParseWithException(globalObject, string);

if (!result && !scope.exception()) {
scope.throwException(globalObject, createSyntaxError(globalObject, "Failed to parse JSON"_s));
Expand Down
7 changes: 5 additions & 2 deletions src/jsc/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2742,10 +2742,13 @@ extern "C" [[ZIG_EXPORT(zero_is_throw)]] JSC::EncodedJSValue EncodedSlice__toJSO
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 throw for a null string. Parse "" instead, so an empty
// input gets the error that JSON.parse("") throws.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (!strPtr->len)
str = emptyString();
}

// 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