blob: 037176bc9ef8f580e67b452a0915f6c103a67fe3 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001// SPDX-License-Identifier: GPL-2.0+
Simon Glass07c6b842015-06-23 15:38:28 -06002/*
3 * Copyright (c) 2013, Google Inc.
4 * Written by Simon Glass <sjg@chromium.org>
5 *
Simon Glass07c6b842015-06-23 15:38:28 -06006 * Perform a grep of an FDT either displaying the source subset or producing
7 * a new .dtb subset which can be used as required.
8 */
9
10#include <assert.h>
11#include <ctype.h>
Masahiro Yamada315fe0a2018-01-21 19:19:15 +090012#include <errno.h>
Simon Glass07c6b842015-06-23 15:38:28 -060013#include <getopt.h>
Masahiro Yamada315fe0a2018-01-21 19:19:15 +090014#include <fcntl.h>
15#include <stdbool.h>
Simon Glass07c6b842015-06-23 15:38:28 -060016#include <stdio.h>
17#include <stdlib.h>
18#include <string.h>
19#include <unistd.h>
Masahiro Yamada6dd10522020-04-16 18:30:18 +090020#include <fdt_region.h>
Simon Glass07c6b842015-06-23 15:38:28 -060021
Masahiro Yamada938f0392018-01-21 19:19:13 +090022#include "fdt_host.h"
Jan Kundrát873de762017-11-03 03:06:35 +010023#include "libfdt_internal.h"
Simon Glass07c6b842015-06-23 15:38:28 -060024
25/* Define DEBUG to get some debugging output on stderr */
26#ifdef DEBUG
27#define debug(a, b...) fprintf(stderr, a, ## b)
28#else
29#define debug(a, b...)
30#endif
31
32/* A linked list of values we are grepping for */
33struct value_node {
34 int type; /* Types this value matches (FDT_IS... mask) */
35 int include; /* 1 to include matches, 0 to exclude */
36 const char *string; /* String to match */
37 struct value_node *next; /* Pointer to next node, or NULL */
38};
39
40/* Output formats we support */
41enum output_t {
42 OUT_DTS, /* Device tree source */
43 OUT_DTB, /* Valid device tree binary */
44 OUT_BIN, /* Fragment of .dtb, for hashing */
45};
46
47/* Holds information which controls our output and options */
48struct display_info {
49 enum output_t output; /* Output format */
50 int add_aliases; /* Add aliases node to output */
51 int all; /* Display all properties/nodes */
52 int colour; /* Display output in ANSI colour */
53 int region_list; /* Output a region list */
54 int flags; /* Flags (FDT_REG_...) */
55 int list_strings; /* List strings in string table */
56 int show_offset; /* Show offset */
57 int show_addr; /* Show address */
58 int header; /* Output an FDT header */
59 int diff; /* Show +/- diff markers */
60 int include_root; /* Include the root node and all properties */
61 int remove_strings; /* Remove unused strings */
62 int show_dts_version; /* Put '/dts-v1/;' on the first line */
63 int types_inc; /* Mask of types that we include (FDT_IS...) */
64 int types_exc; /* Mask of types that we exclude (FDT_IS...) */
65 int invert; /* Invert polarity of match */
Simon Glassef8e0722023-12-17 09:36:22 -070066 int props_up; /* Imply properties up to supernodes */
Simon Glass07c6b842015-06-23 15:38:28 -060067 struct value_node *value_head; /* List of values to match */
68 const char *output_fname; /* Output filename */
69 FILE *fout; /* File to write dts/dtb output */
70};
71
72static void report_error(const char *where, int err)
73{
74 fprintf(stderr, "Error at '%s': %s\n", where, fdt_strerror(err));
75}
76
77/* Supported ANSI colours */
78enum {
79 COL_BLACK,
80 COL_RED,
81 COL_GREEN,
82 COL_YELLOW,
83 COL_BLUE,
84 COL_MAGENTA,
85 COL_CYAN,
86 COL_WHITE,
87
88 COL_NONE = -1,
89};
90
91/**
92 * print_ansi_colour() - Print out the ANSI sequence for a colour
93 *
94 * @fout: Output file
95 * @col: Colour to output (COL_...), or COL_NONE to reset colour
96 */
97static void print_ansi_colour(FILE *fout, int col)
98{
99 if (col == COL_NONE)
100 fprintf(fout, "\033[0m");
101 else
102 fprintf(fout, "\033[1;%dm", col + 30);
103}
104
Simon Glass07c6b842015-06-23 15:38:28 -0600105/**
106 * value_add() - Add a new value to our list of things to grep for
107 *
108 * @disp: Display structure, holding info about our options
109 * @headp: Pointer to header pointer of list
110 * @type: Type of this value (FDT_IS_...)
111 * @include: 1 if we want to include matches, 0 to exclude
112 * @str: String value to match
113 */
114static int value_add(struct display_info *disp, struct value_node **headp,
115 int type, int include, const char *str)
116{
117 struct value_node *node;
118
119 /*
120 * Keep track of which types we are excluding/including. We don't
121 * allow both including and excluding things, because it doesn't make
122 * sense. 'Including' means that everything not mentioned is
123 * excluded. 'Excluding' means that everything not mentioned is
124 * included. So using the two together would be meaningless.
125 */
126 if (include)
127 disp->types_inc |= type;
128 else
129 disp->types_exc |= type;
130 if (disp->types_inc & disp->types_exc & type) {
131 fprintf(stderr,
132 "Cannot use both include and exclude for '%s'\n", str);
133 return -1;
134 }
135
136 str = strdup(str);
Simon Glasscea3b9e2018-06-12 00:04:59 -0600137 if (!str)
138 goto err_mem;
Simon Glass07c6b842015-06-23 15:38:28 -0600139 node = malloc(sizeof(*node));
Simon Glasscea3b9e2018-06-12 00:04:59 -0600140 if (!node)
141 goto err_mem;
Simon Glass07c6b842015-06-23 15:38:28 -0600142 node->next = *headp;
143 node->type = type;
144 node->include = include;
145 node->string = str;
146 *headp = node;
147
148 return 0;
Simon Glasscea3b9e2018-06-12 00:04:59 -0600149err_mem:
150 fprintf(stderr, "Out of memory\n");
151 return -1;
Simon Glass07c6b842015-06-23 15:38:28 -0600152}
153
154static bool util_is_printable_string(const void *data, int len)
155{
156 const char *s = data;
157 const char *ss, *se;
158
159 /* zero length is not */
160 if (len == 0)
161 return 0;
162
163 /* must terminate with zero */
164 if (s[len - 1] != '\0')
165 return 0;
166
167 se = s + len;
168
169 while (s < se) {
170 ss = s;
171 while (s < se && *s && isprint((unsigned char)*s))
172 s++;
173
174 /* not zero, or not done yet */
175 if (*s != '\0' || s == ss)
176 return 0;
177
178 s++;
179 }
180
181 return 1;
182}
183
184static void utilfdt_print_data(const char *data, int len)
185{
186 int i;
187 const char *p = data;
188 const char *s;
189
190 /* no data, don't print */
191 if (len == 0)
192 return;
193
194 if (util_is_printable_string(data, len)) {
195 printf(" = ");
196
197 s = data;
198 do {
199 printf("\"%s\"", s);
200 s += strlen(s) + 1;
201 if (s < data + len)
202 printf(", ");
203 } while (s < data + len);
204
205 } else if ((len % 4) == 0) {
206 const uint32_t *cell = (const uint32_t *)data;
207
208 printf(" = <");
209 for (i = 0, len /= 4; i < len; i++)
210 printf("0x%08x%s", fdt32_to_cpu(cell[i]),
211 i < (len - 1) ? " " : "");
212 printf(">");
213 } else {
214 printf(" = [");
215 for (i = 0; i < len; i++)
Samuel Dionne-Riel32b49552021-02-10 19:43:09 -0500216 printf("%02x%s", (unsigned char)*p++, i < len - 1 ? " " : "");
Simon Glass07c6b842015-06-23 15:38:28 -0600217 printf("]");
218 }
219}
220
221/**
222 * display_fdt_by_regions() - Display regions of an FDT source
223 *
224 * This dumps an FDT as source, but only certain regions of it. This is the
225 * final stage of the grep - we have a list of regions we want to display,
226 * and this function displays them.
227 *
228 * @disp: Display structure, holding info about our options
229 * @blob: FDT blob to display
230 * @region: List of regions to display
231 * @count: Number of regions
232 */
233static int display_fdt_by_regions(struct display_info *disp, const void *blob,
234 struct fdt_region region[], int count)
235{
236 struct fdt_region *reg = region, *reg_end = region + count;
237 uint32_t off_mem_rsvmap = fdt_off_mem_rsvmap(blob);
238 int base = fdt_off_dt_struct(blob);
239 int version = fdt_version(blob);
240 int offset, nextoffset;
241 int tag, depth, shift;
242 FILE *f = disp->fout;
243 uint64_t addr, size;
244 int in_region;
245 int file_ofs;
246 int i;
247
248 if (disp->show_dts_version)
249 fprintf(f, "/dts-v1/;\n");
250
251 if (disp->header) {
252 fprintf(f, "// magic:\t\t0x%x\n", fdt_magic(blob));
253 fprintf(f, "// totalsize:\t\t0x%x (%d)\n", fdt_totalsize(blob),
254 fdt_totalsize(blob));
255 fprintf(f, "// off_dt_struct:\t0x%x\n",
256 fdt_off_dt_struct(blob));
257 fprintf(f, "// off_dt_strings:\t0x%x\n",
258 fdt_off_dt_strings(blob));
259 fprintf(f, "// off_mem_rsvmap:\t0x%x\n", off_mem_rsvmap);
260 fprintf(f, "// version:\t\t%d\n", version);
261 fprintf(f, "// last_comp_version:\t%d\n",
262 fdt_last_comp_version(blob));
263 if (version >= 2) {
264 fprintf(f, "// boot_cpuid_phys:\t0x%x\n",
265 fdt_boot_cpuid_phys(blob));
266 }
267 if (version >= 3) {
268 fprintf(f, "// size_dt_strings:\t0x%x\n",
269 fdt_size_dt_strings(blob));
270 }
271 if (version >= 17) {
272 fprintf(f, "// size_dt_struct:\t0x%x\n",
273 fdt_size_dt_struct(blob));
274 }
275 fprintf(f, "\n");
276 }
277
278 if (disp->flags & FDT_REG_ADD_MEM_RSVMAP) {
279 const struct fdt_reserve_entry *p_rsvmap;
280
281 p_rsvmap = (const struct fdt_reserve_entry *)
282 ((const char *)blob + off_mem_rsvmap);
283 for (i = 0; ; i++) {
284 addr = fdt64_to_cpu(p_rsvmap[i].address);
285 size = fdt64_to_cpu(p_rsvmap[i].size);
286 if (addr == 0 && size == 0)
287 break;
288
289 fprintf(f, "/memreserve/ %llx %llx;\n",
290 (unsigned long long)addr,
291 (unsigned long long)size);
292 }
293 }
294
295 depth = 0;
296 nextoffset = 0;
297 shift = 4; /* 4 spaces per indent */
298 do {
299 const struct fdt_property *prop;
300 const char *name;
301 int show;
302 int len;
303
304 offset = nextoffset;
305
306 /*
307 * Work out the file offset of this offset, and decide
308 * whether it is in the region list or not
309 */
310 file_ofs = base + offset;
311 if (reg < reg_end && file_ofs >= reg->offset + reg->size)
312 reg++;
313 in_region = reg < reg_end && file_ofs >= reg->offset &&
314 file_ofs < reg->offset + reg->size;
315 tag = fdt_next_tag(blob, offset, &nextoffset);
316
317 if (tag == FDT_END)
318 break;
319 show = in_region || disp->all;
320 if (show && disp->diff)
321 fprintf(f, "%c", in_region ? '+' : '-');
322
323 if (!show) {
324 /* Do this here to avoid 'if (show)' in every 'case' */
325 if (tag == FDT_BEGIN_NODE)
326 depth++;
327 else if (tag == FDT_END_NODE)
328 depth--;
329 continue;
330 }
331 if (tag != FDT_END) {
332 if (disp->show_addr)
333 fprintf(f, "%4x: ", file_ofs);
334 if (disp->show_offset)
335 fprintf(f, "%4x: ", file_ofs - base);
336 }
337
338 /* Green means included, red means excluded */
339 if (disp->colour)
340 print_ansi_colour(f, in_region ? COL_GREEN : COL_RED);
341
342 switch (tag) {
343 case FDT_PROP:
344 prop = fdt_get_property_by_offset(blob, offset, NULL);
345 name = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
346 fprintf(f, "%*s%s", depth * shift, "", name);
347 utilfdt_print_data(prop->data,
348 fdt32_to_cpu(prop->len));
349 fprintf(f, ";");
350 break;
351
352 case FDT_NOP:
353 fprintf(f, "%*s// [NOP]", depth * shift, "");
354 break;
355
356 case FDT_BEGIN_NODE:
357 name = fdt_get_name(blob, offset, &len);
358 fprintf(f, "%*s%s {", depth++ * shift, "",
359 *name ? name : "/");
360 break;
361
362 case FDT_END_NODE:
363 fprintf(f, "%*s};", --depth * shift, "");
364 break;
365 }
366
367 /* Reset colour back to normal before end of line */
368 if (disp->colour)
369 print_ansi_colour(f, COL_NONE);
370 fprintf(f, "\n");
371 } while (1);
372
373 /* Print a list of strings if requested */
374 if (disp->list_strings) {
375 const char *str;
376 int str_base = fdt_off_dt_strings(blob);
377
Simon Glass6e902d52023-12-17 09:36:15 -0700378 for (offset = 0;
379 offset < (int)fdt_size_dt_strings(blob);
380 offset += strlen(str) + 1) {
Simon Glass07c6b842015-06-23 15:38:28 -0600381 str = fdt_string(blob, offset);
382 int len = strlen(str) + 1;
383 int show;
384
385 /* Only print strings that are in the region */
386 file_ofs = str_base + offset;
387 in_region = reg < reg_end &&
388 file_ofs >= reg->offset &&
389 file_ofs + len < reg->offset +
390 reg->size;
391 show = in_region || disp->all;
392 if (show && disp->diff)
393 printf("%c", in_region ? '+' : '-');
394 if (disp->show_addr)
395 printf("%4x: ", file_ofs);
396 if (disp->show_offset)
397 printf("%4x: ", offset);
398 printf("%s\n", str);
399 }
400 }
401
402 return 0;
403}
404
405/**
406 * dump_fdt_regions() - Dump regions of an FDT as binary data
407 *
408 * This dumps an FDT as binary, but only certain regions of it. This is the
409 * final stage of the grep - we have a list of regions we want to dump,
410 * and this function dumps them.
411 *
412 * The output of this function may or may not be a valid FDT. To ensure it
413 * is, these disp->flags must be set:
414 *
Robert P. J. Dayc5b1e5d2016-09-07 14:27:59 -0400415 * FDT_REG_SUPERNODES: ensures that subnodes are preceded by their
Simon Glass07c6b842015-06-23 15:38:28 -0600416 * parents. Without this option, fragments of subnode data may be
417 * output without the supernodes above them. This is useful for
418 * hashing but cannot produce a valid FDT.
419 * FDT_REG_ADD_STRING_TAB: Adds a string table to the end of the FDT.
420 * Without this none of the properties will have names
421 * FDT_REG_ADD_MEM_RSVMAP: Adds a mem_rsvmap table - an FDT is invalid
422 * without this.
423 *
424 * @disp: Display structure, holding info about our options
425 * @blob: FDT blob to display
426 * @region: List of regions to display
427 * @count: Number of regions
428 * @out: Output destination
429 */
430static int dump_fdt_regions(struct display_info *disp, const void *blob,
431 struct fdt_region region[], int count, char *out)
432{
433 struct fdt_header *fdt;
434 int size, struct_start;
Simon Glass6e902d52023-12-17 09:36:15 -0700435 unsigned int ptr;
Simon Glass07c6b842015-06-23 15:38:28 -0600436 int i;
437
438 /* Set up a basic header (even if we don't actually write it) */
439 fdt = (struct fdt_header *)out;
440 memset(fdt, '\0', sizeof(*fdt));
441 fdt_set_magic(fdt, FDT_MAGIC);
Simon Glass2943bd22021-12-08 09:55:34 -0700442 struct_start = sizeof(struct fdt_header);
Simon Glass07c6b842015-06-23 15:38:28 -0600443 fdt_set_off_mem_rsvmap(fdt, struct_start);
444 fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
445 fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
446
447 /*
448 * Calculate the total size of the regions we are writing out. The
449 * first will be the mem_rsvmap if the FDT_REG_ADD_MEM_RSVMAP flag
450 * is set. The last will be the string table if FDT_REG_ADD_STRING_TAB
451 * is set.
452 */
453 for (i = size = 0; i < count; i++)
454 size += region[i].size;
455
456 /* Bring in the mem_rsvmap section from the old file if requested */
457 if (count > 0 && (disp->flags & FDT_REG_ADD_MEM_RSVMAP)) {
458 struct_start += region[0].size;
459 size -= region[0].size;
460 }
461 fdt_set_off_dt_struct(fdt, struct_start);
462
463 /* Update the header to have the correct offsets/sizes */
464 if (count >= 2 && (disp->flags & FDT_REG_ADD_STRING_TAB)) {
465 int str_size;
466
467 str_size = region[count - 1].size;
468 fdt_set_size_dt_struct(fdt, size - str_size);
469 fdt_set_off_dt_strings(fdt, struct_start + size - str_size);
470 fdt_set_size_dt_strings(fdt, str_size);
471 fdt_set_totalsize(fdt, struct_start + size);
472 }
473
474 /* Write the header if required */
475 ptr = 0;
476 if (disp->header) {
477 ptr = sizeof(*fdt);
478 while (ptr < fdt_off_mem_rsvmap(fdt))
479 out[ptr++] = '\0';
480 }
481
482 /* Output all the nodes including any mem_rsvmap/string table */
483 for (i = 0; i < count; i++) {
484 struct fdt_region *reg = &region[i];
485
486 memcpy(out + ptr, (const char *)blob + reg->offset, reg->size);
487 ptr += reg->size;
488 }
489
490 return ptr;
491}
492
493/**
494 * show_region_list() - Print out a list of regions
495 *
496 * The list includes the region offset (absolute offset from start of FDT
497 * blob in bytes) and size
498 *
499 * @reg: List of regions to print
500 * @count: Number of regions
501 */
502static void show_region_list(struct fdt_region *reg, int count)
503{
504 int i;
505
506 printf("Regions: %d\n", count);
507 for (i = 0; i < count; i++, reg++) {
508 printf("%d: %-10x %-10x\n", i, reg->offset,
509 reg->offset + reg->size);
510 }
511}
512
513static int check_type_include(void *priv, int type, const char *data, int size)
514{
515 struct display_info *disp = priv;
516 struct value_node *val;
517 int match, none_match = FDT_IS_ANY;
518
519 /* If none of our conditions mention this type, we know nothing */
520 debug("type=%x, data=%s\n", type, data ? data : "(null)");
521 if (!((disp->types_inc | disp->types_exc) & type)) {
522 debug(" - not in any condition\n");
523 return -1;
524 }
525
526 /*
527 * Go through the list of conditions. For inclusive conditions, we
528 * return 1 at the first match. For exclusive conditions, we must
529 * check that there are no matches.
530 */
Simon Glass98685e32017-06-07 10:28:40 -0600531 if (data) {
532 for (val = disp->value_head; val; val = val->next) {
533 if (!(type & val->type))
534 continue;
535 match = fdt_stringlist_contains(data, size,
536 val->string);
537 debug(" - val->type=%x, str='%s', match=%d\n",
538 val->type, val->string, match);
539 if (match && val->include) {
540 debug(" - match inc %s\n", val->string);
541 return 1;
542 }
543 if (match)
544 none_match &= ~val->type;
Simon Glass07c6b842015-06-23 15:38:28 -0600545 }
Simon Glass07c6b842015-06-23 15:38:28 -0600546 }
547
548 /*
549 * If this is an exclusive condition, and nothing matches, then we
550 * should return 1.
551 */
552 if ((type & disp->types_exc) && (none_match & type)) {
553 debug(" - match exc\n");
554 /*
555 * Allow FDT_IS_COMPAT to make the final decision in the
556 * case where there is no specific type
557 */
558 if (type == FDT_IS_NODE && disp->types_exc == FDT_ANY_GLOBAL) {
559 debug(" - supressed exc node\n");
560 return -1;
561 }
562 return 1;
563 }
564
565 /*
566 * Allow FDT_IS_COMPAT to make the final decision in the
567 * case where there is no specific type (inclusive)
568 */
569 if (type == FDT_IS_NODE && disp->types_inc == FDT_ANY_GLOBAL)
570 return -1;
571
572 debug(" - no match, types_inc=%x, types_exc=%x, none_match=%x\n",
573 disp->types_inc, disp->types_exc, none_match);
574
575 return 0;
576}
577
578/**
Simon Glassc5c31222023-12-17 09:36:20 -0700579 * check_props() - Check if a node has properties that we want to include
580 *
581 * Calls check_type_include() for each property in the nodn, returning 1 if
582 * that function returns 1 for any of them
583 *
584 * @disp: Display structure, holding info about our options
585 * @fdt: Devicetree blob to check
586 * @node: Node offset to check
587 * @inc: Current value of the 'include' variable (see h_include())
588 * Return: 0 to exclude, 1 to include, -1 if no information is available
589 */
590static int check_props(struct display_info *disp, const void *fdt, int node,
591 int inc)
592{
593 int offset;
594
595 for (offset = fdt_first_property_offset(fdt, node);
596 offset > 0 && inc != 1;
597 offset = fdt_next_property_offset(fdt, offset)) {
598 const struct fdt_property *prop;
599 const char *str;
600
601 prop = fdt_get_property_by_offset(fdt, offset, NULL);
602 if (!prop)
603 continue;
604 str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
605 inc = check_type_include(disp, FDT_NODE_HAS_PROP, str,
606 strlen(str));
607 }
608
Simon Glassef8e0722023-12-17 09:36:22 -0700609 /* if requested, check all subnodes for this property too */
610 if (inc != 1 && disp->props_up) {
611 int subnode;
612
613 for (subnode = fdt_first_subnode(fdt, node);
614 subnode > 0 && inc != 1;
615 subnode = fdt_next_subnode(fdt, subnode))
616 inc = check_props(disp, fdt, subnode, inc);
617 }
618
Simon Glassc5c31222023-12-17 09:36:20 -0700619 return inc;
620}
621
622/**
Simon Glass5cbecd32023-12-17 09:36:18 -0700623 * h_include() - Include handler function for fdt_first_region()
Simon Glass07c6b842015-06-23 15:38:28 -0600624 *
625 * This function decides whether to include or exclude a node, property or
Simon Glass5cbecd32023-12-17 09:36:18 -0700626 * compatible string. The function is defined by fdt_first_region().
Simon Glass07c6b842015-06-23 15:38:28 -0600627 *
628 * The algorithm is documented in the code - disp->invert is 0 for normal
629 * operation, and 1 to invert the sense of all matches.
630 *
Simon Glass5cbecd32023-12-17 09:36:18 -0700631 * @priv: Private pointer as passed to fdtgrep_find_regions()
632 * @fdt: Pointer to FDT blob
633 * @offset: Offset of this node / property
634 * @type: Type of this part, FDT_IS_...
635 * @data: Pointer to data (node name, property name, compatible string)
636 * @size: Size of data, or 0 if none
637 * Return: 0 to exclude, 1 to include, -1 if no information is available
Simon Glass07c6b842015-06-23 15:38:28 -0600638 */
639static int h_include(void *priv, const void *fdt, int offset, int type,
640 const char *data, int size)
641{
642 struct display_info *disp = priv;
643 int inc, len;
644
645 inc = check_type_include(priv, type, data, size);
646 if (disp->include_root && type == FDT_IS_PROP && offset == 0 && inc)
647 return 1;
648
649 /*
650 * If the node name does not tell us anything, check the
651 * compatible string
652 */
653 if (inc == -1 && type == FDT_IS_NODE) {
654 debug(" - checking compatible2\n");
655 data = fdt_getprop(fdt, offset, "compatible", &len);
656 inc = check_type_include(priv, FDT_IS_COMPAT, data, len);
657 }
658
659 /* If we still have no idea, check for properties in the node */
660 if (inc != 1 && type == FDT_IS_NODE &&
661 (disp->types_inc & FDT_NODE_HAS_PROP)) {
662 debug(" - checking node '%s'\n",
663 fdt_get_name(fdt, offset, NULL));
Simon Glassc5c31222023-12-17 09:36:20 -0700664 inc = check_props(disp, fdt, offset, inc);
Simon Glass07c6b842015-06-23 15:38:28 -0600665 if (inc == -1)
666 inc = 0;
667 }
668
Simon Glassf2786452023-12-17 09:36:19 -0700669 if (inc != -1 && disp->invert)
670 inc = !inc;
Simon Glass07c6b842015-06-23 15:38:28 -0600671 debug(" - returning %d\n", inc);
672
673 return inc;
674}
675
676static int h_cmp_region(const void *v1, const void *v2)
677{
678 const struct fdt_region *region1 = v1, *region2 = v2;
679
680 return region1->offset - region2->offset;
681}
682
683static int fdtgrep_find_regions(const void *fdt,
684 int (*include_func)(void *priv, const void *fdt, int offset,
685 int type, const char *data, int size),
686 struct display_info *disp, struct fdt_region *region,
687 int max_regions, char *path, int path_len, int flags)
688{
689 struct fdt_region_state state;
690 int count;
691 int ret;
692
693 count = 0;
694 ret = fdt_first_region(fdt, include_func, disp,
695 &region[count++], path, path_len,
696 disp->flags, &state);
697 while (ret == 0) {
698 ret = fdt_next_region(fdt, include_func, disp,
699 count < max_regions ? &region[count] : NULL,
700 path, path_len, disp->flags, &state);
701 if (!ret)
702 count++;
703 }
Simon Glass8a5651f2016-03-06 19:45:32 -0700704 if (ret && ret != -FDT_ERR_NOTFOUND)
705 return ret;
Simon Glass07c6b842015-06-23 15:38:28 -0600706
707 /* Find all the aliases and add those regions back in */
708 if (disp->add_aliases && count < max_regions) {
709 int new_count;
710
711 new_count = fdt_add_alias_regions(fdt, region, count,
712 max_regions, &state);
Simon Glass8a5651f2016-03-06 19:45:32 -0700713 if (new_count == -FDT_ERR_NOTFOUND) {
714 /* No alias node found */
715 } else if (new_count < 0) {
716 return new_count;
717 } else if (new_count <= max_regions) {
Simon Glassb044a4f2015-10-17 19:41:16 -0600718 /*
Simon Glass6e902d52023-12-17 09:36:15 -0700719 * The alias regions will now be at the end of the list.
720 * Sort the regions by offset to get things into the
721 * right order
722 */
Simon Glassb044a4f2015-10-17 19:41:16 -0600723 count = new_count;
724 qsort(region, count, sizeof(struct fdt_region),
725 h_cmp_region);
Simon Glass07c6b842015-06-23 15:38:28 -0600726 }
Simon Glass07c6b842015-06-23 15:38:28 -0600727 }
728
Simon Glass07c6b842015-06-23 15:38:28 -0600729 return count;
730}
731
732int utilfdt_read_err_len(const char *filename, char **buffp, off_t *len)
733{
734 int fd = 0; /* assume stdin */
735 char *buf = NULL;
736 off_t bufsize = 1024, offset = 0;
737 int ret = 0;
738
739 *buffp = NULL;
740 if (strcmp(filename, "-") != 0) {
741 fd = open(filename, O_RDONLY);
742 if (fd < 0)
743 return errno;
744 }
745
746 /* Loop until we have read everything */
747 buf = malloc(bufsize);
Mikhail Ilinacea4f52022-11-23 14:31:03 +0300748 if (!buf) {
749 close(fd);
Simon Glass07c6b842015-06-23 15:38:28 -0600750 return -ENOMEM;
Mikhail Ilinacea4f52022-11-23 14:31:03 +0300751 }
Simon Glass07c6b842015-06-23 15:38:28 -0600752 do {
753 /* Expand the buffer to hold the next chunk */
754 if (offset == bufsize) {
755 bufsize *= 2;
756 buf = realloc(buf, bufsize);
Mikhail Ilinacea4f52022-11-23 14:31:03 +0300757 if (!buf) {
758 close(fd);
Simon Glass07c6b842015-06-23 15:38:28 -0600759 return -ENOMEM;
Mikhail Ilinacea4f52022-11-23 14:31:03 +0300760 }
Simon Glass07c6b842015-06-23 15:38:28 -0600761 }
762
763 ret = read(fd, &buf[offset], bufsize - offset);
764 if (ret < 0) {
765 ret = errno;
766 break;
767 }
768 offset += ret;
769 } while (ret != 0);
770
771 /* Clean up, including closing stdin; return errno on error */
772 close(fd);
773 if (ret)
774 free(buf);
775 else
776 *buffp = buf;
777 *len = bufsize;
778 return ret;
779}
780
781int utilfdt_read_err(const char *filename, char **buffp)
782{
783 off_t len;
784 return utilfdt_read_err_len(filename, buffp, &len);
785}
786
787char *utilfdt_read_len(const char *filename, off_t *len)
788{
789 char *buff;
790 int ret = utilfdt_read_err_len(filename, &buff, len);
791
792 if (ret) {
793 fprintf(stderr, "Couldn't open blob from '%s': %s\n", filename,
794 strerror(ret));
795 return NULL;
796 }
797 /* Successful read */
798 return buff;
799}
800
801char *utilfdt_read(const char *filename)
802{
803 off_t len;
804 return utilfdt_read_len(filename, &len);
805}
806
807/**
808 * Run the main fdtgrep operation, given a filename and valid arguments
809 *
810 * @param disp Display information / options
811 * @param filename Filename of blob file
812 * @param return 0 if ok, -ve on error
813 */
814static int do_fdtgrep(struct display_info *disp, const char *filename)
815{
Simon Glassa95f0142018-06-12 00:04:58 -0600816 struct fdt_region *region = NULL;
Simon Glass07c6b842015-06-23 15:38:28 -0600817 int max_regions;
818 int count = 100;
819 char path[1024];
820 char *blob;
821 int i, ret;
822
823 blob = utilfdt_read(filename);
824 if (!blob)
825 return -1;
826 ret = fdt_check_header(blob);
827 if (ret) {
828 fprintf(stderr, "Error: %s\n", fdt_strerror(ret));
829 return ret;
830 }
831
832 /* Allow old files, but they are untested */
833 if (fdt_version(blob) < 17 && disp->value_head) {
834 fprintf(stderr,
835 "Warning: fdtgrep does not fully support version %d files\n",
836 fdt_version(blob));
837 }
838
839 /*
840 * We do two passes, since we don't know how many regions we need.
841 * The first pass will count the regions, but if it is too many,
842 * we do another pass to actually record them.
843 */
Simon Glassa95f0142018-06-12 00:04:58 -0600844 for (i = 0; i < 2; i++) {
Patrick Delaunayc6106222020-01-13 09:33:51 +0100845 region = realloc(region, count * sizeof(struct fdt_region));
Simon Glass07c6b842015-06-23 15:38:28 -0600846 if (!region) {
847 fprintf(stderr, "Out of memory for %d regions\n",
848 count);
849 return -1;
850 }
851 max_regions = count;
852 count = fdtgrep_find_regions(blob,
853 h_include, disp,
854 region, max_regions, path, sizeof(path),
855 disp->flags);
856 if (count < 0) {
Simon Glass41452e42023-12-17 09:36:17 -0700857 report_error("fdtgrep_find_regions", count);
Simon Glassa95f0142018-06-12 00:04:58 -0600858 free(region);
Simon Glass07c6b842015-06-23 15:38:28 -0600859 return -1;
860 }
861 if (count <= max_regions)
862 break;
Patrick Delaunayc6106222020-01-13 09:33:51 +0100863 }
864 if (count > max_regions) {
Simon Glass07c6b842015-06-23 15:38:28 -0600865 free(region);
Patrick Delaunayc6106222020-01-13 09:33:51 +0100866 fprintf(stderr, "Internal error with fdtgrep_find_region()\n");
Simon Glassa95f0142018-06-12 00:04:58 -0600867 return -1;
Simon Glass07c6b842015-06-23 15:38:28 -0600868 }
869
870 /* Optionally print a list of regions */
871 if (disp->region_list)
872 show_region_list(region, count);
873
874 /* Output either source .dts or binary .dtb */
875 if (disp->output == OUT_DTS) {
876 ret = display_fdt_by_regions(disp, blob, region, count);
877 } else {
878 void *fdt;
879 /* Allow reserved memory section to expand slightly */
880 int size = fdt_totalsize(blob) + 16;
881
882 fdt = malloc(size);
883 if (!fdt) {
884 fprintf(stderr, "Out_of_memory\n");
885 ret = -1;
886 goto err;
887 }
888 size = dump_fdt_regions(disp, blob, region, count, fdt);
889 if (disp->remove_strings) {
890 void *out;
891
892 out = malloc(size);
893 if (!out) {
894 fprintf(stderr, "Out_of_memory\n");
895 ret = -1;
896 goto err;
897 }
898 ret = fdt_remove_unused_strings(fdt, out);
899 if (ret < 0) {
900 fprintf(stderr,
901 "Failed to remove unused strings: err=%d\n",
902 ret);
903 goto err;
904 }
905 free(fdt);
906 fdt = out;
907 ret = fdt_pack(fdt);
908 if (ret < 0) {
909 fprintf(stderr, "Failed to pack: err=%d\n",
910 ret);
911 goto err;
912 }
913 size = fdt_totalsize(fdt);
914 }
915
Simon Glass6e902d52023-12-17 09:36:15 -0700916 if ((size_t)size != fwrite(fdt, 1, size, disp->fout)) {
Simon Glass07c6b842015-06-23 15:38:28 -0600917 fprintf(stderr, "Write failure, %d bytes\n", size);
918 free(fdt);
919 ret = 1;
920 goto err;
921 }
922 free(fdt);
923 }
924err:
925 free(blob);
926 free(region);
927
928 return ret;
929}
930
931static const char usage_synopsis[] =
932 "fdtgrep - extract portions from device tree\n"
933 "\n"
934 "Usage:\n"
935 " fdtgrep <options> <dt file>|-\n\n"
936 "Output formats are:\n"
937 "\tdts - device tree soure text\n"
938 "\tdtb - device tree blob (sets -Hmt automatically)\n"
939 "\tbin - device tree fragment (may not be a valid .dtb)";
940
941/* Helper for usage_short_opts string constant */
942#define USAGE_COMMON_SHORT_OPTS "hV"
943
944/* Helper for aligning long_opts array */
945#define a_argument required_argument
946
947/* Helper for usage_long_opts option array */
948#define USAGE_COMMON_LONG_OPTS \
949 {"help", no_argument, NULL, 'h'}, \
950 {"version", no_argument, NULL, 'V'}, \
951 {NULL, no_argument, NULL, 0x0}
952
953/* Helper for usage_opts_help array */
954#define USAGE_COMMON_OPTS_HELP \
955 "Print this help and exit", \
956 "Print version and exit", \
957 NULL
958
959/* Helper for getopt case statements */
960#define case_USAGE_COMMON_FLAGS \
961 case 'h': usage(NULL); \
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +0200962 /* fallthrough */ \
Simon Glass07c6b842015-06-23 15:38:28 -0600963 case 'V': util_version(); \
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +0200964 /* fallthrough */ \
Simon Glass07c6b842015-06-23 15:38:28 -0600965 case '?': usage("unknown option");
966
967static const char usage_short_opts[] =
Simon Glassef8e0722023-12-17 09:36:22 -0700968 "haAc:b:C:defg:G:HIlLmn:N:o:O:p:P:rRsStTuv"
Simon Glass07c6b842015-06-23 15:38:28 -0600969 USAGE_COMMON_SHORT_OPTS;
Simon Glass6e902d52023-12-17 09:36:15 -0700970static const struct option usage_long_opts[] = {
Simon Glass07c6b842015-06-23 15:38:28 -0600971 {"show-address", no_argument, NULL, 'a'},
972 {"colour", no_argument, NULL, 'A'},
973 {"include-node-with-prop", a_argument, NULL, 'b'},
974 {"include-compat", a_argument, NULL, 'c'},
975 {"exclude-compat", a_argument, NULL, 'C'},
976 {"diff", no_argument, NULL, 'd'},
977 {"enter-node", no_argument, NULL, 'e'},
978 {"show-offset", no_argument, NULL, 'f'},
979 {"include-match", a_argument, NULL, 'g'},
980 {"exclude-match", a_argument, NULL, 'G'},
981 {"show-header", no_argument, NULL, 'H'},
982 {"show-version", no_argument, NULL, 'I'},
983 {"list-regions", no_argument, NULL, 'l'},
984 {"list-strings", no_argument, NULL, 'L'},
985 {"include-mem", no_argument, NULL, 'm'},
986 {"include-node", a_argument, NULL, 'n'},
987 {"exclude-node", a_argument, NULL, 'N'},
Simon Glassbbee0622023-12-17 09:36:16 -0700988 {"out", a_argument, NULL, 'o'},
989 {"out-format", a_argument, NULL, 'O'},
Simon Glass07c6b842015-06-23 15:38:28 -0600990 {"include-prop", a_argument, NULL, 'p'},
991 {"exclude-prop", a_argument, NULL, 'P'},
992 {"remove-strings", no_argument, NULL, 'r'},
993 {"include-root", no_argument, NULL, 'R'},
994 {"show-subnodes", no_argument, NULL, 's'},
995 {"skip-supernodes", no_argument, NULL, 'S'},
996 {"show-stringtab", no_argument, NULL, 't'},
997 {"show-aliases", no_argument, NULL, 'T'},
Simon Glassef8e0722023-12-17 09:36:22 -0700998 {"props-up-to-supernode", no_argument, NULL, 'u'},
Simon Glass07c6b842015-06-23 15:38:28 -0600999 {"invert-match", no_argument, NULL, 'v'},
1000 USAGE_COMMON_LONG_OPTS,
1001};
1002static const char * const usage_opts_help[] = {
1003 "Display address",
1004 "Show all nodes/tags, colour those that match",
1005 "Include contains containing property",
1006 "Compatible nodes to include in grep",
1007 "Compatible nodes to exclude in grep",
1008 "Diff: Mark matching nodes with +, others with -",
1009 "Enter direct subnode names of matching nodes",
1010 "Display offset",
1011 "Node/property/compatible string to include in grep",
1012 "Node/property/compatible string to exclude in grep",
1013 "Output a header",
1014 "Put \"/dts-v1/;\" on first line of dts output",
1015 "Output a region list",
1016 "List strings in string table",
1017 "Include mem_rsvmap section in binary output",
1018 "Node to include in grep",
1019 "Node to exclude in grep",
Simon Glassbbee0622023-12-17 09:36:16 -07001020 "-o <output file>",
1021 "-O <output format>",
Simon Glass07c6b842015-06-23 15:38:28 -06001022 "Property to include in grep",
1023 "Property to exclude in grep",
1024 "Remove unused strings from string table",
1025 "Include root node and all properties",
1026 "Show all subnodes matching nodes",
1027 "Don't include supernodes of matching nodes",
1028 "Include string table in binary output",
1029 "Include matching aliases in output",
Simon Glassef8e0722023-12-17 09:36:22 -07001030 "Add -p properties to supernodes too",
Simon Glass07c6b842015-06-23 15:38:28 -06001031 "Invert the sense of matching (select non-matching lines)",
1032 USAGE_COMMON_OPTS_HELP
1033};
1034
1035/**
1036 * Call getopt_long() with standard options
1037 *
1038 * Since all util code runs getopt in the same way, provide a helper.
1039 */
1040#define util_getopt_long() getopt_long(argc, argv, usage_short_opts, \
1041 usage_long_opts, NULL)
1042
1043void util_usage(const char *errmsg, const char *synopsis,
1044 const char *short_opts, struct option const long_opts[],
1045 const char * const opts_help[])
1046{
1047 FILE *fp = errmsg ? stderr : stdout;
1048 const char a_arg[] = "<arg>";
1049 size_t a_arg_len = strlen(a_arg) + 1;
1050 size_t i;
1051 int optlen;
1052
1053 fprintf(fp,
1054 "Usage: %s\n"
1055 "\n"
1056 "Options: -[%s]\n", synopsis, short_opts);
1057
1058 /* prescan the --long opt length to auto-align */
1059 optlen = 0;
1060 for (i = 0; long_opts[i].name; ++i) {
1061 /* +1 is for space between --opt and help text */
1062 int l = strlen(long_opts[i].name) + 1;
1063 if (long_opts[i].has_arg == a_argument)
1064 l += a_arg_len;
1065 if (optlen < l)
1066 optlen = l;
1067 }
1068
1069 for (i = 0; long_opts[i].name; ++i) {
1070 /* helps when adding new applets or options */
1071 assert(opts_help[i] != NULL);
1072
1073 /* first output the short flag if it has one */
1074 if (long_opts[i].val > '~')
1075 fprintf(fp, " ");
1076 else
1077 fprintf(fp, " -%c, ", long_opts[i].val);
1078
1079 /* then the long flag */
1080 if (long_opts[i].has_arg == no_argument) {
1081 fprintf(fp, "--%-*s", optlen, long_opts[i].name);
1082 } else {
1083 fprintf(fp, "--%s %s%*s", long_opts[i].name, a_arg,
1084 (int)(optlen - strlen(long_opts[i].name) -
1085 a_arg_len), "");
1086 }
1087
1088 /* finally the help text */
1089 fprintf(fp, "%s\n", opts_help[i]);
1090 }
1091
1092 if (errmsg) {
1093 fprintf(fp, "\nError: %s\n", errmsg);
1094 exit(EXIT_FAILURE);
1095 } else {
1096 exit(EXIT_SUCCESS);
1097 }
1098}
1099
1100/**
1101 * Show usage and exit
1102 *
1103 * If you name all your usage variables with usage_xxx, then you can call this
1104 * help macro rather than expanding all arguments yourself.
1105 *
1106 * @param errmsg If non-NULL, an error message to display
1107 */
1108#define usage(errmsg) \
1109 util_usage(errmsg, usage_synopsis, usage_short_opts, \
1110 usage_long_opts, usage_opts_help)
1111
1112void util_version(void)
1113{
1114 printf("Version: %s\n", "(U-Boot)");
1115 exit(0);
1116}
1117
1118static void scan_args(struct display_info *disp, int argc, char *argv[])
1119{
1120 int opt;
1121
1122 while ((opt = util_getopt_long()) != EOF) {
1123 int type = 0;
1124 int inc = 1;
1125
1126 switch (opt) {
1127 case_USAGE_COMMON_FLAGS
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +02001128 /* fallthrough */
Simon Glass07c6b842015-06-23 15:38:28 -06001129 case 'a':
1130 disp->show_addr = 1;
1131 break;
1132 case 'A':
1133 disp->all = 1;
1134 break;
1135 case 'b':
1136 type = FDT_NODE_HAS_PROP;
1137 break;
1138 case 'C':
1139 inc = 0;
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +02001140 /* fallthrough */
Simon Glass07c6b842015-06-23 15:38:28 -06001141 case 'c':
1142 type = FDT_IS_COMPAT;
1143 break;
1144 case 'd':
1145 disp->diff = 1;
1146 break;
1147 case 'e':
1148 disp->flags |= FDT_REG_DIRECT_SUBNODES;
1149 break;
1150 case 'f':
1151 disp->show_offset = 1;
1152 break;
1153 case 'G':
1154 inc = 0;
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +02001155 /* fallthrough */
Simon Glass07c6b842015-06-23 15:38:28 -06001156 case 'g':
1157 type = FDT_ANY_GLOBAL;
1158 break;
1159 case 'H':
1160 disp->header = 1;
1161 break;
Simon Glassbbee0622023-12-17 09:36:16 -07001162 case 'I':
1163 disp->show_dts_version = 1;
1164 break;
Simon Glass07c6b842015-06-23 15:38:28 -06001165 case 'l':
1166 disp->region_list = 1;
1167 break;
1168 case 'L':
1169 disp->list_strings = 1;
1170 break;
1171 case 'm':
1172 disp->flags |= FDT_REG_ADD_MEM_RSVMAP;
1173 break;
1174 case 'N':
1175 inc = 0;
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +02001176 /* fallthrough */
Simon Glass07c6b842015-06-23 15:38:28 -06001177 case 'n':
1178 type = FDT_IS_NODE;
1179 break;
1180 case 'o':
1181 disp->output_fname = optarg;
1182 break;
1183 case 'O':
1184 if (!strcmp(optarg, "dtb"))
1185 disp->output = OUT_DTB;
1186 else if (!strcmp(optarg, "dts"))
1187 disp->output = OUT_DTS;
1188 else if (!strcmp(optarg, "bin"))
1189 disp->output = OUT_BIN;
1190 else
1191 usage("Unknown output format");
1192 break;
1193 case 'P':
1194 inc = 0;
Heinrich Schuchardtd0d24562020-05-09 17:12:42 +02001195 /* fallthrough */
Simon Glass07c6b842015-06-23 15:38:28 -06001196 case 'p':
1197 type = FDT_IS_PROP;
1198 break;
1199 case 'r':
1200 disp->remove_strings = 1;
1201 break;
1202 case 'R':
1203 disp->include_root = 1;
1204 break;
1205 case 's':
1206 disp->flags |= FDT_REG_ALL_SUBNODES;
1207 break;
1208 case 'S':
1209 disp->flags &= ~FDT_REG_SUPERNODES;
1210 break;
1211 case 't':
1212 disp->flags |= FDT_REG_ADD_STRING_TAB;
1213 break;
1214 case 'T':
1215 disp->add_aliases = 1;
1216 break;
Simon Glassef8e0722023-12-17 09:36:22 -07001217 case 'u':
1218 disp->props_up = 1;
1219 break;
Simon Glass07c6b842015-06-23 15:38:28 -06001220 case 'v':
1221 disp->invert = 1;
1222 break;
Simon Glass07c6b842015-06-23 15:38:28 -06001223 }
1224
1225 if (type && value_add(disp, &disp->value_head, type, inc,
1226 optarg))
1227 usage("Cannot add value");
1228 }
1229
1230 if (disp->invert && disp->types_exc)
1231 usage("-v has no meaning when used with 'exclude' conditions");
1232}
1233
1234int main(int argc, char *argv[])
1235{
1236 char *filename = NULL;
1237 struct display_info disp;
1238 int ret;
1239
1240 /* set defaults */
1241 memset(&disp, '\0', sizeof(disp));
1242 disp.flags = FDT_REG_SUPERNODES; /* Default flags */
1243
1244 scan_args(&disp, argc, argv);
1245
1246 /* Show matched lines in colour if we can */
1247 disp.colour = disp.all && isatty(0);
1248
1249 /* Any additional arguments can match anything, just like -g */
1250 while (optind < argc - 1) {
1251 if (value_add(&disp, &disp.value_head, FDT_IS_ANY, 1,
1252 argv[optind++]))
1253 usage("Cannot add value");
1254 }
1255
1256 if (optind < argc)
1257 filename = argv[optind++];
1258 if (!filename)
1259 usage("Missing filename");
1260
1261 /* If a valid .dtb is required, set flags to ensure we get one */
1262 if (disp.output == OUT_DTB) {
1263 disp.header = 1;
1264 disp.flags |= FDT_REG_ADD_MEM_RSVMAP | FDT_REG_ADD_STRING_TAB;
1265 }
1266
1267 if (disp.output_fname) {
1268 disp.fout = fopen(disp.output_fname, "w");
1269 if (!disp.fout)
1270 usage("Cannot open output file");
1271 } else {
1272 disp.fout = stdout;
1273 }
1274
1275 /* Run the grep and output the results */
1276 ret = do_fdtgrep(&disp, filename);
1277 if (disp.output_fname)
1278 fclose(disp.fout);
1279 if (ret)
1280 return 1;
1281
1282 return 0;
1283}