1/*-
2 * Copyright (c) 2013 David Chisnall
3 * All rights reserved.
4 *
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.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
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.
17 *
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
28 * SUCH DAMAGE.
29 *
30 * $FreeBSD$
31 */
32
33#ifndef _FDT_HH_
34#define _FDT_HH_
35#include <map>
36
37#include "util.hh"
38#include "string.hh"
39
40namespace dtc
41{
42
43namespace dtb
44{
45struct output_writer;
46class string_table;
47}
48
49namespace fdt
50{
51class property;
52typedef std::map<string, property*> define_map;
53/**
54 * Properties may contain a number of different value, each with a different
55 * label.  This class encapsulates a single value.
56 */
57struct property_value
58{
59	/**
60	 * The label for this data.  This is usually empty.
61	 */
62	string label;
63	/**
64	 * If this value is a string, or something resolved from a string (a
65	 * reference) then this contains the source string.
66	 */
67	string string_data;
68	/**
69	 * The data that should be written to the final output.
70	 */
71	byte_buffer byte_data;
72	/**
73	 * Enumeration describing the possible types of a value.  Note that
74	 * property-coded arrays will appear simply as binary (or possibly
75	 * string, if they happen to be nul-terminated and printable), and must
76	 * be checked separately.
77	 */
78	enum value_type
79	{
80		/**
81		 * This is a list of strings.  When read from source, string
82		 * lists become one property value for each string, however
83		 * when read from binary we have a single property value
84		 * incorporating the entire text, with nul bytes separating the
85		 * strings.
86		 */
87		STRING_LIST,
88		/**
89		 * This property contains a single string.
90		 */
91		STRING,
92		/**
93		 * This is a binary value.  Check the size of byte_data to
94		 * determine how many bytes this contains.
95		 */
96		BINARY,
97		/** This contains a short-form address that should be replaced
98		 * by a fully-qualified version.  This will only appear when
99		 * the input is a device tree source.  When parsed from a
100		 * device tree blob, the cross reference will have already been
101		 * resolved and the property value will be a string containing
102		 * the full path of the target node.  */
103		CROSS_REFERENCE,
104		/**
105		 * This is a phandle reference.  When parsed from source, the
106		 * string_data will contain the node label for the target and,
107		 * after cross references have been resolved, the binary data
108		 * will contain a 32-bit integer that should match the phandle
109		 * property of the target node.
110		 */
111		PHANDLE,
112		/**
113		 * An empty property value.  This will never appear on a real
114		 * property value, it is used by checkers to indicate that no
115		 * property values should exist for a property.
116		 */
117		EMPTY,
118		/**
119		 * The type of this property has not yet been determined.
120		 */
121		UNKNOWN
122	};
123	/**
124	 * The type of this property.
125	 */
126	value_type type;
127	/**
128	 * Returns true if this value is a cross reference, false otherwise.
129	 */
130	inline bool is_cross_reference()
131	{
132		return is_type(CROSS_REFERENCE);
133	}
134	/**
135	 * Returns true if this value is a phandle reference, false otherwise.
136	 */
137	inline bool is_phandle()
138	{
139		return is_type(PHANDLE);
140	}
141	/**
142	 * Returns true if this value is a string, false otherwise.
143	 */
144	inline bool is_string()
145	{
146		return is_type(STRING);
147	}
148	/**
149	 * Returns true if this value is a string list (a nul-separated
150	 * sequence of strings), false otherwise.
151	 */
152	inline bool is_string_list()
153	{
154		return is_type(STRING_LIST);
155	}
156	/**
157	 * Returns true if this value is binary, false otherwise.
158	 */
159	inline bool is_binary()
160	{
161		return is_type(BINARY);
162	}
163	/**
164	 * Returns this property value as a 32-bit integer.  Returns 0 if this
165	 * property value is not 32 bits long.  The bytes in the property value
166	 * are assumed to be in big-endian format, but the return value is in
167	 * the host native endian.
168	 */
169	uint32_t get_as_uint32();
170	/**
171	 * Default constructor, specifying the label of the value.
172	 */
173	property_value(string l=string()) : label(l), type(UNKNOWN) {}
174	/**
175	 * Writes the data for this value into an output buffer.
176	 */
177	void push_to_buffer(byte_buffer &buffer);
178
179	/**
180	 * Writes the property value to the standard output.  This uses the
181	 * following heuristics for deciding how to print the output:
182	 *
183	 * - If the value is nul-terminated and only contains printable
184	 *   characters, it is written as a string.
185	 * - If it is a multiple of 4 bytes long, then it is printed as cells.
186	 * - Otherwise, it is printed as a byte buffer.
187	 */
188	void write_dts(FILE *file);
189	private:
190	/**
191	 * Returns whether the value is of the specified type.  If the type of
192	 * the value has not yet been determined, then this calculates it.
193	 */
194	inline bool is_type(value_type v)
195	{
196		if (type == UNKNOWN)
197		{
198			resolve_type();
199		}
200		return type == v;
201	}
202	/**
203	 * Determines the type of the value based on its contents.
204	 */
205	void resolve_type();
206	/**
207	 * Writes the property value to the specified file as a quoted string.
208	 * This is used when generating DTS.
209	 */
210	void write_as_string(FILE *file);
211	/**
212	 * Writes the property value to the specified file as a sequence of
213	 * 32-bit big-endian cells.  This is used when generating DTS.
214	 */
215	void write_as_cells(FILE *file);
216	/**
217	 * Writes the property value to the specified file as a sequence of
218	 * bytes.  This is used when generating DTS.
219	 */
220	void write_as_bytes(FILE *file);
221};
222
223/**
224 * A value encapsulating a single property.  This contains a key, optionally a
225 * label, and optionally one or more values.
226 */
227class property
228{
229	/**
230	 * The name of this property.
231	 */
232	string key;
233	/**
234	 * An optional label.
235	 */
236	string label;
237	/**
238	 * The values in this property.
239	 */
240	std::vector<property_value> values;
241	/**
242	 * Value indicating that this is a valid property.  If a parse error
243	 * occurs, then this value is false.
244	 */
245	bool valid;
246	/**
247	 * Parses a string property value, i.e. a value enclosed in double quotes.
248	 */
249	void parse_string(input_buffer &input);
250	/**
251	 * Parses one or more 32-bit values enclosed in angle brackets.
252	 */
253	void parse_cells(input_buffer &input);
254	/**
255	 * Parses an array of bytes, contained within square brackets.
256	 */
257	void parse_bytes(input_buffer &input);
258	/**
259	 * Parses a reference.  This is a node label preceded by an ampersand
260	 * symbol, which should expand to the full path to that node.
261	 *
262	 * Note: The specification says that the target of such a reference is
263	 * a node name, however dtc assumes that it is a label, and so we
264	 * follow their interpretation for compatibility.
265	 */
266	void parse_reference(input_buffer &input);
267	/**
268	 * Parse a predefined macro definition for a property.
269	 */
270	void parse_define(input_buffer &input, define_map *defines);
271	/**
272	 * Constructs a new property from two input buffers, pointing to the
273	 * struct and strings tables in the device tree blob, respectively.
274	 * The structs input buffer is assumed to have just consumed the
275	 * FDT_PROP token.
276	 */
277	property(input_buffer &structs, input_buffer &strings);
278	/**
279	 * Parses a new property from the input buffer.
280	 */
281	property(input_buffer &input,
282	         string k,
283	         string l,
284	         bool terminated,
285	         define_map *defines);
286	public:
287	/**
288	 * Creates an empty property.
289	 */
290	property(string k, string l=string()) : key(k), label(l), valid(true)
291	{}
292	/**
293	 * Copy constructor.
294	 */
295	property(property &p) : key(p.key), label(p.label), values(p.values),
296		valid(p.valid) {}
297	/**
298	 * Factory method for constructing a new property.  Attempts to parse a
299	 * property from the input, and returns it on success.  On any parse
300	 * error, this will return 0.
301	 */
302	static property* parse_dtb(input_buffer &structs,
303	                           input_buffer &strings);
304	/**
305	 * Factory method for constructing a new property.  Attempts to parse a
306	 * property from the input, and returns it on success.  On any parse
307	 * error, this will return 0.
308	 */
309	static property* parse(input_buffer &input,
310	                       string key,
311	                       string label=string(),
312	                       bool semicolonTerminated=true,
313	                       define_map *defines=0);
314	/**
315	 * Iterator type used for accessing the values of a property.
316	 */
317	typedef std::vector<property_value>::iterator value_iterator;
318	/**
319	 * Returns an iterator referring to the first value in this property.
320	 */
321	inline value_iterator begin()
322	{
323		return values.begin();
324	}
325	/**
326	 * Returns an iterator referring to the last value in this property.
327	 */
328	inline value_iterator end()
329	{
330		return values.end();
331	}
332	/**
333	 * Adds a new value to an existing property.
334	 */
335	inline void add_value(property_value v)
336	{
337		values.push_back(v);
338	}
339	/**
340	 * Returns the key for this property.
341	 */
342	inline string get_key()
343	{
344		return key;
345	}
346	/**
347	 * Writes the property to the specified writer.  The property name is a
348	 * reference into the strings table.
349	 */
350	void write(dtb::output_writer &writer, dtb::string_table &strings);
351	/**
352	 * Writes in DTS format to the specified file, at the given indent
353	 * level.  This will begin the line with the number of tabs specified
354	 * as the indent level and then write the property in the most
355	 * applicable way that it can determine.
356	 */
357	void write_dts(FILE *file, int indent);
358};
359
360/**
361 * Class encapsulating a device tree node.  Nodes may contain properties and
362 * other nodes.
363 */
364class node
365{
366	public:
367	/**
368	 * The label for this node, if any.  Node labels are used as the
369	 * targets for cross references.
370	 */
371	string label;
372	/**
373	 * The name of the node.
374	 */
375	string name;
376	/**
377	 * The unit address of the node, which is optionally written after the
378	 * name followed by an at symbol.
379	 */
380	string unit_address;
381	private:
382	/**
383	 * The properties contained within this node.
384	 */
385	std::vector<property*> properties;
386	/**
387	 * The children of this node.
388	 */
389	std::vector<node*> children;
390	/**
391	 * A flag indicating whether this node is valid.  This is set to false
392	 * if an error occurs during parsing.
393	 */
394	bool valid;
395	/**
396	 * Parses a name inside a node, writing the string passed as the last
397	 * argument as an error if it fails.
398	 */
399	string parse_name(input_buffer &input,
400	                  bool &is_property,
401	                  const char *error);
402	/**
403	 * Constructs a new node from two input buffers, pointing to the struct
404	 * and strings tables in the device tree blob, respectively.
405	 */
406	node(input_buffer &structs, input_buffer &strings);
407	/**
408	 * Parses a new node from the specified input buffer.  This is called
409	 * when the input cursor is on the open brace for the start of the
410	 * node.  The name, and optionally label and unit address, should have
411	 * already been parsed.
412	 */
413	node(input_buffer &input, string n, string l, string a, define_map*);
414	/**
415	 * Comparison function for properties, used when sorting the properties
416	 * vector.  Orders the properties based on their names.
417	 */
418	static inline bool cmp_properties(property *p1, property *p2);
419		/*
420	{
421		return p1->get_key() < p2->get_key();
422	}
423	*/
424	/**
425	 * Comparison function for nodes, used when sorting the children
426	 * vector.  Orders the nodes based on their names or, if the names are
427	 * the same, by the unit addresses.
428	 */
429	static inline bool cmp_children(node *c1, node *c2);
430		/*
431	{
432		if (c1->name == c2->name)
433		{
434			return c1->unit_address < c2->unit_address;
435		}
436		return c1->name < c2->name;
437	}
438	*/
439	public:
440	/**
441	 * Sorts the node's properties and children into alphabetical order and
442	 * recursively sorts the children.
443	 */
444	void sort();
445	/**
446	 * Iterator type for child nodes.
447	 */
448	typedef std::vector<node*>::iterator child_iterator;
449	/**
450	 * Returns an iterator for the first child of this node.
451	 */
452	inline child_iterator child_begin()
453	{
454		return children.begin();
455	}
456	/**
457	 * Returns an iterator after the last child of this node.
458	 */
459	inline child_iterator child_end()
460	{
461		return children.end();
462	}
463	/**
464	 * Iterator type for properties of a node.
465	 */
466	typedef std::vector<property*>::iterator property_iterator;
467	/**
468	 * Returns an iterator after the last property of this node.
469	 */
470	inline property_iterator property_begin()
471	{
472		return properties.begin();
473	}
474	/**
475	 * Returns an iterator for the first property of this node.
476	 */
477	inline property_iterator property_end()
478	{
479		return properties.end();
480	}
481	/**
482	 * Factory method for constructing a new node.  Attempts to parse a
483	 * node in DTS format from the input, and returns it on success.  On
484	 * any parse error, this will return 0.  This should be called with the
485	 * cursor on the open brace of the property, after the name and so on
486	 * have been parsed.
487	 */
488	static node* parse(input_buffer &input,
489	                   string name,
490	                   string label=string(),
491	                   string address=string(),
492	                   define_map *defines=0);
493	/**
494	 * Factory method for constructing a new node.  Attempts to parse a
495	 * node in DTB format from the input, and returns it on success.  On
496	 * any parse error, this will return 0.  This should be called with the
497	 * cursor on the open brace of the property, after the name and so on
498	 * have been parsed.
499	 */
500	static node* parse_dtb(input_buffer &structs, input_buffer &strings);
501	/**
502	 * Destroys the node, recursively deleting all of its properties and
503	 * children.
504	 */
505	~node();
506	/**
507	 * Returns a property corresponding to the specified key, or 0 if this
508	 * node does not contain a property of that name.
509	 */
510	property *get_property(string key);
511	/**
512	 * Adds a new property to this node.
513	 */
514	inline void add_property(property *p)
515	{
516		properties.push_back(p);
517	}
518	/**
519	 * Merges a node into this one.  Any properties present in both are
520	 * overridden, any properties present in only one are preserved.
521	 */
522	void merge_node(node *other);
523	/**
524	 * Write this node to the specified output.  Although nodes do not
525	 * refer to a string table directly, their properties do.  The string
526	 * table passed as the second argument is used for the names of
527	 * properties within this node and its children.
528	 */
529	void write(dtb::output_writer &writer, dtb::string_table &strings);
530	/**
531	 * Writes the current node as DTS to the specified file.  The second
532	 * parameter is the indent level.  This function will start every line
533	 * with this number of tabs.
534	 */
535	void write_dts(FILE *file, int indent);
536};
537
538/**
539 * Class encapsulating the entire parsed FDT.  This is the top-level class,
540 * which parses the entire DTS representation and write out the finished
541 * version.
542 */
543class device_tree
544{
545	public:
546	/**
547	 * Type used for node paths.  A node path is sequence of names and unit
548	 * addresses.
549	 */
550	typedef std::vector<std::pair<string,string> > node_path;
551	/**
552	 * Name that we should use for phandle nodes.
553	 */
554	enum phandle_format
555	{
556		/** linux,phandle */
557		LINUX,
558		/** phandle */
559		EPAPR,
560		/** Create both nodes. */
561		BOTH
562	};
563	private:
564	/**
565	 * The format that we should use for writing phandles.
566	 */
567	phandle_format phandle_node_name;
568	/**
569	 * Flag indicating that this tree is valid.  This will be set to false
570	 * on parse errors.
571	 */
572	bool valid;
573	/**
574	 * Type used for memory reservations.  A reservation is two 64-bit
575	 * values indicating a base address and length in memory that the
576	 * kernel should not use.  The high 32 bits are ignored on 32-bit
577	 * platforms.
578	 */
579	typedef std::pair<uint64_t, uint64_t> reservation;
580	/**
581	 * The memory reserves table.
582	 */
583	std::vector<reservation> reservations;
584	/**
585	 * Root node.  All other nodes are children of this node.
586	 */
587	node *root;
588	/**
589	 * Mapping from names to nodes.  Only unambiguous names are recorded,
590	 * duplicate names are stored as (node*)-1.
591	 */
592	std::map<string, node*> node_names;
593	/**
594	 * A map from labels to node paths.  When resolving cross references,
595	 * we look up referenced nodes in this and replace the cross reference
596	 * with the full path to its target.
597	 */
598	std::map<string, node_path> node_paths;
599	/**
600	 * A collection of property values that are references to other nodes.
601	 * These should be expanded to the full path of their targets.
602	 */
603	std::vector<property_value*> cross_references;
604	/**
605	 * A collection of property values that refer to phandles.  These will
606	 * be replaced by the value of the phandle property in their
607	 * destination.
608	 */
609	std::vector<property_value*> phandles;
610	/**
611	 * A collection of input buffers that we are using.  These input
612	 * buffers are the ones that own their memory, and so we must preserve
613	 * them for the lifetime of the device tree.
614	 */
615	std::vector<input_buffer*> buffers;
616	/**
617	 * A map of used phandle values to nodes.  All phandles must be unique,
618	 * so we keep a set of ones that the user explicitly provides in the
619	 * input to ensure that we don't reuse them.
620	 *
621	 * This is a map, rather than a set, because we also want to be able to
622	 * find phandles that were provided by the user explicitly when we are
623	 * doing checking.
624	 */
625	std::map<uint32_t, node*> used_phandles;
626	/**
627	 * Paths to search for include files.  This contains a set of
628	 * nul-terminated strings, which are not owned by this class and so
629	 * must be freed separately.
630	 */
631	std::vector<const char*> include_paths;
632	/**
633	 * Dictionary of predefined macros provided on the command line.
634	 */
635	define_map               defines;
636	/**
637	 * The default boot CPU, specified in the device tree header.
638	 */
639	uint32_t boot_cpu;
640	/**
641	 * The number of empty reserve map entries to generate in the blob.
642	 */
643	uint32_t spare_reserve_map_entries;
644	/**
645	 * The minimum size in bytes of the blob.
646	 */
647	uint32_t minimum_blob_size;
648	/**
649	 * The number of bytes of padding to add to the end of the blob.
650	 */
651	uint32_t blob_padding;
652	/**
653	 * Visit all of the nodes recursively, and if they have labels then add
654	 * them to the node_paths and node_names vectors so that they can be
655	 * used in resolving cross references.  Also collects phandle
656	 * properties that have been explicitly added.
657	 */
658	void collect_names_recursive(node* n, node_path &path);
659	/**
660	 * Calls the recursive version of this method on every root node.
661	 */
662	void collect_names();
663	/**
664	 * Resolves all cross references.  Any properties that refer to another
665	 * node must have their values replaced by either the node path or
666	 * phandle value.
667	 */
668	void resolve_cross_references();
669	/**
670	 * Parses root nodes from the top level of a dts file.
671	 */
672	void parse_roots(input_buffer &input, std::vector<node*> &roots);
673	/**
674	 * Allocates a new mmap()'d input buffer for use in parsing.  This
675	 * object then keeps a reference to it, ensuring that it is not
676	 * deallocated until the device tree is destroyed.
677	 */
678	input_buffer *buffer_for_file(const char *path);
679	/**
680	 * Template function that writes a dtb blob using the specified writer.
681	 * The writer defines the output format (assembly, blob).
682	 */
683	template<class writer>
684	void write(int fd);
685	public:
686	/**
687	 * Returns the node referenced by the property.  If this is a tree that
688	 * is in source form, then we have a string that we can use to index
689	 * the cross_references array and so we can just look that up.
690	 */
691	node *referenced_node(property_value &v);
692	/**
693	 * Writes this FDT as a DTB to the specified output.
694	 */
695	void write_binary(int fd);
696	/**
697	 * Writes this FDT as an assembly representation of the DTB to the
698	 * specified output.  The result can then be assembled and linked into
699	 * a program.
700	 */
701	void write_asm(int fd);
702	/**
703	 * Writes the tree in DTS (source) format.
704	 */
705	void write_dts(int fd);
706	/**
707	 * Default constructor.  Creates a valid, but empty FDT.
708	 */
709	device_tree() : phandle_node_name(EPAPR), valid(true), root(0),
710		boot_cpu(0), spare_reserve_map_entries(0),
711		minimum_blob_size(0), blob_padding(0) {}
712	/**
713	 * Constructs a device tree from the specified file name, referring to
714	 * a file that contains a device tree blob.
715	 */
716	void parse_dtb(const char *fn, FILE *depfile);
717	/**
718	 * Constructs a device tree from the specified file name, referring to
719	 * a file that contains device tree source.
720	 */
721	void parse_dts(const char *fn, FILE *depfile);
722	/**
723	 * Destroy the tree and any input buffers that it holds.
724	 */
725	~device_tree();
726	/**
727	 * Returns whether this tree is valid.
728	 */
729	inline bool is_valid()
730	{
731		return valid;
732	}
733	/**
734	 * Sets the format for writing phandle properties.
735	 */
736	inline void set_phandle_format(phandle_format f)
737	{
738		phandle_node_name = f;
739	}
740	/**
741	 * Returns a pointer to the root node of this tree.  No ownership
742	 * transfer.
743	 */
744	inline node *get_root() const
745	{
746		return root;
747	}
748	/**
749	 * Sets the physical boot CPU.
750	 */
751	void set_boot_cpu(uint32_t cpu)
752	{
753		boot_cpu = cpu;
754	}
755	/**
756	 * Sorts the tree.  Useful for debugging device trees.
757	 */
758	void sort()
759	{
760		root->sort();
761	}
762	/**
763	 * Adds a path to search for include files.  The argument must be a
764	 * nul-terminated string representing the path.  The device tree keeps
765	 * a pointer to this string, but does not own it: the caller is
766	 * responsible for freeing it if required.
767	 */
768	void add_include_path(const char *path)
769	{
770		include_paths.push_back(path);
771	}
772	/**
773	 * Sets the number of empty reserve map entries to add.
774	 */
775	void set_empty_reserve_map_entries(uint32_t e)
776	{
777		spare_reserve_map_entries = e;
778	}
779	/**
780	 * Sets the minimum size, in bytes, of the blob.
781	 */
782	void set_blob_minimum_size(uint32_t s)
783	{
784		minimum_blob_size = s;
785	}
786	/**
787	 * Sets the amount of padding to add to the blob.
788	 */
789	void set_blob_padding(uint32_t p)
790	{
791		blob_padding = p;
792	}
793	/**
794	 * Parses a predefined macro value.
795	 */
796	bool parse_define(const char *def);
797};
798
799} // namespace fdt
800
801} // namespace dtc
802
803#endif // !_FDT_HH_
804