Silence -Wformat-truncation warning in crypto/err/err.c
This warning was being tripped because lib_buf and reason_buf made GCC,
incorrectly, believe that the strings could get that long, and then
attempted to sum up the snprintf to 120, obtained by inlining some
things.
Those buffers were larger than they needed to be, so bringing it down is
sufficient to silence things. That said, the buffer bounds are supplied
by the caller and it is expected that truncation can occur, so the
warning is just incorrect. The warning can also be silenced by checking
the snprintf return value. As we're already trying to detect truncation,
we may as well do it with the return value and skip the extra strlen
call.
Either of the two changes is sufficient to suppress the warning, but
both seem worthwhile, so I've done them both.
Change-Id: Ia1b1de67bba55da6f0d07e3682165a1820ce2c9e
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/61805
Auto-Submit: David Benjamin <davidben@google.com>
Reviewed-by: Bob Beck <bbe@google.com>
Commit-Queue: Bob Beck <bbe@google.com>
diff --git a/crypto/err/err.c b/crypto/err/err.c
index d041c5f..e8cf114 100644
--- a/crypto/err/err.c
+++ b/crypto/err/err.c
@@ -552,22 +552,21 @@
const char *lib_str = err_lib_error_string(packed_error);
const char *reason_str = err_reason_error_string(packed_error);
- char lib_buf[64], reason_buf[64];
+ char lib_buf[32], reason_buf[32];
if (lib_str == NULL) {
snprintf(lib_buf, sizeof(lib_buf), "lib(%u)", lib);
lib_str = lib_buf;
}
- if (reason_str == NULL) {
- snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
- reason_str = reason_buf;
- }
+ if (reason_str == NULL) {
+ snprintf(reason_buf, sizeof(reason_buf), "reason(%u)", reason);
+ reason_str = reason_buf;
+ }
- snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s", packed_error,
- lib_str, reason_str);
-
- if (strlen(buf) == len - 1) {
- // output may be truncated; make sure we always have 5 colon-separated
+ int ret = snprintf(buf, len, "error:%08" PRIx32 ":%s:OPENSSL_internal:%s",
+ packed_error, lib_str, reason_str);
+ if (ret >= 0 && (size_t)ret >= len) {
+ // The output was truncated; make sure we always have 5 colon-separated
// fields, i.e. 4 colons.
static const unsigned num_colons = 4;
unsigned i;