xref: /aosp_15_r20/external/dtc/tests/get_phandle.c (revision cd60bc56d4bea3af4ec04523e4d71c2b272c8aff)
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /*
3  * libfdt - Flat Device Tree manipulation
4  *	Testcase for fdt_get_phandle()
5  * Copyright (C) 2006 David Gibson, IBM Corporation.
6  */
7 #include <stdbool.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdint.h>
12 
13 #include <libfdt.h>
14 
15 #include "tests.h"
16 #include "testdata.h"
17 
check_phandle(void * fdt,const char * path,uint32_t checkhandle)18 static void check_phandle(void *fdt, const char *path, uint32_t checkhandle)
19 {
20 	int offset;
21 	uint32_t phandle;
22 
23 	offset = fdt_path_offset(fdt, path);
24 	if (offset < 0)
25 		FAIL("Couldn't find %s", path);
26 
27 	phandle = fdt_get_phandle(fdt, offset);
28 	if (phandle != checkhandle)
29 		FAIL("fdt_get_phandle(%s) returned 0x%x instead of 0x%x\n",
30 		     path, phandle, checkhandle);
31 }
32 
check_phandle_unique(const void * fdt,uint32_t checkhandle)33 static void check_phandle_unique(const void *fdt, uint32_t checkhandle)
34 {
35 	uint32_t phandle;
36 	int offset = -1;
37 
38 	while (true) {
39 		offset = fdt_next_node(fdt, offset, NULL);
40 		if (offset < 0) {
41 			if (offset == -FDT_ERR_NOTFOUND)
42 				break;
43 
44 			FAIL("error looking for phandle %#x", checkhandle);
45 		}
46 
47 		phandle = fdt_get_phandle(fdt, offset);
48 
49 		if (phandle == checkhandle)
50 			FAIL("generated phandle already exists");
51 	}
52 }
53 
main(int argc,char * argv[])54 int main(int argc, char *argv[])
55 {
56 	uint32_t max, phandle;
57 	void *fdt;
58 	int err;
59 
60 	test_init(argc, argv);
61 	fdt = load_blob_arg(argc, argv);
62 
63 	check_phandle(fdt, "/", 0);
64 	check_phandle(fdt, "/subnode@2", PHANDLE_1);
65 	check_phandle(fdt, "/subnode@2/subsubnode@0", PHANDLE_2);
66 
67 	err = fdt_find_max_phandle(fdt, &max);
68 	if (err < 0)
69 		FAIL("fdt_find_max_phandle returned %d instead of 0\n", err);
70 
71 	if (max != PHANDLE_2)
72 		FAIL("fdt_find_max_phandle found 0x%x instead of 0x%x", max,
73 		     PHANDLE_2);
74 
75 	max = fdt_get_max_phandle(fdt);
76 	if (max != PHANDLE_2)
77 		FAIL("fdt_get_max_phandle returned 0x%x instead of 0x%x\n",
78 		     max, PHANDLE_2);
79 
80 	err = fdt_generate_phandle(fdt, &phandle);
81 	if (err < 0)
82 		FAIL("failed to generate phandle: %d", err);
83 
84 	check_phandle_unique(fdt, phandle);
85 
86 	PASS();
87 }
88