1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3 * Testcase for dtc expression support
4 *
5 * Copyright (C) 2008 David Gibson, IBM Corporation.
6 */
7
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdint.h>
12 #include <errno.h>
13
14
15 #include <libfdt.h>
16
17 #include "tests.h"
18 #include "testdata.h"
19
20 static struct test_expr {
21 const char *expr;
22 uint32_t result;
23 } expr_table[] = {
24 #define TE(expr) { #expr, (expr) }
25 TE(0xdeadbeef),
26 TE(-0x21524111),
27 TE(1+1),
28 TE(2*3),
29 TE(4/2),
30 TE(10/3),
31 TE(19%4),
32 TE(1 << 13),
33 TE(0x1000 >> 4),
34 TE(3*2+1), TE(3*(2+1)),
35 TE(1+2*3), TE((1+2)*3),
36 TE(1 < 2), TE(2 < 1), TE(1 < 1),
37 TE(1 <= 2), TE(2 <= 1), TE(1 <= 1),
38 TE(1 > 2), TE(2 > 1), TE(1 > 1),
39 TE(1 >= 2), TE(2 >= 1), TE(1 >= 1),
40 TE(1 == 1), TE(1 == 2),
41 TE(1 != 1), TE(1 != 2),
42 TE(0xabcdabcd & 0xffff0000),
43 TE(0xdead4110 ^ 0xf0f0f0f0),
44 TE(0xabcd0000 | 0x0000abcd),
45 TE(~0x21524110),
46 TE(~~0xdeadbeef),
47 TE(0 && 0), TE(17 && 0), TE(0 && 17), TE(17 && 17),
48 TE(0 || 0), TE(17 || 0), TE(0 || 17), TE(17 || 17),
49 TE(!0), TE(!1), TE(!17), TE(!!0), TE(!!17),
50 TE(0 ? 17 : 39), TE(1 ? 17 : 39), TE(17 ? 0xdeadbeef : 0xabcd1234),
51 TE(11 * 257 * 1321517ULL),
52 TE(123456790 - 4/2 + 17%4),
53 };
54
55 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
56
main(int argc,char * argv[])57 int main(int argc, char *argv[])
58 {
59 void *fdt;
60 const fdt32_t *res;
61 int reslen;
62 int i;
63
64 test_init(argc, argv);
65
66 if ((argc == 3) && (strcmp(argv[1], "-g") == 0)) {
67 FILE *f = fopen(argv[2], "w");
68
69 if (!f)
70 FAIL("Couldn't open \"%s\" for output: %s\n",
71 argv[2], strerror(errno));
72
73 fprintf(f, "/dts-v1/;\n");
74 fprintf(f, "/ {\n");
75 fprintf(f, "\texpressions = <\n");
76 for (i = 0; i < ARRAY_SIZE(expr_table); i++)
77 fprintf(f, "\t\t(%s)\n", expr_table[i].expr);
78 fprintf(f, "\t>;\n");
79 fprintf(f, "};\n");
80 fclose(f);
81 } else {
82 fdt = load_blob_arg(argc, argv);
83
84 res = fdt_getprop(fdt, 0, "expressions", &reslen);
85
86 if (!res)
87 FAIL("Error retrieving expression results: %s\n",
88 fdt_strerror(reslen));
89
90 if (reslen != (ARRAY_SIZE(expr_table) * sizeof(uint32_t)))
91 FAIL("Unexpected length of results %d instead of %zd\n",
92 reslen, ARRAY_SIZE(expr_table) * sizeof(uint32_t));
93
94 for (i = 0; i < ARRAY_SIZE(expr_table); i++)
95 if (fdt32_to_cpu(res[i]) != expr_table[i].result)
96 FAIL("Incorrect result for expression \"%s\","
97 " 0x%x instead of 0x%x\n",
98 expr_table[i].expr, fdt32_to_cpu(res[i]),
99 expr_table[i].result);
100 }
101
102 PASS();
103 }
104