Fork of the vendor (Boundary Devices) u-boot for Reform 2, with minor tweaks. The goal is to migrate to mainstream u-boot or barebox ASAP. The main impediment so far is the 4GB RAM config.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 
 
 

1229 lines
30 KiB

  1. /*
  2. * Copyright (c) 2013, Google Inc.
  3. * Written by Simon Glass <sjg@chromium.org>
  4. *
  5. * SPDX-License-Identifier: GPL-2.0+
  6. *
  7. * Perform a grep of an FDT either displaying the source subset or producing
  8. * a new .dtb subset which can be used as required.
  9. */
  10. #include <assert.h>
  11. #include <ctype.h>
  12. #include <getopt.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <unistd.h>
  17. #include <../include/libfdt.h>
  18. #include <libfdt_internal.h>
  19. /* Define DEBUG to get some debugging output on stderr */
  20. #ifdef DEBUG
  21. #define debug(a, b...) fprintf(stderr, a, ## b)
  22. #else
  23. #define debug(a, b...)
  24. #endif
  25. /* A linked list of values we are grepping for */
  26. struct value_node {
  27. int type; /* Types this value matches (FDT_IS... mask) */
  28. int include; /* 1 to include matches, 0 to exclude */
  29. const char *string; /* String to match */
  30. struct value_node *next; /* Pointer to next node, or NULL */
  31. };
  32. /* Output formats we support */
  33. enum output_t {
  34. OUT_DTS, /* Device tree source */
  35. OUT_DTB, /* Valid device tree binary */
  36. OUT_BIN, /* Fragment of .dtb, for hashing */
  37. };
  38. /* Holds information which controls our output and options */
  39. struct display_info {
  40. enum output_t output; /* Output format */
  41. int add_aliases; /* Add aliases node to output */
  42. int all; /* Display all properties/nodes */
  43. int colour; /* Display output in ANSI colour */
  44. int region_list; /* Output a region list */
  45. int flags; /* Flags (FDT_REG_...) */
  46. int list_strings; /* List strings in string table */
  47. int show_offset; /* Show offset */
  48. int show_addr; /* Show address */
  49. int header; /* Output an FDT header */
  50. int diff; /* Show +/- diff markers */
  51. int include_root; /* Include the root node and all properties */
  52. int remove_strings; /* Remove unused strings */
  53. int show_dts_version; /* Put '/dts-v1/;' on the first line */
  54. int types_inc; /* Mask of types that we include (FDT_IS...) */
  55. int types_exc; /* Mask of types that we exclude (FDT_IS...) */
  56. int invert; /* Invert polarity of match */
  57. struct value_node *value_head; /* List of values to match */
  58. const char *output_fname; /* Output filename */
  59. FILE *fout; /* File to write dts/dtb output */
  60. };
  61. static void report_error(const char *where, int err)
  62. {
  63. fprintf(stderr, "Error at '%s': %s\n", where, fdt_strerror(err));
  64. }
  65. /* Supported ANSI colours */
  66. enum {
  67. COL_BLACK,
  68. COL_RED,
  69. COL_GREEN,
  70. COL_YELLOW,
  71. COL_BLUE,
  72. COL_MAGENTA,
  73. COL_CYAN,
  74. COL_WHITE,
  75. COL_NONE = -1,
  76. };
  77. /**
  78. * print_ansi_colour() - Print out the ANSI sequence for a colour
  79. *
  80. * @fout: Output file
  81. * @col: Colour to output (COL_...), or COL_NONE to reset colour
  82. */
  83. static void print_ansi_colour(FILE *fout, int col)
  84. {
  85. if (col == COL_NONE)
  86. fprintf(fout, "\033[0m");
  87. else
  88. fprintf(fout, "\033[1;%dm", col + 30);
  89. }
  90. /**
  91. * value_add() - Add a new value to our list of things to grep for
  92. *
  93. * @disp: Display structure, holding info about our options
  94. * @headp: Pointer to header pointer of list
  95. * @type: Type of this value (FDT_IS_...)
  96. * @include: 1 if we want to include matches, 0 to exclude
  97. * @str: String value to match
  98. */
  99. static int value_add(struct display_info *disp, struct value_node **headp,
  100. int type, int include, const char *str)
  101. {
  102. struct value_node *node;
  103. /*
  104. * Keep track of which types we are excluding/including. We don't
  105. * allow both including and excluding things, because it doesn't make
  106. * sense. 'Including' means that everything not mentioned is
  107. * excluded. 'Excluding' means that everything not mentioned is
  108. * included. So using the two together would be meaningless.
  109. */
  110. if (include)
  111. disp->types_inc |= type;
  112. else
  113. disp->types_exc |= type;
  114. if (disp->types_inc & disp->types_exc & type) {
  115. fprintf(stderr,
  116. "Cannot use both include and exclude for '%s'\n", str);
  117. return -1;
  118. }
  119. str = strdup(str);
  120. node = malloc(sizeof(*node));
  121. if (!str || !node) {
  122. fprintf(stderr, "Out of memory\n");
  123. return -1;
  124. }
  125. node->next = *headp;
  126. node->type = type;
  127. node->include = include;
  128. node->string = str;
  129. *headp = node;
  130. return 0;
  131. }
  132. static bool util_is_printable_string(const void *data, int len)
  133. {
  134. const char *s = data;
  135. const char *ss, *se;
  136. /* zero length is not */
  137. if (len == 0)
  138. return 0;
  139. /* must terminate with zero */
  140. if (s[len - 1] != '\0')
  141. return 0;
  142. se = s + len;
  143. while (s < se) {
  144. ss = s;
  145. while (s < se && *s && isprint((unsigned char)*s))
  146. s++;
  147. /* not zero, or not done yet */
  148. if (*s != '\0' || s == ss)
  149. return 0;
  150. s++;
  151. }
  152. return 1;
  153. }
  154. static void utilfdt_print_data(const char *data, int len)
  155. {
  156. int i;
  157. const char *p = data;
  158. const char *s;
  159. /* no data, don't print */
  160. if (len == 0)
  161. return;
  162. if (util_is_printable_string(data, len)) {
  163. printf(" = ");
  164. s = data;
  165. do {
  166. printf("\"%s\"", s);
  167. s += strlen(s) + 1;
  168. if (s < data + len)
  169. printf(", ");
  170. } while (s < data + len);
  171. } else if ((len % 4) == 0) {
  172. const uint32_t *cell = (const uint32_t *)data;
  173. printf(" = <");
  174. for (i = 0, len /= 4; i < len; i++)
  175. printf("0x%08x%s", fdt32_to_cpu(cell[i]),
  176. i < (len - 1) ? " " : "");
  177. printf(">");
  178. } else {
  179. printf(" = [");
  180. for (i = 0; i < len; i++)
  181. printf("%02x%s", *p++, i < len - 1 ? " " : "");
  182. printf("]");
  183. }
  184. }
  185. /**
  186. * display_fdt_by_regions() - Display regions of an FDT source
  187. *
  188. * This dumps an FDT as source, but only certain regions of it. This is the
  189. * final stage of the grep - we have a list of regions we want to display,
  190. * and this function displays them.
  191. *
  192. * @disp: Display structure, holding info about our options
  193. * @blob: FDT blob to display
  194. * @region: List of regions to display
  195. * @count: Number of regions
  196. */
  197. static int display_fdt_by_regions(struct display_info *disp, const void *blob,
  198. struct fdt_region region[], int count)
  199. {
  200. struct fdt_region *reg = region, *reg_end = region + count;
  201. uint32_t off_mem_rsvmap = fdt_off_mem_rsvmap(blob);
  202. int base = fdt_off_dt_struct(blob);
  203. int version = fdt_version(blob);
  204. int offset, nextoffset;
  205. int tag, depth, shift;
  206. FILE *f = disp->fout;
  207. uint64_t addr, size;
  208. int in_region;
  209. int file_ofs;
  210. int i;
  211. if (disp->show_dts_version)
  212. fprintf(f, "/dts-v1/;\n");
  213. if (disp->header) {
  214. fprintf(f, "// magic:\t\t0x%x\n", fdt_magic(blob));
  215. fprintf(f, "// totalsize:\t\t0x%x (%d)\n", fdt_totalsize(blob),
  216. fdt_totalsize(blob));
  217. fprintf(f, "// off_dt_struct:\t0x%x\n",
  218. fdt_off_dt_struct(blob));
  219. fprintf(f, "// off_dt_strings:\t0x%x\n",
  220. fdt_off_dt_strings(blob));
  221. fprintf(f, "// off_mem_rsvmap:\t0x%x\n", off_mem_rsvmap);
  222. fprintf(f, "// version:\t\t%d\n", version);
  223. fprintf(f, "// last_comp_version:\t%d\n",
  224. fdt_last_comp_version(blob));
  225. if (version >= 2) {
  226. fprintf(f, "// boot_cpuid_phys:\t0x%x\n",
  227. fdt_boot_cpuid_phys(blob));
  228. }
  229. if (version >= 3) {
  230. fprintf(f, "// size_dt_strings:\t0x%x\n",
  231. fdt_size_dt_strings(blob));
  232. }
  233. if (version >= 17) {
  234. fprintf(f, "// size_dt_struct:\t0x%x\n",
  235. fdt_size_dt_struct(blob));
  236. }
  237. fprintf(f, "\n");
  238. }
  239. if (disp->flags & FDT_REG_ADD_MEM_RSVMAP) {
  240. const struct fdt_reserve_entry *p_rsvmap;
  241. p_rsvmap = (const struct fdt_reserve_entry *)
  242. ((const char *)blob + off_mem_rsvmap);
  243. for (i = 0; ; i++) {
  244. addr = fdt64_to_cpu(p_rsvmap[i].address);
  245. size = fdt64_to_cpu(p_rsvmap[i].size);
  246. if (addr == 0 && size == 0)
  247. break;
  248. fprintf(f, "/memreserve/ %llx %llx;\n",
  249. (unsigned long long)addr,
  250. (unsigned long long)size);
  251. }
  252. }
  253. depth = 0;
  254. nextoffset = 0;
  255. shift = 4; /* 4 spaces per indent */
  256. do {
  257. const struct fdt_property *prop;
  258. const char *name;
  259. int show;
  260. int len;
  261. offset = nextoffset;
  262. /*
  263. * Work out the file offset of this offset, and decide
  264. * whether it is in the region list or not
  265. */
  266. file_ofs = base + offset;
  267. if (reg < reg_end && file_ofs >= reg->offset + reg->size)
  268. reg++;
  269. in_region = reg < reg_end && file_ofs >= reg->offset &&
  270. file_ofs < reg->offset + reg->size;
  271. tag = fdt_next_tag(blob, offset, &nextoffset);
  272. if (tag == FDT_END)
  273. break;
  274. show = in_region || disp->all;
  275. if (show && disp->diff)
  276. fprintf(f, "%c", in_region ? '+' : '-');
  277. if (!show) {
  278. /* Do this here to avoid 'if (show)' in every 'case' */
  279. if (tag == FDT_BEGIN_NODE)
  280. depth++;
  281. else if (tag == FDT_END_NODE)
  282. depth--;
  283. continue;
  284. }
  285. if (tag != FDT_END) {
  286. if (disp->show_addr)
  287. fprintf(f, "%4x: ", file_ofs);
  288. if (disp->show_offset)
  289. fprintf(f, "%4x: ", file_ofs - base);
  290. }
  291. /* Green means included, red means excluded */
  292. if (disp->colour)
  293. print_ansi_colour(f, in_region ? COL_GREEN : COL_RED);
  294. switch (tag) {
  295. case FDT_PROP:
  296. prop = fdt_get_property_by_offset(blob, offset, NULL);
  297. name = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
  298. fprintf(f, "%*s%s", depth * shift, "", name);
  299. utilfdt_print_data(prop->data,
  300. fdt32_to_cpu(prop->len));
  301. fprintf(f, ";");
  302. break;
  303. case FDT_NOP:
  304. fprintf(f, "%*s// [NOP]", depth * shift, "");
  305. break;
  306. case FDT_BEGIN_NODE:
  307. name = fdt_get_name(blob, offset, &len);
  308. fprintf(f, "%*s%s {", depth++ * shift, "",
  309. *name ? name : "/");
  310. break;
  311. case FDT_END_NODE:
  312. fprintf(f, "%*s};", --depth * shift, "");
  313. break;
  314. }
  315. /* Reset colour back to normal before end of line */
  316. if (disp->colour)
  317. print_ansi_colour(f, COL_NONE);
  318. fprintf(f, "\n");
  319. } while (1);
  320. /* Print a list of strings if requested */
  321. if (disp->list_strings) {
  322. const char *str;
  323. int str_base = fdt_off_dt_strings(blob);
  324. for (offset = 0; offset < fdt_size_dt_strings(blob);
  325. offset += strlen(str) + 1) {
  326. str = fdt_string(blob, offset);
  327. int len = strlen(str) + 1;
  328. int show;
  329. /* Only print strings that are in the region */
  330. file_ofs = str_base + offset;
  331. in_region = reg < reg_end &&
  332. file_ofs >= reg->offset &&
  333. file_ofs + len < reg->offset +
  334. reg->size;
  335. show = in_region || disp->all;
  336. if (show && disp->diff)
  337. printf("%c", in_region ? '+' : '-');
  338. if (disp->show_addr)
  339. printf("%4x: ", file_ofs);
  340. if (disp->show_offset)
  341. printf("%4x: ", offset);
  342. printf("%s\n", str);
  343. }
  344. }
  345. return 0;
  346. }
  347. /**
  348. * dump_fdt_regions() - Dump regions of an FDT as binary data
  349. *
  350. * This dumps an FDT as binary, but only certain regions of it. This is the
  351. * final stage of the grep - we have a list of regions we want to dump,
  352. * and this function dumps them.
  353. *
  354. * The output of this function may or may not be a valid FDT. To ensure it
  355. * is, these disp->flags must be set:
  356. *
  357. * FDT_REG_SUPERNODES: ensures that subnodes are preceded by their
  358. * parents. Without this option, fragments of subnode data may be
  359. * output without the supernodes above them. This is useful for
  360. * hashing but cannot produce a valid FDT.
  361. * FDT_REG_ADD_STRING_TAB: Adds a string table to the end of the FDT.
  362. * Without this none of the properties will have names
  363. * FDT_REG_ADD_MEM_RSVMAP: Adds a mem_rsvmap table - an FDT is invalid
  364. * without this.
  365. *
  366. * @disp: Display structure, holding info about our options
  367. * @blob: FDT blob to display
  368. * @region: List of regions to display
  369. * @count: Number of regions
  370. * @out: Output destination
  371. */
  372. static int dump_fdt_regions(struct display_info *disp, const void *blob,
  373. struct fdt_region region[], int count, char *out)
  374. {
  375. struct fdt_header *fdt;
  376. int size, struct_start;
  377. int ptr;
  378. int i;
  379. /* Set up a basic header (even if we don't actually write it) */
  380. fdt = (struct fdt_header *)out;
  381. memset(fdt, '\0', sizeof(*fdt));
  382. fdt_set_magic(fdt, FDT_MAGIC);
  383. struct_start = FDT_ALIGN(sizeof(struct fdt_header),
  384. sizeof(struct fdt_reserve_entry));
  385. fdt_set_off_mem_rsvmap(fdt, struct_start);
  386. fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
  387. fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
  388. /*
  389. * Calculate the total size of the regions we are writing out. The
  390. * first will be the mem_rsvmap if the FDT_REG_ADD_MEM_RSVMAP flag
  391. * is set. The last will be the string table if FDT_REG_ADD_STRING_TAB
  392. * is set.
  393. */
  394. for (i = size = 0; i < count; i++)
  395. size += region[i].size;
  396. /* Bring in the mem_rsvmap section from the old file if requested */
  397. if (count > 0 && (disp->flags & FDT_REG_ADD_MEM_RSVMAP)) {
  398. struct_start += region[0].size;
  399. size -= region[0].size;
  400. }
  401. fdt_set_off_dt_struct(fdt, struct_start);
  402. /* Update the header to have the correct offsets/sizes */
  403. if (count >= 2 && (disp->flags & FDT_REG_ADD_STRING_TAB)) {
  404. int str_size;
  405. str_size = region[count - 1].size;
  406. fdt_set_size_dt_struct(fdt, size - str_size);
  407. fdt_set_off_dt_strings(fdt, struct_start + size - str_size);
  408. fdt_set_size_dt_strings(fdt, str_size);
  409. fdt_set_totalsize(fdt, struct_start + size);
  410. }
  411. /* Write the header if required */
  412. ptr = 0;
  413. if (disp->header) {
  414. ptr = sizeof(*fdt);
  415. while (ptr < fdt_off_mem_rsvmap(fdt))
  416. out[ptr++] = '\0';
  417. }
  418. /* Output all the nodes including any mem_rsvmap/string table */
  419. for (i = 0; i < count; i++) {
  420. struct fdt_region *reg = &region[i];
  421. memcpy(out + ptr, (const char *)blob + reg->offset, reg->size);
  422. ptr += reg->size;
  423. }
  424. return ptr;
  425. }
  426. /**
  427. * show_region_list() - Print out a list of regions
  428. *
  429. * The list includes the region offset (absolute offset from start of FDT
  430. * blob in bytes) and size
  431. *
  432. * @reg: List of regions to print
  433. * @count: Number of regions
  434. */
  435. static void show_region_list(struct fdt_region *reg, int count)
  436. {
  437. int i;
  438. printf("Regions: %d\n", count);
  439. for (i = 0; i < count; i++, reg++) {
  440. printf("%d: %-10x %-10x\n", i, reg->offset,
  441. reg->offset + reg->size);
  442. }
  443. }
  444. static int check_type_include(void *priv, int type, const char *data, int size)
  445. {
  446. struct display_info *disp = priv;
  447. struct value_node *val;
  448. int match, none_match = FDT_IS_ANY;
  449. /* If none of our conditions mention this type, we know nothing */
  450. debug("type=%x, data=%s\n", type, data ? data : "(null)");
  451. if (!((disp->types_inc | disp->types_exc) & type)) {
  452. debug(" - not in any condition\n");
  453. return -1;
  454. }
  455. /*
  456. * Go through the list of conditions. For inclusive conditions, we
  457. * return 1 at the first match. For exclusive conditions, we must
  458. * check that there are no matches.
  459. */
  460. if (data) {
  461. for (val = disp->value_head; val; val = val->next) {
  462. if (!(type & val->type))
  463. continue;
  464. match = fdt_stringlist_contains(data, size,
  465. val->string);
  466. debug(" - val->type=%x, str='%s', match=%d\n",
  467. val->type, val->string, match);
  468. if (match && val->include) {
  469. debug(" - match inc %s\n", val->string);
  470. return 1;
  471. }
  472. if (match)
  473. none_match &= ~val->type;
  474. }
  475. }
  476. /*
  477. * If this is an exclusive condition, and nothing matches, then we
  478. * should return 1.
  479. */
  480. if ((type & disp->types_exc) && (none_match & type)) {
  481. debug(" - match exc\n");
  482. /*
  483. * Allow FDT_IS_COMPAT to make the final decision in the
  484. * case where there is no specific type
  485. */
  486. if (type == FDT_IS_NODE && disp->types_exc == FDT_ANY_GLOBAL) {
  487. debug(" - supressed exc node\n");
  488. return -1;
  489. }
  490. return 1;
  491. }
  492. /*
  493. * Allow FDT_IS_COMPAT to make the final decision in the
  494. * case where there is no specific type (inclusive)
  495. */
  496. if (type == FDT_IS_NODE && disp->types_inc == FDT_ANY_GLOBAL)
  497. return -1;
  498. debug(" - no match, types_inc=%x, types_exc=%x, none_match=%x\n",
  499. disp->types_inc, disp->types_exc, none_match);
  500. return 0;
  501. }
  502. /**
  503. * h_include() - Include handler function for fdt_find_regions()
  504. *
  505. * This function decides whether to include or exclude a node, property or
  506. * compatible string. The function is defined by fdt_find_regions().
  507. *
  508. * The algorithm is documented in the code - disp->invert is 0 for normal
  509. * operation, and 1 to invert the sense of all matches.
  510. *
  511. * See
  512. */
  513. static int h_include(void *priv, const void *fdt, int offset, int type,
  514. const char *data, int size)
  515. {
  516. struct display_info *disp = priv;
  517. int inc, len;
  518. inc = check_type_include(priv, type, data, size);
  519. if (disp->include_root && type == FDT_IS_PROP && offset == 0 && inc)
  520. return 1;
  521. /*
  522. * If the node name does not tell us anything, check the
  523. * compatible string
  524. */
  525. if (inc == -1 && type == FDT_IS_NODE) {
  526. debug(" - checking compatible2\n");
  527. data = fdt_getprop(fdt, offset, "compatible", &len);
  528. inc = check_type_include(priv, FDT_IS_COMPAT, data, len);
  529. }
  530. /* If we still have no idea, check for properties in the node */
  531. if (inc != 1 && type == FDT_IS_NODE &&
  532. (disp->types_inc & FDT_NODE_HAS_PROP)) {
  533. debug(" - checking node '%s'\n",
  534. fdt_get_name(fdt, offset, NULL));
  535. for (offset = fdt_first_property_offset(fdt, offset);
  536. offset > 0 && inc != 1;
  537. offset = fdt_next_property_offset(fdt, offset)) {
  538. const struct fdt_property *prop;
  539. const char *str;
  540. prop = fdt_get_property_by_offset(fdt, offset, NULL);
  541. if (!prop)
  542. continue;
  543. str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
  544. inc = check_type_include(priv, FDT_NODE_HAS_PROP, str,
  545. strlen(str));
  546. }
  547. if (inc == -1)
  548. inc = 0;
  549. }
  550. switch (inc) {
  551. case 1:
  552. inc = !disp->invert;
  553. break;
  554. case 0:
  555. inc = disp->invert;
  556. break;
  557. }
  558. debug(" - returning %d\n", inc);
  559. return inc;
  560. }
  561. static int h_cmp_region(const void *v1, const void *v2)
  562. {
  563. const struct fdt_region *region1 = v1, *region2 = v2;
  564. return region1->offset - region2->offset;
  565. }
  566. static int fdtgrep_find_regions(const void *fdt,
  567. int (*include_func)(void *priv, const void *fdt, int offset,
  568. int type, const char *data, int size),
  569. struct display_info *disp, struct fdt_region *region,
  570. int max_regions, char *path, int path_len, int flags)
  571. {
  572. struct fdt_region_state state;
  573. int count;
  574. int ret;
  575. count = 0;
  576. ret = fdt_first_region(fdt, include_func, disp,
  577. &region[count++], path, path_len,
  578. disp->flags, &state);
  579. while (ret == 0) {
  580. ret = fdt_next_region(fdt, include_func, disp,
  581. count < max_regions ? &region[count] : NULL,
  582. path, path_len, disp->flags, &state);
  583. if (!ret)
  584. count++;
  585. }
  586. if (ret && ret != -FDT_ERR_NOTFOUND)
  587. return ret;
  588. /* Find all the aliases and add those regions back in */
  589. if (disp->add_aliases && count < max_regions) {
  590. int new_count;
  591. new_count = fdt_add_alias_regions(fdt, region, count,
  592. max_regions, &state);
  593. if (new_count == -FDT_ERR_NOTFOUND) {
  594. /* No alias node found */
  595. } else if (new_count < 0) {
  596. return new_count;
  597. } else if (new_count <= max_regions) {
  598. /*
  599. * The alias regions will now be at the end of the list.
  600. * Sort the regions by offset to get things into the
  601. * right order
  602. */
  603. count = new_count;
  604. qsort(region, count, sizeof(struct fdt_region),
  605. h_cmp_region);
  606. }
  607. }
  608. return count;
  609. }
  610. int utilfdt_read_err_len(const char *filename, char **buffp, off_t *len)
  611. {
  612. int fd = 0; /* assume stdin */
  613. char *buf = NULL;
  614. off_t bufsize = 1024, offset = 0;
  615. int ret = 0;
  616. *buffp = NULL;
  617. if (strcmp(filename, "-") != 0) {
  618. fd = open(filename, O_RDONLY);
  619. if (fd < 0)
  620. return errno;
  621. }
  622. /* Loop until we have read everything */
  623. buf = malloc(bufsize);
  624. if (!buf)
  625. return -ENOMEM;
  626. do {
  627. /* Expand the buffer to hold the next chunk */
  628. if (offset == bufsize) {
  629. bufsize *= 2;
  630. buf = realloc(buf, bufsize);
  631. if (!buf)
  632. return -ENOMEM;
  633. }
  634. ret = read(fd, &buf[offset], bufsize - offset);
  635. if (ret < 0) {
  636. ret = errno;
  637. break;
  638. }
  639. offset += ret;
  640. } while (ret != 0);
  641. /* Clean up, including closing stdin; return errno on error */
  642. close(fd);
  643. if (ret)
  644. free(buf);
  645. else
  646. *buffp = buf;
  647. *len = bufsize;
  648. return ret;
  649. }
  650. int utilfdt_read_err(const char *filename, char **buffp)
  651. {
  652. off_t len;
  653. return utilfdt_read_err_len(filename, buffp, &len);
  654. }
  655. char *utilfdt_read_len(const char *filename, off_t *len)
  656. {
  657. char *buff;
  658. int ret = utilfdt_read_err_len(filename, &buff, len);
  659. if (ret) {
  660. fprintf(stderr, "Couldn't open blob from '%s': %s\n", filename,
  661. strerror(ret));
  662. return NULL;
  663. }
  664. /* Successful read */
  665. return buff;
  666. }
  667. char *utilfdt_read(const char *filename)
  668. {
  669. off_t len;
  670. return utilfdt_read_len(filename, &len);
  671. }
  672. /**
  673. * Run the main fdtgrep operation, given a filename and valid arguments
  674. *
  675. * @param disp Display information / options
  676. * @param filename Filename of blob file
  677. * @param return 0 if ok, -ve on error
  678. */
  679. static int do_fdtgrep(struct display_info *disp, const char *filename)
  680. {
  681. struct fdt_region *region;
  682. int max_regions;
  683. int count = 100;
  684. char path[1024];
  685. char *blob;
  686. int i, ret;
  687. blob = utilfdt_read(filename);
  688. if (!blob)
  689. return -1;
  690. ret = fdt_check_header(blob);
  691. if (ret) {
  692. fprintf(stderr, "Error: %s\n", fdt_strerror(ret));
  693. return ret;
  694. }
  695. /* Allow old files, but they are untested */
  696. if (fdt_version(blob) < 17 && disp->value_head) {
  697. fprintf(stderr,
  698. "Warning: fdtgrep does not fully support version %d files\n",
  699. fdt_version(blob));
  700. }
  701. /*
  702. * We do two passes, since we don't know how many regions we need.
  703. * The first pass will count the regions, but if it is too many,
  704. * we do another pass to actually record them.
  705. */
  706. for (i = 0; i < 3; i++) {
  707. region = malloc(count * sizeof(struct fdt_region));
  708. if (!region) {
  709. fprintf(stderr, "Out of memory for %d regions\n",
  710. count);
  711. return -1;
  712. }
  713. max_regions = count;
  714. count = fdtgrep_find_regions(blob,
  715. h_include, disp,
  716. region, max_regions, path, sizeof(path),
  717. disp->flags);
  718. if (count < 0) {
  719. report_error("fdt_find_regions", count);
  720. return -1;
  721. }
  722. if (count <= max_regions)
  723. break;
  724. free(region);
  725. }
  726. /* Optionally print a list of regions */
  727. if (disp->region_list)
  728. show_region_list(region, count);
  729. /* Output either source .dts or binary .dtb */
  730. if (disp->output == OUT_DTS) {
  731. ret = display_fdt_by_regions(disp, blob, region, count);
  732. } else {
  733. void *fdt;
  734. /* Allow reserved memory section to expand slightly */
  735. int size = fdt_totalsize(blob) + 16;
  736. fdt = malloc(size);
  737. if (!fdt) {
  738. fprintf(stderr, "Out_of_memory\n");
  739. ret = -1;
  740. goto err;
  741. }
  742. size = dump_fdt_regions(disp, blob, region, count, fdt);
  743. if (disp->remove_strings) {
  744. void *out;
  745. out = malloc(size);
  746. if (!out) {
  747. fprintf(stderr, "Out_of_memory\n");
  748. ret = -1;
  749. goto err;
  750. }
  751. ret = fdt_remove_unused_strings(fdt, out);
  752. if (ret < 0) {
  753. fprintf(stderr,
  754. "Failed to remove unused strings: err=%d\n",
  755. ret);
  756. goto err;
  757. }
  758. free(fdt);
  759. fdt = out;
  760. ret = fdt_pack(fdt);
  761. if (ret < 0) {
  762. fprintf(stderr, "Failed to pack: err=%d\n",
  763. ret);
  764. goto err;
  765. }
  766. size = fdt_totalsize(fdt);
  767. }
  768. if (size != fwrite(fdt, 1, size, disp->fout)) {
  769. fprintf(stderr, "Write failure, %d bytes\n", size);
  770. free(fdt);
  771. ret = 1;
  772. goto err;
  773. }
  774. free(fdt);
  775. }
  776. err:
  777. free(blob);
  778. free(region);
  779. return ret;
  780. }
  781. static const char usage_synopsis[] =
  782. "fdtgrep - extract portions from device tree\n"
  783. "\n"
  784. "Usage:\n"
  785. " fdtgrep <options> <dt file>|-\n\n"
  786. "Output formats are:\n"
  787. "\tdts - device tree soure text\n"
  788. "\tdtb - device tree blob (sets -Hmt automatically)\n"
  789. "\tbin - device tree fragment (may not be a valid .dtb)";
  790. /* Helper for usage_short_opts string constant */
  791. #define USAGE_COMMON_SHORT_OPTS "hV"
  792. /* Helper for aligning long_opts array */
  793. #define a_argument required_argument
  794. /* Helper for usage_long_opts option array */
  795. #define USAGE_COMMON_LONG_OPTS \
  796. {"help", no_argument, NULL, 'h'}, \
  797. {"version", no_argument, NULL, 'V'}, \
  798. {NULL, no_argument, NULL, 0x0}
  799. /* Helper for usage_opts_help array */
  800. #define USAGE_COMMON_OPTS_HELP \
  801. "Print this help and exit", \
  802. "Print version and exit", \
  803. NULL
  804. /* Helper for getopt case statements */
  805. #define case_USAGE_COMMON_FLAGS \
  806. case 'h': usage(NULL); \
  807. case 'V': util_version(); \
  808. case '?': usage("unknown option");
  809. static const char usage_short_opts[] =
  810. "haAc:b:C:defg:G:HIlLmn:N:o:O:p:P:rRsStTv"
  811. USAGE_COMMON_SHORT_OPTS;
  812. static struct option const usage_long_opts[] = {
  813. {"show-address", no_argument, NULL, 'a'},
  814. {"colour", no_argument, NULL, 'A'},
  815. {"include-node-with-prop", a_argument, NULL, 'b'},
  816. {"include-compat", a_argument, NULL, 'c'},
  817. {"exclude-compat", a_argument, NULL, 'C'},
  818. {"diff", no_argument, NULL, 'd'},
  819. {"enter-node", no_argument, NULL, 'e'},
  820. {"show-offset", no_argument, NULL, 'f'},
  821. {"include-match", a_argument, NULL, 'g'},
  822. {"exclude-match", a_argument, NULL, 'G'},
  823. {"show-header", no_argument, NULL, 'H'},
  824. {"show-version", no_argument, NULL, 'I'},
  825. {"list-regions", no_argument, NULL, 'l'},
  826. {"list-strings", no_argument, NULL, 'L'},
  827. {"include-mem", no_argument, NULL, 'm'},
  828. {"include-node", a_argument, NULL, 'n'},
  829. {"exclude-node", a_argument, NULL, 'N'},
  830. {"include-prop", a_argument, NULL, 'p'},
  831. {"exclude-prop", a_argument, NULL, 'P'},
  832. {"remove-strings", no_argument, NULL, 'r'},
  833. {"include-root", no_argument, NULL, 'R'},
  834. {"show-subnodes", no_argument, NULL, 's'},
  835. {"skip-supernodes", no_argument, NULL, 'S'},
  836. {"show-stringtab", no_argument, NULL, 't'},
  837. {"show-aliases", no_argument, NULL, 'T'},
  838. {"out", a_argument, NULL, 'o'},
  839. {"out-format", a_argument, NULL, 'O'},
  840. {"invert-match", no_argument, NULL, 'v'},
  841. USAGE_COMMON_LONG_OPTS,
  842. };
  843. static const char * const usage_opts_help[] = {
  844. "Display address",
  845. "Show all nodes/tags, colour those that match",
  846. "Include contains containing property",
  847. "Compatible nodes to include in grep",
  848. "Compatible nodes to exclude in grep",
  849. "Diff: Mark matching nodes with +, others with -",
  850. "Enter direct subnode names of matching nodes",
  851. "Display offset",
  852. "Node/property/compatible string to include in grep",
  853. "Node/property/compatible string to exclude in grep",
  854. "Output a header",
  855. "Put \"/dts-v1/;\" on first line of dts output",
  856. "Output a region list",
  857. "List strings in string table",
  858. "Include mem_rsvmap section in binary output",
  859. "Node to include in grep",
  860. "Node to exclude in grep",
  861. "Property to include in grep",
  862. "Property to exclude in grep",
  863. "Remove unused strings from string table",
  864. "Include root node and all properties",
  865. "Show all subnodes matching nodes",
  866. "Don't include supernodes of matching nodes",
  867. "Include string table in binary output",
  868. "Include matching aliases in output",
  869. "-o <output file>",
  870. "-O <output format>",
  871. "Invert the sense of matching (select non-matching lines)",
  872. USAGE_COMMON_OPTS_HELP
  873. };
  874. /**
  875. * Call getopt_long() with standard options
  876. *
  877. * Since all util code runs getopt in the same way, provide a helper.
  878. */
  879. #define util_getopt_long() getopt_long(argc, argv, usage_short_opts, \
  880. usage_long_opts, NULL)
  881. void util_usage(const char *errmsg, const char *synopsis,
  882. const char *short_opts, struct option const long_opts[],
  883. const char * const opts_help[])
  884. {
  885. FILE *fp = errmsg ? stderr : stdout;
  886. const char a_arg[] = "<arg>";
  887. size_t a_arg_len = strlen(a_arg) + 1;
  888. size_t i;
  889. int optlen;
  890. fprintf(fp,
  891. "Usage: %s\n"
  892. "\n"
  893. "Options: -[%s]\n", synopsis, short_opts);
  894. /* prescan the --long opt length to auto-align */
  895. optlen = 0;
  896. for (i = 0; long_opts[i].name; ++i) {
  897. /* +1 is for space between --opt and help text */
  898. int l = strlen(long_opts[i].name) + 1;
  899. if (long_opts[i].has_arg == a_argument)
  900. l += a_arg_len;
  901. if (optlen < l)
  902. optlen = l;
  903. }
  904. for (i = 0; long_opts[i].name; ++i) {
  905. /* helps when adding new applets or options */
  906. assert(opts_help[i] != NULL);
  907. /* first output the short flag if it has one */
  908. if (long_opts[i].val > '~')
  909. fprintf(fp, " ");
  910. else
  911. fprintf(fp, " -%c, ", long_opts[i].val);
  912. /* then the long flag */
  913. if (long_opts[i].has_arg == no_argument) {
  914. fprintf(fp, "--%-*s", optlen, long_opts[i].name);
  915. } else {
  916. fprintf(fp, "--%s %s%*s", long_opts[i].name, a_arg,
  917. (int)(optlen - strlen(long_opts[i].name) -
  918. a_arg_len), "");
  919. }
  920. /* finally the help text */
  921. fprintf(fp, "%s\n", opts_help[i]);
  922. }
  923. if (errmsg) {
  924. fprintf(fp, "\nError: %s\n", errmsg);
  925. exit(EXIT_FAILURE);
  926. } else {
  927. exit(EXIT_SUCCESS);
  928. }
  929. }
  930. /**
  931. * Show usage and exit
  932. *
  933. * If you name all your usage variables with usage_xxx, then you can call this
  934. * help macro rather than expanding all arguments yourself.
  935. *
  936. * @param errmsg If non-NULL, an error message to display
  937. */
  938. #define usage(errmsg) \
  939. util_usage(errmsg, usage_synopsis, usage_short_opts, \
  940. usage_long_opts, usage_opts_help)
  941. void util_version(void)
  942. {
  943. printf("Version: %s\n", "(U-Boot)");
  944. exit(0);
  945. }
  946. static void scan_args(struct display_info *disp, int argc, char *argv[])
  947. {
  948. int opt;
  949. while ((opt = util_getopt_long()) != EOF) {
  950. int type = 0;
  951. int inc = 1;
  952. switch (opt) {
  953. case_USAGE_COMMON_FLAGS
  954. case 'a':
  955. disp->show_addr = 1;
  956. break;
  957. case 'A':
  958. disp->all = 1;
  959. break;
  960. case 'b':
  961. type = FDT_NODE_HAS_PROP;
  962. break;
  963. case 'C':
  964. inc = 0;
  965. /* no break */
  966. case 'c':
  967. type = FDT_IS_COMPAT;
  968. break;
  969. case 'd':
  970. disp->diff = 1;
  971. break;
  972. case 'e':
  973. disp->flags |= FDT_REG_DIRECT_SUBNODES;
  974. break;
  975. case 'f':
  976. disp->show_offset = 1;
  977. break;
  978. case 'G':
  979. inc = 0;
  980. /* no break */
  981. case 'g':
  982. type = FDT_ANY_GLOBAL;
  983. break;
  984. case 'H':
  985. disp->header = 1;
  986. break;
  987. case 'l':
  988. disp->region_list = 1;
  989. break;
  990. case 'L':
  991. disp->list_strings = 1;
  992. break;
  993. case 'm':
  994. disp->flags |= FDT_REG_ADD_MEM_RSVMAP;
  995. break;
  996. case 'N':
  997. inc = 0;
  998. /* no break */
  999. case 'n':
  1000. type = FDT_IS_NODE;
  1001. break;
  1002. case 'o':
  1003. disp->output_fname = optarg;
  1004. break;
  1005. case 'O':
  1006. if (!strcmp(optarg, "dtb"))
  1007. disp->output = OUT_DTB;
  1008. else if (!strcmp(optarg, "dts"))
  1009. disp->output = OUT_DTS;
  1010. else if (!strcmp(optarg, "bin"))
  1011. disp->output = OUT_BIN;
  1012. else
  1013. usage("Unknown output format");
  1014. break;
  1015. case 'P':
  1016. inc = 0;
  1017. /* no break */
  1018. case 'p':
  1019. type = FDT_IS_PROP;
  1020. break;
  1021. case 'r':
  1022. disp->remove_strings = 1;
  1023. break;
  1024. case 'R':
  1025. disp->include_root = 1;
  1026. break;
  1027. case 's':
  1028. disp->flags |= FDT_REG_ALL_SUBNODES;
  1029. break;
  1030. case 'S':
  1031. disp->flags &= ~FDT_REG_SUPERNODES;
  1032. break;
  1033. case 't':
  1034. disp->flags |= FDT_REG_ADD_STRING_TAB;
  1035. break;
  1036. case 'T':
  1037. disp->add_aliases = 1;
  1038. break;
  1039. case 'v':
  1040. disp->invert = 1;
  1041. break;
  1042. case 'I':
  1043. disp->show_dts_version = 1;
  1044. break;
  1045. }
  1046. if (type && value_add(disp, &disp->value_head, type, inc,
  1047. optarg))
  1048. usage("Cannot add value");
  1049. }
  1050. if (disp->invert && disp->types_exc)
  1051. usage("-v has no meaning when used with 'exclude' conditions");
  1052. }
  1053. int main(int argc, char *argv[])
  1054. {
  1055. char *filename = NULL;
  1056. struct display_info disp;
  1057. int ret;
  1058. /* set defaults */
  1059. memset(&disp, '\0', sizeof(disp));
  1060. disp.flags = FDT_REG_SUPERNODES; /* Default flags */
  1061. scan_args(&disp, argc, argv);
  1062. /* Show matched lines in colour if we can */
  1063. disp.colour = disp.all && isatty(0);
  1064. /* Any additional arguments can match anything, just like -g */
  1065. while (optind < argc - 1) {
  1066. if (value_add(&disp, &disp.value_head, FDT_IS_ANY, 1,
  1067. argv[optind++]))
  1068. usage("Cannot add value");
  1069. }
  1070. if (optind < argc)
  1071. filename = argv[optind++];
  1072. if (!filename)
  1073. usage("Missing filename");
  1074. /* If a valid .dtb is required, set flags to ensure we get one */
  1075. if (disp.output == OUT_DTB) {
  1076. disp.header = 1;
  1077. disp.flags |= FDT_REG_ADD_MEM_RSVMAP | FDT_REG_ADD_STRING_TAB;
  1078. }
  1079. if (disp.output_fname) {
  1080. disp.fout = fopen(disp.output_fname, "w");
  1081. if (!disp.fout)
  1082. usage("Cannot open output file");
  1083. } else {
  1084. disp.fout = stdout;
  1085. }
  1086. /* Run the grep and output the results */
  1087. ret = do_fdtgrep(&disp, filename);
  1088. if (disp.output_fname)
  1089. fclose(disp.fout);
  1090. if (ret)
  1091. return 1;
  1092. return 0;
  1093. }