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