[vector] Fix heap buffer overflow in append_base64 / append_len

When the sum old_len + out_len (or old_len + l) exceeded INT_MAX,
the (int) cast turned it negative.  resize_full() treated negative
size as zero, alloc(0) succeeded, and the subsequent write loop
overflowed the buffer.

Fix both layers:

- resize_full(): reject negative size_ (return false) instead of
  silently treating it as zero.  This is defense-in-depth for every
  caller that casts unsigned to int.

- append_len() and append_base64(): use hb_unsigned_add_overflows()
  to detect unsigned wraparound before the cast.  This catches the
  case where old_len + new_bytes > UINT_MAX wraps to a small
  positive value that would pass the negative check.

Assisted-by: Claude <noreply@anthropic.com>
This commit is contained in:
Behdad Esfahbod committed 2026-05-16 13:06:40 +01:00
1 parent 0cf18e7b64
commit cf9c3eb36e
2 files changed
+9 -3

No files matched your search

+6 -2
View File
@@ -46,7 +46,9 @@ struct hb_vector_buf_t : hb_vector_t<char>
bool append_len (const char *s, unsigned l)
{
unsigned old_len = length;
if (unlikely (!resize_dirty ((int) (old_len + l))))
unsigned new_len;
if (unlikely (hb_unsigned_add_overflows (old_len, l, &new_len) ||
!resize_dirty ((int) new_len)))
return false;
hb_memcpy (arrayZ + old_len, s, l);
return true;
@@ -155,7 +157,9 @@ struct hb_vector_buf_t : hb_vector_t<char>
{
unsigned out_len = ((len + 2) / 3) * 4;
unsigned old_len = length;
if (unlikely (!resize_dirty ((int) (old_len + out_len))))
unsigned new_len;
if (unlikely (hb_unsigned_add_overflows (old_len, out_len, &new_len) ||
!resize_dirty ((int) new_len)))
return false;
char *dst = arrayZ + old_len;
+3 -1
View File
@@ -635,7 +635,9 @@ struct hb_vector_t
HB_ALWAYS_INLINE_VECTOR_ALLOCS
bool resize_full (int size_, bool initialize, bool exact)
{
unsigned int size = size_ < 0 ? 0u : (unsigned int) size_;
if (unlikely (size_ < 0))
return false;
unsigned int size = (unsigned int) size_;
if (!alloc (size, exact))
return false;