Fix binary varint decoders to reject values overflowing uint32_t/uint64_t declared widths

This commit is contained in:
Andrea Mazzoleni 2026-07-30 10:58:35 +02:00
parent 05a5cc605d
commit 74fb2c7474
2 changed files with 99 additions and 12 deletions

View file

@ -586,7 +586,7 @@ int sgetb32(STREAM* f, uint32_t* value)
{
uint32_t v;
unsigned char b;
unsigned char s;
unsigned s;
int c;
v = 0;
@ -603,14 +603,17 @@ loop:
if ((b & 0x80) == 0) {
v |= (uint32_t)b << s;
s += 7;
if (s >= 32) {
/* LCOV_EXCL_START */
return -1;
/* LCOV_EXCL_STOP */
}
goto loop;
}
/*
* Check for overflow: s > 28 means more than 4 non-terminal bytes (> 32 bits),
* and at s == 28 only 4 bits (0x0f) fit in uint32_t
*/
if (tommy_unlikely(s > 28 || (s == 28 && (b & 0x70) != 0))) {
return -1;
}
v |= (uint32_t)(b & 0x7f) << s;
*value = v;
@ -622,7 +625,7 @@ int sgetb64(STREAM* f, uint64_t* value)
{
uint64_t v;
unsigned char b;
unsigned char s;
unsigned s;
int c;
v = 0;
@ -639,14 +642,17 @@ loop:
if ((b & 0x80) == 0) {
v |= (uint64_t)b << s;
s += 7;
if (s >= 64) {
/* LCOV_EXCL_START */
return -1;
/* LCOV_EXCL_STOP */
}
goto loop;
}
/*
* Check for overflow: s > 63 means more than 9 non-terminal bytes (> 64 bits),
* and at s == 63 only 1 bit (0x01) fits in uint64_t
*/
if (tommy_unlikely(s > 63 || (s == 63 && (b & 0x7e) != 0))) {
return -1;
}
v |= (uint64_t)(b & 0x7f) << s;
*value = v;