]> Sergey Matveev's repositories - bfs.git/commitdiff
alloc: Test allocation size overflows
authorTavian Barnes <tavianator@tavianator.com>
Fri, 6 Oct 2023 16:37:01 +0000 (12:37 -0400)
committerTavian Barnes <tavianator@tavianator.com>
Fri, 6 Oct 2023 16:37:01 +0000 (12:37 -0400)
src/alloc.h
tests/alloc.c

index 5f0c42385e0c2705e0e0631633fbeb8fcd346f7d..fd3e5f0fa721c23a271624f3eabe42f6eeba808e 100644 (file)
@@ -132,11 +132,11 @@ void *zalloc(size_t align, size_t size);
 
 /** Allocate memory for an array. */
 #define ALLOC_ARRAY(type, count) \
-       (type *)alloc(alignof(type), sizeof_array(type, count));
+       (type *)alloc(alignof(type), sizeof_array(type, count))
 
 /** Allocate zeroed memory for an array. */
 #define ZALLOC_ARRAY(type, count) \
-       (type *)zalloc(alignof(type), sizeof_array(type, count));
+       (type *)zalloc(alignof(type), sizeof_array(type, count))
 
 /** Allocate memory for a flexible struct. */
 #define ALLOC_FLEX(type, member, count) \
index 9e6e892d2ca96e701f6719078a1674e0b539aca9..382131f5fda0e764fec0a4986a1d20b7dd41d960 100644 (file)
@@ -3,6 +3,7 @@
 
 #include "../src/alloc.h"
 #include "../src/diag.h"
+#include <errno.h>
 #include <stdlib.h>
 
 int main(void) {
@@ -13,13 +14,20 @@ int main(void) {
        };
        bfs_verify(sizeof_flex(struct flexible, bar, 0) >= sizeof(struct flexible));
        bfs_verify(sizeof_flex(struct flexible, bar, 16) % alignof(struct flexible) == 0);
-       bfs_verify(sizeof_flex(struct flexible, bar, SIZE_MAX / sizeof(int) + 1)
-                  == align_floor(alignof(struct flexible), SIZE_MAX));
+
+       size_t too_many = SIZE_MAX / sizeof(int) + 1;
+       bfs_verify(sizeof_flex(struct flexible, bar, too_many) == align_floor(alignof(struct flexible), SIZE_MAX));
 
        // Corner case: sizeof(type) > align_ceil(alignof(type), offsetof(type, member))
        // Doesn't happen in typical ABIs
        bfs_verify(flex_size(8, 16, 4, 4, 1) == 16);
 
+       // Make sure we detect allocation size overflows
+       bfs_verify(ALLOC_ARRAY(int, too_many) == NULL && errno == EOVERFLOW);
+       bfs_verify(ZALLOC_ARRAY(int, too_many) == NULL && errno == EOVERFLOW);
+       bfs_verify(ALLOC_FLEX(struct flexible, bar, too_many) == NULL && errno == EOVERFLOW);
+       bfs_verify(ZALLOC_FLEX(struct flexible, bar, too_many) == NULL && errno == EOVERFLOW);
+
        // varena tests
        struct varena varena;
        VARENA_INIT(&varena, struct flexible, bar);