2 * Copyright (c) 2013 David Chisnall
5 * This software was developed by SRI International and the University of
6 * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
7 * ("CTSRD"), as part of the DARPA CRASH research programme.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <unordered_map>
36 #include <unordered_set>
58 * Type for (owned) pointers to properties.
60 typedef std::shared_ptr<property> property_ptr;
62 * Owning pointer to a node.
64 typedef std::unique_ptr<node> node_ptr;
66 * Map from macros to property pointers.
68 typedef std::unordered_map<string, property_ptr> define_map;
70 * Properties may contain a number of different value, each with a different
71 * label. This class encapsulates a single value.
76 * The label for this data. This is usually empty.
80 * If this value is a string, or something resolved from a string (a
81 * reference) then this contains the source string.
85 * The data that should be written to the final output.
87 byte_buffer byte_data;
89 * Enumeration describing the possible types of a value. Note that
90 * property-coded arrays will appear simply as binary (or possibly
91 * string, if they happen to be nul-terminated and printable), and must
92 * be checked separately.
97 * This is a list of strings. When read from source, string
98 * lists become one property value for each string, however
99 * when read from binary we have a single property value
100 * incorporating the entire text, with nul bytes separating the
105 * This property contains a single string.
109 * This is a binary value. Check the size of byte_data to
110 * determine how many bytes this contains.
113 /** This contains a short-form address that should be replaced
114 * by a fully-qualified version. This will only appear when
115 * the input is a device tree source. When parsed from a
116 * device tree blob, the cross reference will have already been
117 * resolved and the property value will be a string containing
118 * the full path of the target node. */
121 * This is a phandle reference. When parsed from source, the
122 * string_data will contain the node label for the target and,
123 * after cross references have been resolved, the binary data
124 * will contain a 32-bit integer that should match the phandle
125 * property of the target node.
129 * An empty property value. This will never appear on a real
130 * property value, it is used by checkers to indicate that no
131 * property values should exist for a property.
135 * The type of this property has not yet been determined.
140 * The type of this property.
144 * Returns true if this value is a cross reference, false otherwise.
146 inline bool is_cross_reference()
148 return is_type(CROSS_REFERENCE);
151 * Returns true if this value is a phandle reference, false otherwise.
153 inline bool is_phandle()
155 return is_type(PHANDLE);
158 * Returns true if this value is a string, false otherwise.
160 inline bool is_string()
162 return is_type(STRING);
165 * Returns true if this value is a string list (a nul-separated
166 * sequence of strings), false otherwise.
168 inline bool is_string_list()
170 return is_type(STRING_LIST);
173 * Returns true if this value is binary, false otherwise.
175 inline bool is_binary()
177 return is_type(BINARY);
180 * Returns this property value as a 32-bit integer. Returns 0 if this
181 * property value is not 32 bits long. The bytes in the property value
182 * are assumed to be in big-endian format, but the return value is in
183 * the host native endian.
185 uint32_t get_as_uint32();
187 * Default constructor, specifying the label of the value.
189 property_value(string l=string()) : label(l), type(UNKNOWN) {}
191 * Writes the data for this value into an output buffer.
193 void push_to_buffer(byte_buffer &buffer);
196 * Writes the property value to the standard output. This uses the
197 * following heuristics for deciding how to print the output:
199 * - If the value is nul-terminated and only contains printable
200 * characters, it is written as a string.
201 * - If it is a multiple of 4 bytes long, then it is printed as cells.
202 * - Otherwise, it is printed as a byte buffer.
204 void write_dts(FILE *file);
206 * Tries to merge adjacent property values, returns true if it succeeds and
209 bool try_to_merge(property_value &other);
212 * Returns whether the value is of the specified type. If the type of
213 * the value has not yet been determined, then this calculates it.
215 inline bool is_type(value_type v)
224 * Determines the type of the value based on its contents.
228 * Writes the property value to the specified file as a quoted string.
229 * This is used when generating DTS.
231 void write_as_string(FILE *file);
233 * Writes the property value to the specified file as a sequence of
234 * 32-bit big-endian cells. This is used when generating DTS.
236 void write_as_cells(FILE *file);
238 * Writes the property value to the specified file as a sequence of
239 * bytes. This is used when generating DTS.
241 void write_as_bytes(FILE *file);
245 * A value encapsulating a single property. This contains a key, optionally a
246 * label, and optionally one or more values.
251 * The name of this property.
259 * The values in this property.
261 std::vector<property_value> values;
263 * Value indicating that this is a valid property. If a parse error
264 * occurs, then this value is false.
268 * Parses a string property value, i.e. a value enclosed in double quotes.
270 void parse_string(input_buffer &input);
272 * Parses one or more 32-bit values enclosed in angle brackets.
274 void parse_cells(input_buffer &input, int cell_size);
276 * Parses an array of bytes, contained within square brackets.
278 void parse_bytes(input_buffer &input);
280 * Parses a reference. This is a node label preceded by an ampersand
281 * symbol, which should expand to the full path to that node.
283 * Note: The specification says that the target of such a reference is
284 * a node name, however dtc assumes that it is a label, and so we
285 * follow their interpretation for compatibility.
287 void parse_reference(input_buffer &input);
289 * Parse a predefined macro definition for a property.
291 void parse_define(input_buffer &input, define_map *defines);
293 * Constructs a new property from two input buffers, pointing to the
294 * struct and strings tables in the device tree blob, respectively.
295 * The structs input buffer is assumed to have just consumed the
298 property(input_buffer &structs, input_buffer &strings);
300 * Parses a new property from the input buffer.
302 property(input_buffer &input,
306 define_map *defines);
309 * Creates an empty property.
311 property(string k, string l=string()) : key(k), label(l), valid(true)
316 property(property &p) : key(p.key), label(p.label), values(p.values),
319 * Factory method for constructing a new property. Attempts to parse a
320 * property from the input, and returns it on success. On any parse
321 * error, this will return 0.
323 static property_ptr parse_dtb(input_buffer &structs,
324 input_buffer &strings);
326 * Factory method for constructing a new property. Attempts to parse a
327 * property from the input, and returns it on success. On any parse
328 * error, this will return 0.
330 static property_ptr parse(input_buffer &input,
332 string label=string(),
333 bool semicolonTerminated=true,
334 define_map *defines=0);
336 * Iterator type used for accessing the values of a property.
338 typedef std::vector<property_value>::iterator value_iterator;
340 * Returns an iterator referring to the first value in this property.
342 inline value_iterator begin()
344 return values.begin();
347 * Returns an iterator referring to the last value in this property.
349 inline value_iterator end()
354 * Adds a new value to an existing property.
356 inline void add_value(property_value v)
361 * Returns the key for this property.
363 inline string get_key()
368 * Writes the property to the specified writer. The property name is a
369 * reference into the strings table.
371 void write(dtb::output_writer &writer, dtb::string_table &strings);
373 * Writes in DTS format to the specified file, at the given indent
374 * level. This will begin the line with the number of tabs specified
375 * as the indent level and then write the property in the most
376 * applicable way that it can determine.
378 void write_dts(FILE *file, int indent);
382 * Class encapsulating a device tree node. Nodes may contain properties and
389 * The label for this node, if any. Node labels are used as the
390 * targets for cross references.
394 * The name of the node.
398 * The unit address of the node, which is optionally written after the
399 * name followed by an at symbol.
403 * The type for the property vector.
405 typedef std::vector<property_ptr> property_vector;
407 * Iterator type for child nodes.
409 typedef std::vector<node_ptr>::iterator child_iterator;
412 * Adaptor to use children in range-based for loops.
416 child_range(node &nd) : n(nd) {}
417 child_iterator begin() { return n.child_begin(); }
418 child_iterator end() { return n.child_end(); }
423 * Adaptor to use properties in range-based for loops.
425 struct property_range
427 property_range(node &nd) : n(nd) {}
428 property_vector::iterator begin() { return n.property_begin(); }
429 property_vector::iterator end() { return n.property_end(); }
434 * The properties contained within this node.
436 property_vector props;
438 * The children of this node.
440 std::vector<node_ptr> children;
442 * A flag indicating whether this node is valid. This is set to false
443 * if an error occurs during parsing.
447 * Parses a name inside a node, writing the string passed as the last
448 * argument as an error if it fails.
450 string parse_name(input_buffer &input,
454 * Constructs a new node from two input buffers, pointing to the struct
455 * and strings tables in the device tree blob, respectively.
457 node(input_buffer &structs, input_buffer &strings);
459 * Parses a new node from the specified input buffer. This is called
460 * when the input cursor is on the open brace for the start of the
461 * node. The name, and optionally label and unit address, should have
462 * already been parsed.
464 node(input_buffer &input, string n, string l, string a, define_map*);
466 * Comparison function for properties, used when sorting the properties
467 * vector. Orders the properties based on their names.
469 static inline bool cmp_properties(property_ptr &p1, property_ptr &p2);
472 return p1->get_key() < p2->get_key();
476 * Comparison function for nodes, used when sorting the children
477 * vector. Orders the nodes based on their names or, if the names are
478 * the same, by the unit addresses.
480 static inline bool cmp_children(node_ptr &c1, node_ptr &c2);
483 * Sorts the node's properties and children into alphabetical order and
484 * recursively sorts the children.
488 * Returns an iterator for the first child of this node.
490 inline child_iterator child_begin()
492 return children.begin();
495 * Returns an iterator after the last child of this node.
497 inline child_iterator child_end()
499 return children.end();
501 inline child_range child_nodes()
503 return child_range(*this);
505 inline property_range properties()
507 return property_range(*this);
510 * Returns an iterator after the last property of this node.
512 inline property_vector::iterator property_begin()
514 return props.begin();
517 * Returns an iterator for the first property of this node.
519 inline property_vector::iterator property_end()
524 * Factory method for constructing a new node. Attempts to parse a
525 * node in DTS format from the input, and returns it on success. On
526 * any parse error, this will return 0. This should be called with the
527 * cursor on the open brace of the property, after the name and so on
530 static node_ptr parse(input_buffer &input,
532 string label=string(),
533 string address=string(),
534 define_map *defines=0);
536 * Factory method for constructing a new node. Attempts to parse a
537 * node in DTB format from the input, and returns it on success. On
538 * any parse error, this will return 0. This should be called with the
539 * cursor on the open brace of the property, after the name and so on
542 static node_ptr parse_dtb(input_buffer &structs, input_buffer &strings);
544 * Returns a property corresponding to the specified key, or 0 if this
545 * node does not contain a property of that name.
547 property_ptr get_property(string key);
549 * Adds a new property to this node.
551 inline void add_property(property_ptr &p)
556 * Merges a node into this one. Any properties present in both are
557 * overridden, any properties present in only one are preserved.
559 void merge_node(node_ptr other);
561 * Write this node to the specified output. Although nodes do not
562 * refer to a string table directly, their properties do. The string
563 * table passed as the second argument is used for the names of
564 * properties within this node and its children.
566 void write(dtb::output_writer &writer, dtb::string_table &strings);
568 * Writes the current node as DTS to the specified file. The second
569 * parameter is the indent level. This function will start every line
570 * with this number of tabs.
572 void write_dts(FILE *file, int indent);
574 * Recursively visit this node and then its children.
576 void visit(std::function<void(node&)>);
580 * Class encapsulating the entire parsed FDT. This is the top-level class,
581 * which parses the entire DTS representation and write out the finished
588 * Type used for node paths. A node path is sequence of names and unit
591 typedef std::vector<std::pair<string,string> > node_path;
593 * Name that we should use for phandle nodes.
601 /** Create both nodes. */
606 * The format that we should use for writing phandles.
608 phandle_format phandle_node_name;
610 * Flag indicating that this tree is valid. This will be set to false
615 * Type used for memory reservations. A reservation is two 64-bit
616 * values indicating a base address and length in memory that the
617 * kernel should not use. The high 32 bits are ignored on 32-bit
620 typedef std::pair<uint64_t, uint64_t> reservation;
622 * The memory reserves table.
624 std::vector<reservation> reservations;
626 * Root node. All other nodes are children of this node.
630 * Mapping from names to nodes. Only unambiguous names are recorded,
631 * duplicate names are stored as (node*)-1.
633 std::unordered_map<string, node*> node_names;
635 * A map from labels to node paths. When resolving cross references,
636 * we look up referenced nodes in this and replace the cross reference
637 * with the full path to its target.
639 std::unordered_map<string, node_path> node_paths;
641 * A collection of property values that are references to other nodes.
642 * These should be expanded to the full path of their targets.
644 std::vector<property_value*> cross_references;
646 * A collection of property values that refer to phandles. These will
647 * be replaced by the value of the phandle property in their
650 std::vector<property_value*> phandles;
652 * The names of nodes that target phandles.
654 std::unordered_set<string> phandle_targets;
656 * A collection of input buffers that we are using. These input
657 * buffers are the ones that own their memory, and so we must preserve
658 * them for the lifetime of the device tree.
660 std::vector<std::unique_ptr<input_buffer>> buffers;
662 * A map of used phandle values to nodes. All phandles must be unique,
663 * so we keep a set of ones that the user explicitly provides in the
664 * input to ensure that we don't reuse them.
666 * This is a map, rather than a set, because we also want to be able to
667 * find phandles that were provided by the user explicitly when we are
670 std::unordered_map<uint32_t, node*> used_phandles;
672 * Paths to search for include files. This contains a set of
673 * nul-terminated strings, which are not owned by this class and so
674 * must be freed separately.
676 std::vector<std::string> include_paths;
678 * Dictionary of predefined macros provided on the command line.
682 * The default boot CPU, specified in the device tree header.
686 * The number of empty reserve map entries to generate in the blob.
688 uint32_t spare_reserve_map_entries;
690 * The minimum size in bytes of the blob.
692 uint32_t minimum_blob_size;
694 * The number of bytes of padding to add to the end of the blob.
696 uint32_t blob_padding;
698 * Visit all of the nodes recursively, and if they have labels then add
699 * them to the node_paths and node_names vectors so that they can be
700 * used in resolving cross references. Also collects phandle
701 * properties that have been explicitly added.
703 void collect_names_recursive(node_ptr &n, node_path &path);
705 * Assign phandle properties to all nodes that have been referenced and
706 * require one. This method will recursively visit the tree starting at
707 * the node that it is passed.
709 void assign_phandles(node_ptr &n, uint32_t &next);
711 * Calls the recursive version of this method on every root node.
713 void collect_names();
715 * Resolves all cross references. Any properties that refer to another
716 * node must have their values replaced by either the node path or
719 void resolve_cross_references();
721 * Parse a top-level include directive.
723 bool parse_include(input_buffer &input,
724 const std::string &dir,
725 std::vector<node_ptr> &roots,
729 * Parses a dts file in the given buffer and adds the roots to the parsed
730 * set. The `read_header` argument indicates whether the header has
731 * already been read. Some dts files place the header in an include,
732 * rather than in the top-level file.
734 void parse_file(input_buffer &input,
735 const std::string &dir,
736 std::vector<node_ptr> &roots,
740 * Allocates a new mmap()'d input buffer for use in parsing. This
741 * object then keeps a reference to it, ensuring that it is not
742 * deallocated until the device tree is destroyed.
744 input_buffer *buffer_for_file(const char *path, bool warn=true);
746 * Template function that writes a dtb blob using the specified writer.
747 * The writer defines the output format (assembly, blob).
749 template<class writer>
753 * Returns the node referenced by the property. If this is a tree that
754 * is in source form, then we have a string that we can use to index
755 * the cross_references array and so we can just look that up.
757 node *referenced_node(property_value &v);
759 * Writes this FDT as a DTB to the specified output.
761 void write_binary(int fd);
763 * Writes this FDT as an assembly representation of the DTB to the
764 * specified output. The result can then be assembled and linked into
767 void write_asm(int fd);
769 * Writes the tree in DTS (source) format.
771 void write_dts(int fd);
773 * Default constructor. Creates a valid, but empty FDT.
775 device_tree() : phandle_node_name(EPAPR), valid(true),
776 boot_cpu(0), spare_reserve_map_entries(0),
777 minimum_blob_size(0), blob_padding(0) {}
779 * Constructs a device tree from the specified file name, referring to
780 * a file that contains a device tree blob.
782 void parse_dtb(const char *fn, FILE *depfile);
784 * Constructs a device tree from the specified file name, referring to
785 * a file that contains device tree source.
787 void parse_dts(const char *fn, FILE *depfile);
789 * Returns whether this tree is valid.
791 inline bool is_valid()
796 * Sets the format for writing phandle properties.
798 inline void set_phandle_format(phandle_format f)
800 phandle_node_name = f;
803 * Returns a pointer to the root node of this tree. No ownership
806 inline const node_ptr &get_root() const
811 * Sets the physical boot CPU.
813 void set_boot_cpu(uint32_t cpu)
818 * Sorts the tree. Useful for debugging device trees.
825 * Adds a path to search for include files. The argument must be a
826 * nul-terminated string representing the path. The device tree keeps
827 * a pointer to this string, but does not own it: the caller is
828 * responsible for freeing it if required.
830 void add_include_path(const char *path)
833 include_paths.push_back(std::move(p));
836 * Sets the number of empty reserve map entries to add.
838 void set_empty_reserve_map_entries(uint32_t e)
840 spare_reserve_map_entries = e;
843 * Sets the minimum size, in bytes, of the blob.
845 void set_blob_minimum_size(uint32_t s)
847 minimum_blob_size = s;
850 * Sets the amount of padding to add to the blob.
852 void set_blob_padding(uint32_t p)
857 * Parses a predefined macro value.
859 bool parse_define(const char *def);