Add protection from multiplication overflows in hb-map.hh

- Limit max population size of map to prevent size from overflowing.
- Fix possibly overflow population * 8
- Correctly handle copying a map that's in error.
This commit is contained in:
Garret Rieger committed 2026-08-18 15:41:54 -06:00
1 parent b8c25fc5ae
commit b65d287b8f
2 files changed
+29 -2

No files matched your search

+15 -2
View File
@@ -49,11 +49,16 @@ struct hb_hashmap_t
void _copy (const hb_hashmap_t& o)
{
if (unlikely (!o.successful))
{
successful = false;
return;
}
if (unlikely (!o.mask)) return;
if (hb_is_trivially_copy_assignable (item_t))
{
items = (item_t *) hb_malloc (sizeof (item_t) * (o.mask + 1));
items = (item_t *) hb_malloc2 ((o.mask + 1), sizeof (item_t));
if (unlikely (!items))
{
successful = false;
@@ -199,6 +204,14 @@ struct hb_hashmap_t
bool alloc (unsigned new_population = 0)
{
if (unlikely (!successful)) return false;
if (unlikely (population > 0x3FFFFFFFu || new_population > 0x3FFFFFFFu))
{
// Population sizes >0x3FFFFFFF will result in power
// being larger than 31, which in turn leads to a new size
// that overflows u32.
successful = false;
return false;
}
if (new_population != 0 && (new_population + new_population / 2) < mask) return true;
@@ -288,7 +301,7 @@ struct hb_hashmap_t
occupancy++;
population++;
if (unlikely (length > max_chain_length) && occupancy * 8 > mask)
if (unlikely (length > max_chain_length) && occupancy > mask / 8)
alloc (mask - 8); // This ensures we jump to next larger size
return true;
+14
View File
@@ -353,6 +353,20 @@ main (int argc, char **argv)
hb_always_assert (keys.is_equal (hb_set_t (m.keys ())));
hb_always_assert (values.is_equal (hb_set_t (m.values ())));
}
/* Test allocation bounds and overflow protection. */
{
hb_map_t m1;
hb_always_assert (!m1.alloc ((unsigned) -1));
hb_always_assert (m1.in_error ());
hb_map_t m2;
hb_always_assert (!m2.alloc (0x40000000u));
hb_always_assert (m2.in_error ());
/* Test copy of map in error state. */
hb_map_t m3 (m1);
hb_always_assert (m3.in_error ());
}
return 0;
}