From 107ffbf44b341411977bf6575fe0bd365a5451f4 Mon Sep 17 00:00:00 2001 From: Jeremy Cline Date: Mon, 14 Dec 2020 16:10:24 -0500 Subject: resultgen: avoid null pointer dereference from realloc realloc() and friends return NULL if they fail; simplify the new_escaped_json_string() by allocating all the necessary memory up-front and checking for a failed allocation. new_escaped_json_string() can already return NULL since json_oject_new_string_len() returns NULL for various undocumented error paths, and NULL is valid input for json_object_object_add(), which this new_escaped_json_string() is currently exclusively used with. Thus, returning NULL when memory allocation fails should be safe. Signed-off-by: Jeremy Cline Reviewed-by: Petri Latvala --- runner/resultgen.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/runner/resultgen.c b/runner/resultgen.c index 3fe83b43..46007803 100644 --- a/runner/resultgen.c +++ b/runner/resultgen.c @@ -412,14 +412,21 @@ static struct json_object *new_escaped_json_string(const char *buf, size_t len) size_t strsize = 0; size_t i; + /* + * Test output may be garbage; strings passed to json-c need to be + * UTF-8 encoded so any non-ASCII characters are converted to their + * UTF-8 representation, which requires 2 bytes per character. + */ + str = malloc(len * 2); + if (!str) + return NULL; + for (i = 0; i < len; i++) { if (buf[i] > 0 && buf[i] < 128) { - str = realloc(str, strsize + 1); str[strsize] = buf[i]; ++strsize; } else { /* Encode > 128 character to UTF-8. */ - str = realloc(str, strsize + 2); str[strsize] = ((unsigned char)buf[i] >> 6) | 0xC0; str[strsize + 1] = ((unsigned char)buf[i] & 0x3F) | 0x80; strsize += 2; -- cgit v1.2.3