1 /*
2  * Copyright (c) 2014 Brian Swetland
3  *
4  * Use of this source code is governed by a MIT-style
5  * license that can be found in the LICENSE file or at
6  * https://opensource.org/licenses/MIT
7  */
8 
9 #include "devicetree.h"
10 
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <errno.h>
16 
error(const char * msg)17 void error(const char *msg) {
18     printf("error: %s\n", msg);
19 };
20 
indent(u32 n)21 void indent(u32 n) {
22     while (n-- > 0)
23         putchar(' ');
24 }
25 
hexdump(u8 * data,u32 count)26 void hexdump(u8 *data, u32 count) {
27     while (count-- > 0)
28         printf("%02x ", *data++);
29 }
30 
loadfile(const char * fn,dt_slice_t * out)31 int loadfile(const char *fn, dt_slice_t *out) {
32     void *data = NULL;
33     off_t end;
34     int fd;
35     if ((fd = open(fn, O_RDONLY)) < 0)
36         return -1;
37     if ((end = lseek(fd, 0, SEEK_END)) == -1)
38         goto oops;
39     if (lseek(fd, 0, SEEK_SET))
40         goto oops;
41     if ((data = malloc(end + 1)) == NULL)
42         goto oops;
43     if ((read(fd, data, end) != end))
44         goto oops;
45     out->data = data;
46     out->size = end;
47     close(fd);
48     return 0;
49 oops:
50     free(data);
51     close(fd);
52     return -1;
53 }
54 
55 static int _depth = 0;
56 
node_cb(int depth,const char * name,void * cookie)57 int node_cb(int depth, const char *name, void *cookie) {
58     _depth = depth;
59     indent(depth*2);
60     printf("node: '%s'\n", name);
61     return 0;
62 }
63 
prop_cb(const char * name,u8 * data,u32 size,void * cookie)64 int prop_cb(const char *name, u8 *data, u32 size, void *cookie) {
65     indent(_depth * 2 + 2);
66     printf("prop '%s' sz=%d\n", name, size);
67     indent(_depth * 2 + 2);
68     printf("data ");
69     hexdump(data, size);
70     printf("\n");
71     return 0;
72 }
73 
main(int argc,char ** argv)74 int main(int argc, char **argv) {
75     devicetree_t dt;
76     dt_slice_t s;
77 
78     dt.error = error;
79 
80     if (argc != 2)
81         return -1;
82     if (loadfile(argv[1], &s))
83         return -1;
84     if (dt_init(&dt, s.data, s.size))
85         return -1;
86 
87     printf("magic %x\n", dt.hdr.magic);
88     printf("size %d\n", dt.hdr.size);
89     printf("off_struct %d (%d)\n", dt.hdr.off_struct, dt.hdr.sz_struct);
90     printf("off_strings %d (%d)\n", dt.hdr.off_strings, dt.hdr.sz_strings);
91     printf("version %d (min %d)\n", dt.hdr.version, dt.hdr.version_compat);
92 
93     dt_walk(&dt, node_cb, prop_cb, NULL);
94     return 0;
95 }
96 
97