xref: /freebsd/contrib/libcbor/test/memory_utils_test.c (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
1 /*
2  * Copyright (c) 2014-2020 Pavel Kalvoda <me@pavelkalvoda.com>
3  *
4  * libcbor is free software; you can redistribute it and/or modify
5  * it under the terms of the MIT license. See LICENSE for details.
6  */
7 
8 #include "cbor/internal/memory_utils.h"
9 #include <string.h>
10 #include "assertions.h"
11 
12 static void test_safe_multiply(void **_CBOR_UNUSED(_state)) {
13   assert_true(_cbor_safe_to_multiply(1, 1));
14   assert_true(_cbor_safe_to_multiply(SIZE_MAX, 0));
15   assert_true(_cbor_safe_to_multiply(SIZE_MAX, 1));
16   assert_false(_cbor_safe_to_multiply(SIZE_MAX, 2));
17   assert_false(_cbor_safe_to_multiply(SIZE_MAX, SIZE_MAX));
18 }
19 
20 static void test_safe_add(void **_CBOR_UNUSED(_state)) {
21   assert_true(_cbor_safe_to_add(1, 1));
22   assert_true(_cbor_safe_to_add(SIZE_MAX - 1, 1));
23   assert_true(_cbor_safe_to_add(SIZE_MAX, 0));
24   assert_false(_cbor_safe_to_add(SIZE_MAX, 1));
25   assert_false(_cbor_safe_to_add(SIZE_MAX, 2));
26   assert_false(_cbor_safe_to_add(SIZE_MAX, SIZE_MAX));
27   assert_false(_cbor_safe_to_add(SIZE_MAX - 1, SIZE_MAX));
28   assert_false(_cbor_safe_to_add(SIZE_MAX - 1, SIZE_MAX - 1));
29 }
30 
31 static void test_safe_signalling_add(void **_CBOR_UNUSED(_state)) {
32   assert_size_equal(_cbor_safe_signaling_add(1, 2), 3);
33   assert_size_equal(_cbor_safe_signaling_add(0, 1), 0);
34   assert_size_equal(_cbor_safe_signaling_add(0, SIZE_MAX), 0);
35   assert_size_equal(_cbor_safe_signaling_add(1, SIZE_MAX), 0);
36   assert_size_equal(_cbor_safe_signaling_add(1, SIZE_MAX - 1), SIZE_MAX);
37 }
38 
39 static void test_realloc_multiple(void **_CBOR_UNUSED(_state)) {
40   unsigned char *data = malloc(1);
41   data[0] = 0x2a;
42 
43   data = _cbor_realloc_multiple(data, /*item_size=*/1, /*item_count=*/10);
44   assert_size_equal(data[0], 0x2a);
45   data[9] = 0x2b;  // Sanitizer will stop us if not ok
46   free(data);
47 
48   assert_null(_cbor_realloc_multiple(NULL, SIZE_MAX, 2));
49 }
50 
51 int main(void) {
52   const struct CMUnitTest tests[] = {
53       cmocka_unit_test(test_safe_multiply),
54       cmocka_unit_test(test_safe_add),
55       cmocka_unit_test(test_safe_signalling_add),
56       cmocka_unit_test(test_realloc_multiple),
57   };
58   return cmocka_run_group_tests(tests, NULL, NULL);
59 }
60