From e584855b2289fd8155b837f00f67343cc9cd8f66 Mon Sep 17 00:00:00 2001 From: Martin Willers Date: Tue, 17 Nov 2020 01:27:36 +0100 Subject: Avoid memory access errors with 4-chars context ids (#250) For a 4-chars CTXID, i.e. one that does not include a null character, the strlen() calls were happily accessing memory until they eventually encountered a null character somewhere in memory. This was detected by valgrind, which reported a memory error when using a CTXID such as "INTM": ==21924== Conditional jump or move depends on uninitialised value(s) ==21924== at 0x4C30F78: strlen (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==21924== by 0x4E4B5A0: dlt_print_id (dlt_common.c:303) ==21924== by 0x4E4CF47: dlt_message_header_flags (dlt_common.c:687) ==21924== by 0x4E51434: dlt_message_print_ascii (dlt_common.c:3169) ==21924== by 0x4E4247A: dlt_user_print_msg (dlt_user.c:4108) ==21924== by 0x4E46D92: dlt_user_log_send_log (dlt_user.c:3670) ==21924== by 0x4E46F14: dlt_user_log_write_finish (dlt_user.c:1611) Sanitize some code Using memset() and memcpy() is always preferable to hand-rolled loops, because compilers have built-in support for them. Signed-off-by: Martin Willers --- src/shared/dlt_common.c | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) (limited to 'src/shared') diff --git a/src/shared/dlt_common.c b/src/shared/dlt_common.c index 2ff3775..254f4ce 100644 --- a/src/shared/dlt_common.c +++ b/src/shared/dlt_common.c @@ -286,25 +286,32 @@ DltReturnValue dlt_print_char_string(char **text, int textlength, uint8_t *ptr, return DLT_RETURN_OK; } +size_t dlt_strnlen_s(const char* str, size_t maxsize) +{ + if (str == NULL) + return 0; + + for (size_t i = 0; i < maxsize; ++i) { + if (str[i] == '\0') + return i; + } + return maxsize; +} + void dlt_print_id(char *text, const char *id) { /* check nullpointer */ if ((text == NULL) || (id == NULL)) return; - int i, len; - /* Initialize text */ - for (i = 0; i < DLT_ID_SIZE; i++) - text[i] = '-'; + memset(text, '-', DLT_ID_SIZE); text[DLT_ID_SIZE] = 0; - len = ((strlen(id) <= DLT_ID_SIZE) ? strlen(id) : DLT_ID_SIZE); + size_t len = dlt_strnlen_s(id, DLT_ID_SIZE); - /* Check id*/ - for (i = 0; i < len; i++) - text[i] = id[i]; + memcpy(text, id, len); } void dlt_set_id(char *id, const char *text) -- cgit v1.2.1