mirror of
https://github.com/trezor/trezor-firmware.git
synced 2024-12-22 14:28:07 +00:00
Reworked bn_format.
- Fix off-by-one in buffer size. - Don't return uninitialized stack if number too large.
This commit is contained in:
parent
9add21439a
commit
c61ab76ad7
31
bignum.c
31
bignum.c
@ -990,7 +990,19 @@ size_t bn_format(const bignum256 *amnt, const char *prefix, const char *suffix,
|
||||
size_t prefixlen = prefix ? strlen(prefix) : 0;
|
||||
size_t suffixlen = suffix ? strlen(suffix) : 0;
|
||||
|
||||
char *start = &out[prefixlen + suffixlen], *end = &out[outlen];
|
||||
/* add prefix to beginning of out buffer */
|
||||
if (prefixlen) {
|
||||
memcpy(out, prefix, prefixlen);
|
||||
}
|
||||
/* add suffix to end of out buffer */
|
||||
if (suffixlen) {
|
||||
memcpy(&out[outlen - suffixlen - 1], suffix, suffixlen);
|
||||
}
|
||||
/* nul terminate (even if suffix = NULL) */
|
||||
out[outlen - 1] = '\0';
|
||||
|
||||
/* fill number between prefix and suffix (between start and end) */
|
||||
char *start = &out[prefixlen], *end = &out[outlen - suffixlen - 1];
|
||||
char *str = end;
|
||||
|
||||
#define BN_FORMAT_PUSH_CHECKED(c) \
|
||||
@ -1056,19 +1068,14 @@ size_t bn_format(const bignum256 *amnt, const char *prefix, const char *suffix,
|
||||
BN_FORMAT_PUSH(0);
|
||||
}
|
||||
|
||||
size_t len = end - str;
|
||||
/* finally move number to &out[prefixlen] to close the gap between
|
||||
* prefix and str. len is length of number + suffix + traling 0
|
||||
*/
|
||||
size_t len = &out[outlen] - str;
|
||||
memmove(&out[prefixlen], str, len);
|
||||
|
||||
if (prefixlen) {
|
||||
memcpy(out, prefix, prefixlen);
|
||||
}
|
||||
if (suffixlen) {
|
||||
memcpy(&out[prefixlen + len], suffix, suffixlen);
|
||||
}
|
||||
|
||||
size_t length = prefixlen + len + suffixlen;
|
||||
out[length] = '\0';
|
||||
return length;
|
||||
/* return length of number including prefix and suffix without trailing 0 */
|
||||
return prefixlen + len - 1;
|
||||
}
|
||||
|
||||
#if USE_BN_PRINT
|
||||
|
11
test_check.c
11
test_check.c
@ -622,6 +622,17 @@ START_TEST(test_bignum_format) {
|
||||
r = bn_format(&a, "quite a long prefix", "even longer suffix", 60, 0, false, buf, sizeof(buf));
|
||||
ck_assert_int_eq(r, 116);
|
||||
ck_assert_str_eq(buf, "quite a long prefix115792089237316195.423570985008687907853269984665640564039457584007913129639935even longer suffix");
|
||||
|
||||
bn_read_be(fromhex("0000000000000000000000000000000000000000000000000123456789abcdef"), &a);
|
||||
memset(buf, 'a', sizeof(buf));
|
||||
r = bn_format(&a, "prefix", "suffix", 10, 0, false, buf, 31);
|
||||
ck_assert_str_eq(buf, "prefix8198552.9216486895suffix");
|
||||
ck_assert_int_eq(r, 30);
|
||||
|
||||
memset(buf, 'a', sizeof(buf));
|
||||
r = bn_format(&a, "prefix", "suffix", 10, 0, false, buf, 30);
|
||||
ck_assert_int_eq(r, 0);
|
||||
ck_assert_str_eq(buf, "prefix198552.9216486895suffix");
|
||||
}
|
||||
END_TEST
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user