Skip to content
Open
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
33 changes: 28 additions & 5 deletions core/engine/src/builtins/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -873,11 +873,7 @@ impl Json {
// a. Let isArray be ? IsArray(value).
// b. If isArray is true, return ? SerializeJSONArray(state, value).
// c. Return ? SerializeJSONObject(state, value).
return if obj.is_array_abstract()? {
Ok(Some(Self::serialize_json_array(state, &obj, context)?))
} else {
Ok(Some(Self::serialize_json_object(state, &obj, context)?))
};
return Ok(Some(Self::serialize_json_nested(state, &obj, context)?));
}

// 12. Return undefined.
Expand Down Expand Up @@ -953,6 +949,33 @@ impl Json {
js_string!(&product[..])
}

/// Serializes a nested object or array, counting the descent as host recursion.
///
/// `SerializeJSONObject` and `SerializeJSONArray` recurse natively, one native frame per
/// level of nesting, so without this the depth is bounded only by the native stack and a
/// deeply nested value aborts the process instead of reporting the configured recursion
/// limit.
fn serialize_json_nested(
state: &mut StateRecord,
value: &JsObject,
context: &mut Context,
) -> JsResult<JsString> {
context.vm.host_call_depth += 1;
let result = context
.check_runtime_limits()
.and_then(|()| value.is_array_abstract())
.and_then(|is_array| {
if is_array {
Self::serialize_json_array(state, value, context)
} else {
Self::serialize_json_object(state, value, context)
}
});
context.vm.host_call_depth = context.vm.host_call_depth.saturating_sub(1);

result
}

/// `25.5.2.4 SerializeJSONObject ( state, value )`
///
/// More information:
Expand Down
49 changes: 48 additions & 1 deletion core/engine/src/builtins/json/tests.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use boa_macros::js_str;
use indoc::indoc;

use crate::{JsNativeErrorKind, JsValue, TestAction, js_string, run_test_actions};
use crate::{
JsNativeErrorKind, JsValue, TestAction, error::RuntimeLimitError, js_string, run_test_actions,
};

#[test]
fn json_sanity() {
Expand Down Expand Up @@ -362,3 +364,48 @@ fn json_stringify_cyclic_nested_object_throws_type_error() {
"cyclic object value",
)]);
}

#[test]
fn json_stringify_deep_nesting_reports_the_recursion_limit() {
run_test_actions([
TestAction::inspect_context(|context| {
context.runtime_limits_mut().set_recursion_limit(64);
}),
TestAction::run(indoc! {r#"
function nestObjects(depth) {
const root = {};
let node = root;
for (let i = 0; i < depth; i++) {
node.a = {};
node = node.a;
}
return root;
}

function nestArrays(depth) {
const root = [];
let node = root;
for (let i = 0; i < depth; i++) {
node[0] = [];
node = node[0];
}
return root;
}
"#}),
// Nesting within the limit is unaffected.
TestAction::assert_eq(
"JSON.stringify(nestObjects(4))",
js_string!(r#"{"a":{"a":{"a":{"a":{}}}}}"#),
),
TestAction::assert_eq("JSON.stringify(nestArrays(3))", js_string!("[[[[]]]]")),
// Deeper nesting reports the limit instead of exhausting the native stack.
TestAction::assert_runtime_limit_error(
"JSON.stringify(nestObjects(200))",
RuntimeLimitError::Recursion,
),
TestAction::assert_runtime_limit_error(
"JSON.stringify(nestArrays(200))",
RuntimeLimitError::Recursion,
),
]);
}
51 changes: 51 additions & 0 deletions core/engine/src/value/conversions/serde_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,35 @@ impl JsValue {
self.to_json_inner(context, &mut seen_objects)
}

/// Counts one level of the conversion as host recursion before converting an object.
///
/// The conversion recurses natively through nested objects and arrays, one native frame per
/// level, so without this the depth is bounded only by the native stack and a deeply nested
/// value aborts the process instead of reporting the configured recursion limit. Only objects
/// recurse, so only they are counted, which keeps the depth in step with
/// `SerializeJSONNested` and leaves a primitive leaf costing nothing.
fn to_json_inner(
&self,
context: &mut Context,
seen_objects: &mut HashSet<JsObject>,
) -> JsResult<Option<Value>> {
if !self.is_object() {
return self.to_json_variant(context, seen_objects);
}

context.vm.host_call_depth += 1;
let result = context
.check_runtime_limits()
.and_then(|()| self.to_json_variant(context, seen_objects));
context.vm.host_call_depth = context.vm.host_call_depth.saturating_sub(1);

result
}

fn to_json_variant(
&self,
context: &mut Context,
seen_objects: &mut HashSet<JsObject>,
) -> JsResult<Option<Value>> {
match self.variant() {
JsVariant::Null => Ok(Some(Value::Null)),
Expand Down Expand Up @@ -215,6 +240,32 @@ mod tests {
Context, JsObject, JsValue, TestAction, js_string, object::JsArray, run_test_actions,
};

#[test]
fn to_json_deep_nesting_reports_the_recursion_limit() {
run_test_actions([
TestAction::run(indoc! {r#"
var root = {};
var node = root;
for (var i = 0; i < 200; i++) {
node.a = {};
node = node.a;
}
"#}),
TestAction::inspect_context(|context| {
context.runtime_limits_mut().set_recursion_limit(64);

let global = context.global_object();
let root = global.get(js_string!("root"), context).unwrap();
let error = root.to_json(context).unwrap_err();

assert!(
error.to_string().contains("recursive calls"),
"expected the recursion limit, got {error}"
);
}),
]);
}

#[test]
fn json_conversions() {
const DATA: &str = indoc! {r#"
Expand Down
Loading