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