1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (c) 2013, Google Inc.
4 * Written by Simon Glass <sjg@chromium.org>
6 * Perform a grep of an FDT either displaying the source subset or producing
7 * a new .dtb subset which can be used as required.
22 #include "libfdt_internal.h"
24 /* Define DEBUG to get some debugging output on stderr */
26 #define debug(a, b...) fprintf(stderr, a, ## b)
28 #define debug(a, b...)
31 /* A linked list of values we are grepping for */
33 int type; /* Types this value matches (FDT_IS... mask) */
34 int include; /* 1 to include matches, 0 to exclude */
35 const char *string; /* String to match */
36 struct value_node *next; /* Pointer to next node, or NULL */
39 /* Output formats we support */
41 OUT_DTS, /* Device tree source */
42 OUT_DTB, /* Valid device tree binary */
43 OUT_BIN, /* Fragment of .dtb, for hashing */
46 /* Holds information which controls our output and options */
48 enum output_t output; /* Output format */
49 int add_aliases; /* Add aliases node to output */
50 int all; /* Display all properties/nodes */
51 int colour; /* Display output in ANSI colour */
52 int region_list; /* Output a region list */
53 int flags; /* Flags (FDT_REG_...) */
54 int list_strings; /* List strings in string table */
55 int show_offset; /* Show offset */
56 int show_addr; /* Show address */
57 int header; /* Output an FDT header */
58 int diff; /* Show +/- diff markers */
59 int include_root; /* Include the root node and all properties */
60 int remove_strings; /* Remove unused strings */
61 int show_dts_version; /* Put '/dts-v1/;' on the first line */
62 int types_inc; /* Mask of types that we include (FDT_IS...) */
63 int types_exc; /* Mask of types that we exclude (FDT_IS...) */
64 int invert; /* Invert polarity of match */
65 struct value_node *value_head; /* List of values to match */
66 const char *output_fname; /* Output filename */
67 FILE *fout; /* File to write dts/dtb output */
70 static void report_error(const char *where, int err)
72 fprintf(stderr, "Error at '%s': %s\n", where, fdt_strerror(err));
75 /* Supported ANSI colours */
90 * print_ansi_colour() - Print out the ANSI sequence for a colour
93 * @col: Colour to output (COL_...), or COL_NONE to reset colour
95 static void print_ansi_colour(FILE *fout, int col)
98 fprintf(fout, "\033[0m");
100 fprintf(fout, "\033[1;%dm", col + 30);
105 * value_add() - Add a new value to our list of things to grep for
107 * @disp: Display structure, holding info about our options
108 * @headp: Pointer to header pointer of list
109 * @type: Type of this value (FDT_IS_...)
110 * @include: 1 if we want to include matches, 0 to exclude
111 * @str: String value to match
113 static int value_add(struct display_info *disp, struct value_node **headp,
114 int type, int include, const char *str)
116 struct value_node *node;
119 * Keep track of which types we are excluding/including. We don't
120 * allow both including and excluding things, because it doesn't make
121 * sense. 'Including' means that everything not mentioned is
122 * excluded. 'Excluding' means that everything not mentioned is
123 * included. So using the two together would be meaningless.
126 disp->types_inc |= type;
128 disp->types_exc |= type;
129 if (disp->types_inc & disp->types_exc & type) {
131 "Cannot use both include and exclude for '%s'\n", str);
136 node = malloc(sizeof(*node));
138 fprintf(stderr, "Out of memory\n");
143 node->include = include;
150 static bool util_is_printable_string(const void *data, int len)
152 const char *s = data;
155 /* zero length is not */
159 /* must terminate with zero */
160 if (s[len - 1] != '\0')
167 while (s < se && *s && isprint((unsigned char)*s))
170 /* not zero, or not done yet */
171 if (*s != '\0' || s == ss)
180 static void utilfdt_print_data(const char *data, int len)
183 const char *p = data;
186 /* no data, don't print */
190 if (util_is_printable_string(data, len)) {
199 } while (s < data + len);
201 } else if ((len % 4) == 0) {
202 const uint32_t *cell = (const uint32_t *)data;
205 for (i = 0, len /= 4; i < len; i++)
206 printf("0x%08x%s", fdt32_to_cpu(cell[i]),
207 i < (len - 1) ? " " : "");
211 for (i = 0; i < len; i++)
212 printf("%02x%s", *p++, i < len - 1 ? " " : "");
218 * display_fdt_by_regions() - Display regions of an FDT source
220 * This dumps an FDT as source, but only certain regions of it. This is the
221 * final stage of the grep - we have a list of regions we want to display,
222 * and this function displays them.
224 * @disp: Display structure, holding info about our options
225 * @blob: FDT blob to display
226 * @region: List of regions to display
227 * @count: Number of regions
229 static int display_fdt_by_regions(struct display_info *disp, const void *blob,
230 struct fdt_region region[], int count)
232 struct fdt_region *reg = region, *reg_end = region + count;
233 uint32_t off_mem_rsvmap = fdt_off_mem_rsvmap(blob);
234 int base = fdt_off_dt_struct(blob);
235 int version = fdt_version(blob);
236 int offset, nextoffset;
237 int tag, depth, shift;
238 FILE *f = disp->fout;
244 if (disp->show_dts_version)
245 fprintf(f, "/dts-v1/;\n");
248 fprintf(f, "// magic:\t\t0x%x\n", fdt_magic(blob));
249 fprintf(f, "// totalsize:\t\t0x%x (%d)\n", fdt_totalsize(blob),
250 fdt_totalsize(blob));
251 fprintf(f, "// off_dt_struct:\t0x%x\n",
252 fdt_off_dt_struct(blob));
253 fprintf(f, "// off_dt_strings:\t0x%x\n",
254 fdt_off_dt_strings(blob));
255 fprintf(f, "// off_mem_rsvmap:\t0x%x\n", off_mem_rsvmap);
256 fprintf(f, "// version:\t\t%d\n", version);
257 fprintf(f, "// last_comp_version:\t%d\n",
258 fdt_last_comp_version(blob));
260 fprintf(f, "// boot_cpuid_phys:\t0x%x\n",
261 fdt_boot_cpuid_phys(blob));
264 fprintf(f, "// size_dt_strings:\t0x%x\n",
265 fdt_size_dt_strings(blob));
268 fprintf(f, "// size_dt_struct:\t0x%x\n",
269 fdt_size_dt_struct(blob));
274 if (disp->flags & FDT_REG_ADD_MEM_RSVMAP) {
275 const struct fdt_reserve_entry *p_rsvmap;
277 p_rsvmap = (const struct fdt_reserve_entry *)
278 ((const char *)blob + off_mem_rsvmap);
280 addr = fdt64_to_cpu(p_rsvmap[i].address);
281 size = fdt64_to_cpu(p_rsvmap[i].size);
282 if (addr == 0 && size == 0)
285 fprintf(f, "/memreserve/ %llx %llx;\n",
286 (unsigned long long)addr,
287 (unsigned long long)size);
293 shift = 4; /* 4 spaces per indent */
295 const struct fdt_property *prop;
303 * Work out the file offset of this offset, and decide
304 * whether it is in the region list or not
306 file_ofs = base + offset;
307 if (reg < reg_end && file_ofs >= reg->offset + reg->size)
309 in_region = reg < reg_end && file_ofs >= reg->offset &&
310 file_ofs < reg->offset + reg->size;
311 tag = fdt_next_tag(blob, offset, &nextoffset);
315 show = in_region || disp->all;
316 if (show && disp->diff)
317 fprintf(f, "%c", in_region ? '+' : '-');
320 /* Do this here to avoid 'if (show)' in every 'case' */
321 if (tag == FDT_BEGIN_NODE)
323 else if (tag == FDT_END_NODE)
327 if (tag != FDT_END) {
329 fprintf(f, "%4x: ", file_ofs);
330 if (disp->show_offset)
331 fprintf(f, "%4x: ", file_ofs - base);
334 /* Green means included, red means excluded */
336 print_ansi_colour(f, in_region ? COL_GREEN : COL_RED);
340 prop = fdt_get_property_by_offset(blob, offset, NULL);
341 name = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
342 fprintf(f, "%*s%s", depth * shift, "", name);
343 utilfdt_print_data(prop->data,
344 fdt32_to_cpu(prop->len));
349 fprintf(f, "%*s// [NOP]", depth * shift, "");
353 name = fdt_get_name(blob, offset, &len);
354 fprintf(f, "%*s%s {", depth++ * shift, "",
359 fprintf(f, "%*s};", --depth * shift, "");
363 /* Reset colour back to normal before end of line */
365 print_ansi_colour(f, COL_NONE);
369 /* Print a list of strings if requested */
370 if (disp->list_strings) {
372 int str_base = fdt_off_dt_strings(blob);
374 for (offset = 0; offset < fdt_size_dt_strings(blob);
375 offset += strlen(str) + 1) {
376 str = fdt_string(blob, offset);
377 int len = strlen(str) + 1;
380 /* Only print strings that are in the region */
381 file_ofs = str_base + offset;
382 in_region = reg < reg_end &&
383 file_ofs >= reg->offset &&
384 file_ofs + len < reg->offset +
386 show = in_region || disp->all;
387 if (show && disp->diff)
388 printf("%c", in_region ? '+' : '-');
390 printf("%4x: ", file_ofs);
391 if (disp->show_offset)
392 printf("%4x: ", offset);
401 * dump_fdt_regions() - Dump regions of an FDT as binary data
403 * This dumps an FDT as binary, but only certain regions of it. This is the
404 * final stage of the grep - we have a list of regions we want to dump,
405 * and this function dumps them.
407 * The output of this function may or may not be a valid FDT. To ensure it
408 * is, these disp->flags must be set:
410 * FDT_REG_SUPERNODES: ensures that subnodes are preceded by their
411 * parents. Without this option, fragments of subnode data may be
412 * output without the supernodes above them. This is useful for
413 * hashing but cannot produce a valid FDT.
414 * FDT_REG_ADD_STRING_TAB: Adds a string table to the end of the FDT.
415 * Without this none of the properties will have names
416 * FDT_REG_ADD_MEM_RSVMAP: Adds a mem_rsvmap table - an FDT is invalid
419 * @disp: Display structure, holding info about our options
420 * @blob: FDT blob to display
421 * @region: List of regions to display
422 * @count: Number of regions
423 * @out: Output destination
425 static int dump_fdt_regions(struct display_info *disp, const void *blob,
426 struct fdt_region region[], int count, char *out)
428 struct fdt_header *fdt;
429 int size, struct_start;
433 /* Set up a basic header (even if we don't actually write it) */
434 fdt = (struct fdt_header *)out;
435 memset(fdt, '\0', sizeof(*fdt));
436 fdt_set_magic(fdt, FDT_MAGIC);
437 struct_start = FDT_ALIGN(sizeof(struct fdt_header),
438 sizeof(struct fdt_reserve_entry));
439 fdt_set_off_mem_rsvmap(fdt, struct_start);
440 fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
441 fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
444 * Calculate the total size of the regions we are writing out. The
445 * first will be the mem_rsvmap if the FDT_REG_ADD_MEM_RSVMAP flag
446 * is set. The last will be the string table if FDT_REG_ADD_STRING_TAB
449 for (i = size = 0; i < count; i++)
450 size += region[i].size;
452 /* Bring in the mem_rsvmap section from the old file if requested */
453 if (count > 0 && (disp->flags & FDT_REG_ADD_MEM_RSVMAP)) {
454 struct_start += region[0].size;
455 size -= region[0].size;
457 fdt_set_off_dt_struct(fdt, struct_start);
459 /* Update the header to have the correct offsets/sizes */
460 if (count >= 2 && (disp->flags & FDT_REG_ADD_STRING_TAB)) {
463 str_size = region[count - 1].size;
464 fdt_set_size_dt_struct(fdt, size - str_size);
465 fdt_set_off_dt_strings(fdt, struct_start + size - str_size);
466 fdt_set_size_dt_strings(fdt, str_size);
467 fdt_set_totalsize(fdt, struct_start + size);
470 /* Write the header if required */
474 while (ptr < fdt_off_mem_rsvmap(fdt))
478 /* Output all the nodes including any mem_rsvmap/string table */
479 for (i = 0; i < count; i++) {
480 struct fdt_region *reg = ®ion[i];
482 memcpy(out + ptr, (const char *)blob + reg->offset, reg->size);
490 * show_region_list() - Print out a list of regions
492 * The list includes the region offset (absolute offset from start of FDT
493 * blob in bytes) and size
495 * @reg: List of regions to print
496 * @count: Number of regions
498 static void show_region_list(struct fdt_region *reg, int count)
502 printf("Regions: %d\n", count);
503 for (i = 0; i < count; i++, reg++) {
504 printf("%d: %-10x %-10x\n", i, reg->offset,
505 reg->offset + reg->size);
509 static int check_type_include(void *priv, int type, const char *data, int size)
511 struct display_info *disp = priv;
512 struct value_node *val;
513 int match, none_match = FDT_IS_ANY;
515 /* If none of our conditions mention this type, we know nothing */
516 debug("type=%x, data=%s\n", type, data ? data : "(null)");
517 if (!((disp->types_inc | disp->types_exc) & type)) {
518 debug(" - not in any condition\n");
523 * Go through the list of conditions. For inclusive conditions, we
524 * return 1 at the first match. For exclusive conditions, we must
525 * check that there are no matches.
528 for (val = disp->value_head; val; val = val->next) {
529 if (!(type & val->type))
531 match = fdt_stringlist_contains(data, size,
533 debug(" - val->type=%x, str='%s', match=%d\n",
534 val->type, val->string, match);
535 if (match && val->include) {
536 debug(" - match inc %s\n", val->string);
540 none_match &= ~val->type;
545 * If this is an exclusive condition, and nothing matches, then we
548 if ((type & disp->types_exc) && (none_match & type)) {
549 debug(" - match exc\n");
551 * Allow FDT_IS_COMPAT to make the final decision in the
552 * case where there is no specific type
554 if (type == FDT_IS_NODE && disp->types_exc == FDT_ANY_GLOBAL) {
555 debug(" - supressed exc node\n");
562 * Allow FDT_IS_COMPAT to make the final decision in the
563 * case where there is no specific type (inclusive)
565 if (type == FDT_IS_NODE && disp->types_inc == FDT_ANY_GLOBAL)
568 debug(" - no match, types_inc=%x, types_exc=%x, none_match=%x\n",
569 disp->types_inc, disp->types_exc, none_match);
575 * h_include() - Include handler function for fdt_find_regions()
577 * This function decides whether to include or exclude a node, property or
578 * compatible string. The function is defined by fdt_find_regions().
580 * The algorithm is documented in the code - disp->invert is 0 for normal
581 * operation, and 1 to invert the sense of all matches.
585 static int h_include(void *priv, const void *fdt, int offset, int type,
586 const char *data, int size)
588 struct display_info *disp = priv;
591 inc = check_type_include(priv, type, data, size);
592 if (disp->include_root && type == FDT_IS_PROP && offset == 0 && inc)
596 * If the node name does not tell us anything, check the
599 if (inc == -1 && type == FDT_IS_NODE) {
600 debug(" - checking compatible2\n");
601 data = fdt_getprop(fdt, offset, "compatible", &len);
602 inc = check_type_include(priv, FDT_IS_COMPAT, data, len);
605 /* If we still have no idea, check for properties in the node */
606 if (inc != 1 && type == FDT_IS_NODE &&
607 (disp->types_inc & FDT_NODE_HAS_PROP)) {
608 debug(" - checking node '%s'\n",
609 fdt_get_name(fdt, offset, NULL));
610 for (offset = fdt_first_property_offset(fdt, offset);
611 offset > 0 && inc != 1;
612 offset = fdt_next_property_offset(fdt, offset)) {
613 const struct fdt_property *prop;
616 prop = fdt_get_property_by_offset(fdt, offset, NULL);
619 str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
620 inc = check_type_include(priv, FDT_NODE_HAS_PROP, str,
635 debug(" - returning %d\n", inc);
640 static int h_cmp_region(const void *v1, const void *v2)
642 const struct fdt_region *region1 = v1, *region2 = v2;
644 return region1->offset - region2->offset;
647 static int fdtgrep_find_regions(const void *fdt,
648 int (*include_func)(void *priv, const void *fdt, int offset,
649 int type, const char *data, int size),
650 struct display_info *disp, struct fdt_region *region,
651 int max_regions, char *path, int path_len, int flags)
653 struct fdt_region_state state;
658 ret = fdt_first_region(fdt, include_func, disp,
659 ®ion[count++], path, path_len,
660 disp->flags, &state);
662 ret = fdt_next_region(fdt, include_func, disp,
663 count < max_regions ? ®ion[count] : NULL,
664 path, path_len, disp->flags, &state);
668 if (ret && ret != -FDT_ERR_NOTFOUND)
671 /* Find all the aliases and add those regions back in */
672 if (disp->add_aliases && count < max_regions) {
675 new_count = fdt_add_alias_regions(fdt, region, count,
676 max_regions, &state);
677 if (new_count == -FDT_ERR_NOTFOUND) {
678 /* No alias node found */
679 } else if (new_count < 0) {
681 } else if (new_count <= max_regions) {
683 * The alias regions will now be at the end of the list.
684 * Sort the regions by offset to get things into the
688 qsort(region, count, sizeof(struct fdt_region),
696 int utilfdt_read_err_len(const char *filename, char **buffp, off_t *len)
698 int fd = 0; /* assume stdin */
700 off_t bufsize = 1024, offset = 0;
704 if (strcmp(filename, "-") != 0) {
705 fd = open(filename, O_RDONLY);
710 /* Loop until we have read everything */
711 buf = malloc(bufsize);
715 /* Expand the buffer to hold the next chunk */
716 if (offset == bufsize) {
718 buf = realloc(buf, bufsize);
723 ret = read(fd, &buf[offset], bufsize - offset);
731 /* Clean up, including closing stdin; return errno on error */
741 int utilfdt_read_err(const char *filename, char **buffp)
744 return utilfdt_read_err_len(filename, buffp, &len);
747 char *utilfdt_read_len(const char *filename, off_t *len)
750 int ret = utilfdt_read_err_len(filename, &buff, len);
753 fprintf(stderr, "Couldn't open blob from '%s': %s\n", filename,
757 /* Successful read */
761 char *utilfdt_read(const char *filename)
764 return utilfdt_read_len(filename, &len);
768 * Run the main fdtgrep operation, given a filename and valid arguments
770 * @param disp Display information / options
771 * @param filename Filename of blob file
772 * @param return 0 if ok, -ve on error
774 static int do_fdtgrep(struct display_info *disp, const char *filename)
776 struct fdt_region *region = NULL;
783 blob = utilfdt_read(filename);
786 ret = fdt_check_header(blob);
788 fprintf(stderr, "Error: %s\n", fdt_strerror(ret));
792 /* Allow old files, but they are untested */
793 if (fdt_version(blob) < 17 && disp->value_head) {
795 "Warning: fdtgrep does not fully support version %d files\n",
800 * We do two passes, since we don't know how many regions we need.
801 * The first pass will count the regions, but if it is too many,
802 * we do another pass to actually record them.
804 for (i = 0; i < 2; i++) {
805 region = malloc(count * sizeof(struct fdt_region));
807 fprintf(stderr, "Out of memory for %d regions\n",
812 count = fdtgrep_find_regions(blob,
814 region, max_regions, path, sizeof(path),
817 report_error("fdt_find_regions", count);
821 if (count <= max_regions)
824 fprintf(stderr, "Internal error with fdtgrep_find_region)(\n");
828 /* Optionally print a list of regions */
829 if (disp->region_list)
830 show_region_list(region, count);
832 /* Output either source .dts or binary .dtb */
833 if (disp->output == OUT_DTS) {
834 ret = display_fdt_by_regions(disp, blob, region, count);
837 /* Allow reserved memory section to expand slightly */
838 int size = fdt_totalsize(blob) + 16;
842 fprintf(stderr, "Out_of_memory\n");
846 size = dump_fdt_regions(disp, blob, region, count, fdt);
847 if (disp->remove_strings) {
852 fprintf(stderr, "Out_of_memory\n");
856 ret = fdt_remove_unused_strings(fdt, out);
859 "Failed to remove unused strings: err=%d\n",
867 fprintf(stderr, "Failed to pack: err=%d\n",
871 size = fdt_totalsize(fdt);
874 if (size != fwrite(fdt, 1, size, disp->fout)) {
875 fprintf(stderr, "Write failure, %d bytes\n", size);
889 static const char usage_synopsis[] =
890 "fdtgrep - extract portions from device tree\n"
893 " fdtgrep <options> <dt file>|-\n\n"
894 "Output formats are:\n"
895 "\tdts - device tree soure text\n"
896 "\tdtb - device tree blob (sets -Hmt automatically)\n"
897 "\tbin - device tree fragment (may not be a valid .dtb)";
899 /* Helper for usage_short_opts string constant */
900 #define USAGE_COMMON_SHORT_OPTS "hV"
902 /* Helper for aligning long_opts array */
903 #define a_argument required_argument
905 /* Helper for usage_long_opts option array */
906 #define USAGE_COMMON_LONG_OPTS \
907 {"help", no_argument, NULL, 'h'}, \
908 {"version", no_argument, NULL, 'V'}, \
909 {NULL, no_argument, NULL, 0x0}
911 /* Helper for usage_opts_help array */
912 #define USAGE_COMMON_OPTS_HELP \
913 "Print this help and exit", \
914 "Print version and exit", \
917 /* Helper for getopt case statements */
918 #define case_USAGE_COMMON_FLAGS \
919 case 'h': usage(NULL); \
920 case 'V': util_version(); \
921 case '?': usage("unknown option");
923 static const char usage_short_opts[] =
924 "haAc:b:C:defg:G:HIlLmn:N:o:O:p:P:rRsStTv"
925 USAGE_COMMON_SHORT_OPTS;
926 static struct option const usage_long_opts[] = {
927 {"show-address", no_argument, NULL, 'a'},
928 {"colour", no_argument, NULL, 'A'},
929 {"include-node-with-prop", a_argument, NULL, 'b'},
930 {"include-compat", a_argument, NULL, 'c'},
931 {"exclude-compat", a_argument, NULL, 'C'},
932 {"diff", no_argument, NULL, 'd'},
933 {"enter-node", no_argument, NULL, 'e'},
934 {"show-offset", no_argument, NULL, 'f'},
935 {"include-match", a_argument, NULL, 'g'},
936 {"exclude-match", a_argument, NULL, 'G'},
937 {"show-header", no_argument, NULL, 'H'},
938 {"show-version", no_argument, NULL, 'I'},
939 {"list-regions", no_argument, NULL, 'l'},
940 {"list-strings", no_argument, NULL, 'L'},
941 {"include-mem", no_argument, NULL, 'm'},
942 {"include-node", a_argument, NULL, 'n'},
943 {"exclude-node", a_argument, NULL, 'N'},
944 {"include-prop", a_argument, NULL, 'p'},
945 {"exclude-prop", a_argument, NULL, 'P'},
946 {"remove-strings", no_argument, NULL, 'r'},
947 {"include-root", no_argument, NULL, 'R'},
948 {"show-subnodes", no_argument, NULL, 's'},
949 {"skip-supernodes", no_argument, NULL, 'S'},
950 {"show-stringtab", no_argument, NULL, 't'},
951 {"show-aliases", no_argument, NULL, 'T'},
952 {"out", a_argument, NULL, 'o'},
953 {"out-format", a_argument, NULL, 'O'},
954 {"invert-match", no_argument, NULL, 'v'},
955 USAGE_COMMON_LONG_OPTS,
957 static const char * const usage_opts_help[] = {
959 "Show all nodes/tags, colour those that match",
960 "Include contains containing property",
961 "Compatible nodes to include in grep",
962 "Compatible nodes to exclude in grep",
963 "Diff: Mark matching nodes with +, others with -",
964 "Enter direct subnode names of matching nodes",
966 "Node/property/compatible string to include in grep",
967 "Node/property/compatible string to exclude in grep",
969 "Put \"/dts-v1/;\" on first line of dts output",
970 "Output a region list",
971 "List strings in string table",
972 "Include mem_rsvmap section in binary output",
973 "Node to include in grep",
974 "Node to exclude in grep",
975 "Property to include in grep",
976 "Property to exclude in grep",
977 "Remove unused strings from string table",
978 "Include root node and all properties",
979 "Show all subnodes matching nodes",
980 "Don't include supernodes of matching nodes",
981 "Include string table in binary output",
982 "Include matching aliases in output",
984 "-O <output format>",
985 "Invert the sense of matching (select non-matching lines)",
986 USAGE_COMMON_OPTS_HELP
990 * Call getopt_long() with standard options
992 * Since all util code runs getopt in the same way, provide a helper.
994 #define util_getopt_long() getopt_long(argc, argv, usage_short_opts, \
995 usage_long_opts, NULL)
997 void util_usage(const char *errmsg, const char *synopsis,
998 const char *short_opts, struct option const long_opts[],
999 const char * const opts_help[])
1001 FILE *fp = errmsg ? stderr : stdout;
1002 const char a_arg[] = "<arg>";
1003 size_t a_arg_len = strlen(a_arg) + 1;
1010 "Options: -[%s]\n", synopsis, short_opts);
1012 /* prescan the --long opt length to auto-align */
1014 for (i = 0; long_opts[i].name; ++i) {
1015 /* +1 is for space between --opt and help text */
1016 int l = strlen(long_opts[i].name) + 1;
1017 if (long_opts[i].has_arg == a_argument)
1023 for (i = 0; long_opts[i].name; ++i) {
1024 /* helps when adding new applets or options */
1025 assert(opts_help[i] != NULL);
1027 /* first output the short flag if it has one */
1028 if (long_opts[i].val > '~')
1031 fprintf(fp, " -%c, ", long_opts[i].val);
1033 /* then the long flag */
1034 if (long_opts[i].has_arg == no_argument) {
1035 fprintf(fp, "--%-*s", optlen, long_opts[i].name);
1037 fprintf(fp, "--%s %s%*s", long_opts[i].name, a_arg,
1038 (int)(optlen - strlen(long_opts[i].name) -
1042 /* finally the help text */
1043 fprintf(fp, "%s\n", opts_help[i]);
1047 fprintf(fp, "\nError: %s\n", errmsg);
1055 * Show usage and exit
1057 * If you name all your usage variables with usage_xxx, then you can call this
1058 * help macro rather than expanding all arguments yourself.
1060 * @param errmsg If non-NULL, an error message to display
1062 #define usage(errmsg) \
1063 util_usage(errmsg, usage_synopsis, usage_short_opts, \
1064 usage_long_opts, usage_opts_help)
1066 void util_version(void)
1068 printf("Version: %s\n", "(U-Boot)");
1072 static void scan_args(struct display_info *disp, int argc, char *argv[])
1076 while ((opt = util_getopt_long()) != EOF) {
1081 case_USAGE_COMMON_FLAGS
1083 disp->show_addr = 1;
1089 type = FDT_NODE_HAS_PROP;
1095 type = FDT_IS_COMPAT;
1101 disp->flags |= FDT_REG_DIRECT_SUBNODES;
1104 disp->show_offset = 1;
1110 type = FDT_ANY_GLOBAL;
1116 disp->region_list = 1;
1119 disp->list_strings = 1;
1122 disp->flags |= FDT_REG_ADD_MEM_RSVMAP;
1131 disp->output_fname = optarg;
1134 if (!strcmp(optarg, "dtb"))
1135 disp->output = OUT_DTB;
1136 else if (!strcmp(optarg, "dts"))
1137 disp->output = OUT_DTS;
1138 else if (!strcmp(optarg, "bin"))
1139 disp->output = OUT_BIN;
1141 usage("Unknown output format");
1150 disp->remove_strings = 1;
1153 disp->include_root = 1;
1156 disp->flags |= FDT_REG_ALL_SUBNODES;
1159 disp->flags &= ~FDT_REG_SUPERNODES;
1162 disp->flags |= FDT_REG_ADD_STRING_TAB;
1165 disp->add_aliases = 1;
1171 disp->show_dts_version = 1;
1175 if (type && value_add(disp, &disp->value_head, type, inc,
1177 usage("Cannot add value");
1180 if (disp->invert && disp->types_exc)
1181 usage("-v has no meaning when used with 'exclude' conditions");
1184 int main(int argc, char *argv[])
1186 char *filename = NULL;
1187 struct display_info disp;
1191 memset(&disp, '\0', sizeof(disp));
1192 disp.flags = FDT_REG_SUPERNODES; /* Default flags */
1194 scan_args(&disp, argc, argv);
1196 /* Show matched lines in colour if we can */
1197 disp.colour = disp.all && isatty(0);
1199 /* Any additional arguments can match anything, just like -g */
1200 while (optind < argc - 1) {
1201 if (value_add(&disp, &disp.value_head, FDT_IS_ANY, 1,
1203 usage("Cannot add value");
1207 filename = argv[optind++];
1209 usage("Missing filename");
1211 /* If a valid .dtb is required, set flags to ensure we get one */
1212 if (disp.output == OUT_DTB) {
1214 disp.flags |= FDT_REG_ADD_MEM_RSVMAP | FDT_REG_ADD_STRING_TAB;
1217 if (disp.output_fname) {
1218 disp.fout = fopen(disp.output_fname, "w");
1220 usage("Cannot open output file");
1225 /* Run the grep and output the results */
1226 ret = do_fdtgrep(&disp, filename);
1227 if (disp.output_fname)