[v2,5/5] telemetry: remove VLA in json string format function
Checks
Commit Message
Since variable length arrays (VLAs) are potentially unsecure and
unsupported by some compilers, rework the code to remove their use. As
with previous changes to remove VLAs in the telemetry code, this
function uses two methods to avoid modifying the buffer when adding to
it fails:
* if there are only a few characters in the buffer, save them off to
restore on failure, then use the buffer as-is,
* otherwise use malloc rather than a VLA to allocate a temporary buffer
and copy from that on success only.
Signed-off-by: Bruce Richardson <bruce.richardson@intel.com>
---
app/test/test_telemetry_json.c | 2 +-
lib/telemetry/telemetry_json.h | 19 +++++++++++++++++--
2 files changed, 18 insertions(+), 3 deletions(-)
@@ -129,7 +129,7 @@ test_string_char_escaping(void)
{
static const char str[] = "A string across\ntwo lines and \"with quotes\"!";
const char *expected = "\"A string across\\ntwo lines and \\\"with quotes\\\"!\"";
- char buf[sizeof(str) + 10];
+ char buf[sizeof(str) + 10] = "";
int used = 0;
used = rte_tel_json_str(buf, sizeof(buf), used, str);
@@ -130,13 +130,28 @@ __json_format_str_to_buf(char *buf, const int len,
static inline int
__json_format_str(char *buf, const int len, const char *prefix, const char *str, const char *suffix)
{
- char tmp[len];
int ret;
+ char saved[4] = "";
+ char *tmp;
+
+ if (strnlen(buf, sizeof(saved)) < sizeof(saved)) {
+ /* we have only a few bytes in buffer, so save them off to restore on error*/
+ strcpy(saved, buf);
+ ret = __json_format_str_to_buf(buf, len, prefix, str, suffix);
+ if (ret == 0)
+ strcpy(buf, saved); /* restore */
+ return ret;
+ }
+
+ tmp = malloc(len);
+ if (tmp == NULL)
+ return 0;
ret = __json_format_str_to_buf(tmp, len, prefix, str, suffix);
if (ret > 0)
- strcpy(buf, tmp);
+ strcpy(buf, saved);
+ free(tmp);
return ret;
}