From b65d287b8f799545ff4d2dd52694ea42fb1e55ef Mon Sep 17 00:00:00 2001 From: Garret Rieger Date: Tue, 18 Aug 2026 21:06:30 +0000 Subject: [PATCH] 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. --- src/hb-map.hh | 17 +++++++++++++++-- src/test-map.cc | 14 ++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/hb-map.hh b/src/hb-map.hh index 56c0e4e44..6a5e160c6 100644 --- a/src/hb-map.hh +++ b/src/hb-map.hh @@ -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; diff --git a/src/test-map.cc b/src/test-map.cc index a68da8c82..f001af318 100644 --- a/src/test-map.cc +++ b/src/test-map.cc @@ -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; }