Commit 1043d0a0 authored by Simon Glass's avatar Simon Glass
Browse files

fdt: Add fdtgrep tool



This tool allows us to extract subsets of a device tree file. It is used by
the SPL vuild, which needs to cut down the device tree size for use in
limited memory.

This tool was originally written for libfdt but it has not been accepted
upstream, so for now, include it in U-Boot. Several utilfdt library
functions been included inline here.

If fdtgrep is eventually accepted in libfdt then we can bring that version
of libfdt in here, and drop fdtgrep (requiring that fdtgrep is provided by
the user).

If it is not accepted then another approach would be to write a special
tool for chopping down device tree files for SPL. While it would use the
same libfdt support, it would be less code than fdtgrep.c because it would
not have general-purpose functions.

Another approach (which was used with v1 of this series) is to sprinkler all
the device tree files with #ifdef. I don't like that idea.

Signed-off-by: default avatarSimon Glass <sjg@chromium.org>
parent c3c4c005
......@@ -58,7 +58,8 @@ hostprogs-$(CONFIG_FIT_SIGNATURE) += fit_info fit_check_sign
FIT_SIG_OBJS-$(CONFIG_FIT_SIGNATURE) := common/image-sig.o
# Flattened device tree objects
LIBFDT_OBJS := $(addprefix lib/libfdt/, \
fdt.o fdt_ro.o fdt_rw.o fdt_strerror.o fdt_wip.o)
fdt.o fdt_ro.o fdt_rw.o fdt_strerror.o fdt_wip.o \
fdt_region.o)
RSA_OBJS-$(CONFIG_FIT_SIGNATURE) := $(addprefix lib/rsa/, \
rsa-sign.o rsa-verify.o rsa-checksum.o \
rsa-mod-exp.o)
......@@ -155,6 +156,9 @@ hostprogs-$(CONFIG_ARMADA_XP) += kwboot
hostprogs-y += proftool
hostprogs-$(CONFIG_STATIC_RELA) += relocate-rela
hostprogs-y += fdtgrep
fdtgrep-objs += $(LIBFDT_OBJS) fdtgrep.o
# We build some files with extra pedantic flags to try to minimize things
# that won't build on some weird host compiler -- though there are lots of
# exceptions for files that aren't complaint.
......
/*
* Copyright (c) 2013, Google Inc.
* Written by Simon Glass <sjg@chromium.org>
*
* SPDX-License-Identifier: GPL-2.0+
*
* Perform a grep of an FDT either displaying the source subset or producing
* a new .dtb subset which can be used as required.
*/
#include <assert.h>
#include <ctype.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <../include/libfdt.h>
#include <libfdt_internal.h>
/* Define DEBUG to get some debugging output on stderr */
#ifdef DEBUG
#define debug(a, b...) fprintf(stderr, a, ## b)
#else
#define debug(a, b...)
#endif
/* A linked list of values we are grepping for */
struct value_node {
int type; /* Types this value matches (FDT_IS... mask) */
int include; /* 1 to include matches, 0 to exclude */
const char *string; /* String to match */
struct value_node *next; /* Pointer to next node, or NULL */
};
/* Output formats we support */
enum output_t {
OUT_DTS, /* Device tree source */
OUT_DTB, /* Valid device tree binary */
OUT_BIN, /* Fragment of .dtb, for hashing */
};
/* Holds information which controls our output and options */
struct display_info {
enum output_t output; /* Output format */
int add_aliases; /* Add aliases node to output */
int all; /* Display all properties/nodes */
int colour; /* Display output in ANSI colour */
int region_list; /* Output a region list */
int flags; /* Flags (FDT_REG_...) */
int list_strings; /* List strings in string table */
int show_offset; /* Show offset */
int show_addr; /* Show address */
int header; /* Output an FDT header */
int diff; /* Show +/- diff markers */
int include_root; /* Include the root node and all properties */
int remove_strings; /* Remove unused strings */
int show_dts_version; /* Put '/dts-v1/;' on the first line */
int types_inc; /* Mask of types that we include (FDT_IS...) */
int types_exc; /* Mask of types that we exclude (FDT_IS...) */
int invert; /* Invert polarity of match */
struct value_node *value_head; /* List of values to match */
const char *output_fname; /* Output filename */
FILE *fout; /* File to write dts/dtb output */
};
static void report_error(const char *where, int err)
{
fprintf(stderr, "Error at '%s': %s\n", where, fdt_strerror(err));
}
/* Supported ANSI colours */
enum {
COL_BLACK,
COL_RED,
COL_GREEN,
COL_YELLOW,
COL_BLUE,
COL_MAGENTA,
COL_CYAN,
COL_WHITE,
COL_NONE = -1,
};
/**
* print_ansi_colour() - Print out the ANSI sequence for a colour
*
* @fout: Output file
* @col: Colour to output (COL_...), or COL_NONE to reset colour
*/
static void print_ansi_colour(FILE *fout, int col)
{
if (col == COL_NONE)
fprintf(fout, "\033[0m");
else
fprintf(fout, "\033[1;%dm", col + 30);
}
/**
* value_add() - Add a new value to our list of things to grep for
*
* @disp: Display structure, holding info about our options
* @headp: Pointer to header pointer of list
* @type: Type of this value (FDT_IS_...)
* @include: 1 if we want to include matches, 0 to exclude
* @str: String value to match
*/
static int value_add(struct display_info *disp, struct value_node **headp,
int type, int include, const char *str)
{
struct value_node *node;
/*
* Keep track of which types we are excluding/including. We don't
* allow both including and excluding things, because it doesn't make
* sense. 'Including' means that everything not mentioned is
* excluded. 'Excluding' means that everything not mentioned is
* included. So using the two together would be meaningless.
*/
if (include)
disp->types_inc |= type;
else
disp->types_exc |= type;
if (disp->types_inc & disp->types_exc & type) {
fprintf(stderr,
"Cannot use both include and exclude for '%s'\n", str);
return -1;
}
str = strdup(str);
node = malloc(sizeof(*node));
if (!str || !node) {
fprintf(stderr, "Out of memory\n");
return -1;
}
node->next = *headp;
node->type = type;
node->include = include;
node->string = str;
*headp = node;
return 0;
}
static bool util_is_printable_string(const void *data, int len)
{
const char *s = data;
const char *ss, *se;
/* zero length is not */
if (len == 0)
return 0;
/* must terminate with zero */
if (s[len - 1] != '\0')
return 0;
se = s + len;
while (s < se) {
ss = s;
while (s < se && *s && isprint((unsigned char)*s))
s++;
/* not zero, or not done yet */
if (*s != '\0' || s == ss)
return 0;
s++;
}
return 1;
}
static void utilfdt_print_data(const char *data, int len)
{
int i;
const char *p = data;
const char *s;
/* no data, don't print */
if (len == 0)
return;
if (util_is_printable_string(data, len)) {
printf(" = ");
s = data;
do {
printf("\"%s\"", s);
s += strlen(s) + 1;
if (s < data + len)
printf(", ");
} while (s < data + len);
} else if ((len % 4) == 0) {
const uint32_t *cell = (const uint32_t *)data;
printf(" = <");
for (i = 0, len /= 4; i < len; i++)
printf("0x%08x%s", fdt32_to_cpu(cell[i]),
i < (len - 1) ? " " : "");
printf(">");
} else {
printf(" = [");
for (i = 0; i < len; i++)
printf("%02x%s", *p++, i < len - 1 ? " " : "");
printf("]");
}
}
/**
* display_fdt_by_regions() - Display regions of an FDT source
*
* This dumps an FDT as source, but only certain regions of it. This is the
* final stage of the grep - we have a list of regions we want to display,
* and this function displays them.
*
* @disp: Display structure, holding info about our options
* @blob: FDT blob to display
* @region: List of regions to display
* @count: Number of regions
*/
static int display_fdt_by_regions(struct display_info *disp, const void *blob,
struct fdt_region region[], int count)
{
struct fdt_region *reg = region, *reg_end = region + count;
uint32_t off_mem_rsvmap = fdt_off_mem_rsvmap(blob);
int base = fdt_off_dt_struct(blob);
int version = fdt_version(blob);
int offset, nextoffset;
int tag, depth, shift;
FILE *f = disp->fout;
uint64_t addr, size;
int in_region;
int file_ofs;
int i;
if (disp->show_dts_version)
fprintf(f, "/dts-v1/;\n");
if (disp->header) {
fprintf(f, "// magic:\t\t0x%x\n", fdt_magic(blob));
fprintf(f, "// totalsize:\t\t0x%x (%d)\n", fdt_totalsize(blob),
fdt_totalsize(blob));
fprintf(f, "// off_dt_struct:\t0x%x\n",
fdt_off_dt_struct(blob));
fprintf(f, "// off_dt_strings:\t0x%x\n",
fdt_off_dt_strings(blob));
fprintf(f, "// off_mem_rsvmap:\t0x%x\n", off_mem_rsvmap);
fprintf(f, "// version:\t\t%d\n", version);
fprintf(f, "// last_comp_version:\t%d\n",
fdt_last_comp_version(blob));
if (version >= 2) {
fprintf(f, "// boot_cpuid_phys:\t0x%x\n",
fdt_boot_cpuid_phys(blob));
}
if (version >= 3) {
fprintf(f, "// size_dt_strings:\t0x%x\n",
fdt_size_dt_strings(blob));
}
if (version >= 17) {
fprintf(f, "// size_dt_struct:\t0x%x\n",
fdt_size_dt_struct(blob));
}
fprintf(f, "\n");
}
if (disp->flags & FDT_REG_ADD_MEM_RSVMAP) {
const struct fdt_reserve_entry *p_rsvmap;
p_rsvmap = (const struct fdt_reserve_entry *)
((const char *)blob + off_mem_rsvmap);
for (i = 0; ; i++) {
addr = fdt64_to_cpu(p_rsvmap[i].address);
size = fdt64_to_cpu(p_rsvmap[i].size);
if (addr == 0 && size == 0)
break;
fprintf(f, "/memreserve/ %llx %llx;\n",
(unsigned long long)addr,
(unsigned long long)size);
}
}
depth = 0;
nextoffset = 0;
shift = 4; /* 4 spaces per indent */
do {
const struct fdt_property *prop;
const char *name;
int show;
int len;
offset = nextoffset;
/*
* Work out the file offset of this offset, and decide
* whether it is in the region list or not
*/
file_ofs = base + offset;
if (reg < reg_end && file_ofs >= reg->offset + reg->size)
reg++;
in_region = reg < reg_end && file_ofs >= reg->offset &&
file_ofs < reg->offset + reg->size;
tag = fdt_next_tag(blob, offset, &nextoffset);
if (tag == FDT_END)
break;
show = in_region || disp->all;
if (show && disp->diff)
fprintf(f, "%c", in_region ? '+' : '-');
if (!show) {
/* Do this here to avoid 'if (show)' in every 'case' */
if (tag == FDT_BEGIN_NODE)
depth++;
else if (tag == FDT_END_NODE)
depth--;
continue;
}
if (tag != FDT_END) {
if (disp->show_addr)
fprintf(f, "%4x: ", file_ofs);
if (disp->show_offset)
fprintf(f, "%4x: ", file_ofs - base);
}
/* Green means included, red means excluded */
if (disp->colour)
print_ansi_colour(f, in_region ? COL_GREEN : COL_RED);
switch (tag) {
case FDT_PROP:
prop = fdt_get_property_by_offset(blob, offset, NULL);
name = fdt_string(blob, fdt32_to_cpu(prop->nameoff));
fprintf(f, "%*s%s", depth * shift, "", name);
utilfdt_print_data(prop->data,
fdt32_to_cpu(prop->len));
fprintf(f, ";");
break;
case FDT_NOP:
fprintf(f, "%*s// [NOP]", depth * shift, "");
break;
case FDT_BEGIN_NODE:
name = fdt_get_name(blob, offset, &len);
fprintf(f, "%*s%s {", depth++ * shift, "",
*name ? name : "/");
break;
case FDT_END_NODE:
fprintf(f, "%*s};", --depth * shift, "");
break;
}
/* Reset colour back to normal before end of line */
if (disp->colour)
print_ansi_colour(f, COL_NONE);
fprintf(f, "\n");
} while (1);
/* Print a list of strings if requested */
if (disp->list_strings) {
const char *str;
int str_base = fdt_off_dt_strings(blob);
for (offset = 0; offset < fdt_size_dt_strings(blob);
offset += strlen(str) + 1) {
str = fdt_string(blob, offset);
int len = strlen(str) + 1;
int show;
/* Only print strings that are in the region */
file_ofs = str_base + offset;
in_region = reg < reg_end &&
file_ofs >= reg->offset &&
file_ofs + len < reg->offset +
reg->size;
show = in_region || disp->all;
if (show && disp->diff)
printf("%c", in_region ? '+' : '-');
if (disp->show_addr)
printf("%4x: ", file_ofs);
if (disp->show_offset)
printf("%4x: ", offset);
printf("%s\n", str);
}
}
return 0;
}
/**
* dump_fdt_regions() - Dump regions of an FDT as binary data
*
* This dumps an FDT as binary, but only certain regions of it. This is the
* final stage of the grep - we have a list of regions we want to dump,
* and this function dumps them.
*
* The output of this function may or may not be a valid FDT. To ensure it
* is, these disp->flags must be set:
*
* FDT_REG_SUPERNODES: ensures that subnodes are preceeded by their
* parents. Without this option, fragments of subnode data may be
* output without the supernodes above them. This is useful for
* hashing but cannot produce a valid FDT.
* FDT_REG_ADD_STRING_TAB: Adds a string table to the end of the FDT.
* Without this none of the properties will have names
* FDT_REG_ADD_MEM_RSVMAP: Adds a mem_rsvmap table - an FDT is invalid
* without this.
*
* @disp: Display structure, holding info about our options
* @blob: FDT blob to display
* @region: List of regions to display
* @count: Number of regions
* @out: Output destination
*/
static int dump_fdt_regions(struct display_info *disp, const void *blob,
struct fdt_region region[], int count, char *out)
{
struct fdt_header *fdt;
int size, struct_start;
int ptr;
int i;
/* Set up a basic header (even if we don't actually write it) */
fdt = (struct fdt_header *)out;
memset(fdt, '\0', sizeof(*fdt));
fdt_set_magic(fdt, FDT_MAGIC);
struct_start = FDT_ALIGN(sizeof(struct fdt_header),
sizeof(struct fdt_reserve_entry));
fdt_set_off_mem_rsvmap(fdt, struct_start);
fdt_set_version(fdt, FDT_LAST_SUPPORTED_VERSION);
fdt_set_last_comp_version(fdt, FDT_FIRST_SUPPORTED_VERSION);
/*
* Calculate the total size of the regions we are writing out. The
* first will be the mem_rsvmap if the FDT_REG_ADD_MEM_RSVMAP flag
* is set. The last will be the string table if FDT_REG_ADD_STRING_TAB
* is set.
*/
for (i = size = 0; i < count; i++)
size += region[i].size;
/* Bring in the mem_rsvmap section from the old file if requested */
if (count > 0 && (disp->flags & FDT_REG_ADD_MEM_RSVMAP)) {
struct_start += region[0].size;
size -= region[0].size;
}
fdt_set_off_dt_struct(fdt, struct_start);
/* Update the header to have the correct offsets/sizes */
if (count >= 2 && (disp->flags & FDT_REG_ADD_STRING_TAB)) {
int str_size;
str_size = region[count - 1].size;
fdt_set_size_dt_struct(fdt, size - str_size);
fdt_set_off_dt_strings(fdt, struct_start + size - str_size);
fdt_set_size_dt_strings(fdt, str_size);
fdt_set_totalsize(fdt, struct_start + size);
}
/* Write the header if required */
ptr = 0;
if (disp->header) {
ptr = sizeof(*fdt);
while (ptr < fdt_off_mem_rsvmap(fdt))
out[ptr++] = '\0';
}
/* Output all the nodes including any mem_rsvmap/string table */
for (i = 0; i < count; i++) {
struct fdt_region *reg = &region[i];
memcpy(out + ptr, (const char *)blob + reg->offset, reg->size);
ptr += reg->size;
}
return ptr;
}
/**
* show_region_list() - Print out a list of regions
*
* The list includes the region offset (absolute offset from start of FDT
* blob in bytes) and size
*
* @reg: List of regions to print
* @count: Number of regions
*/
static void show_region_list(struct fdt_region *reg, int count)
{
int i;
printf("Regions: %d\n", count);
for (i = 0; i < count; i++, reg++) {
printf("%d: %-10x %-10x\n", i, reg->offset,
reg->offset + reg->size);
}
}
static int check_type_include(void *priv, int type, const char *data, int size)
{
struct display_info *disp = priv;
struct value_node *val;
int match, none_match = FDT_IS_ANY;
/* If none of our conditions mention this type, we know nothing */
debug("type=%x, data=%s\n", type, data ? data : "(null)");
if (!((disp->types_inc | disp->types_exc) & type)) {
debug(" - not in any condition\n");
return -1;
}
/*
* Go through the list of conditions. For inclusive conditions, we
* return 1 at the first match. For exclusive conditions, we must
* check that there are no matches.
*/
for (val = disp->value_head; val; val = val->next) {
if (!(type & val->type))
continue;
match = fdt_stringlist_contains(data, size, val->string);
debug(" - val->type=%x, str='%s', match=%d\n",
val->type, val->string, match);
if (match && val->include) {
debug(" - match inc %s\n", val->string);
return 1;
}
if (match)
none_match &= ~val->type;
}
/*
* If this is an exclusive condition, and nothing matches, then we
* should return 1.
*/
if ((type & disp->types_exc) && (none_match & type)) {
debug(" - match exc\n");
/*
* Allow FDT_IS_COMPAT to make the final decision in the
* case where there is no specific type
*/
if (type == FDT_IS_NODE && disp->types_exc == FDT_ANY_GLOBAL) {
debug(" - supressed exc node\n");
return -1;
}
return 1;
}
/*
* Allow FDT_IS_COMPAT to make the final decision in the
* case where there is no specific type (inclusive)
*/
if (type == FDT_IS_NODE && disp->types_inc == FDT_ANY_GLOBAL)
return -1;
debug(" - no match, types_inc=%x, types_exc=%x, none_match=%x\n",
disp->types_inc, disp->types_exc, none_match);
return 0;
}
/**
* h_include() - Include handler function for fdt_find_regions()
*
* This function decides whether to include or exclude a node, property or
* compatible string. The function is defined by fdt_find_regions().
*
* The algorithm is documented in the code - disp->invert is 0 for normal
* operation, and 1 to invert the sense of all matches.
*
* See
*/
static int h_include(void *priv, const void *fdt, int offset, int type,
const char *data, int size)
{
struct display_info *disp = priv;
int inc, len;
inc = check_type_include(priv, type, data, size);
if (disp->include_root && type == FDT_IS_PROP && offset == 0 && inc)
return 1;
/*
* If the node name does not tell us anything, check the
* compatible string
*/
if (inc == -1 && type == FDT_IS_NODE) {
debug(" - checking compatible2\n");
data = fdt_getprop(fdt, offset, "compatible", &len);
inc = check_type_include(priv, FDT_IS_COMPAT, data, len);
}
/* If we still have no idea, check for properties in the node */
if (inc != 1 && type == FDT_IS_NODE &&
(disp->types_inc & FDT_NODE_HAS_PROP)) {
debug(" - checking node '%s'\n",
fdt_get_name(fdt, offset, NULL));
for (offset = fdt_first_property_offset(fdt, offset);
offset > 0 && inc != 1;
offset = fdt_next_property_offset(fdt, offset)) {
const struct fdt_property *prop;
const char *str;