2 * Copyright (c) 2013 David Chisnall
5 * This software was developed by SRI International and the University of
6 * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-10-C-0237)
7 * ("CTSRD"), as part of the DARPA CRASH research programme.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 #define __STDC_LIMIT_MACROS 1
48 #include <sys/types.h>
61 property_value::get_as_uint32()
63 if (byte_data.size() != 4)
68 v &= byte_data[0] << 24;
69 v &= byte_data[1] << 16;
70 v &= byte_data[2] << 8;
71 v &= byte_data[3] << 0;
76 property_value::push_to_buffer(byte_buffer &buffer)
78 if (!byte_data.empty())
80 buffer.insert(buffer.end(), byte_data.begin(), byte_data.end());
84 push_string(buffer, string_data, true);
91 property_value::write_dts(FILE *file)
97 assert(0 && "Invalid type");
100 case CROSS_REFERENCE:
101 write_as_string(file);
104 write_as_cells(file);
107 if (byte_data.size() % 4 == 0)
109 write_as_cells(file);
112 write_as_bytes(file);
118 property_value::resolve_type()
124 if (byte_data.empty())
129 if (byte_data.back() == 0)
131 bool is_all_printable = true;
134 bool lastWasNull = false;
135 for (auto i : byte_data)
138 is_all_printable &= (i == '\0') || isprint(i);
141 // If there are two nulls in a row, then we're probably binary.
154 if (!is_all_printable)
159 if ((is_all_printable && (bytes > nuls)) || bytes == 0)
173 property_value::size()
175 if (!byte_data.empty())
177 return byte_data.size();
179 return string_data.size() + 1;
183 property_value::write_as_string(FILE *file)
186 if (byte_data.empty())
188 fputs(string_data.c_str(), file);
192 bool hasNull = (byte_data.back() == '\0');
193 // Remove trailing null bytes from the string before printing as dts.
196 byte_data.pop_back();
198 for (auto i : byte_data)
200 // FIXME Escape tabs, newlines, and so on.
203 fputs("\", \"", file);
210 byte_data.push_back('\0');
217 property_value::write_as_cells(FILE *file)
220 assert((byte_data.size() % 4) == 0);
221 for (auto i=byte_data.begin(), e=byte_data.end(); i!=e ; ++i)
231 fprintf(file, "0x%" PRIx32, v);
241 property_value::write_as_bytes(FILE *file)
244 for (auto i=byte_data.begin(), e=byte_data.end(); i!=e ; i++)
246 fprintf(file, "%02hhx", *i);
256 property::parse_string(text_input_buffer &input)
259 assert(*input == '"');
261 std::vector<char> bytes;
262 bool isEscaped = false;
263 while (char c = *input)
265 if (c == '"' && !isEscaped)
270 isEscaped = (c == '\\');
274 v.string_data = string(bytes.begin(), bytes.end());
279 property::parse_cells(text_input_buffer &input, int cell_size)
281 assert(*input == '<');
285 while (!input.consume('>'))
288 // If this is a phandle then we need to get the name of the
290 if (input.consume('&'))
294 input.parse_error("reference only permitted in 32-bit arrays");
300 if (!input.consume('{'))
302 referenced = input.parse_node_name();
306 referenced = input.parse_to('}');
309 if (referenced.empty())
311 input.parse_error("Expected node name");
316 // If we already have some bytes, make the phandle a
317 // separate component.
318 if (!v.byte_data.empty())
321 v = property_value();
323 v.string_data = referenced;
324 v.type = property_value::PHANDLE;
326 v = property_value();
330 //FIXME: We should support labels in the middle
331 //of these, but we don't.
332 unsigned long long val;
333 if (!input.consume_integer_expression(val))
335 input.parse_error("Expected numbers in array of cells");
342 v.byte_data.push_back(val);
345 push_big_endian(v.byte_data, (uint16_t)val);
348 push_big_endian(v.byte_data, (uint32_t)val);
351 push_big_endian(v.byte_data, (uint64_t)val);
354 assert(0 && "Invalid cell size!");
359 // Don't store an empty string value here.
360 if (v.byte_data.size() > 0)
367 property::parse_bytes(text_input_buffer &input)
369 assert(*input == '[');
373 while (!input.consume(']'))
376 //FIXME: We should support
377 //labels in the middle of
378 //these, but we don't.
380 if (!input.consume_hex_byte(val))
382 input.parse_error("Expected hex bytes in array of bytes");
386 v.byte_data.push_back(val);
394 property::parse_reference(text_input_buffer &input)
396 assert(*input == '&');
400 v.string_data = input.parse_node_name();
401 if (v.string_data.empty())
403 input.parse_error("Expected node name");
407 v.type = property_value::CROSS_REFERENCE;
411 property::property(input_buffer &structs, input_buffer &strings)
413 uint32_t name_offset;
415 valid = structs.consume_binary(length) &&
416 structs.consume_binary(name_offset);
419 fprintf(stderr, "Failed to read property\n");
423 input_buffer name_buffer = strings.buffer_from_offset(name_offset);
424 if (name_buffer.finished())
426 fprintf(stderr, "Property name offset %" PRIu32
427 " is past the end of the strings table\n",
432 key = name_buffer.parse_to(0);
434 // If we're empty, do not push anything as value.
441 for (uint32_t i=0 ; i<length ; i++)
443 if (!(valid = structs.consume_binary(byte)))
445 fprintf(stderr, "Failed to read property value\n");
448 v.byte_data.push_back(byte);
453 void property::parse_define(text_input_buffer &input, define_map *defines)
458 input.parse_error("No predefined properties to match name\n");
462 string name = input.parse_property_name();
463 define_map::iterator found;
464 if ((name == string()) ||
465 ((found = defines->find(name)) == defines->end()))
467 input.parse_error("Undefined property name\n");
471 values.push_back((*found).second->values[0]);
474 property::property(text_input_buffer &input,
477 bool semicolonTerminated,
478 define_map *defines) : key(k), labels(l), valid(true)
486 parse_define(input, defines);
493 input.parse_error("Invalid property value.");
498 unsigned long long bits = 0;
499 valid = input.consume("/bits/");
501 valid &= input.consume_integer(bits);
506 input.parse_error("Invalid size for elements");
513 input.parse_error("/bits/ directive is only valid on arrays");
517 parse_cells(input, bits);
524 parse_cells(input, 32);
530 parse_reference(input);
538 } while (input.consume(','));
539 if (semicolonTerminated && !input.consume(';'))
541 input.parse_error("Expected ; at end of property");
547 property::parse_dtb(input_buffer &structs, input_buffer &strings)
549 property_ptr p(new property(structs, strings));
558 property::parse(text_input_buffer &input, string &&key, string_set &&label,
559 bool semicolonTerminated, define_map *defines)
561 property_ptr p(new property(input,
574 property::write(dtb::output_writer &writer, dtb::string_table &strings)
576 writer.write_token(dtb::FDT_PROP);
577 byte_buffer value_buffer;
578 for (value_iterator i=begin(), e=end() ; i!=e ; ++i)
580 i->push_to_buffer(value_buffer);
582 writer.write_data((uint32_t)value_buffer.size());
583 writer.write_comment(key);
584 writer.write_data(strings.add_string(key));
585 writer.write_data(value_buffer);
589 property_value::try_to_merge(property_value &other)
595 __builtin_unreachable();
602 case CROSS_REFERENCE:
606 if (other.type == PHANDLE || other.type == BINARY)
609 byte_data.insert(byte_data.end(), other.byte_data.begin(),
610 other.byte_data.end());
618 property::write_dts(FILE *file, int indent)
620 for (int i=0 ; i<indent ; i++)
625 for (auto &l : labels)
627 fputs(l.c_str(), file);
633 fputs(key.c_str(), file);
637 std::vector<property_value> *vals = &values;
638 std::vector<property_value> v;
639 // If we've got multiple values then try to merge them all together.
640 if (values.size() > 1)
643 v.push_back(values.front());
644 for (auto i=(++begin()), e=end() ; i!=e ; ++i)
646 if (!v.back().try_to_merge(*i))
653 for (auto i=vals->begin(), e=vals->end() ; i!=e ; ++i)
667 property::offset_of_value(property_value &val)
670 for (auto &v : values)
682 node::parse_name(text_input_buffer &input, bool &is_property, const char *error)
691 return input.parse_property_name();
693 string n = input.parse_node_or_property_name(is_property);
698 input.parse_error(error);
706 node::visit(std::function<void(node&)> fn)
709 for (auto &&c : children)
715 node::node(input_buffer &structs, input_buffer &strings) : valid(true)
717 std::vector<char> bytes;
718 while (structs[0] != '\0' && structs[0] != '@')
720 bytes.push_back(structs[0]);
723 name = string(bytes.begin(), bytes.end());
725 if (structs[0] == '@')
728 while (structs[0] != '\0')
730 bytes.push_back(structs[0]);
733 unit_address = string(bytes.begin(), bytes.end());
737 while (structs.consume_binary(token))
742 fprintf(stderr, "Unexpected token 0x%" PRIx32
743 " while parsing node.\n", token);
746 // Child node, parse it.
747 case dtb::FDT_BEGIN_NODE:
749 node_ptr child = node::parse_dtb(structs, strings);
755 children.push_back(std::move(child));
758 // End of this node, no errors.
759 case dtb::FDT_END_NODE:
761 // Property, parse it.
764 property_ptr prop = property::parse_dtb(structs, strings);
770 props.push_back(prop);
774 // End of structs table. Should appear after
775 // the end of the last node.
777 fprintf(stderr, "Unexpected FDT_END token while parsing node.\n");
780 // NOPs are padding. Ignore them.
785 fprintf(stderr, "Failed to read token from structs table while parsing node.\n");
791 node::node(const string &n,
792 const std::vector<property_ptr> &p)
795 props.insert(props.begin(), p.begin(), p.end());
798 node_ptr node::create_special_node(const string &name,
799 const std::vector<property_ptr> &props)
801 node_ptr n(new node(name, props));
805 node::node(text_input_buffer &input,
807 std::unordered_set<string> &&l,
810 : labels(l), name(n), unit_address(a), valid(true)
812 if (!input.consume('{'))
814 input.parse_error("Expected { to start new device tree node.\n");
817 while (valid && !input.consume('}'))
819 // flag set if we find any characters that are only in
820 // the property name character set, not the node
821 bool is_property = false;
822 string child_name, child_address;
823 std::unordered_set<string> child_labels;
824 auto parse_delete = [&](const char *expected, bool at)
826 if (child_name == string())
828 input.parse_error(expected);
833 if (at && input.consume('@'))
836 child_name += parse_name(input, is_property, "Expected unit address");
838 if (!input.consume(';'))
840 input.parse_error("Expected semicolon");
846 if (input.consume("/delete-node/"))
849 child_name = input.parse_node_name();
850 parse_delete("Expected node name", true);
853 deleted_children.insert(child_name);
857 if (input.consume("/delete-property/"))
860 child_name = input.parse_property_name();
861 parse_delete("Expected property name", false);
864 deleted_props.insert(child_name);
868 child_name = parse_name(input, is_property,
869 "Expected property or node name");
870 while (input.consume(':'))
872 // Node labels can contain any characters? The
873 // spec doesn't say, so we guess so...
875 child_labels.insert(std::move(child_name));
876 child_name = parse_name(input, is_property, "Expected property or node name");
878 if (input.consume('@'))
880 child_address = parse_name(input, is_property, "Expected unit address");
887 // If we're parsing a property, then we must actually do that.
888 if (input.consume('='))
890 property_ptr p = property::parse(input, std::move(child_name),
891 std::move(child_labels), true, defines);
901 else if (!is_property && *input == ('{'))
903 node_ptr child = node::parse(input, std::move(child_name),
904 std::move(child_labels), std::move(child_address), defines);
907 children.push_back(std::move(child));
914 else if (input.consume(';'))
916 props.push_back(property_ptr(new property(std::move(child_name), std::move(child_labels))));
920 input.parse_error("Error parsing property. Expected property value");
930 node::cmp_properties(property_ptr &p1, property_ptr &p2)
932 return p1->get_key() < p2->get_key();
936 node::cmp_children(node_ptr &c1, node_ptr &c2)
938 if (c1->name == c2->name)
940 return c1->unit_address < c2->unit_address;
942 return c1->name < c2->name;
948 std::sort(property_begin(), property_end(), cmp_properties);
949 std::sort(child_begin(), child_end(), cmp_children);
950 for (auto &c : child_nodes())
957 node::parse(text_input_buffer &input,
963 node_ptr n(new node(input,
976 node::parse_dtb(input_buffer &structs, input_buffer &strings)
978 node_ptr n(new node(structs, strings));
987 node::get_property(const string &key)
989 for (auto &i : props)
991 if (i->get_key() == key)
1000 node::merge_node(node_ptr other)
1002 for (auto &l : other->labels)
1006 // Note: this is an O(n*m) operation. It might be sensible to
1007 // optimise this if we find that there are nodes with very
1008 // large numbers of properties, but for typical usage the
1009 // entire vector will fit (easily) into cache, so iterating
1010 // over it repeatedly isn't that expensive.
1011 for (auto &p : other->properties())
1014 for (auto &mp : properties())
1016 if (mp->get_key() == p->get_key())
1028 for (auto &c : other->children)
1031 for (auto &i : children)
1033 if (i->name == c->name && i->unit_address == c->unit_address)
1035 i->merge_node(std::move(c));
1042 children.push_back(std::move(c));
1045 children.erase(std::remove_if(children.begin(), children.end(),
1046 [&](const node_ptr &p) {
1047 string full_name = p->name;
1048 if (p->unit_address != string())
1051 full_name += p->unit_address;
1053 if (other->deleted_children.count(full_name) > 0)
1055 other->deleted_children.erase(full_name);
1059 }), children.end());
1060 props.erase(std::remove_if(props.begin(), props.end(),
1061 [&](const property_ptr &p) {
1062 if (other->deleted_props.count(p->get_key()) > 0)
1064 other->deleted_props.erase(p->get_key());
1072 node::write(dtb::output_writer &writer, dtb::string_table &strings)
1074 writer.write_token(dtb::FDT_BEGIN_NODE);
1075 byte_buffer name_buffer;
1076 push_string(name_buffer, name);
1077 if (unit_address != string())
1079 name_buffer.push_back('@');
1080 push_string(name_buffer, unit_address);
1082 writer.write_comment(name);
1083 writer.write_data(name_buffer);
1084 writer.write_data((uint8_t)0);
1085 for (auto p : properties())
1087 p->write(writer, strings);
1089 for (auto &c : child_nodes())
1091 c->write(writer, strings);
1093 writer.write_token(dtb::FDT_END_NODE);
1097 node::write_dts(FILE *file, int indent)
1099 for (int i=0 ; i<indent ; i++)
1104 for (auto &label : labels)
1106 fprintf(file, "%s: ", label.c_str());
1109 if (name != string())
1111 fputs(name.c_str(), file);
1113 if (unit_address != string())
1116 fputs(unit_address.c_str(), file);
1118 fputs(" {\n\n", file);
1119 for (auto p : properties())
1121 p->write_dts(file, indent+1);
1123 for (auto &c : child_nodes())
1125 c->write_dts(file, indent+1);
1127 for (int i=0 ; i<indent ; i++)
1131 fputs("};\n", file);
1135 device_tree::collect_names_recursive(node_ptr &n, node_path &path)
1137 path.push_back(std::make_pair(n->name, n->unit_address));
1138 for (const string &name : n->labels)
1140 if (name != string())
1142 auto iter = node_names.find(name);
1143 if (iter == node_names.end())
1145 node_names.insert(std::make_pair(name, n.get()));
1146 node_paths.insert(std::make_pair(name, path));
1150 node_names.erase(iter);
1151 auto i = node_paths.find(name);
1152 if (i != node_paths.end())
1154 node_paths.erase(name);
1156 fprintf(stderr, "Label not unique: %s. References to this label will not be resolved.\n", name.c_str());
1160 for (auto &c : n->child_nodes())
1162 collect_names_recursive(c, path);
1164 // Now we collect the phandles and properties that reference
1166 for (auto &p : n->properties())
1172 fixups.push_back({path, p, v});
1174 if (v.is_cross_reference())
1176 cross_references.push_back(&v);
1179 if ((p->get_key() == "phandle") ||
1180 (p->get_key() == "linux,phandle"))
1182 if (p->begin()->byte_data.size() != 4)
1184 fprintf(stderr, "Invalid phandle value for node %s. Should be a 4-byte value.\n", n->name.c_str());
1189 uint32_t phandle = p->begin()->get_as_uint32();
1190 used_phandles.insert(std::make_pair(phandle, n.get()));
1198 device_tree::collect_names()
1203 cross_references.clear();
1205 collect_names_recursive(root, p);
1209 device_tree::resolve_cross_references()
1211 for (auto *pv : cross_references)
1213 node_path path = node_paths[pv->string_data];
1214 auto p = path.begin();
1215 auto pe = path.end();
1218 // Skip the first name in the path. It's always "", and implicitly /
1219 for (++p ; p!=pe ; ++p)
1221 pv->byte_data.push_back('/');
1222 push_string(pv->byte_data, p->first);
1223 if (!(p->second.empty()))
1225 pv->byte_data.push_back('@');
1226 push_string(pv->byte_data, p->second);
1229 pv->byte_data.push_back(0);
1232 std::unordered_map<property_value*, fixup&> phandle_set;
1233 for (auto &i : fixups)
1235 phandle_set.insert({&i.val, i});
1237 std::vector<std::reference_wrapper<fixup>> sorted_phandles;
1238 root->visit([&](node &n) {
1239 for (auto &p : n.properties())
1243 auto i = phandle_set.find(&v);
1244 if (i != phandle_set.end())
1246 sorted_phandles.push_back(i->second);
1251 assert(sorted_phandles.size() == fixups.size());
1253 uint32_t phandle = 1;
1254 for (auto &i : sorted_phandles)
1256 string target_name = i.get().val.string_data;
1257 node *target = nullptr;
1259 // If the node name is a path, then look it up by following the path,
1260 // otherwise jump directly to the named node.
1261 if (target_name[0] == '/')
1264 target = root.get();
1265 std::istringstream ss(target_name);
1266 string path_element;
1267 // Read the leading /
1268 std::getline(ss, path_element, '/');
1269 // Iterate over path elements
1273 std::getline(ss, path_element, '/');
1274 std::istringstream nss(path_element);
1275 string node_name, node_address;
1276 std::getline(nss, node_name, '@');
1277 std::getline(nss, node_address, '@');
1278 node *next = nullptr;
1279 for (auto &c : target->child_nodes())
1281 if (c->name == node_name)
1283 if (c->unit_address == node_address)
1290 possible = path + c->name;
1291 if (c->unit_address != string())
1294 possible += c->unit_address;
1300 if (node_address != string())
1303 path += node_address;
1306 if (target == nullptr)
1314 target = node_names[target_name];
1316 if (target == nullptr)
1320 unresolved_fixups.push_back(i);
1325 fprintf(stderr, "Failed to find node with label: %s\n", target_name.c_str());
1326 if (possible != string())
1328 fprintf(stderr, "Possible intended match: %s\n", possible.c_str());
1334 // If there is an existing phandle, use it
1335 property_ptr p = target->get_property("phandle");
1338 p = target->get_property("linux,phandle");
1342 // Otherwise insert a new phandle node
1344 while (used_phandles.find(phandle) != used_phandles.end())
1346 // Note that we only don't need to
1347 // store this phandle in the set,
1348 // because we are monotonically
1349 // increasing the value of phandle and
1350 // so will only ever revisit this value
1351 // if we have used 2^32 phandles, at
1352 // which point our blob won't fit in
1353 // any 32-bit system and we've done
1354 // something badly wrong elsewhere
1358 push_big_endian(v.byte_data, phandle++);
1359 if (phandle_node_name == BOTH || phandle_node_name == LINUX)
1361 p.reset(new property("linux,phandle"));
1363 target->add_property(p);
1365 if (phandle_node_name == BOTH || phandle_node_name == EPAPR)
1367 p.reset(new property("phandle"));
1369 target->add_property(p);
1372 p->begin()->push_to_buffer(i.get().val.byte_data);
1373 assert(i.get().val.byte_data.size() == 4);
1379 device_tree::parse_file(text_input_buffer &input,
1380 std::vector<node_ptr> &roots,
1385 if (input.consume("/dts-v1/;"))
1390 if (input.consume("/plugin/;"))
1397 input.parse_error("Expected /dts-v1/; version string");
1399 // Read any memory reservations
1400 while (input.consume("/memreserve/"))
1402 unsigned long long start, len;
1404 // Read the start and length.
1405 if (!(input.consume_integer_expression(start) &&
1406 (input.next_token(),
1407 input.consume_integer_expression(len))))
1409 input.parse_error("Expected size on /memreserve/ node.");
1413 reservations.push_back(reservation(start, len));
1416 while (valid && !input.finished())
1419 if (input.consume('/'))
1422 n = node::parse(input, string(), string_set(), string(), &defines);
1424 else if (input.consume('&'))
1427 string name = input.parse_node_name();
1429 n = node::parse(input, std::move(name), string_set(), string(), &defines);
1433 input.parse_error("Failed to find root node /.");
1437 roots.push_back(std::move(n));
1447 template<class writer> void
1448 device_tree::write(int fd)
1450 dtb::string_table st;
1453 writer reservation_writer;
1454 writer struct_writer;
1455 writer strings_writer;
1457 // Build the reservation table
1458 reservation_writer.write_comment(string("Memory reservations"));
1459 reservation_writer.write_label(string("dt_reserve_map"));
1460 for (auto &i : reservations)
1462 reservation_writer.write_comment(string("Reservation start"));
1463 reservation_writer.write_data(i.first);
1464 reservation_writer.write_comment(string("Reservation length"));
1465 reservation_writer.write_data(i.first);
1467 // Write n spare reserve map entries, plus the trailing 0.
1468 for (uint32_t i=0 ; i<=spare_reserve_map_entries ; i++)
1470 reservation_writer.write_data((uint64_t)0);
1471 reservation_writer.write_data((uint64_t)0);
1475 struct_writer.write_comment(string("Device tree"));
1476 struct_writer.write_label(string("dt_struct_start"));
1477 root->write(struct_writer, st);
1478 struct_writer.write_token(dtb::FDT_END);
1479 struct_writer.write_label(string("dt_struct_end"));
1481 st.write(strings_writer);
1482 // Find the strings size before we stick padding on the end.
1483 // Note: We should possibly use a new writer for the padding.
1484 head.size_dt_strings = strings_writer.size();
1486 // Stick the padding in the strings writer, but after the
1487 // marker indicating that it's the end.
1488 // Note: We probably should add a padding call to the writer so
1489 // that the asm back end can write padding directives instead
1490 // of a load of 0 bytes.
1491 for (uint32_t i=0 ; i<blob_padding ; i++)
1493 strings_writer.write_data((uint8_t)0);
1495 head.totalsize = sizeof(head) + strings_writer.size() +
1496 struct_writer.size() + reservation_writer.size();
1497 while (head.totalsize < minimum_blob_size)
1500 strings_writer.write_data((uint8_t)0);
1502 head.off_dt_struct = sizeof(head) + reservation_writer.size();;
1503 head.off_dt_strings = head.off_dt_struct + struct_writer.size();
1504 head.off_mem_rsvmap = sizeof(head);
1505 head.boot_cpuid_phys = boot_cpu;
1506 head.size_dt_struct = struct_writer.size();
1507 head.write(head_writer);
1509 head_writer.write_to_file(fd);
1510 reservation_writer.write_to_file(fd);
1511 struct_writer.write_to_file(fd);
1512 strings_writer.write_label(string("dt_blob_end"));
1513 strings_writer.write_to_file(fd);
1517 device_tree::referenced_node(property_value &v)
1521 return node_names[v.string_data];
1525 return used_phandles[v.get_as_uint32()];
1531 device_tree::write_binary(int fd)
1533 write<dtb::binary_writer>(fd);
1537 device_tree::write_asm(int fd)
1539 write<dtb::asm_writer>(fd);
1543 device_tree::write_dts(int fd)
1545 FILE *file = fdopen(fd, "w");
1546 fputs("/dts-v1/;\n\n", file);
1548 if (!reservations.empty())
1550 const char msg[] = "/memreserve/";
1551 fwrite(msg, sizeof(msg), 1, file);
1552 for (auto &i : reservations)
1554 fprintf(file, " %" PRIx64 " %" PRIx64, i.first, i.second);
1556 fputs(";\n\n", file);
1560 root->write_dts(file, 0);
1565 device_tree::parse_dtb(const string &fn, FILE *)
1567 auto in = input_buffer::buffer_for_file(fn);
1573 input_buffer &input = *in;
1575 valid = h.read_dtb(input);
1576 boot_cpu = h.boot_cpuid_phys;
1577 if (h.last_comp_version > 17)
1579 fprintf(stderr, "Don't know how to read this version of the device tree blob");
1586 input_buffer reservation_map =
1587 input.buffer_from_offset(h.off_mem_rsvmap, 0);
1588 uint64_t start, length;
1591 if (!(reservation_map.consume_binary(start) &&
1592 reservation_map.consume_binary(length)))
1594 fprintf(stderr, "Failed to read memory reservation table\n");
1598 } while (!((start == 0) && (length == 0)));
1599 input_buffer struct_table =
1600 input.buffer_from_offset(h.off_dt_struct, h.size_dt_struct);
1601 input_buffer strings_table =
1602 input.buffer_from_offset(h.off_dt_strings, h.size_dt_strings);
1604 if (!(struct_table.consume_binary(token) &&
1605 (token == dtb::FDT_BEGIN_NODE)))
1607 fprintf(stderr, "Expected FDT_BEGIN_NODE token.\n");
1611 root = node::parse_dtb(struct_table, strings_table);
1612 if (!(struct_table.consume_binary(token) && (token == dtb::FDT_END)))
1614 fprintf(stderr, "Expected FDT_END token after parsing root node.\n");
1618 valid = (root != 0);
1622 device_tree::node_path::to_string() const
1627 if ((p == pe) || (p+1 == pe))
1631 // Skip the first name in the path. It's always "", and implicitly /
1632 for (++p ; p!=pe ; ++p)
1636 if (!(p->second.empty()))
1646 device_tree::parse_dts(const string &fn, FILE *depfile)
1648 auto in = input_buffer::buffer_for_file(fn);
1654 std::vector<node_ptr> roots;
1655 std::unordered_set<string> defnames;
1656 for (auto &i : defines)
1658 defnames.insert(i.first);
1660 text_input_buffer input(std::move(in),
1661 std::move(defnames),
1662 std::vector<string>(include_paths),
1665 bool read_header = false;
1666 parse_file(input, roots, read_header);
1667 switch (roots.size())
1671 input.parse_error("Failed to find root node /.");
1674 root = std::move(roots[0]);
1678 root = std::move(roots[0]);
1679 for (auto i=++(roots.begin()), e=roots.end() ; i!=e ; ++i)
1682 string name = node->name;
1683 if (name == string())
1685 root->merge_node(std::move(node));
1689 auto existing = node_names.find(name);
1690 if (existing == node_names.end())
1693 existing = node_names.find(name);
1695 if (existing == node_names.end())
1697 fprintf(stderr, "Unable to merge node: %s\n", name.c_str());
1701 existing->second->merge_node(std::move(node));
1708 resolve_cross_references();
1711 std::vector<property_ptr> symbols;
1712 // Create a symbol table. Each label in this device tree may be
1713 // referenced by other plugins, so we create a __symbols__ node inside
1714 // the root that contains mappings (properties) from label names to
1716 for (auto &s : node_paths)
1719 v.string_data = s.second.to_string();
1720 v.type = property_value::STRING;
1721 string name = s.first;
1722 auto prop = std::make_shared<property>(std::move(name));
1724 symbols.push_back(prop);
1726 root->add_child(node::create_special_node("__symbols__", symbols));
1727 // If this is a plugin, then we also need to create two extra nodes.
1728 // Internal phandles will need to be renumbered to avoid conflicts with
1729 // already-loaded nodes and external references will need to be
1733 // Create the fixups entry. This is of the form:
1734 // {target} = {path}:{property name}:{offset}
1735 auto create_fixup_entry = [&](fixup &i, string target)
1737 string value = i.path.to_string();
1739 value += i.prop->get_key();
1741 value += std::to_string(i.prop->offset_of_value(i.val));
1743 v.string_data = value;
1744 v.type = property_value::STRING;
1745 auto prop = std::make_shared<property>(std::move(target));
1749 // If we have any unresolved phandle references in this plugin,
1750 // then we must update them to 0xdeadbeef and leave a property in
1751 // the /__fixups__ node whose key is the label and whose value is
1752 // as described above.
1753 if (!unresolved_fixups.empty())
1756 for (auto &i : unresolved_fixups)
1758 auto &val = i.get().val;
1759 symbols.push_back(create_fixup_entry(i, val.string_data));
1760 val.byte_data.push_back(0xde);
1761 val.byte_data.push_back(0xad);
1762 val.byte_data.push_back(0xbe);
1763 val.byte_data.push_back(0xef);
1764 val.type = property_value::BINARY;
1766 root->add_child(node::create_special_node("__fixups__", symbols));
1769 // If we have any resolved phandle references in this plugin, then
1770 // we must leave a property in the /__local_fixups__ node whose key
1771 // is 'fixup' and whose value is as described above.
1772 for (auto &i : fixups)
1774 if (!i.val.is_phandle())
1778 symbols.push_back(create_fixup_entry(i, "fixup"));
1780 // We've iterated over all fixups, but only emit the
1781 // __local_fixups__ if we found some that were resolved internally.
1782 if (!symbols.empty())
1784 root->add_child(node::create_special_node("__local_fixups__", symbols));
1790 bool device_tree::parse_define(const char *def)
1792 const char *val = strchr(def, '=');
1795 if (strlen(def) != 0)
1803 string name(def, val-def);
1804 string name_copy = name;
1806 std::unique_ptr<input_buffer> raw(new input_buffer(val, strlen(val)));
1807 text_input_buffer in(std::move(raw),
1808 std::unordered_set<string>(),
1809 std::vector<string>(),
1812 property_ptr p = property::parse(in, std::move(name_copy), string_set(), false);