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