1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3 * Copyright 2011 The Chromium Authors, All Rights Reserved.
4 *
5 * utilfdt_test - Tests for utilfdt library
6 */
7 #include <assert.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdint.h>
12 #include <stdarg.h>
13
14 #include <libfdt.h>
15 #include <util.h>
16
17 #include "tests.h"
18 #include "testdata.h"
19
check(const char * fmt,int expect_type,int expect_size)20 static void check(const char *fmt, int expect_type, int expect_size)
21 {
22 int type;
23 int size;
24
25 if (utilfdt_decode_type(fmt, &type, &size))
26 FAIL("format '%s': valid format string returned failure", fmt);
27 if (expect_type != type)
28 FAIL("format '%s': expected type='%c', got type='%c'", fmt,
29 expect_type, type);
30 if (expect_size != size)
31 FAIL("format '%s': expected size=%d, got size=%d", fmt,
32 expect_size, size);
33 }
34
checkfail(const char * fmt)35 static void checkfail(const char *fmt)
36 {
37 int type;
38 int size;
39
40 if (!utilfdt_decode_type(fmt, &type, &size))
41 FAIL("format '%s': invalid format string returned success",
42 fmt);
43 }
44
45 /**
46 * Add the given modifier to each of the valid sizes, and check that we get
47 * correct values.
48 *
49 * \param modifier Modifer string to use as a prefix
50 * \param expected_size The size (in bytes) that we expect (ignored for
51 * strings)
52 */
check_sizes(char * modifier,int expected_size)53 static void check_sizes(char *modifier, int expected_size)
54 {
55 char fmt[10], *ptr;
56
57 /* set up a string with a hole in it for the format character */
58 if (strlen(modifier) + 2 >= sizeof(fmt))
59 FAIL("modifier string '%s' too long", modifier);
60 strcpy(fmt, modifier);
61 ptr = fmt + strlen(fmt);
62 ptr[1] = '\0';
63
64 /* now try each format character in turn */
65 *ptr = 'i';
66 check(fmt, 'i', expected_size);
67
68 *ptr = 'u';
69 check(fmt, 'u', expected_size);
70
71 *ptr = 'x';
72 check(fmt, 'x', expected_size);
73
74 *ptr = 's';
75 check(fmt, 's', -1);
76
77 *ptr = 'r';
78 check(fmt, 'r', -1);
79 }
80
test_utilfdt_decode_type(void)81 static void test_utilfdt_decode_type(void)
82 {
83 char fmt[10];
84 int ch;
85
86 /* check all the valid modifiers and sizes */
87 check_sizes("", -1);
88 check_sizes("b", 1);
89 check_sizes("hh", 1);
90 check_sizes("h", 2);
91 check_sizes("l", 4);
92
93 /* try every other character */
94 checkfail("");
95 for (ch = ' '; ch < 127; ch++) {
96 if (!strchr("iuxsr", ch)) {
97 *fmt = ch;
98 fmt[1] = '\0';
99 checkfail(fmt);
100 }
101 }
102
103 /* try a few modifiers at the end */
104 checkfail("sx");
105 checkfail("ihh");
106 checkfail("xb");
107
108 /* and one for the doomsday archives */
109 checkfail("He has all the virtues I dislike and none of the vices "
110 "I admire.");
111 }
112
main(int argc,char * argv[])113 int main(int argc, char *argv[])
114 {
115 test_utilfdt_decode_type();
116 PASS();
117 }
118