Details
-
Improvement
-
Resolution: Unresolved
-
Unknown
-
None
-
None
-
None
-
C Drivers
Description
Scope
Check return values of bson_snprintf.
Background & Motivation
Calls to bson_snprintf may truncate if the destination does not have enough capacity:
char dest[3]; |
int req = bson_snprintf (dest, sizeof dest, "%s", "foobar"); |
ASSERT_CMPSTR (dest, "fo"); // "foobar" is truncated. |
ASSERT_CMPINT (req, ==, 6); // Return value indicates required capacity (excluding NULL) |
If the destination does not have enough capacity, bson_snprintf returns the number of bytes required (excluding the trailing NULL byte).
Many calls to bson_snprintf do not check the return value. This contributed to the bug reported in CDRIVER-4816.
Possible Solution
If the destination is expected to always have enough capacity (and is otherwise a bug), assert the return value is less than the capacity. Example:
int req = bson_snprintf (dest, sizeof dest, format, input); |
BSON_ASSERT (bson_in_range_size_t_signed (req));
|
// Check `dest` had enough capacity.
|
BSON_ASSERT ((size_t) req < sizeof dest); |
If the destination is not always expected to have enough capacity (and truncating is OK), check the return value is > 0 (no error occurred).
int req = bson_snprintf (dest, sizeof dest, format, input); |
// Check no error occurred. `dest` may expectedly not have enough capacity.
|
BSON_ASSERT (req > 0);
|