2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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
35 #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 input.parse_error("Expected numbers in array of cells");
344 v.byte_data.push_back(val);
347 push_big_endian(v.byte_data, (uint16_t)val);
350 push_big_endian(v.byte_data, (uint32_t)val);
353 push_big_endian(v.byte_data, (uint64_t)val);
356 assert(0 && "Invalid cell size!");
361 // Don't store an empty string value here.
362 if (v.byte_data.size() > 0)
369 property::parse_bytes(text_input_buffer &input)
371 assert(*input == '[');
375 while (!input.consume(']'))
378 //FIXME: We should support
379 //labels in the middle of
380 //these, but we don't.
382 if (!input.consume_hex_byte(val))
384 input.parse_error("Expected hex bytes in array of bytes");
388 v.byte_data.push_back(val);
396 property::parse_reference(text_input_buffer &input)
398 assert(*input == '&');
402 v.string_data = input.parse_node_name();
403 if (v.string_data.empty())
405 input.parse_error("Expected node name");
409 v.type = property_value::CROSS_REFERENCE;
413 property::property(input_buffer &structs, input_buffer &strings)
415 uint32_t name_offset;
417 valid = structs.consume_binary(length) &&
418 structs.consume_binary(name_offset);
421 fprintf(stderr, "Failed to read property\n");
425 input_buffer name_buffer = strings.buffer_from_offset(name_offset);
426 if (name_buffer.finished())
428 fprintf(stderr, "Property name offset %" PRIu32
429 " is past the end of the strings table\n",
434 key = name_buffer.parse_to(0);
436 // If we're empty, do not push anything as value.
443 for (uint32_t i=0 ; i<length ; i++)
445 if (!(valid = structs.consume_binary(byte)))
447 fprintf(stderr, "Failed to read property value\n");
450 v.byte_data.push_back(byte);
455 void property::parse_define(text_input_buffer &input, define_map *defines)
460 input.parse_error("No predefined properties to match name\n");
464 string name = input.parse_property_name();
465 define_map::iterator found;
466 if ((name == string()) ||
467 ((found = defines->find(name)) == defines->end()))
469 input.parse_error("Undefined property name\n");
473 values.push_back((*found).second->values[0]);
476 property::property(text_input_buffer &input,
479 bool semicolonTerminated,
480 define_map *defines) : key(k), labels(l), valid(true)
488 parse_define(input, defines);
495 input.parse_error("Invalid property value.");
500 if (input.consume("/incbin/(\""))
502 auto loc = input.location();
503 std::string filename = input.parse_to('"');
504 if (!(valid = input.consume('"')))
506 loc.report_error("Syntax error, expected '\"' to terminate /incbin/(");
510 if (!(valid = input.read_binary_file(filename, v.byte_data)))
512 input.parse_error("Cannot open binary include file");
515 if (!(valid &= input.consume(')')))
517 input.parse_error("Syntax error, expected ')' to terminate /incbin/(");
523 unsigned long long bits = 0;
524 valid = input.consume("/bits/");
526 valid &= input.consume_integer(bits);
531 input.parse_error("Invalid size for elements");
538 input.parse_error("/bits/ directive is only valid on arrays");
542 parse_cells(input, bits);
549 parse_cells(input, 32);
555 parse_reference(input);
563 } while (input.consume(','));
564 if (semicolonTerminated && !input.consume(';'))
566 input.parse_error("Expected ; at end of property");
572 property::parse_dtb(input_buffer &structs, input_buffer &strings)
574 property_ptr p(new property(structs, strings));
583 property::parse(text_input_buffer &input, string &&key, string_set &&label,
584 bool semicolonTerminated, define_map *defines)
586 property_ptr p(new property(input,
599 property::write(dtb::output_writer &writer, dtb::string_table &strings)
601 writer.write_token(dtb::FDT_PROP);
602 byte_buffer value_buffer;
603 for (value_iterator i=begin(), e=end() ; i!=e ; ++i)
605 i->push_to_buffer(value_buffer);
607 writer.write_data((uint32_t)value_buffer.size());
608 writer.write_comment(key);
609 writer.write_data(strings.add_string(key));
610 writer.write_data(value_buffer);
614 property_value::try_to_merge(property_value &other)
620 __builtin_unreachable();
627 case CROSS_REFERENCE:
631 if (other.type == PHANDLE || other.type == BINARY)
634 byte_data.insert(byte_data.end(), other.byte_data.begin(),
635 other.byte_data.end());
643 property::write_dts(FILE *file, int indent)
645 for (int i=0 ; i<indent ; i++)
650 for (auto &l : labels)
652 fputs(l.c_str(), file);
658 fputs(key.c_str(), file);
662 std::vector<property_value> *vals = &values;
663 std::vector<property_value> v;
664 // If we've got multiple values then try to merge them all together.
665 if (values.size() > 1)
668 v.push_back(values.front());
669 for (auto i=(++begin()), e=end() ; i!=e ; ++i)
671 if (!v.back().try_to_merge(*i))
678 for (auto i=vals->begin(), e=vals->end() ; i!=e ; ++i)
692 property::offset_of_value(property_value &val)
695 for (auto &v : values)
707 node::parse_name(text_input_buffer &input, bool &is_property, const char *error)
716 return input.parse_property_name();
718 string n = input.parse_node_or_property_name(is_property);
723 input.parse_error(error);
731 node::visit(std::function<visit_behavior(node&, node*)> fn, node *parent)
733 visit_behavior behavior;
734 behavior = fn(*this, parent);
735 if (behavior == VISIT_BREAK)
739 else if (behavior != VISIT_CONTINUE)
741 for (auto &&c : children)
743 behavior = c->visit(fn, this);
744 // Any status other than VISIT_RECURSE stops our execution and
745 // bubbles up to our caller. The caller may then either continue
746 // visiting nodes that are siblings to this one or completely halt
748 if (behavior != VISIT_RECURSE)
754 // Continue recursion by default
755 return VISIT_RECURSE;
758 node::node(input_buffer &structs, input_buffer &strings) : valid(true)
760 std::vector<char> bytes;
761 while (structs[0] != '\0' && structs[0] != '@')
763 bytes.push_back(structs[0]);
766 name = string(bytes.begin(), bytes.end());
768 if (structs[0] == '@')
771 while (structs[0] != '\0')
773 bytes.push_back(structs[0]);
776 unit_address = string(bytes.begin(), bytes.end());
780 while (structs.consume_binary(token))
785 fprintf(stderr, "Unexpected token 0x%" PRIx32
786 " while parsing node.\n", token);
789 // Child node, parse it.
790 case dtb::FDT_BEGIN_NODE:
792 node_ptr child = node::parse_dtb(structs, strings);
798 children.push_back(std::move(child));
801 // End of this node, no errors.
802 case dtb::FDT_END_NODE:
804 // Property, parse it.
807 property_ptr prop = property::parse_dtb(structs, strings);
813 props.push_back(prop);
817 // End of structs table. Should appear after
818 // the end of the last node.
820 fprintf(stderr, "Unexpected FDT_END token while parsing node.\n");
823 // NOPs are padding. Ignore them.
828 fprintf(stderr, "Failed to read token from structs table while parsing node.\n");
834 node::node(const string &n,
835 const std::vector<property_ptr> &p)
838 props.insert(props.begin(), p.begin(), p.end());
841 node_ptr node::create_special_node(const string &name,
842 const std::vector<property_ptr> &props)
844 node_ptr n(new node(name, props));
848 node::node(text_input_buffer &input,
850 std::unordered_set<string> &&l,
853 : labels(l), name(n), unit_address(a), valid(true)
855 if (!input.consume('{'))
857 input.parse_error("Expected { to start new device tree node.\n");
860 while (valid && !input.consume('}'))
862 // flag set if we find any characters that are only in
863 // the property name character set, not the node
864 bool is_property = false;
865 string child_name, child_address;
866 std::unordered_set<string> child_labels;
867 auto parse_delete = [&](const char *expected, bool at)
869 if (child_name == string())
871 input.parse_error(expected);
876 if (at && input.consume('@'))
879 child_name += parse_name(input, is_property, "Expected unit address");
881 if (!input.consume(';'))
883 input.parse_error("Expected semicolon");
889 if (input.consume("/delete-node/"))
892 child_name = input.parse_node_name();
893 parse_delete("Expected node name", true);
896 deleted_children.insert(child_name);
900 if (input.consume("/delete-property/"))
903 child_name = input.parse_property_name();
904 parse_delete("Expected property name", false);
907 deleted_props.insert(child_name);
911 child_name = parse_name(input, is_property,
912 "Expected property or node name");
913 while (input.consume(':'))
915 // Node labels can contain any characters? The
916 // spec doesn't say, so we guess so...
918 child_labels.insert(std::move(child_name));
919 child_name = parse_name(input, is_property, "Expected property or node name");
921 if (input.consume('@'))
923 child_address = parse_name(input, is_property, "Expected unit address");
930 // If we're parsing a property, then we must actually do that.
931 if (input.consume('='))
933 property_ptr p = property::parse(input, std::move(child_name),
934 std::move(child_labels), true, defines);
944 else if (!is_property && *input == ('{'))
946 node_ptr child = node::parse(input, std::move(child_name),
947 std::move(child_labels), std::move(child_address), defines);
950 children.push_back(std::move(child));
957 else if (input.consume(';'))
959 props.push_back(property_ptr(new property(std::move(child_name), std::move(child_labels))));
963 input.parse_error("Error parsing property. Expected property value");
973 node::cmp_properties(property_ptr &p1, property_ptr &p2)
975 return p1->get_key() < p2->get_key();
979 node::cmp_children(node_ptr &c1, node_ptr &c2)
981 if (c1->name == c2->name)
983 return c1->unit_address < c2->unit_address;
985 return c1->name < c2->name;
991 std::sort(property_begin(), property_end(), cmp_properties);
992 std::sort(child_begin(), child_end(), cmp_children);
993 for (auto &c : child_nodes())
1000 node::parse(text_input_buffer &input,
1004 define_map *defines)
1006 node_ptr n(new node(input,
1019 node::parse_dtb(input_buffer &structs, input_buffer &strings)
1021 node_ptr n(new node(structs, strings));
1030 node::get_property(const string &key)
1032 for (auto &i : props)
1034 if (i->get_key() == key)
1043 node::merge_node(node_ptr &other)
1045 for (auto &l : other->labels)
1049 // Note: this is an O(n*m) operation. It might be sensible to
1050 // optimise this if we find that there are nodes with very
1051 // large numbers of properties, but for typical usage the
1052 // entire vector will fit (easily) into cache, so iterating
1053 // over it repeatedly isn't that expensive.
1054 for (auto &p : other->properties())
1057 for (auto &mp : properties())
1059 if (mp->get_key() == p->get_key())
1071 for (auto &c : other->children)
1074 for (auto &i : children)
1076 if (i->name == c->name && i->unit_address == c->unit_address)
1085 children.push_back(std::move(c));
1088 children.erase(std::remove_if(children.begin(), children.end(),
1089 [&](const node_ptr &p) {
1090 string full_name = p->name;
1091 if (p->unit_address != string())
1094 full_name += p->unit_address;
1096 if (other->deleted_children.count(full_name) > 0)
1098 other->deleted_children.erase(full_name);
1102 }), children.end());
1103 props.erase(std::remove_if(props.begin(), props.end(),
1104 [&](const property_ptr &p) {
1105 if (other->deleted_props.count(p->get_key()) > 0)
1107 other->deleted_props.erase(p->get_key());
1115 node::write(dtb::output_writer &writer, dtb::string_table &strings)
1117 writer.write_token(dtb::FDT_BEGIN_NODE);
1118 byte_buffer name_buffer;
1119 push_string(name_buffer, name);
1120 if (unit_address != string())
1122 name_buffer.push_back('@');
1123 push_string(name_buffer, unit_address);
1125 writer.write_comment(name);
1126 writer.write_data(name_buffer);
1127 writer.write_data((uint8_t)0);
1128 for (auto p : properties())
1130 p->write(writer, strings);
1132 for (auto &c : child_nodes())
1134 c->write(writer, strings);
1136 writer.write_token(dtb::FDT_END_NODE);
1140 node::write_dts(FILE *file, int indent)
1142 for (int i=0 ; i<indent ; i++)
1147 for (auto &label : labels)
1149 fprintf(file, "%s: ", label.c_str());
1152 if (name != string())
1154 fputs(name.c_str(), file);
1156 if (unit_address != string())
1159 fputs(unit_address.c_str(), file);
1161 fputs(" {\n\n", file);
1162 for (auto p : properties())
1164 p->write_dts(file, indent+1);
1166 for (auto &c : child_nodes())
1168 c->write_dts(file, indent+1);
1170 for (int i=0 ; i<indent ; i++)
1174 fputs("};\n", file);
1178 device_tree::collect_names_recursive(node_ptr &n, node_path &path)
1180 path.push_back(std::make_pair(n->name, n->unit_address));
1181 for (const string &name : n->labels)
1183 if (name != string())
1185 auto iter = node_names.find(name);
1186 if (iter == node_names.end())
1188 node_names.insert(std::make_pair(name, n.get()));
1189 node_paths.insert(std::make_pair(name, path));
1193 node_names.erase(iter);
1194 auto i = node_paths.find(name);
1195 if (i != node_paths.end())
1197 node_paths.erase(name);
1199 fprintf(stderr, "Label not unique: %s. References to this label will not be resolved.\n", name.c_str());
1203 for (auto &c : n->child_nodes())
1205 collect_names_recursive(c, path);
1207 // Now we collect the phandles and properties that reference
1209 for (auto &p : n->properties())
1215 fixups.push_back({path, p, v});
1217 if (v.is_cross_reference())
1219 cross_references.push_back(&v);
1222 if ((p->get_key() == "phandle") ||
1223 (p->get_key() == "linux,phandle"))
1225 if (p->begin()->byte_data.size() != 4)
1227 fprintf(stderr, "Invalid phandle value for node %s. Should be a 4-byte value.\n", n->name.c_str());
1232 uint32_t phandle = p->begin()->get_as_uint32();
1233 used_phandles.insert(std::make_pair(phandle, n.get()));
1241 device_tree::collect_names()
1246 cross_references.clear();
1248 collect_names_recursive(root, p);
1252 device_tree::assign_phandle(node *n, uint32_t &phandle)
1254 // If there is an existing phandle, use it
1255 property_ptr p = n->get_property("phandle");
1258 p = n->get_property("linux,phandle");
1262 // Otherwise insert a new phandle node
1264 while (used_phandles.find(phandle) != used_phandles.end())
1266 // Note that we only don't need to
1267 // store this phandle in the set,
1268 // because we are monotonically
1269 // increasing the value of phandle and
1270 // so will only ever revisit this value
1271 // if we have used 2^32 phandles, at
1272 // which point our blob won't fit in
1273 // any 32-bit system and we've done
1274 // something badly wrong elsewhere
1278 push_big_endian(v.byte_data, phandle++);
1279 if (phandle_node_name == BOTH || phandle_node_name == LINUX)
1281 p.reset(new property("linux,phandle"));
1285 if (phandle_node_name == BOTH || phandle_node_name == EPAPR)
1287 p.reset(new property("phandle"));
1297 device_tree::assign_phandles(node_ptr &n, uint32_t &next)
1299 if (!n->labels.empty())
1301 assign_phandle(n.get(), next);
1304 for (auto &c : n->child_nodes())
1306 assign_phandles(c, next);
1311 device_tree::resolve_cross_references(uint32_t &phandle)
1313 for (auto *pv : cross_references)
1315 node_path path = node_paths[pv->string_data];
1316 auto p = path.begin();
1317 auto pe = path.end();
1320 // Skip the first name in the path. It's always "", and implicitly /
1321 for (++p ; p!=pe ; ++p)
1323 pv->byte_data.push_back('/');
1324 push_string(pv->byte_data, p->first);
1325 if (!(p->second.empty()))
1327 pv->byte_data.push_back('@');
1328 push_string(pv->byte_data, p->second);
1331 pv->byte_data.push_back(0);
1334 std::unordered_map<property_value*, fixup&> phandle_set;
1335 for (auto &i : fixups)
1337 phandle_set.insert({&i.val, i});
1339 std::vector<std::reference_wrapper<fixup>> sorted_phandles;
1340 root->visit([&](node &n, node *) {
1341 for (auto &p : n.properties())
1345 auto i = phandle_set.find(&v);
1346 if (i != phandle_set.end())
1348 sorted_phandles.push_back(i->second);
1353 return node::VISIT_RECURSE;
1355 assert(sorted_phandles.size() == fixups.size());
1357 for (auto &i : sorted_phandles)
1359 string target_name = i.get().val.string_data;
1360 node *target = nullptr;
1362 // If the node name is a path, then look it up by following the path,
1363 // otherwise jump directly to the named node.
1364 if (target_name[0] == '/')
1367 target = root.get();
1368 std::istringstream ss(target_name);
1369 string path_element;
1370 // Read the leading /
1371 std::getline(ss, path_element, '/');
1372 // Iterate over path elements
1376 std::getline(ss, path_element, '/');
1377 std::istringstream nss(path_element);
1378 string node_name, node_address;
1379 std::getline(nss, node_name, '@');
1380 std::getline(nss, node_address, '@');
1381 node *next = nullptr;
1382 for (auto &c : target->child_nodes())
1384 if (c->name == node_name)
1386 if (c->unit_address == node_address)
1393 possible = path + c->name;
1394 if (c->unit_address != string())
1397 possible += c->unit_address;
1403 if (node_address != string())
1406 path += node_address;
1409 if (target == nullptr)
1417 target = node_names[target_name];
1419 if (target == nullptr)
1423 unresolved_fixups.push_back(i);
1428 fprintf(stderr, "Failed to find node with label: %s\n", target_name.c_str());
1429 if (possible != string())
1431 fprintf(stderr, "Possible intended match: %s\n", possible.c_str());
1437 // If there is an existing phandle, use it
1438 property_ptr p = assign_phandle(target, phandle);
1439 p->begin()->push_to_buffer(i.get().val.byte_data);
1440 assert(i.get().val.byte_data.size() == 4);
1446 device_tree::parse_file(text_input_buffer &input,
1447 std::vector<node_ptr> &roots,
1452 if (input.consume("/dts-v1/;"))
1457 if (input.consume("/plugin/;"))
1464 input.parse_error("Expected /dts-v1/; version string");
1466 // Read any memory reservations
1467 while (input.consume("/memreserve/"))
1469 unsigned long long start, len;
1471 // Read the start and length.
1472 if (!(input.consume_integer_expression(start) &&
1473 (input.next_token(),
1474 input.consume_integer_expression(len))))
1476 input.parse_error("Expected size on /memreserve/ node.");
1480 reservations.push_back(reservation(start, len));
1483 while (valid && !input.finished())
1486 if (input.consume('/'))
1489 n = node::parse(input, string(), string_set(), string(), &defines);
1491 else if (input.consume('&'))
1495 bool name_is_path_reference = false;
1496 // This is to deal with names intended as path references, e.g. &{/path}.
1497 // While it may make sense in a non-plugin context, we don't support such
1498 // usage at this time.
1499 if (input.consume('{') && is_plugin)
1501 name = input.parse_to('}');
1503 name_is_path_reference = true;
1507 name = input.parse_node_name();
1510 n = node::parse(input, std::move(name), string_set(), string(), &defines);
1511 n->name_is_path_reference = name_is_path_reference;
1515 input.parse_error("Failed to find root node /.");
1519 roots.push_back(std::move(n));
1529 template<class writer> void
1530 device_tree::write(int fd)
1532 dtb::string_table st;
1535 writer reservation_writer;
1536 writer struct_writer;
1537 writer strings_writer;
1539 // Build the reservation table
1540 reservation_writer.write_comment(string("Memory reservations"));
1541 reservation_writer.write_label(string("dt_reserve_map"));
1542 for (auto &i : reservations)
1544 reservation_writer.write_comment(string("Reservation start"));
1545 reservation_writer.write_data(i.first);
1546 reservation_writer.write_comment(string("Reservation length"));
1547 reservation_writer.write_data(i.first);
1549 // Write n spare reserve map entries, plus the trailing 0.
1550 for (uint32_t i=0 ; i<=spare_reserve_map_entries ; i++)
1552 reservation_writer.write_data((uint64_t)0);
1553 reservation_writer.write_data((uint64_t)0);
1557 struct_writer.write_comment(string("Device tree"));
1558 struct_writer.write_label(string("dt_struct_start"));
1559 root->write(struct_writer, st);
1560 struct_writer.write_token(dtb::FDT_END);
1561 struct_writer.write_label(string("dt_struct_end"));
1563 st.write(strings_writer);
1564 // Find the strings size before we stick padding on the end.
1565 // Note: We should possibly use a new writer for the padding.
1566 head.size_dt_strings = strings_writer.size();
1568 // Stick the padding in the strings writer, but after the
1569 // marker indicating that it's the end.
1570 // Note: We probably should add a padding call to the writer so
1571 // that the asm back end can write padding directives instead
1572 // of a load of 0 bytes.
1573 for (uint32_t i=0 ; i<blob_padding ; i++)
1575 strings_writer.write_data((uint8_t)0);
1577 head.totalsize = sizeof(head) + strings_writer.size() +
1578 struct_writer.size() + reservation_writer.size();
1579 while (head.totalsize < minimum_blob_size)
1582 strings_writer.write_data((uint8_t)0);
1584 head.off_dt_struct = sizeof(head) + reservation_writer.size();;
1585 head.off_dt_strings = head.off_dt_struct + struct_writer.size();
1586 head.off_mem_rsvmap = sizeof(head);
1587 head.boot_cpuid_phys = boot_cpu;
1588 head.size_dt_struct = struct_writer.size();
1589 head.write(head_writer);
1591 head_writer.write_to_file(fd);
1592 reservation_writer.write_to_file(fd);
1593 struct_writer.write_to_file(fd);
1594 strings_writer.write_label(string("dt_blob_end"));
1595 strings_writer.write_to_file(fd);
1599 device_tree::referenced_node(property_value &v)
1603 return node_names[v.string_data];
1607 return used_phandles[v.get_as_uint32()];
1613 device_tree::write_binary(int fd)
1615 write<dtb::binary_writer>(fd);
1619 device_tree::write_asm(int fd)
1621 write<dtb::asm_writer>(fd);
1625 device_tree::write_dts(int fd)
1627 FILE *file = fdopen(fd, "w");
1628 fputs("/dts-v1/;\n\n", file);
1630 if (!reservations.empty())
1632 const char msg[] = "/memreserve/";
1633 fwrite(msg, sizeof(msg), 1, file);
1634 for (auto &i : reservations)
1636 fprintf(file, " %" PRIx64 " %" PRIx64, i.first, i.second);
1638 fputs(";\n\n", file);
1642 root->write_dts(file, 0);
1647 device_tree::parse_dtb(const string &fn, FILE *)
1649 auto in = input_buffer::buffer_for_file(fn);
1655 input_buffer &input = *in;
1657 valid = h.read_dtb(input);
1658 boot_cpu = h.boot_cpuid_phys;
1659 if (h.last_comp_version > 17)
1661 fprintf(stderr, "Don't know how to read this version of the device tree blob");
1668 input_buffer reservation_map =
1669 input.buffer_from_offset(h.off_mem_rsvmap, 0);
1670 uint64_t start, length;
1673 if (!(reservation_map.consume_binary(start) &&
1674 reservation_map.consume_binary(length)))
1676 fprintf(stderr, "Failed to read memory reservation table\n");
1680 } while (!((start == 0) && (length == 0)));
1681 input_buffer struct_table =
1682 input.buffer_from_offset(h.off_dt_struct, h.size_dt_struct);
1683 input_buffer strings_table =
1684 input.buffer_from_offset(h.off_dt_strings, h.size_dt_strings);
1686 if (!(struct_table.consume_binary(token) &&
1687 (token == dtb::FDT_BEGIN_NODE)))
1689 fprintf(stderr, "Expected FDT_BEGIN_NODE token.\n");
1693 root = node::parse_dtb(struct_table, strings_table);
1694 if (!(struct_table.consume_binary(token) && (token == dtb::FDT_END)))
1696 fprintf(stderr, "Expected FDT_END token after parsing root node.\n");
1700 valid = (root != 0);
1704 device_tree::node_path::to_string() const
1709 if ((p == pe) || (p+1 == pe))
1713 // Skip the first name in the path. It's always "", and implicitly /
1714 for (++p ; p!=pe ; ++p)
1718 if (!(p->second.empty()))
1728 device_tree::create_fragment_wrapper(node_ptr &node, int &fragnum)
1730 // In a plugin, we can massage these non-/ root nodes into into a fragment
1731 std::string fragment_address = "fragment@" + std::to_string(fragnum);
1734 std::vector<property_ptr> symbols;
1736 // Intentionally left empty
1737 node_ptr newroot = node::create_special_node("", symbols);
1738 node_ptr wrapper = node::create_special_node("__overlay__", symbols);
1740 // Generate the fragment with $propname = <&name>
1742 std::string propname;
1743 v.string_data = node->name;
1744 if (!node->name_is_path_reference)
1746 propname = "target";
1747 v.type = property_value::PHANDLE;
1751 propname = "target-path";
1752 v.type = property_value::STRING;
1754 auto prop = std::make_shared<property>(std::string(propname));
1756 symbols.push_back(prop);
1758 node_ptr fragment = node::create_special_node(fragment_address, symbols);
1760 wrapper->merge_node(node);
1761 fragment->add_child(std::move(wrapper));
1762 newroot->add_child(std::move(fragment));
1767 device_tree::generate_root(node_ptr &node, int &fragnum)
1770 string name = node->name;
1771 if (name == string())
1773 return std::move(node);
1775 else if (!is_plugin)
1780 return create_fragment_wrapper(node, fragnum);
1784 device_tree::reassign_fragment_numbers(node_ptr &node, int &delta)
1787 for (auto &c : node->child_nodes())
1789 if (c->name == std::string("fragment"))
1791 int current_address = std::stoi(c->unit_address, nullptr, 16);
1792 std::ostringstream new_address;
1793 current_address += delta;
1794 // It's possible that we hopped more than one somewhere, so just reset
1795 // delta to the next in sequence.
1796 delta = current_address + 1;
1797 new_address << std::hex << current_address;
1798 c->unit_address = new_address.str();
1804 device_tree::parse_dts(const string &fn, FILE *depfile)
1806 auto in = input_buffer::buffer_for_file(fn);
1812 std::vector<node_ptr> roots;
1813 std::unordered_set<string> defnames;
1814 for (auto &i : defines)
1816 defnames.insert(i.first);
1818 text_input_buffer input(std::move(in),
1819 std::move(defnames),
1820 std::vector<string>(include_paths),
1823 bool read_header = false;
1825 parse_file(input, roots, read_header);
1826 switch (roots.size())
1830 input.parse_error("Failed to find root node /.");
1833 root = generate_root(roots[0], fragnum);
1837 input.parse_error("Failed to find root node /.");
1843 root = generate_root(roots[0], fragnum);
1847 input.parse_error("Failed to find root node /.");
1850 for (auto i=++(roots.begin()), e=roots.end() ; i!=e ; ++i)
1853 string name = node->name;
1854 if (name == string())
1858 // Re-assign any fragment numbers based on a delta of
1859 // fragnum before we merge it
1860 reassign_fragment_numbers(node, fragnum);
1862 root->merge_node(node);
1866 auto existing = node_names.find(name);
1867 if (existing == node_names.end())
1870 existing = node_names.find(name);
1872 if (existing == node_names.end())
1876 auto fragment = create_fragment_wrapper(node, fragnum);
1877 root->merge_node(fragment);
1881 fprintf(stderr, "Unable to merge node: %s\n", name.c_str());
1886 existing->second->merge_node(node);
1893 uint32_t phandle = 1;
1894 // If we're writing symbols, go ahead and assign phandles to the entire
1895 // tree. We'll do this before we resolve cross references, just to keep
1896 // order semi-predictable and stable.
1899 assign_phandles(root, phandle);
1901 resolve_cross_references(phandle);
1904 std::vector<property_ptr> symbols;
1905 // Create a symbol table. Each label in this device tree may be
1906 // referenced by other plugins, so we create a __symbols__ node inside
1907 // the root that contains mappings (properties) from label names to
1909 for (auto &s : node_paths)
1912 v.string_data = s.second.to_string();
1913 v.type = property_value::STRING;
1914 string name = s.first;
1915 auto prop = std::make_shared<property>(std::move(name));
1917 symbols.push_back(prop);
1919 root->add_child(node::create_special_node("__symbols__", symbols));
1921 // If this is a plugin, then we also need to create two extra nodes.
1922 // Internal phandles will need to be renumbered to avoid conflicts with
1923 // already-loaded nodes and external references will need to be
1927 std::vector<property_ptr> symbols;
1928 // Create the fixups entry. This is of the form:
1929 // {target} = {path}:{property name}:{offset}
1930 auto create_fixup_entry = [&](fixup &i, string target)
1932 string value = i.path.to_string();
1934 value += i.prop->get_key();
1936 value += std::to_string(i.prop->offset_of_value(i.val));
1938 v.string_data = value;
1939 v.type = property_value::STRING;
1940 auto prop = std::make_shared<property>(std::move(target));
1944 // If we have any unresolved phandle references in this plugin,
1945 // then we must update them to 0xdeadbeef and leave a property in
1946 // the /__fixups__ node whose key is the label and whose value is
1947 // as described above.
1948 if (!unresolved_fixups.empty())
1950 for (auto &i : unresolved_fixups)
1952 auto &val = i.get().val;
1953 symbols.push_back(create_fixup_entry(i, val.string_data));
1954 val.byte_data.push_back(0xde);
1955 val.byte_data.push_back(0xad);
1956 val.byte_data.push_back(0xbe);
1957 val.byte_data.push_back(0xef);
1958 val.type = property_value::BINARY;
1960 root->add_child(node::create_special_node("__fixups__", symbols));
1963 // If we have any resolved phandle references in this plugin, then
1964 // we must create a child in the __local_fixups__ node whose path
1965 // matches the node path from the root and whose value contains the
1966 // location of the reference within a property.
1968 // Create a local_fixups node that is initially empty.
1969 node_ptr local_fixups = node::create_special_node("__local_fixups__", symbols);
1970 for (auto &i : fixups)
1972 if (!i.val.is_phandle())
1976 node *n = local_fixups.get();
1977 for (auto &p : i.path)
1979 // Skip the implicit root
1980 if (p.first.empty())
1985 for (auto &c : n->child_nodes())
1987 if (c->name == p.first)
1989 string path = p.first;
1990 if (!(p.second.empty()))
1995 n->add_child(node::create_special_node(path, symbols));
1996 n = (--n->child_end())->get();
2001 n->add_child(node::create_special_node(p.first, symbols));
2002 n = (--n->child_end())->get();
2007 push_big_endian(pv.byte_data, static_cast<uint32_t>(i.prop->offset_of_value(i.val)));
2008 pv.type = property_value::BINARY;
2009 auto key = i.prop->get_key();
2010 property_ptr prop = n->get_property(key);
2011 // If we don't have an existing property then create one and
2012 // use this property value
2015 prop = std::make_shared<property>(std::move(key));
2016 n->add_property(prop);
2017 prop->add_value(pv);
2021 // If we do have an existing property value, try to append
2023 property_value &old_val = *(--prop->end());
2024 if (!old_val.try_to_merge(pv))
2026 prop->add_value(pv);
2030 // We've iterated over all fixups, but only emit the
2031 // __local_fixups__ if we found some that were resolved internally.
2032 if (local_fixups->child_begin() != local_fixups->child_end())
2034 root->add_child(std::move(local_fixups));
2039 bool device_tree::parse_define(const char *def)
2041 const char *val = strchr(def, '=');
2044 if (strlen(def) != 0)
2052 string name(def, val-def);
2053 string name_copy = name;
2055 std::unique_ptr<input_buffer> raw(new input_buffer(val, strlen(val)));
2056 text_input_buffer in(std::move(raw),
2057 std::unordered_set<string>(),
2058 std::vector<string>(),
2061 property_ptr p = property::parse(in, std::move(name_copy), string_set(), false);