]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-alloc-util.c
Merge pull request #12223 from yuwata/network-wireguard-preshared-key-file
[thirdparty/systemd.git] / src / test / test-alloc-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <stdint.h>
4
5 #include "alloc-util.h"
6 #include "macro.h"
7 #include "memory-util.h"
8
9 static void test_alloca(void) {
10 static const uint8_t zero[997] = { };
11 char *t;
12
13 t = alloca_align(17, 512);
14 assert_se(!((uintptr_t)t & 0xff));
15 memzero(t, 17);
16
17 t = alloca0_align(997, 1024);
18 assert_se(!((uintptr_t)t & 0x1ff));
19 assert_se(!memcmp(t, zero, 997));
20 }
21
22 static void test_GREEDY_REALLOC(void) {
23 _cleanup_free_ int *a = NULL, *b = NULL;
24 size_t n_allocated = 0, i;
25
26 /* Give valgrind a chance to verify our realloc operations */
27
28 for (i = 0; i < 2048; i++) {
29 assert_se(GREEDY_REALLOC(a, n_allocated, i + 1));
30 a[i] = i;
31 assert_se(GREEDY_REALLOC(a, n_allocated, i / 2));
32 }
33
34 for (i = 30, n_allocated = 0; i < 2048; i+=7) {
35 assert_se(GREEDY_REALLOC(b, n_allocated, i + 1));
36 b[i] = i;
37 assert_se(GREEDY_REALLOC(b, n_allocated, i / 2));
38 }
39 }
40
41 static void test_memdup_multiply_and_greedy_realloc(void) {
42 int org[] = {1, 2, 3};
43 _cleanup_free_ int *dup;
44 int *p;
45 size_t i, allocated = 3;
46
47 dup = (int*) memdup_suffix0_multiply(org, sizeof(int), 3);
48 assert_se(dup);
49 assert_se(dup[0] == 1);
50 assert_se(dup[1] == 2);
51 assert_se(dup[2] == 3);
52 assert_se(*(uint8_t*) (dup + 3) == (uint8_t) 0);
53 free(dup);
54
55 dup = (int*) memdup_multiply(org, sizeof(int), 3);
56 assert_se(dup);
57 assert_se(dup[0] == 1);
58 assert_se(dup[1] == 2);
59 assert_se(dup[2] == 3);
60
61 p = dup;
62 assert_se(greedy_realloc0((void**) &dup, &allocated, 2, sizeof(int)) == p);
63
64 p = (int *) greedy_realloc0((void**) &dup, &allocated, 10, sizeof(int));
65 assert_se(p == dup);
66 assert_se(allocated >= 10);
67 assert_se(p[0] == 1);
68 assert_se(p[1] == 2);
69 assert_se(p[2] == 3);
70 for (i = 3; i < allocated; i++)
71 assert_se(p[i] == 0);
72 }
73
74 static void test_bool_assign(void) {
75 bool b, c, *cp = &c, d, e, f, g, h;
76
77 b = 123;
78 *cp = -11;
79 d = 0xF & 0xFF;
80 e = b & d;
81 f = 0x0;
82 g = cp; /* cast from pointer */
83 h = NULL; /* cast from pointer */
84
85 assert(b);
86 assert(c);
87 assert(d);
88 assert(e);
89 assert(!f);
90 assert(g);
91 assert(!h);
92 }
93
94 int main(int argc, char *argv[]) {
95 test_alloca();
96 test_GREEDY_REALLOC();
97 test_memdup_multiply_and_greedy_realloc();
98 test_bool_assign();
99
100 return 0;
101 }