Skip to content

Commit

Permalink
Merge pull request #1238 from jphickey/fix-1237-stringbuf-check
Browse files Browse the repository at this point in the history
Fix #1237, avoid calling memchr() with unknown size buffer
  • Loading branch information
astrogeco committed Mar 25, 2022
2 parents ba426bb + ea791ac commit 571e952
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
16 changes: 15 additions & 1 deletion ut_assert/inc/utassert.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@
#include <stdio.h>
#include <math.h>

/**
* @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.
*
Expand Down Expand Up @@ -605,7 +617,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) \
Expand Down
14 changes: 14 additions & 0 deletions ut_assert/src/utassert.c
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,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);
Expand All @@ -489,6 +499,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);
Expand Down

0 comments on commit 571e952

Please sign in to comment.