From ea791ac28d1f0383e39feb0801edd9b20f95783a Mon Sep 17 00:00:00 2001 From: Joseph Hickey Date: Fri, 25 Mar 2022 10:33:16 -0400 Subject: [PATCH] Fix #1237, avoid calling memchr() with unknown size buffer In some systems, passing a large size value to memchr() causes it to return NULL, even if the char is guaranteed to be found within the actual valid buffer memory. This modifies the string buffer comparison function to actively check for this sentinel value and use "strlen()" instead. --- ut_assert/inc/utassert.h | 16 +++++++++++++++- ut_assert/src/utassert.c | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/ut_assert/inc/utassert.h b/ut_assert/inc/utassert.h index bd5f250b5..fd159f387 100644 --- a/ut_assert/inc/utassert.h +++ b/ut_assert/inc/utassert.h @@ -44,6 +44,18 @@ #include #include +/** + * @brief Flag for use with UtAssert_STRINGBUF_EQ when the string is known to be NULL terminated + * + * The UtAssert_STRINGBUF_EQ is provided to facilitate checking fixed-length strings, which do not + * require NULL termination. + * + * If this macro is used to compare against a standard C string that is guaranteed to be NULL + * terminated, this constant may be passed to the UtAssert_STRINGBUF_EQ macro in place of the + * size parameter for that string. + */ +#define UTASSERT_STRINGBUF_NULL_TERM SIZE_MAX + /** * Define various types of messages that can be generated by a test. * @@ -607,7 +619,9 @@ typedef struct * includes the actual string in the log, but filters embedded newlines to keep the log clean. * * If the string arguments are guaranteed to be NULL terminated and/or the max size is - * not known, then the SIZE_MAX constant may be passed for the respective string. + * not known, then the UTASSERT_STRINGBUF_NULL_TERM constant may be passed as the size for + * that string. This mechanism allows this check to be used with normal, terminated C strings, + * as well as fixed-length, unterminated strings. * */ #define UtAssert_STRINGBUF_EQ(str1, size1, str2, size2) \ diff --git a/ut_assert/src/utassert.c b/ut_assert/src/utassert.c index 4d3f064e2..c63dec87c 100644 --- a/ut_assert/src/utassert.c +++ b/ut_assert/src/utassert.c @@ -473,6 +473,16 @@ bool UtAssert_StringBufCompare(const char *String1, size_t String1Max, const cha { EndPtr1 = NULL; } + else if (String1Max == UTASSERT_STRINGBUF_NULL_TERM) + { + /* + * NOTE: it is technically undefined behavior to pass a size to memchr() + * that is larger than the actual buffer, even if it is known/guaranteed + * to find a match within the actual buffer. Therefore the regular strlen() + * is used instead. + */ + EndPtr1 = String1 + strlen(String1); + } else { EndPtr1 = memchr(String1, 0, String1Max); @@ -491,6 +501,10 @@ bool UtAssert_StringBufCompare(const char *String1, size_t String1Max, const cha { EndPtr2 = NULL; } + else if (String2Max == UTASSERT_STRINGBUF_NULL_TERM) + { + EndPtr2 = String2 + strlen(String2); + } else { EndPtr2 = memchr(String2, 0, String2Max);