Truly independent web browser
LibJS: Check stack space while internalizing JSON.parse results
Andreas Klingfba34b1950b6
diff --git a/Libraries/LibJS/Rust/src/runtime/json_object.rs b/Libraries/LibJS/Rust/src/runtime/json_object.rsindex 91ac4c169f1..bef8dc8f2d3 100644--- a/Libraries/LibJS/Rust/src/runtime/json_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/json_object.rs@@ -1681,6 +1681,12 @@ impl JSONObject {records: &JSONParseRecords<'_>,parse_record: Option<usize>,) -> ThrowCompletionOr<Value> {+ // NB: A reviver can replace a value with an arbitrarily deep object graph, which would otherwise run out of+ // stack.+ if vm.did_reach_stack_space_limit() {+ return vm.throw_completion(ErrorKind::InternalError, ErrorType::CallStackSizeExceeded, &[]);+ }+let realm = vm.current_realm().expect("JSON is parsed in a realm");// 1. Let value be ? Get(holder, name).diff --git a/Tests/LibJS/Runtime/builtins/JSON/JSON.parse-reviver.js b/Tests/LibJS/Runtime/builtins/JSON/JSON.parse-reviver.jsindex 65197795e88..3a1381e89d2 100644--- a/Tests/LibJS/Runtime/builtins/JSON/JSON.parse-reviver.js+++ b/Tests/LibJS/Runtime/builtins/JSON/JSON.parse-reviver.js@@ -45,3 +45,15 @@ test("reviver context has no source for forward-modified values", () => {});expect(result).toEqual([1, { injected: true }]);});++test("reviver that inserts a deeply nested value throws instead of exhausting the stack", () => {+ let replacement = {};+ for (let i = 0; i < 1000000; ++i) replacement = { child: replacement };++ expect(() => {+ JSON.parse("[0, 0]", function (key, value) {+ if (key === "0") this[1] = replacement;+ return value;+ });+ }).toThrowWithMessage(InternalError, "Call stack size limit exceeded");+});