From abe94812b3b6ed6897e4375756e57afa233702ae Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sun, 18 Apr 2021 15:29:54 -0700 Subject: malloc-gnu-tests, etc.: test ptrdiff_t overflow * modules/calloc-gnu-tests (Depends-on): * modules/malloc-gnu-tests (Depends-on): * modules/realloc-gnu-tests (Depends-on): Add stdint. * tests/test-calloc-gnu.c (main): * tests/test-malloc-gnu.c (main):, * tests/test-realloc-gnu.c (main): Test for ptrdiff_t overflow. --- tests/test-calloc-gnu.c | 14 +++++++++++++- tests/test-malloc-gnu.c | 11 ++++++++++- tests/test-realloc-gnu.c | 10 ++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/test-calloc-gnu.c b/tests/test-calloc-gnu.c index 953bd778b3..eb336e1a6a 100644 --- a/tests/test-calloc-gnu.c +++ b/tests/test-calloc-gnu.c @@ -17,6 +17,7 @@ #include #include +#include /* Return 8. Usual compilers are not able to infer something about the return value. */ @@ -49,7 +50,7 @@ main () 'volatile' is needed to defeat an incorrect optimization by clang 10, see . */ { - void * volatile p = calloc ((size_t) -1 / 8 + 1, eight ()); + void * volatile p = calloc (SIZE_MAX / 8 + 1, eight ()); if (p != NULL) { free (p); @@ -57,5 +58,16 @@ main () } } + /* Likewise for PTRDIFF_MAX. */ + if (PTRDIFF_MAX / 8 < SIZE_MAX) + { + void * volatile p = calloc (PTRDIFF_MAX / 8 + 1, eight ()); + if (p != NULL) + { + free (p); + return 2; + } + } + return 0; } diff --git a/tests/test-malloc-gnu.c b/tests/test-malloc-gnu.c index 58a697f720..ce7e4fec2a 100644 --- a/tests/test-malloc-gnu.c +++ b/tests/test-malloc-gnu.c @@ -17,6 +17,7 @@ #include #include +#include int main () @@ -25,7 +26,15 @@ main () char *p = malloc (0); if (p == NULL) return 1; - free (p); + + /* Check that malloc (n) fails when n exceeds PTRDIFF_MAX. */ + if (PTRDIFF_MAX < SIZE_MAX) + { + size_t n = PTRDIFF_MAX, n1 = n + 1; + if (malloc (n1) != NULL) + return 1; + } + return 0; } diff --git a/tests/test-realloc-gnu.c b/tests/test-realloc-gnu.c index 296852049e..9c7344f151 100644 --- a/tests/test-realloc-gnu.c +++ b/tests/test-realloc-gnu.c @@ -17,6 +17,7 @@ #include #include +#include int main () @@ -26,6 +27,15 @@ main () if (p == NULL) return 1; + /* Check that realloc (p, n) fails when p is non-null and n exceeds + PTRDIFF_MAX. */ + if (PTRDIFF_MAX < SIZE_MAX) + { + size_t n = PTRDIFF_MAX, n1 = n + 1; + if (realloc (p, n1) != NULL) + return 1; + } + free (p); return 0; } -- cgit v1.2.1