2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (c) 2013 David Chisnall
7 * This software was developed by SRI International and the University of
8 * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
9 * ("CTSRD"), as part of the DARPA CRASH research programme.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #define __STDC_LIMIT_MACROS 1
50 #include <sys/types.h>
63 property_value::get_as_uint32()
65 if (byte_data.size() != 4)
70 v &= byte_data[0] << 24;
71 v &= byte_data[1] << 16;
72 v &= byte_data[2] << 8;
73 v &= byte_data[3] << 0;
78 property_value::push_to_buffer(byte_buffer &buffer)
80 if (!byte_data.empty())
82 buffer.insert(buffer.end(), byte_data.begin(), byte_data.end());
86 push_string(buffer, string_data, true);
93 property_value::write_dts(FILE *file)
99 assert(0 && "Invalid type");
102 case CROSS_REFERENCE:
103 write_as_string(file);
106 write_as_cells(file);
109 if (byte_data.size() % 4 == 0)
111 write_as_cells(file);
114 write_as_bytes(file);
120 property_value::resolve_type()
126 if (byte_data.empty())
131 if (byte_data.back() == 0)
133 bool is_all_printable = true;
136 bool lastWasNull = false;
137 for (auto i : byte_data)
140 is_all_printable &= (i == '\0') || isprint(i);
143 // If there are two nulls in a row, then we're probably binary.
156 if (!is_all_printable)
161 if ((is_all_printable && (bytes > nuls)) || bytes == 0)
175 property_value::size()
177 if (!byte_data.empty())
179 return byte_data.size();
181 return string_data.size() + 1;
185 property_value::write_as_string(FILE *file)
188 if (byte_data.empty())
190 fputs(string_data.c_str(), file);
194 bool hasNull = (byte_data.back() == '\0');
195 // Remove trailing null bytes from the string before printing as dts.
198 byte_data.pop_back();
200 for (auto i : byte_data)
202 // FIXME Escape tabs, newlines, and so on.
205 fputs("\", \"", file);
212 byte_data.push_back('\0');
219 property_value::write_as_cells(FILE *file)
222 assert((byte_data.size() % 4) == 0);
223 for (auto i=byte_data.begin(), e=byte_data.end(); i!=e ; ++i)
233 fprintf(file, "0x%" PRIx32, v);
243 property_value::write_as_bytes(FILE *file)
246 for (auto i=byte_data.begin(), e=byte_data.end(); i!=e ; i++)
248 fprintf(file, "%02hhx", *i);
258 property::parse_string(text_input_buffer &input)
261 assert(*input == '"');
263 std::vector<char> bytes;
264 bool isEscaped = false;
265 while (char c = *input)
267 if (c == '"' && !isEscaped)
272 isEscaped = (c == '\\');
276 v.string_data = string(bytes.begin(), bytes.end());
281 property::parse_cells(text_input_buffer &input, int cell_size)
283 assert(*input == '<');
287 while (!input.consume('>'))
290 // If this is a phandle then we need to get the name of the
292 if (input.consume('&'))
296 input.parse_error("reference only permitted in 32-bit arrays");
302 if (!input.consume('{'))
304 referenced = input.parse_node_name();
308 referenced = input.parse_to('}');
311 if (referenced.empty())
313 input.parse_error("Expected node name");
318 // If we already have some bytes, make the phandle a
319 // separate component.
320 if (!v.byte_data.empty())
323 v = property_value();
325 v.string_data = referenced;
326 v.type = property_value::PHANDLE;
328 v = property_value();
332 //FIXME: We should support labels in the middle
333 //of these, but we don't.
334 unsigned long long val;
335 if (!input.consume_integer_expression(val))
337 // FIXME: Distinguish invalid syntax from a
338 // number that cannot be represented in an
339 // unsigned long long.
340 input.parse_error("Expected numbers in array of cells");
344 // FIXME: No sign information available, so cannot
345 // distinguish small negative values from large
346 // positive ones, and thus we have to conservatively
347 // permit anything that looks like a sign-extended
349 if (cell_size < 64 && val >= (1ull << cell_size) &&
350 (val | ((1ull << (cell_size - 1)) - 1)) !=
351 std::numeric_limits<unsigned long long>::max())
353 std::string msg = "Value does not fit in a " +
354 std::to_string(cell_size) + "-bit cell";
355 input.parse_error(msg.c_str());
362 v.byte_data.push_back(val);
365 push_big_endian(v.byte_data, (uint16_t)val);
368 push_big_endian(v.byte_data, (uint32_t)val);
371 push_big_endian(v.byte_data, (uint64_t)val);
374 assert(0 && "Invalid cell size!");
379 // Don't store an empty string value here.
380 if (v.byte_data.size() > 0)
387 property::parse_bytes(text_input_buffer &input)
389 assert(*input == '[');
393 while (!input.consume(']'))
396 //FIXME: We should support
397 //labels in the middle of
398 //these, but we don't.
400 if (!input.consume_hex_byte(val))
402 input.parse_error("Expected hex bytes in array of bytes");
406 v.byte_data.push_back(val);
414 property::parse_reference(text_input_buffer &input)
416 assert(*input == '&');
420 v.string_data = input.parse_node_name();
421 if (v.string_data.empty())
423 input.parse_error("Expected node name");
427 v.type = property_value::CROSS_REFERENCE;
431 property::property(input_buffer &structs, input_buffer &strings)
433 uint32_t name_offset;
435 valid = structs.consume_binary(length) &&
436 structs.consume_binary(name_offset);
439 fprintf(stderr, "Failed to read property\n");
443 input_buffer name_buffer = strings.buffer_from_offset(name_offset);
444 if (name_buffer.finished())
446 fprintf(stderr, "Property name offset %" PRIu32
447 " is past the end of the strings table\n",
452 key = name_buffer.parse_to(0);
454 // If we're empty, do not push anything as value.
461 for (uint32_t i=0 ; i<length ; i++)
463 if (!(valid = structs.consume_binary(byte)))
465 fprintf(stderr, "Failed to read property value\n");
468 v.byte_data.push_back(byte);
473 void property::parse_define(text_input_buffer &input, define_map *defines)
478 input.parse_error("No predefined properties to match name\n");
482 string name = input.parse_property_name();
483 define_map::iterator found;
484 if ((name == string()) ||
485 ((found = defines->find(name)) == defines->end()))
487 input.parse_error("Undefined property name\n");
491 values.push_back((*found).second->values[0]);
494 property::property(text_input_buffer &input,
497 bool semicolonTerminated,
498 define_map *defines) : key(k), labels(l), valid(true)
506 parse_define(input, defines);
514 input.parse_error("Invalid property value.");
519 if (input.consume("/incbin/(\""))
521 auto loc = input.location();
522 std::string filename = input.parse_to('"');
523 if (!(valid = input.consume('"')))
525 loc.report_error("Syntax error, expected '\"' to terminate /incbin/(");
529 if (!(valid = input.read_binary_file(filename, v.byte_data)))
531 input.parse_error("Cannot open binary include file");
534 if (!(valid &= input.consume(')')))
536 input.parse_error("Syntax error, expected ')' to terminate /incbin/(");
542 unsigned long long bits = 0;
543 valid = input.consume("/bits/");
545 valid &= input.consume_integer(bits);
550 input.parse_error("Invalid size for elements");
557 input.parse_error("/bits/ directive is only valid on arrays");
561 parse_cells(input, bits);
568 parse_cells(input, 32);
574 parse_reference(input);
582 } while (input.consume(','));
583 if (semicolonTerminated && !input.consume(';'))
585 input.parse_error("Expected ; at end of property");
591 property::parse_dtb(input_buffer &structs, input_buffer &strings)
593 property_ptr p(new property(structs, strings));
602 property::parse(text_input_buffer &input, string &&key, string_set &&label,
603 bool semicolonTerminated, define_map *defines)
605 property_ptr p(new property(input,
618 property::write(dtb::output_writer &writer, dtb::string_table &strings)
620 writer.write_token(dtb::FDT_PROP);
621 byte_buffer value_buffer;
622 for (value_iterator i=begin(), e=end() ; i!=e ; ++i)
624 i->push_to_buffer(value_buffer);
626 writer.write_data((uint32_t)value_buffer.size());
627 writer.write_comment(key);
628 writer.write_data(strings.add_string(key));
629 writer.write_data(value_buffer);
633 property_value::try_to_merge(property_value &other)
639 __builtin_unreachable();
647 case CROSS_REFERENCE:
651 if (other.type == PHANDLE || other.type == BINARY)
654 byte_data.insert(byte_data.end(), other.byte_data.begin(),
655 other.byte_data.end());
663 property::write_dts(FILE *file, int indent)
665 for (int i=0 ; i<indent ; i++)
670 for (auto &l : labels)
672 fputs(l.c_str(), file);
678 fputs(key.c_str(), file);
682 std::vector<property_value> *vals = &values;
683 std::vector<property_value> v;
684 // If we've got multiple values then try to merge them all together.
685 if (values.size() > 1)
688 v.push_back(values.front());
689 for (auto i=(++begin()), e=end() ; i!=e ; ++i)
691 if (!v.back().try_to_merge(*i))
698 for (auto i=vals->begin(), e=vals->end() ; i!=e ; ++i)
712 property::offset_of_value(property_value &val)
715 for (auto &v : values)
727 node::parse_name(text_input_buffer &input, bool &is_property, const char *error)
736 return input.parse_property_name();
738 string n = input.parse_node_or_property_name(is_property);
743 input.parse_error(error);
751 node::visit(std::function<visit_behavior(node&, node*)> fn, node *parent)
753 visit_behavior behavior;
754 behavior = fn(*this, parent);
755 if (behavior == VISIT_BREAK)
759 else if (behavior != VISIT_CONTINUE)
761 for (auto &&c : children)
763 behavior = c->visit(fn, this);
764 // Any status other than VISIT_RECURSE stops our execution and
765 // bubbles up to our caller. The caller may then either continue
766 // visiting nodes that are siblings to this one or completely halt
768 if (behavior != VISIT_RECURSE)
774 // Continue recursion by default
775 return VISIT_RECURSE;
778 node::node(input_buffer &structs, input_buffer &strings) : valid(true)
780 std::vector<char> bytes;
781 while (structs[0] != '\0' && structs[0] != '@')
783 bytes.push_back(structs[0]);
786 name = string(bytes.begin(), bytes.end());
788 if (structs[0] == '@')
791 while (structs[0] != '\0')
793 bytes.push_back(structs[0]);
796 unit_address = string(bytes.begin(), bytes.end());
800 while (structs.consume_binary(token))
805 fprintf(stderr, "Unexpected token 0x%" PRIx32
806 " while parsing node.\n", token);
809 // Child node, parse it.
810 case dtb::FDT_BEGIN_NODE:
812 node_ptr child = node::parse_dtb(structs, strings);
818 children.push_back(std::move(child));
821 // End of this node, no errors.
822 case dtb::FDT_END_NODE:
824 // Property, parse it.
827 property_ptr prop = property::parse_dtb(structs, strings);
833 props.push_back(prop);
837 // End of structs table. Should appear after
838 // the end of the last node.
840 fprintf(stderr, "Unexpected FDT_END token while parsing node.\n");
843 // NOPs are padding. Ignore them.
848 fprintf(stderr, "Failed to read token from structs table while parsing node.\n");
854 node::node(const string &n,
855 const std::vector<property_ptr> &p)
858 props.insert(props.begin(), p.begin(), p.end());
861 node_ptr node::create_special_node(const string &name,
862 const std::vector<property_ptr> &props)
864 // Work around for the fact that we can't call make_shared on something
865 // with a private constructor. Instead create a subclass with a public
866 // constructor that is visible only in this function and construct that
868 struct constructable_node : public node
870 constructable_node(const string &n, const std::vector<property_ptr> &p) : node(n, p) {}
872 node_ptr n{std::make_shared<constructable_node>(name, props)};
876 node::node(text_input_buffer &input,
879 std::unordered_set<string> &&l,
882 : labels(l), name(n), unit_address(a), valid(true)
884 if (!input.consume('{'))
886 input.parse_error("Expected { to start new device tree node.\n");
889 while (valid && !input.consume('}'))
891 // flag set if we find any characters that are only in
892 // the property name character set, not the node
893 bool is_property = false;
894 // flag set if our node is marked as /omit-if-no-ref/ to be
895 // garbage collected later if nothing references it
896 bool marked_omit_if_no_ref = false;
897 string child_name, child_address;
898 std::unordered_set<string> child_labels;
899 auto parse_delete = [&](const char *expected, bool at)
901 if (child_name == string())
903 input.parse_error(expected);
908 if (at && input.consume('@'))
911 child_name += parse_name(input, is_property, "Expected unit address");
913 if (!input.consume(';'))
915 input.parse_error("Expected semicolon");
921 if (input.consume("/delete-node/"))
924 child_name = input.parse_node_name();
925 parse_delete("Expected node name", true);
928 deleted_children.insert(child_name);
932 if (input.consume("/delete-property/"))
935 child_name = input.parse_property_name();
936 parse_delete("Expected property name", false);
939 deleted_props.insert(child_name);
943 if (input.consume("/omit-if-no-ref/"))
946 marked_omit_if_no_ref = true;
947 tree.set_needs_garbage_collection();
949 child_name = parse_name(input, is_property,
950 "Expected property or node name");
951 while (input.consume(':'))
953 // Node labels can contain any characters? The
954 // spec doesn't say, so we guess so...
956 child_labels.insert(std::move(child_name));
957 child_name = parse_name(input, is_property, "Expected property or node name");
959 if (input.consume('@'))
961 child_address = parse_name(input, is_property, "Expected unit address");
968 // If we're parsing a property, then we must actually do that.
969 if (input.consume('='))
971 property_ptr p = property::parse(input, std::move(child_name),
972 std::move(child_labels), true, defines);
982 else if (!is_property && *input == ('{'))
984 node_ptr child = node::parse(input, tree, std::move(child_name),
985 std::move(child_labels), std::move(child_address), defines);
988 child->omit_if_no_ref = marked_omit_if_no_ref;
989 children.push_back(std::move(child));
996 else if (input.consume(';'))
998 props.push_back(property_ptr(new property(std::move(child_name), std::move(child_labels))));
1002 input.parse_error("Error parsing property. Expected property value");
1012 node::cmp_properties(property_ptr &p1, property_ptr &p2)
1014 return p1->get_key() < p2->get_key();
1018 node::cmp_children(node_ptr &c1, node_ptr &c2)
1020 if (c1->name == c2->name)
1022 return c1->unit_address < c2->unit_address;
1024 return c1->name < c2->name;
1030 std::sort(property_begin(), property_end(), cmp_properties);
1031 std::sort(child_begin(), child_end(), cmp_children);
1032 for (auto &c : child_nodes())
1039 node::parse(text_input_buffer &input,
1044 define_map *defines)
1046 // Work around for the fact that we can't call make_shared on something
1047 // with a private constructor. Instead create a subclass with a public
1048 // constructor that is visible only in this function and construct that
1050 struct constructable_node : public node
1052 constructable_node(text_input_buffer &input,
1055 std::unordered_set<std::string> &&l,
1057 define_map*m) : node(input,
1065 node_ptr n{std::make_shared<constructable_node>(input,
1079 node::parse_dtb(input_buffer &structs, input_buffer &strings)
1081 node_ptr n(new node(structs, strings));
1090 node::get_property(const string &key)
1092 for (auto &i : props)
1094 if (i->get_key() == key)
1103 node::merge_node(node_ptr &other)
1105 for (auto &l : other->labels)
1109 children.erase(std::remove_if(children.begin(), children.end(),
1110 [&](const node_ptr &p) {
1111 string full_name = p->name;
1112 if (p->unit_address != string())
1115 full_name += p->unit_address;
1117 if (other->deleted_children.count(full_name) > 0)
1119 other->deleted_children.erase(full_name);
1123 }), children.end());
1124 props.erase(std::remove_if(props.begin(), props.end(),
1125 [&](const property_ptr &p) {
1126 if (other->deleted_props.count(p->get_key()) > 0)
1128 other->deleted_props.erase(p->get_key());
1133 // Note: this is an O(n*m) operation. It might be sensible to
1134 // optimise this if we find that there are nodes with very
1135 // large numbers of properties, but for typical usage the
1136 // entire vector will fit (easily) into cache, so iterating
1137 // over it repeatedly isn't that expensive.
1138 for (auto &p : other->properties())
1141 for (auto &mp : properties())
1143 if (mp->get_key() == p->get_key())
1155 for (auto &c : other->children)
1158 for (auto &i : children)
1160 if (i->name == c->name && i->unit_address == c->unit_address)
1169 children.push_back(std::move(c));
1175 node::write(dtb::output_writer &writer, dtb::string_table &strings)
1177 writer.write_token(dtb::FDT_BEGIN_NODE);
1178 byte_buffer name_buffer;
1179 push_string(name_buffer, name);
1180 if (unit_address != string())
1182 name_buffer.push_back('@');
1183 push_string(name_buffer, unit_address);
1185 writer.write_comment(name);
1186 writer.write_data(name_buffer);
1187 writer.write_data((uint8_t)0);
1188 for (auto p : properties())
1190 p->write(writer, strings);
1192 for (auto &c : child_nodes())
1194 c->write(writer, strings);
1196 writer.write_token(dtb::FDT_END_NODE);
1200 node::write_dts(FILE *file, int indent)
1202 for (int i=0 ; i<indent ; i++)
1207 for (auto &label : labels)
1209 fprintf(file, "%s: ", label.c_str());
1212 if (name != string())
1214 fputs(name.c_str(), file);
1216 if (unit_address != string())
1219 fputs(unit_address.c_str(), file);
1221 fputs(" {\n\n", file);
1222 for (auto p : properties())
1224 p->write_dts(file, indent+1);
1226 for (auto &c : child_nodes())
1228 c->write_dts(file, indent+1);
1230 for (int i=0 ; i<indent ; i++)
1234 fputs("};\n", file);
1238 device_tree::collect_names_recursive(node_ptr parent, node_ptr n, node_path &path)
1240 path.push_back(std::make_pair(n->name, n->unit_address));
1241 for (const string &name : n->labels)
1243 if (name != string())
1245 auto iter = node_names.find(name);
1246 if (iter == node_names.end())
1248 node_names.insert(std::make_pair(name, n));
1249 node_paths.insert(std::make_pair(name, path));
1250 ordered_node_paths.push_back({name, path});
1253 node_name_parents.insert({name, parent});
1258 node_names.erase(iter);
1259 auto i = node_paths.find(name);
1260 if (i != node_paths.end())
1262 node_paths.erase(name);
1264 fprintf(stderr, "Label not unique: %s. References to this label will not be resolved.\n", name.c_str());
1268 for (auto &c : n->child_nodes())
1270 collect_names_recursive(n, c, path);
1272 // Now we collect the phandles and properties that reference
1274 for (auto &p : n->properties())
1280 fixups.push_back({path, p, v});
1282 if (v.is_cross_reference())
1284 cross_references.push_back(&v);
1287 if ((p->get_key() == "phandle") ||
1288 (p->get_key() == "linux,phandle"))
1290 if (p->begin()->byte_data.size() != 4)
1292 fprintf(stderr, "Invalid phandle value for node %s. Should be a 4-byte value.\n", n->name.c_str());
1297 uint32_t phandle = p->begin()->get_as_uint32();
1298 used_phandles.insert(std::make_pair(phandle, n));
1306 device_tree::collect_names()
1311 ordered_node_paths.clear();
1312 cross_references.clear();
1314 collect_names_recursive(nullptr, root, p);
1318 device_tree::assign_phandle(node_ptr n, uint32_t &phandle)
1320 // If there is an existing phandle, use it
1321 property_ptr p = n->get_property("phandle");
1324 p = n->get_property("linux,phandle");
1328 // Otherwise insert a new phandle node
1330 while (used_phandles.find(phandle) != used_phandles.end())
1332 // Note that we only don't need to
1333 // store this phandle in the set,
1334 // because we are monotonically
1335 // increasing the value of phandle and
1336 // so will only ever revisit this value
1337 // if we have used 2^32 phandles, at
1338 // which point our blob won't fit in
1339 // any 32-bit system and we've done
1340 // something badly wrong elsewhere
1344 push_big_endian(v.byte_data, phandle++);
1345 if (phandle_node_name == BOTH || phandle_node_name == LINUX)
1347 p.reset(new property("linux,phandle"));
1351 if (phandle_node_name == BOTH || phandle_node_name == EPAPR)
1353 p.reset(new property("phandle"));
1363 device_tree::assign_phandles(node_ptr n, uint32_t &next)
1365 if (!n->labels.empty())
1367 assign_phandle(n, next);
1370 for (auto &c : n->child_nodes())
1372 assign_phandles(c, next);
1377 device_tree::resolve_cross_references(uint32_t &phandle)
1379 for (auto *pv : cross_references)
1381 node_path path = node_paths[pv->string_data];
1382 auto p = path.begin();
1383 auto pe = path.end();
1386 // Skip the first name in the path. It's always "", and implicitly /
1387 for (++p ; p!=pe ; ++p)
1389 pv->byte_data.push_back('/');
1390 push_string(pv->byte_data, p->first);
1391 if (!(p->second.empty()))
1393 pv->byte_data.push_back('@');
1394 push_string(pv->byte_data, p->second);
1397 pv->byte_data.push_back(0);
1400 std::unordered_map<property_value*, fixup&> phandle_set;
1401 for (auto &i : fixups)
1403 phandle_set.insert({&i.val, i});
1405 std::vector<std::reference_wrapper<fixup>> sorted_phandles;
1406 root->visit([&](node &n, node *) {
1407 for (auto &p : n.properties())
1411 auto i = phandle_set.find(&v);
1412 if (i != phandle_set.end())
1414 sorted_phandles.push_back(i->second);
1419 return node::VISIT_RECURSE;
1421 assert(sorted_phandles.size() == fixups.size());
1422 for (auto &i : sorted_phandles)
1424 string target_name = i.get().val.string_data;
1427 // If the node name is a path, then look it up by following the path,
1428 // otherwise jump directly to the named node.
1429 if (target_name[0] == '/')
1433 std::istringstream ss(target_name);
1434 string path_element;
1435 // Read the leading /
1436 std::getline(ss, path_element, '/');
1437 // Iterate over path elements
1441 std::getline(ss, path_element, '/');
1442 std::istringstream nss(path_element);
1443 string node_name, node_address;
1444 std::getline(nss, node_name, '@');
1445 std::getline(nss, node_address, '@');
1447 for (auto &c : target->child_nodes())
1449 if (c->name == node_name)
1451 if (c->unit_address == node_address)
1458 possible = path + c->name;
1459 if (c->unit_address != string())
1462 possible += c->unit_address;
1468 if (node_address != string())
1471 path += node_address;
1474 if (target == nullptr)
1482 target = node_names[target_name];
1484 if (target == nullptr)
1488 unresolved_fixups.push_back(i);
1493 fprintf(stderr, "Failed to find node with label: %s\n", target_name.c_str());
1494 if (possible != string())
1496 fprintf(stderr, "Possible intended match: %s\n", possible.c_str());
1502 // If there is an existing phandle, use it
1503 property_ptr p = assign_phandle(target, phandle);
1504 p->begin()->push_to_buffer(i.get().val.byte_data);
1505 assert(i.get().val.byte_data.size() == 4);
1510 device_tree::garbage_collect_marked_nodes()
1512 std::unordered_set<node_ptr> previously_referenced_nodes;
1513 std::unordered_set<node_ptr> newly_referenced_nodes;
1515 auto mark_referenced_nodes_used = [&](node &n)
1517 for (auto &p : n.properties())
1523 node_ptr nx = node_names[v.string_data];
1526 // Try it again, but as a path
1527 for (auto &s : node_paths)
1529 if (v.string_data == s.second.to_string())
1531 nx = node_names[s.first];
1538 // Couldn't resolve this one?
1541 // Only mark those currently unmarked
1545 newly_referenced_nodes.insert(nx);
1552 // Seed our referenced nodes with those that have been seen by a node that
1553 // either will not be omitted if it's unreferenced or has a symbol.
1554 // Nodes with symbols are explicitly not garbage collected because they may
1555 // be expected for referencing by an overlay, and we do not want surprises
1557 root->visit([&](node &n, node *) {
1558 if (!n.omit_if_no_ref || (write_symbols && !n.labels.empty()))
1560 mark_referenced_nodes_used(n);
1562 // Recurse as normal
1563 return node::VISIT_RECURSE;
1566 while (!newly_referenced_nodes.empty())
1568 previously_referenced_nodes = newly_referenced_nodes;
1569 newly_referenced_nodes.clear();
1570 for (auto &n : previously_referenced_nodes)
1572 mark_referenced_nodes_used(*n);
1576 previously_referenced_nodes.clear();
1577 bool children_deleted = false;
1580 root->visit([&](node &n, node *) {
1581 bool gc_children = false;
1583 for (auto &cn : n.child_nodes())
1585 if (cn->omit_if_no_ref && !cn->used)
1594 children_deleted = true;
1595 n.delete_children_if([](node_ptr &nx) {
1596 return (nx->omit_if_no_ref && !nx->used);
1599 return node::VISIT_CONTINUE;
1602 return node::VISIT_RECURSE;
1605 return children_deleted;
1609 device_tree::parse_file(text_input_buffer &input,
1610 std::vector<node_ptr> &roots,
1615 while (input.consume("/dts-v1/;"))
1620 if (input.consume("/plugin/;"))
1627 input.parse_error("Expected /dts-v1/; version string");
1629 // Read any memory reservations
1630 while (input.consume("/memreserve/"))
1632 unsigned long long start, len;
1634 // Read the start and length.
1635 if (!(input.consume_integer_expression(start) &&
1636 (input.next_token(),
1637 input.consume_integer_expression(len))))
1639 input.parse_error("Expected size on /memreserve/ node.");
1643 reservations.push_back(reservation(start, len));
1649 while (valid && !input.finished())
1652 if (input.consume("/delete-node/"))
1654 // Top-level /delete-node/ directives refer to references that must
1655 // be deleted later.
1657 auto expect = [&](auto token, const char *msg)
1659 if (!input.consume(token))
1661 input.parse_error(msg);
1667 if (expect('&', "Expected reference after top-level /delete-node/."))
1669 string ref = input.parse_node_name();
1670 if (ref == string())
1672 input.parse_error("Expected label name for top-level /delete-node/.");
1677 deletions.push_back(std::move(ref));
1679 expect(';', "Missing semicolon.");
1683 else if (input.consume('/'))
1686 n = node::parse(input, *this, string(), string_set(), string(), &defines);
1688 else if (input.consume('&'))
1692 bool name_is_path_reference = false;
1693 // This is to deal with names intended as path references, e.g. &{/path}.
1694 // While it may make sense in a non-plugin context, we don't support such
1695 // usage at this time.
1696 if (input.consume('{') && is_plugin)
1698 name = input.parse_to('}');
1700 name_is_path_reference = true;
1704 name = input.parse_node_name();
1707 n = node::parse(input, *this, std::move(name), string_set(), string(), &defines);
1710 n->name_is_path_reference = name_is_path_reference;
1715 input.parse_error("Failed to find root node /.");
1719 roots.push_back(std::move(n));
1729 template<class writer> void
1730 device_tree::write(int fd)
1732 dtb::string_table st;
1735 writer reservation_writer;
1736 writer struct_writer;
1737 writer strings_writer;
1739 // Build the reservation table
1740 reservation_writer.write_comment(string("Memory reservations"));
1741 reservation_writer.write_label(string("dt_reserve_map"));
1742 for (auto &i : reservations)
1744 reservation_writer.write_comment(string("Reservation start"));
1745 reservation_writer.write_data(i.first);
1746 reservation_writer.write_comment(string("Reservation length"));
1747 reservation_writer.write_data(i.second);
1749 // Write n spare reserve map entries, plus the trailing 0.
1750 for (uint32_t i=0 ; i<=spare_reserve_map_entries ; i++)
1752 reservation_writer.write_data((uint64_t)0);
1753 reservation_writer.write_data((uint64_t)0);
1757 struct_writer.write_comment(string("Device tree"));
1758 struct_writer.write_label(string("dt_struct_start"));
1759 root->write(struct_writer, st);
1760 struct_writer.write_token(dtb::FDT_END);
1761 struct_writer.write_label(string("dt_struct_end"));
1763 st.write(strings_writer);
1764 // Find the strings size before we stick padding on the end.
1765 // Note: We should possibly use a new writer for the padding.
1766 head.size_dt_strings = strings_writer.size();
1768 // Stick the padding in the strings writer, but after the
1769 // marker indicating that it's the end.
1770 // Note: We probably should add a padding call to the writer so
1771 // that the asm back end can write padding directives instead
1772 // of a load of 0 bytes.
1773 for (uint32_t i=0 ; i<blob_padding ; i++)
1775 strings_writer.write_data((uint8_t)0);
1777 head.totalsize = sizeof(head) + strings_writer.size() +
1778 struct_writer.size() + reservation_writer.size();
1779 while (head.totalsize < minimum_blob_size)
1782 strings_writer.write_data((uint8_t)0);
1784 head.off_dt_struct = sizeof(head) + reservation_writer.size();;
1785 head.off_dt_strings = head.off_dt_struct + struct_writer.size();
1786 head.off_mem_rsvmap = sizeof(head);
1787 head.boot_cpuid_phys = boot_cpu;
1788 head.size_dt_struct = struct_writer.size();
1789 head.write(head_writer);
1791 head_writer.write_to_file(fd);
1792 reservation_writer.write_to_file(fd);
1793 struct_writer.write_to_file(fd);
1794 strings_writer.write_label(string("dt_blob_end"));
1795 strings_writer.write_to_file(fd);
1799 device_tree::referenced_node(property_value &v)
1803 return node_names[v.string_data];
1807 return used_phandles[v.get_as_uint32()];
1813 device_tree::write_binary(int fd)
1815 write<dtb::binary_writer>(fd);
1819 device_tree::write_asm(int fd)
1821 write<dtb::asm_writer>(fd);
1825 device_tree::write_dts(int fd)
1827 FILE *file = fdopen(fd, "w");
1828 fputs("/dts-v1/;\n\n", file);
1830 if (!reservations.empty())
1832 const char msg[] = "/memreserve/";
1833 // Exclude the null byte when we're writing it out to the file.
1834 fwrite(msg, sizeof(msg) - 1, 1, file);
1835 for (auto &i : reservations)
1837 fprintf(file, " 0x%" PRIx64 " 0x%" PRIx64, i.first, i.second);
1839 fputs(";\n\n", file);
1843 root->write_dts(file, 0);
1848 device_tree::parse_dtb(const string &fn, FILE *)
1850 auto in = input_buffer::buffer_for_file(fn);
1856 input_buffer &input = *in;
1858 valid = h.read_dtb(input);
1859 boot_cpu = h.boot_cpuid_phys;
1860 if (h.last_comp_version > 17)
1862 fprintf(stderr, "Don't know how to read this version of the device tree blob");
1869 input_buffer reservation_map =
1870 input.buffer_from_offset(h.off_mem_rsvmap, 0);
1871 uint64_t start, length;
1874 if (!(reservation_map.consume_binary(start) &&
1875 reservation_map.consume_binary(length)))
1877 fprintf(stderr, "Failed to read memory reservation table\n");
1881 if (start != 0 || length != 0)
1883 reservations.push_back(reservation(start, length));
1885 } while (!((start == 0) && (length == 0)));
1886 input_buffer struct_table =
1887 input.buffer_from_offset(h.off_dt_struct, h.size_dt_struct);
1888 input_buffer strings_table =
1889 input.buffer_from_offset(h.off_dt_strings, h.size_dt_strings);
1891 if (!(struct_table.consume_binary(token) &&
1892 (token == dtb::FDT_BEGIN_NODE)))
1894 fprintf(stderr, "Expected FDT_BEGIN_NODE token.\n");
1898 root = node::parse_dtb(struct_table, strings_table);
1899 if (!(struct_table.consume_binary(token) && (token == dtb::FDT_END)))
1901 fprintf(stderr, "Expected FDT_END token after parsing root node.\n");
1905 valid = (root != 0);
1909 device_tree::node_path::to_string() const
1914 if ((p == pe) || (p+1 == pe))
1918 // Skip the first name in the path. It's always "", and implicitly /
1919 for (++p ; p!=pe ; ++p)
1923 if (!(p->second.empty()))
1933 device_tree::create_fragment_wrapper(node_ptr &node, int &fragnum)
1935 // In a plugin, we can massage these non-/ root nodes into into a fragment
1936 std::string fragment_address = "fragment@" + std::to_string(fragnum);
1939 std::vector<property_ptr> symbols;
1941 // Intentionally left empty
1942 node_ptr newroot = node::create_special_node("", symbols);
1943 node_ptr wrapper = node::create_special_node("__overlay__", symbols);
1945 // Generate the fragment with $propname = <&name>
1947 std::string propname;
1948 v.string_data = node->name;
1949 if (!node->name_is_path_reference)
1951 propname = "target";
1952 v.type = property_value::PHANDLE;
1956 propname = "target-path";
1957 v.type = property_value::STRING;
1959 auto prop = std::make_shared<property>(std::string(propname));
1961 symbols.push_back(prop);
1963 node_ptr fragment = node::create_special_node(fragment_address, symbols);
1965 wrapper->merge_node(node);
1966 fragment->add_child(std::move(wrapper));
1967 newroot->add_child(std::move(fragment));
1972 device_tree::generate_root(node_ptr &node, int &fragnum)
1975 string name = node->name;
1976 if (name == string())
1978 return std::move(node);
1980 else if (!is_plugin)
1985 return create_fragment_wrapper(node, fragnum);
1989 device_tree::reassign_fragment_numbers(node_ptr &node, int &delta)
1992 for (auto &c : node->child_nodes())
1994 if (c->name == std::string("fragment"))
1996 int current_address = std::stoi(c->unit_address, nullptr, 16);
1997 std::ostringstream new_address;
1998 current_address += delta;
1999 // It's possible that we hopped more than one somewhere, so just reset
2000 // delta to the next in sequence.
2001 delta = current_address + 1;
2002 new_address << std::hex << current_address;
2003 c->unit_address = new_address.str();
2009 device_tree::parse_dts(const string &fn, FILE *depfile)
2011 auto in = input_buffer::buffer_for_file(fn);
2017 std::vector<node_ptr> roots;
2018 std::unordered_set<string> defnames;
2019 for (auto &i : defines)
2021 defnames.insert(i.first);
2023 text_input_buffer input(std::move(in),
2024 std::move(defnames),
2025 std::vector<string>(include_paths),
2028 bool read_header = false;
2030 parse_file(input, roots, read_header);
2031 switch (roots.size())
2035 input.parse_error("Failed to find root node /.");
2038 root = generate_root(roots[0], fragnum);
2042 input.parse_error("Failed to find root node /.");
2048 root = generate_root(roots[0], fragnum);
2052 input.parse_error("Failed to find root node /.");
2055 for (auto i=++(roots.begin()), e=roots.end() ; i!=e ; ++i)
2058 string name = node->name;
2059 if (name == string())
2063 // Re-assign any fragment numbers based on a delta of
2064 // fragnum before we merge it
2065 reassign_fragment_numbers(node, fragnum);
2067 root->merge_node(node);
2071 auto existing = node_names.find(name);
2072 if (existing == node_names.end())
2075 existing = node_names.find(name);
2077 if (existing == node_names.end())
2081 auto fragment = create_fragment_wrapper(node, fragnum);
2082 root->merge_node(fragment);
2086 fprintf(stderr, "Unable to merge node: %s\n", name.c_str());
2091 existing->second->merge_node(node);
2098 for (auto &ref : deletions)
2100 auto parent = node_name_parents[ref];
2101 auto node = node_names[ref];
2104 fprintf(stderr, "Top-level /delete-node/ directive refers to label %s, which is not found.\n", ref.c_str());
2108 parent->delete_children_if([&](node_ptr &child) { return child == node; });
2111 // Return value indicates whether we've dirtied the tree or not and need to
2113 if (garbage_collect && garbage_collect_marked_nodes())
2117 uint32_t phandle = 1;
2118 // If we're writing symbols, go ahead and assign phandles to the entire
2119 // tree. We'll do this before we resolve cross references, just to keep
2120 // order semi-predictable and stable.
2123 assign_phandles(root, phandle);
2125 resolve_cross_references(phandle);
2128 std::vector<property_ptr> symbols;
2129 // Create a symbol table. Each label in this device tree may be
2130 // referenced by other plugins, so we create a __symbols__ node inside
2131 // the root that contains mappings (properties) from label names to
2133 for (auto i=ordered_node_paths.rbegin(), e=ordered_node_paths.rend() ; i!=e ; ++i)
2136 if (node_paths.find(s.first) == node_paths.end())
2138 // Erased node, skip it.
2142 v.string_data = s.second.to_string();
2143 v.type = property_value::STRING;
2144 string name = s.first;
2145 auto prop = std::make_shared<property>(std::move(name));
2147 symbols.push_back(prop);
2149 root->add_child(node::create_special_node("__symbols__", symbols));
2151 // If this is a plugin, then we also need to create two extra nodes.
2152 // Internal phandles will need to be renumbered to avoid conflicts with
2153 // already-loaded nodes and external references will need to be
2157 std::vector<property_ptr> symbols;
2158 // Create the fixups entry. This is of the form:
2159 // {target} = {path}:{property name}:{offset}
2160 auto create_fixup_entry = [&](fixup &i, string target)
2162 string value = i.path.to_string();
2164 value += i.prop->get_key();
2166 value += std::to_string(i.prop->offset_of_value(i.val));
2168 v.string_data = value;
2169 v.type = property_value::STRING;
2170 auto prop = std::make_shared<property>(std::move(target));
2174 // If we have any unresolved phandle references in this plugin,
2175 // then we must update them to 0xdeadbeef and leave a property in
2176 // the /__fixups__ node whose key is the label and whose value is
2177 // as described above.
2178 if (!unresolved_fixups.empty())
2180 for (auto &i : unresolved_fixups)
2182 auto &val = i.get().val;
2183 symbols.push_back(create_fixup_entry(i, val.string_data));
2184 val.byte_data.push_back(0xde);
2185 val.byte_data.push_back(0xad);
2186 val.byte_data.push_back(0xbe);
2187 val.byte_data.push_back(0xef);
2188 val.type = property_value::BINARY;
2190 root->add_child(node::create_special_node("__fixups__", symbols));
2193 // If we have any resolved phandle references in this plugin, then
2194 // we must create a child in the __local_fixups__ node whose path
2195 // matches the node path from the root and whose value contains the
2196 // location of the reference within a property.
2198 // Create a local_fixups node that is initially empty.
2199 node_ptr local_fixups = node::create_special_node("__local_fixups__", symbols);
2200 for (auto &i : fixups)
2202 if (!i.val.is_phandle())
2206 node_ptr n = local_fixups;
2207 for (auto &p : i.path)
2209 // Skip the implicit root
2210 if (p.first.empty())
2215 for (auto &c : n->child_nodes())
2217 if (c->name == p.first)
2219 if (c->unit_address == p.second)
2229 string path = p.first;
2230 if (!(p.second.empty()))
2235 n->add_child(node::create_special_node(path, symbols));
2236 n = *(--(n->child_end()));
2241 push_big_endian(pv.byte_data, static_cast<uint32_t>(i.prop->offset_of_value(i.val)));
2242 pv.type = property_value::BINARY;
2243 auto key = i.prop->get_key();
2244 property_ptr prop = n->get_property(key);
2245 // If we don't have an existing property then create one and
2246 // use this property value
2249 prop = std::make_shared<property>(std::move(key));
2250 n->add_property(prop);
2251 prop->add_value(pv);
2255 // If we do have an existing property value, try to append
2257 property_value &old_val = *(--prop->end());
2258 if (!old_val.try_to_merge(pv))
2260 prop->add_value(pv);
2264 // We've iterated over all fixups, but only emit the
2265 // __local_fixups__ if we found some that were resolved internally.
2266 if (local_fixups->child_begin() != local_fixups->child_end())
2268 root->add_child(std::move(local_fixups));
2273 bool device_tree::parse_define(const char *def)
2275 const char *val = strchr(def, '=');
2278 if (strlen(def) != 0)
2286 string name(def, val-def);
2287 string name_copy = name;
2289 std::unique_ptr<input_buffer> raw(new input_buffer(val, strlen(val)));
2290 text_input_buffer in(std::move(raw),
2291 std::unordered_set<string>(),
2292 std::vector<string>(),
2295 property_ptr p = property::parse(in, std::move(name_copy), string_set(), false);