]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-strxcpyx.c
tree-wide: various ubsan zero size memory fixes
[thirdparty/systemd.git] / src / test / test-strxcpyx.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <string.h>
4
5 #include "string-util.h"
6 #include "strxcpyx.h"
7 #include "util.h"
8
9 static void test_strpcpy(void) {
10 char target[25];
11 char *s = target;
12 size_t space_left;
13
14 space_left = sizeof(target);
15 space_left = strpcpy(&s, space_left, "12345");
16 space_left = strpcpy(&s, space_left, "hey hey hey");
17 space_left = strpcpy(&s, space_left, "waldo");
18 space_left = strpcpy(&s, space_left, "ba");
19 space_left = strpcpy(&s, space_left, "r");
20 space_left = strpcpy(&s, space_left, "foo");
21
22 assert_se(streq(target, "12345hey hey heywaldobar"));
23 assert_se(space_left == 0);
24 }
25
26 static void test_strpcpyf(void) {
27 char target[25];
28 char *s = target;
29 size_t space_left;
30
31 space_left = sizeof(target);
32 space_left = strpcpyf(&s, space_left, "space left: %zu. ", space_left);
33 space_left = strpcpyf(&s, space_left, "foo%s", "bar");
34
35 assert_se(streq(target, "space left: 25. foobar"));
36 assert_se(space_left == 3);
37
38 /* test overflow */
39 s = target;
40 space_left = strpcpyf(&s, 12, "00 left: %i. ", 999);
41 assert_se(streq(target, "00 left: 99"));
42 assert_se(space_left == 0);
43 assert_se(target[12] == '2');
44 }
45
46 static void test_strpcpyl(void) {
47 char target[25];
48 char *s = target;
49 size_t space_left;
50
51 space_left = sizeof(target);
52 space_left = strpcpyl(&s, space_left, "waldo", " test", " waldo. ", NULL);
53 space_left = strpcpyl(&s, space_left, "Banana", NULL);
54
55 assert_se(streq(target, "waldo test waldo. Banana"));
56 assert_se(space_left == 1);
57 }
58
59 static void test_strscpy(void) {
60 char target[25];
61 size_t space_left;
62
63 space_left = sizeof(target);
64 space_left = strscpy(target, space_left, "12345");
65
66 assert_se(streq(target, "12345"));
67 assert_se(space_left == 20);
68 }
69
70 static void test_strscpyl(void) {
71 char target[25];
72 size_t space_left;
73
74 space_left = sizeof(target);
75 space_left = strscpyl(target, space_left, "12345", "waldo", "waldo", NULL);
76
77 assert_se(streq(target, "12345waldowaldo"));
78 assert_se(space_left == 10);
79 }
80
81 int main(int argc, char *argv[]) {
82 test_strpcpy();
83 test_strpcpyf();
84 test_strpcpyl();
85 test_strscpy();
86 test_strscpyl();
87
88 return 0;
89 }