]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/test/test-alloc-util.c
tree-wide: various ubsan zero size memory fixes
[thirdparty/systemd.git] / src / test / test-alloc-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
b66de1f9 2
f30788ee
YW
3#include <stdint.h>
4
b66de1f9
RC
5#include "alloc-util.h"
6#include "macro.h"
7#include "util.h"
8
9static 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
f30788ee 22static void test_memdup_multiply_and_greedy_realloc(void) {
b66de1f9 23 int org[] = {1, 2, 3};
f30788ee
YW
24 _cleanup_free_ int *dup;
25 int *p;
26 size_t i, allocated = 3;
b66de1f9 27
f30788ee 28 dup = (int*) memdup_suffix0_multiply(org, sizeof(int), 3);
b66de1f9
RC
29 assert_se(dup);
30 assert_se(dup[0] == 1);
31 assert_se(dup[1] == 2);
32 assert_se(dup[2] == 3);
f30788ee 33 assert_se(*(uint8_t*) (dup + 3) == (uint8_t) 0);
b66de1f9 34 free(dup);
f30788ee
YW
35
36 dup = (int*) memdup_multiply(org, sizeof(int), 3);
37 assert_se(dup);
38 assert_se(dup[0] == 1);
39 assert_se(dup[1] == 2);
40 assert_se(dup[2] == 3);
41
42 p = dup;
43 assert_se(greedy_realloc0((void**) &dup, &allocated, 2, sizeof(int)) == p);
44
45 p = (int *) greedy_realloc0((void**) &dup, &allocated, 10, sizeof(int));
46 assert_se(p == dup);
47 assert_se(allocated >= 10);
48 assert_se(p[0] == 1);
49 assert_se(p[1] == 2);
50 assert_se(p[2] == 3);
51 for (i = 3; i < allocated; i++)
52 assert_se(p[i] == 0);
b66de1f9
RC
53}
54
37e744e8 55static void test_bool_assign(void) {
108ccae9 56 bool b, c, *cp = &c, d, e, f, g, h;
37e744e8
ZJS
57
58 b = 123;
59 *cp = -11;
60 d = 0xF & 0xFF;
61 e = b & d;
62 f = 0x0;
108ccae9
ZJS
63 g = cp; /* cast from pointer */
64 h = NULL; /* cast from pointer */
37e744e8
ZJS
65
66 assert(b);
67 assert(c);
68 assert(d);
69 assert(e);
70 assert(!f);
108ccae9
ZJS
71 assert(g);
72 assert(!h);
37e744e8
ZJS
73}
74
b66de1f9
RC
75int main(int argc, char *argv[]) {
76 test_alloca();
f30788ee 77 test_memdup_multiply_and_greedy_realloc();
37e744e8 78 test_bool_assign();
b66de1f9
RC
79
80 return 0;
81}