From 8ea91b7792fc0b3ed7777983bf7ee3fc8dc20ef4 Mon Sep 17 00:00:00 2001 From: s-hadinger <49731213+s-hadinger@users.noreply.github.com> Date: Tue, 11 Apr 2023 23:13:02 +0200 Subject: [PATCH] Berry fix rare crash in json parsing (#18395) --- lib/libesp32/berry/src/be_jsonlib.c | 4 ++++ lib/libesp32/berry/tests/json.be | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/lib/libesp32/berry/src/be_jsonlib.c b/lib/libesp32/berry/src/be_jsonlib.c index 1d7049ea1..c0c764792 100644 --- a/lib/libesp32/berry/src/be_jsonlib.c +++ b/lib/libesp32/berry/src/be_jsonlib.c @@ -183,6 +183,10 @@ static const char* parser_string(bvm *vm, const char *json) } } be_assert(ch == '"'); + /* require the stack to have some free space for the string, + since parsing deeply nested objects might + crash the VM due to insufficient stack space. */ + be_stack_require(vm, 1 + BE_STACK_FREE_MIN); be_pushnstring(vm, buf, cast_int(dst - buf)); be_free(vm, buf, len); return json + 1; /* skip '"' */ diff --git a/lib/libesp32/berry/tests/json.be b/lib/libesp32/berry/tests/json.be index 6e1aaaf8d..3664ba08b 100644 --- a/lib/libesp32/berry/tests/json.be +++ b/lib/libesp32/berry/tests/json.be @@ -34,6 +34,12 @@ assert_load_failed('{"ke: 1}') assert_load_failed('{"key": 1x}') assert_load_failed('{"key"}') assert_load_failed('{"key": 1, }') +# insanely long, nested object +var text = 'null' +for i : 0 .. 200 + text = '{"nested":' + text + ', "num": 1, "bool": true, "str": "abc", "n": null, "arr": [1, 2, 3]}' +end +json.load(text) # do nothing, just check that it doesn't crash # dump tests