Skip to content

Commit d535444

Browse files
cjwinklhoferdkalowsk
authored andcommitted
json: fix encoding of string null pointer
A segmentation fault occurs when a zero initialized struct with a string field (JSON_TOK_STRING) is encoded. Encode a string null pointer as an empty JSON string "". Signed-off-by: Christoph Winklhofer <[email protected]>
1 parent 2a9be50 commit d535444

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

lib/utils/json.c

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1218,6 +1218,10 @@ static int json_escape_internal(const char *str,
12181218
const char *cur;
12191219
int ret = 0;
12201220

1221+
if (str == NULL) {
1222+
return ret;
1223+
}
1224+
12211225
for (cur = str; ret == 0 && *cur; cur++) {
12221226
char escaped = escape_as(*cur);
12231227

tests/lib/json/src/main.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2178,4 +2178,24 @@ ZTEST(lib_json_test, test_json_enums)
21782178
"Enums not decoded correctly");
21792179
}
21802180

2181+
ZTEST(lib_json_test, test_json_string_nullptr)
2182+
{
2183+
int ret = 0;
2184+
2185+
struct test_struct ts = {0};
2186+
char *buffer;
2187+
size_t len;
2188+
2189+
len = json_calc_encoded_len(test_descr, ARRAY_SIZE(test_descr), &ts);
2190+
zassert(len > 0, "encoded size incorrect");
2191+
2192+
buffer = alloca(len + 1);
2193+
ret = json_obj_encode_buf(test_descr, ARRAY_SIZE(test_descr), &ts, buffer, len + 1);
2194+
zassert_equal(ret, 0, "Encoding function failed");
2195+
2196+
ret = json_obj_parse(buffer, len, test_descr, ARRAY_SIZE(test_descr), &ts);
2197+
zassert_equal(ret, (1 << ARRAY_SIZE(test_descr)) - 1, "Not all fields decoded correctly");
2198+
zassert_str_equal(ts.some_string, "", "String not decoded correctly");
2199+
}
2200+
21812201
ZTEST_SUITE(lib_json_test, NULL, NULL, NULL, NULL, NULL);

0 commit comments

Comments
 (0)