Define functions that wrap around the standard snprintf() and vsnprintf() functions to check the return value. If the return value is negative or greater than or equal to the buffer length call abort(), otherwise return it as-is. This makes it safe to blindly use the return value to increment an index when building up a string. --- lib/util/stringutils.c | 29 +++++++++++++++++++++++++++++ lib/util/stringutils.h | 24 ++++++++++++++++++++++++ 2 files changed, 53 insertions(+)
diff --git a/lib/util/stringutils.c b/lib/util/stringutils.c index 89cbeda..db4a448 100644 --- a/lib/util/stringutils.c +++ b/lib/util/stringutils.c @@ -348,3 +348,32 @@ char *scrub_for_print( return dst; } + +int +xsnprintf( + char * restrict s, + size_t n, + const char * restrict format, + ...) +{ + va_list arg; + va_start(arg, format); + int ret = xvsnprintf(s, n, format, arg); + va_end(arg); + return ret; +} + +int +xvsnprintf( + char * restrict s, + size_t n, + const char * restrict format, + va_list arg) +{ + int ret = vsnprintf(s, n, format, arg); + if ((ret < 0) || ((size_t)ret >= n)) + { + abort(); + } + return ret; +} diff --git a/lib/util/stringutils.h b/lib/util/stringutils.h index f8831b5..a06328b 100644 --- a/lib/util/stringutils.h +++ b/lib/util/stringutils.h @@ -5,6 +5,8 @@ * Low-level string parsing utilities */ +#include "macros.h" +#include <stdarg.h> #include <stddef.h> /* @@ -171,4 +173,26 @@ char *scrub_for_print( size_t * dst_len_out, char const *other_chars_to_escape); +/** + * @brief same as snprintf(), but calls abort() if snprintf() returns + * less than 0 or >= n. + */ +int +xsnprintf( + char * restrict s, + size_t n, + const char * restrict format, + ...) WARN_PRINTF(3, 4); + +/** + * @brief same as vsnprintf(), but calls abort() if vsnprintf() + * returns less than 0 or >= n. + */ +int +xvsnprintf( + char * restrict s, + size_t n, + const char * restrict format, + va_list arg) WARN_PRINTF(3, 0); + #endif /* !LIB_UTIL_STRINGUTILS_H */ -- 2.4.5 ------------------------------------------------------------------------------ Don't Limit Your Business. Reach for the Cloud. GigeNET's Cloud Solutions provide you with the tools and support that you need to offload your IT needs and focus on growing your business. Configured For All Businesses. Start Your Cloud Today. https://www.gigenetcloud.com/ _______________________________________________ rpstir-devel mailing list rpstir-devel@lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/rpstir-devel