1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  * libfdt - Flat Device Tree manipulation
4  *	Testcase for string references in dtc
5  * Copyright (C) 2006 David Gibson, IBM Corporation.
6  */
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <string.h>
10 #include <stdint.h>
11 
12 #include <libfdt.h>
13 
14 #include "tests.h"
15 #include "testdata.h"
16 
check_ref(const void * fdt,int node,const char * checkpath)17 static void check_ref(const void *fdt, int node, const char *checkpath)
18 {
19 	const char *p;
20 	int len;
21 
22 	p = fdt_getprop(fdt, node, "ref", &len);
23 	if (!p)
24 		FAIL("fdt_getprop(%d, \"ref\"): %s", node, fdt_strerror(len));
25 	if (!streq(p, checkpath))
26 		FAIL("'ref' in node at %d has value \"%s\" instead of \"%s\"",
27 		     node, p, checkpath);
28 
29 	p = fdt_getprop(fdt, node, "lref", &len);
30 	if (!p)
31 		FAIL("fdt_getprop(%d, \"lref\"): %s", node, fdt_strerror(len));
32 	if (!streq(p, checkpath))
33 		FAIL("'lref' in node at %d has value \"%s\" instead of \"%s\"",
34 		     node, p, checkpath);
35 }
36 
check_rref(const void * fdt)37 static void check_rref(const void *fdt)
38 {
39 	const char *p;
40 	int len;
41 
42 	/* Check reference to root node */
43 	p = fdt_getprop(fdt, 0, "rref", &len);
44 	if (!p)
45 		FAIL("fdt_getprop(0, \"rref\"): %s", fdt_strerror(len));
46 	if (!streq(p, "/"))
47 		FAIL("'rref' in root node has value \"%s\" instead of \"/\"",
48 		     p);
49 }
50 
main(int argc,char * argv[])51 int main(int argc, char *argv[])
52 {
53 	void *fdt;
54 	const char *p;
55 	int len, multilen;
56 	int n1, n2, n3, n4;
57 
58 	test_init(argc, argv);
59 	fdt = load_blob_arg(argc, argv);
60 
61 	n1 = fdt_path_offset(fdt, "/node1");
62 	if (n1 < 0)
63 		FAIL("fdt_path_offset(/node1): %s", fdt_strerror(n1));
64 	n2 = fdt_path_offset(fdt, "/node2");
65 	if (n2 < 0)
66 		FAIL("fdt_path_offset(/node2): %s", fdt_strerror(n2));
67 
68 	check_ref(fdt, n1, "/node2");
69 	check_ref(fdt, n2, "/node1");
70 
71 	/* Check multiple reference */
72 	multilen = strlen("/node1") + strlen("/node2") + 2;
73 	p = fdt_getprop(fdt, 0, "multiref", &len);
74 	if (!p)
75 		FAIL("fdt_getprop(0, \"multiref\"): %s", fdt_strerror(len));
76 	if (len != multilen)
77 		FAIL("multiref has wrong length, %d instead of %d",
78 		     len, multilen);
79 	if ((!streq(p, "/node1") || !streq(p + strlen("/node1") + 1, "/node2")))
80 		FAIL("multiref has wrong value");
81 
82 	/* Check reference to nested nodes with common prefix */
83 	n3 = fdt_path_offset(fdt, "/foo/baz");
84 	if (n3 < 0)
85 		FAIL("fdt_path_offset(/foo/baz): %s", fdt_strerror(n3));
86 	n4 = fdt_path_offset(fdt, "/foobar/baz");
87 	if (n4 < 0)
88 		FAIL("fdt_path_offset(/foobar/baz): %s", fdt_strerror(n4));
89 	check_ref(fdt, n3, "/foobar/baz");
90 	check_ref(fdt, n4, "/foo/baz");
91 
92 	check_rref(fdt);
93 
94 	PASS();
95 }
96