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;
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 < 3; 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);
820 if (count <= max_regions)
825 /* Optionally print a list of regions */
826 if (disp->region_list)
827 show_region_list(region, count);
829 /* Output either source .dts or binary .dtb */
830 if (disp->output == OUT_DTS) {
831 ret = display_fdt_by_regions(disp, blob, region, count);
834 /* Allow reserved memory section to expand slightly */
835 int size = fdt_totalsize(blob) + 16;
839 fprintf(stderr, "Out_of_memory\n");
843 size = dump_fdt_regions(disp, blob, region, count, fdt);
844 if (disp->remove_strings) {
849 fprintf(stderr, "Out_of_memory\n");
853 ret = fdt_remove_unused_strings(fdt, out);
856 "Failed to remove unused strings: err=%d\n",
864 fprintf(stderr, "Failed to pack: err=%d\n",
868 size = fdt_totalsize(fdt);
871 if (size != fwrite(fdt, 1, size, disp->fout)) {
872 fprintf(stderr, "Write failure, %d bytes\n", size);
886 static const char usage_synopsis[] =
887 "fdtgrep - extract portions from device tree\n"
890 " fdtgrep <options> <dt file>|-\n\n"
891 "Output formats are:\n"
892 "\tdts - device tree soure text\n"
893 "\tdtb - device tree blob (sets -Hmt automatically)\n"
894 "\tbin - device tree fragment (may not be a valid .dtb)";
896 /* Helper for usage_short_opts string constant */
897 #define USAGE_COMMON_SHORT_OPTS "hV"
899 /* Helper for aligning long_opts array */
900 #define a_argument required_argument
902 /* Helper for usage_long_opts option array */
903 #define USAGE_COMMON_LONG_OPTS \
904 {"help", no_argument, NULL, 'h'}, \
905 {"version", no_argument, NULL, 'V'}, \
906 {NULL, no_argument, NULL, 0x0}
908 /* Helper for usage_opts_help array */
909 #define USAGE_COMMON_OPTS_HELP \
910 "Print this help and exit", \
911 "Print version and exit", \
914 /* Helper for getopt case statements */
915 #define case_USAGE_COMMON_FLAGS \
916 case 'h': usage(NULL); \
917 case 'V': util_version(); \
918 case '?': usage("unknown option");
920 static const char usage_short_opts[] =
921 "haAc:b:C:defg:G:HIlLmn:N:o:O:p:P:rRsStTv"
922 USAGE_COMMON_SHORT_OPTS;
923 static struct option const usage_long_opts[] = {
924 {"show-address", no_argument, NULL, 'a'},
925 {"colour", no_argument, NULL, 'A'},
926 {"include-node-with-prop", a_argument, NULL, 'b'},
927 {"include-compat", a_argument, NULL, 'c'},
928 {"exclude-compat", a_argument, NULL, 'C'},
929 {"diff", no_argument, NULL, 'd'},
930 {"enter-node", no_argument, NULL, 'e'},
931 {"show-offset", no_argument, NULL, 'f'},
932 {"include-match", a_argument, NULL, 'g'},
933 {"exclude-match", a_argument, NULL, 'G'},
934 {"show-header", no_argument, NULL, 'H'},
935 {"show-version", no_argument, NULL, 'I'},
936 {"list-regions", no_argument, NULL, 'l'},
937 {"list-strings", no_argument, NULL, 'L'},
938 {"include-mem", no_argument, NULL, 'm'},
939 {"include-node", a_argument, NULL, 'n'},
940 {"exclude-node", a_argument, NULL, 'N'},
941 {"include-prop", a_argument, NULL, 'p'},
942 {"exclude-prop", a_argument, NULL, 'P'},
943 {"remove-strings", no_argument, NULL, 'r'},
944 {"include-root", no_argument, NULL, 'R'},
945 {"show-subnodes", no_argument, NULL, 's'},
946 {"skip-supernodes", no_argument, NULL, 'S'},
947 {"show-stringtab", no_argument, NULL, 't'},
948 {"show-aliases", no_argument, NULL, 'T'},
949 {"out", a_argument, NULL, 'o'},
950 {"out-format", a_argument, NULL, 'O'},
951 {"invert-match", no_argument, NULL, 'v'},
952 USAGE_COMMON_LONG_OPTS,
954 static const char * const usage_opts_help[] = {
956 "Show all nodes/tags, colour those that match",
957 "Include contains containing property",
958 "Compatible nodes to include in grep",
959 "Compatible nodes to exclude in grep",
960 "Diff: Mark matching nodes with +, others with -",
961 "Enter direct subnode names of matching nodes",
963 "Node/property/compatible string to include in grep",
964 "Node/property/compatible string to exclude in grep",
966 "Put \"/dts-v1/;\" on first line of dts output",
967 "Output a region list",
968 "List strings in string table",
969 "Include mem_rsvmap section in binary output",
970 "Node to include in grep",
971 "Node to exclude in grep",
972 "Property to include in grep",
973 "Property to exclude in grep",
974 "Remove unused strings from string table",
975 "Include root node and all properties",
976 "Show all subnodes matching nodes",
977 "Don't include supernodes of matching nodes",
978 "Include string table in binary output",
979 "Include matching aliases in output",
981 "-O <output format>",
982 "Invert the sense of matching (select non-matching lines)",
983 USAGE_COMMON_OPTS_HELP
987 * Call getopt_long() with standard options
989 * Since all util code runs getopt in the same way, provide a helper.
991 #define util_getopt_long() getopt_long(argc, argv, usage_short_opts, \
992 usage_long_opts, NULL)
994 void util_usage(const char *errmsg, const char *synopsis,
995 const char *short_opts, struct option const long_opts[],
996 const char * const opts_help[])
998 FILE *fp = errmsg ? stderr : stdout;
999 const char a_arg[] = "<arg>";
1000 size_t a_arg_len = strlen(a_arg) + 1;
1007 "Options: -[%s]\n", synopsis, short_opts);
1009 /* prescan the --long opt length to auto-align */
1011 for (i = 0; long_opts[i].name; ++i) {
1012 /* +1 is for space between --opt and help text */
1013 int l = strlen(long_opts[i].name) + 1;
1014 if (long_opts[i].has_arg == a_argument)
1020 for (i = 0; long_opts[i].name; ++i) {
1021 /* helps when adding new applets or options */
1022 assert(opts_help[i] != NULL);
1024 /* first output the short flag if it has one */
1025 if (long_opts[i].val > '~')
1028 fprintf(fp, " -%c, ", long_opts[i].val);
1030 /* then the long flag */
1031 if (long_opts[i].has_arg == no_argument) {
1032 fprintf(fp, "--%-*s", optlen, long_opts[i].name);
1034 fprintf(fp, "--%s %s%*s", long_opts[i].name, a_arg,
1035 (int)(optlen - strlen(long_opts[i].name) -
1039 /* finally the help text */
1040 fprintf(fp, "%s\n", opts_help[i]);
1044 fprintf(fp, "\nError: %s\n", errmsg);
1052 * Show usage and exit
1054 * If you name all your usage variables with usage_xxx, then you can call this
1055 * help macro rather than expanding all arguments yourself.
1057 * @param errmsg If non-NULL, an error message to display
1059 #define usage(errmsg) \
1060 util_usage(errmsg, usage_synopsis, usage_short_opts, \
1061 usage_long_opts, usage_opts_help)
1063 void util_version(void)
1065 printf("Version: %s\n", "(U-Boot)");
1069 static void scan_args(struct display_info *disp, int argc, char *argv[])
1073 while ((opt = util_getopt_long()) != EOF) {
1078 case_USAGE_COMMON_FLAGS
1080 disp->show_addr = 1;
1086 type = FDT_NODE_HAS_PROP;
1092 type = FDT_IS_COMPAT;
1098 disp->flags |= FDT_REG_DIRECT_SUBNODES;
1101 disp->show_offset = 1;
1107 type = FDT_ANY_GLOBAL;
1113 disp->region_list = 1;
1116 disp->list_strings = 1;
1119 disp->flags |= FDT_REG_ADD_MEM_RSVMAP;
1128 disp->output_fname = optarg;
1131 if (!strcmp(optarg, "dtb"))
1132 disp->output = OUT_DTB;
1133 else if (!strcmp(optarg, "dts"))
1134 disp->output = OUT_DTS;
1135 else if (!strcmp(optarg, "bin"))
1136 disp->output = OUT_BIN;
1138 usage("Unknown output format");
1147 disp->remove_strings = 1;
1150 disp->include_root = 1;
1153 disp->flags |= FDT_REG_ALL_SUBNODES;
1156 disp->flags &= ~FDT_REG_SUPERNODES;
1159 disp->flags |= FDT_REG_ADD_STRING_TAB;
1162 disp->add_aliases = 1;
1168 disp->show_dts_version = 1;
1172 if (type && value_add(disp, &disp->value_head, type, inc,
1174 usage("Cannot add value");
1177 if (disp->invert && disp->types_exc)
1178 usage("-v has no meaning when used with 'exclude' conditions");
1181 int main(int argc, char *argv[])
1183 char *filename = NULL;
1184 struct display_info disp;
1188 memset(&disp, '\0', sizeof(disp));
1189 disp.flags = FDT_REG_SUPERNODES; /* Default flags */
1191 scan_args(&disp, argc, argv);
1193 /* Show matched lines in colour if we can */
1194 disp.colour = disp.all && isatty(0);
1196 /* Any additional arguments can match anything, just like -g */
1197 while (optind < argc - 1) {
1198 if (value_add(&disp, &disp.value_head, FDT_IS_ANY, 1,
1200 usage("Cannot add value");
1204 filename = argv[optind++];
1206 usage("Missing filename");
1208 /* If a valid .dtb is required, set flags to ensure we get one */
1209 if (disp.output == OUT_DTB) {
1211 disp.flags |= FDT_REG_ADD_MEM_RSVMAP | FDT_REG_ADD_STRING_TAB;
1214 if (disp.output_fname) {
1215 disp.fout = fopen(disp.output_fname, "w");
1217 usage("Cannot open output file");
1222 /* Run the grep and output the results */
1223 ret = do_fdtgrep(&disp, filename);
1224 if (disp.output_fname)