diff --git a/src/graph/serialize.hh b/src/graph/serialize.hh index d33b736ad..fc25b76a7 100644 --- a/src/graph/serialize.hh +++ b/src/graph/serialize.hh @@ -249,7 +249,8 @@ inline graph_result_t serialize (const graph_t& graph) if (!size) return Ok(hb_blob_get_empty ()); - if (unlikely (!buffer.alloc (size))) { + // The output blob cannot represent a larger size; check before alloc () narrows it. + if (unlikely (size > INT_MAX || !buffer.alloc (size))) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Unable to allocate output buffer."); return Err(ALLOCATION_FAILURE); } diff --git a/test/api/test-subset-repacker.c b/test/api/test-subset-repacker.c index 19a0755e6..155746d9d 100644 --- a/test/api/test-subset-repacker.c +++ b/test/api/test-subset-repacker.c @@ -205,6 +205,44 @@ test_hb_repack_with_cy_struct (void) free (hb_objs); } +static void +test_hb_repack_total_size_overflow (void) +{ + /* The objects add up to 4GiB + 16KiB while every offset still fits in + * 32 bits. All objects share the same storage to keep memory use low. */ + const unsigned num_children = 4096; + const unsigned child_size = 1u << 20; + + char *data = calloc (child_size, 1); + hb_subset_serialize_object_t *hb_objs = calloc (num_children + 1, sizeof (hb_subset_serialize_object_t)); + hb_subset_serialize_link_t *links = calloc (num_children, sizeof (hb_subset_serialize_link_t)); + g_assert_nonnull (data); + g_assert_nonnull (hb_objs); + g_assert_nonnull (links); + + for (unsigned i = 0; i < num_children; i++) + { + hb_objs[i].head = data; + hb_objs[i].tail = data + child_size; + + links[i].width = 4; + links[i].position = i * 4; + links[i].objidx = i + 1; + } + + hb_objs[num_children].head = data; + hb_objs[num_children].tail = data + num_children * 4; + hb_objs[num_children].num_real_links = num_children; + hb_objs[num_children].real_links = links; + + hb_blob_t *result = hb_subset_serialize_or_fail (HB_TAG_NONE, hb_objs, num_children + 1); + g_assert_null (result); + + free (links); + free (hb_objs); + free (data); +} + int main (int argc, char **argv) @@ -212,6 +250,7 @@ main (int argc, char **argv) hb_test_init (&argc, &argv); hb_test_add (test_hb_repack_with_cy_struct); + hb_test_add (test_hb_repack_total_size_overflow); return hb_test_run(); }