From 478d5bdafe18ce4c7d4007eaabd887b64fc7ec9d Mon Sep 17 00:00:00 2001 From: Thomas Haller Date: Tue, 12 Jan 2021 09:49:57 +0100 Subject: [PATCH] shared: fix unit tests for nm_utils_get_next_realloc_size() The change broke unit tests on 32 bit systems. Change the code again to make it more similar to what it was before. Now only on 64 bit systems there is any difference compared to before. That makes it easier about reasoning for how the unit test should be (in most cases, it is unchanged). Fixes: 040c86f15cbf ('shared: avoid compiler warning for nm_utils_get_next_realloc_size() returning huge sizes') --- shared/nm-glib-aux/tests/test-shared-general.c | 8 ++++++-- shared/nm-std-aux/nm-std-utils.c | 12 ++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/shared/nm-glib-aux/tests/test-shared-general.c b/shared/nm-glib-aux/tests/test-shared-general.c index 3907bf8dd..d0fdedd51 100644 --- a/shared/nm-glib-aux/tests/test-shared-general.c +++ b/shared/nm-glib-aux/tests/test-shared-general.c @@ -798,7 +798,9 @@ test_nm_utils_get_next_realloc_size(void) } /* reserved_false is generally the next power of two - 24. */ - if (!truncated_false) { + if (reserved_false == G_MAXSIZE) + g_assert_cmpuint(requested, >, G_MAXSIZE / 2u - 24u); + else if (!reserved_false) { g_assert_cmpuint(reserved_false, <=, G_MAXSIZE - 24u); if (reserved_false >= 40) { const gsize _pow2 = reserved_false + 24u; @@ -816,7 +818,9 @@ test_nm_utils_get_next_realloc_size(void) } /* reserved_true is generally the next 4k border - 24. */ - if (!truncated_true) { + if (reserved_true == G_MAXSIZE) + g_assert_cmpuint(requested, >, G_MAXSIZE - 0x1000u - 24u); + else if (!truncated_true) { g_assert_cmpuint(reserved_true, <=, G_MAXSIZE - 24u); if (reserved_true > 8168u) { const gsize page_border = reserved_true + 24u; diff --git a/shared/nm-std-aux/nm-std-utils.c b/shared/nm-std-aux/nm-std-utils.c index 9bf08e02a..8c7623715 100644 --- a/shared/nm-std-aux/nm-std-utils.c +++ b/shared/nm-std-aux/nm-std-utils.c @@ -65,16 +65,16 @@ nm_utils_get_next_realloc_size(bool true_realloc, size_t requested) return n - 24u; } - /* For large allocations (with !true_realloc) we allocate memory in chunks of - * 4K (- 24 bytes extra), assuming that the memory gets mmapped and thus - * realloc() is efficient by just reordering pages. */ - n = ((requested + (0x0FFFu + 24u)) & ~((size_t) 0x0FFFu)) - 24u; - - if (NM_UNLIKELY(n < requested)) { + if (NM_UNLIKELY(requested > SIZE_MAX - 0x1000u - 24u)) { /* overflow happened. */ goto out_huge; } + /* For large allocations (with !true_realloc) we allocate memory in chunks of + * 4K (- 24 bytes extra), assuming that the memory gets mmapped and thus + * realloc() is efficient by just reordering pages. */ + n = ((requested + (0x0FFFu + 24u)) & ~((size_t) 0x0FFFu)) - 24u; + nm_assert(n >= requested); return n; out_huge: