diff options
author | Jeremy Cline <jcline@redhat.com> | 2020-12-14 16:10:24 -0500 |
---|---|---|
committer | Petri Latvala <petri.latvala@intel.com> | 2020-12-15 11:04:55 +0200 |
commit | 107ffbf44b341411977bf6575fe0bd365a5451f4 (patch) | |
tree | 273ade2341bfb270d38a3bc34025153d759d0f7b | |
parent | 5717cf5143bc902ff04d5b9d9367e98f911ec8f5 (diff) |
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 <jcline@redhat.com>
Reviewed-by: Petri Latvala <petri.latvala@intel.com>
-rw-r--r-- | runner/resultgen.c | 11 |
1 files 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; |