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 #include "input_buffer.hh"
52 #ifndef MAP_PREFAULT_READ
53 #define MAP_PREFAULT_READ 0
61 * Subclass of input_buffer that mmap()s a file and owns the resulting memory.
62 * When this object is destroyed, the memory is unmapped.
64 struct mmap_input_buffer : public dtc::input_buffer
67 const string &filename() const override
72 * Constructs a new buffer from the file passed in as a file
75 mmap_input_buffer(int fd, string &&filename);
77 * Unmaps the buffer, if one exists.
79 virtual ~mmap_input_buffer();
82 * Input buffer read from standard input. This is used for reading device tree
83 * blobs and source from standard input. It reads the entire input into
84 * malloc'd memory, so will be very slow for large inputs. DTS and DTB files
85 * are very rarely more than 10KB though, so this is probably not a problem.
87 struct stream_input_buffer : public dtc::input_buffer
89 const string &filename() const override
91 static string n = "<standard input>";
95 * The buffer that will store the data read from the standard input.
99 * Constructs a new buffer from the standard input.
101 stream_input_buffer();
104 mmap_input_buffer::mmap_input_buffer(int fd, std::string &&filename)
105 : input_buffer(0, 0), fn(filename)
110 perror("Failed to stat file");
113 buffer = (const char*)mmap(0, size, PROT_READ, MAP_PRIVATE |
114 MAP_PREFAULT_READ, fd, 0);
115 if (buffer == MAP_FAILED)
117 perror("Failed to mmap file");
122 mmap_input_buffer::~mmap_input_buffer()
126 munmap((void*)buffer, size);
130 stream_input_buffer::stream_input_buffer() : input_buffer(0, 0)
133 while ((c = fgetc(stdin)) != EOF)
141 } // Anonymous namespace
148 input_buffer::skip_to(char c)
150 while ((cursor < size) && (buffer[cursor] != c))
157 text_input_buffer::skip_to(char c)
159 while (!finished() && (*(*this) != c))
166 text_input_buffer::skip_spaces()
168 if (finished()) { return; }
170 bool last_nl = false;
171 while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\f')
172 || (c == '\v') || (c == '\r'))
174 last_nl = ((c == '\n') || (c == '\r'));
185 // Skip C preprocessor leftovers
186 if ((c == '#') && ((cursor == 0) || last_nl))
191 if (consume("/include/"))
199 text_input_buffer::handle_include()
201 bool reallyInclude = true;
205 string name = parse_property_name();
206 if (defines.count(name) > 0)
208 reallyInclude = true;
215 parse_error("Expected quoted filename");
218 string file = parse_to('"');
224 string include_file = dir + '/' + file;
225 auto include_buffer = input_buffer::buffer_for_file(include_file, false);
226 if (include_buffer == 0)
228 for (auto i : include_paths)
230 include_file = i + '/' + file;
231 include_buffer = input_buffer::buffer_for_file(include_file, false);
232 if (include_buffer != 0)
241 fputs(include_file.c_str(), depfile);
245 parse_error("Unable to locate input file");
248 input_stack.push(std::move(include_buffer));
252 input_buffer::buffer_from_offset(int offset, int s)
256 return input_buffer();
264 return input_buffer();
266 if (s > (size-offset))
268 return input_buffer();
270 return input_buffer(&buffer[offset], s);
274 input_buffer::consume(const char *str)
276 int len = strlen(str);
277 if (len > size - cursor)
283 for (int i=0 ; i<len ; ++i)
285 if (str[i] != (*this)[i])
297 input_buffer::consume_integer(unsigned long long &outInt)
299 // The first character must be a digit. Hex and octal strings
300 // are prefixed by 0 and 0x, respectively.
301 if (!isdigit((*this)[0]))
305 char *end= const_cast<char*>(&buffer[size]);
306 outInt = strtoull(&buffer[cursor], &end, 0);
307 if (end == &buffer[cursor])
311 cursor = end - buffer;
318 * Convenience typedef for the type that we use for all values.
320 typedef unsigned long long valty;
323 * Expression tree currently being parsed.
327 typedef text_input_buffer::source_location source_location;
329 * The type that is returned when computing the result. The boolean value
330 * indicates whether this is a valid expression.
332 * FIXME: Once we can use C++17, this should be `std::optional`.
334 typedef std::pair<valty, bool> result;
336 * Evaluate this node, taking into account operator precedence.
338 virtual result operator()() = 0;
340 * Returns the precedence of this node. Lower values indicate higher
343 virtual int precedence() = 0;
345 * Constructs an expression, storing the location where it was created.
347 expression(source_location l) : loc(l) {}
348 virtual ~expression() {}
351 * Dumps this expression to `std::cerr`, appending a newline if `nl` is
354 void dump(bool nl=false)
359 std::cerr << "{nullptr}\n";
370 * Method that sublcasses override to implement the behaviour of `dump()`.
372 virtual void dump_impl() = 0;
379 * Expression wrapping a single integer. Leaf nodes in the expression tree.
381 class terminal_expr : public expression
384 * The value that this wraps.
388 * Evaluate. Trivially returns the value that this class wraps.
390 result operator()() override
394 int precedence() override
402 terminal_expr(source_location l, valty v) : expression(l), val(v) {}
404 void dump_impl() override { std::cerr << val; }
409 * Parenthetical expression. Exists to make the contents opaque.
411 struct paren_expression : public expression
414 * The expression within the parentheses.
416 expression_ptr subexpr;
418 * Constructor. Takes the child expression as the only argument.
420 paren_expression(source_location l, expression_ptr p) : expression(l),
421 subexpr(std::move(p)) {}
422 int precedence() override
427 * Evaluate - just forwards to the underlying expression.
429 result operator()() override
434 void dump_impl() override
444 * Template class for unary operators. The `OpChar` template parameter is
445 * solely for debugging and makes it easy to print the expression. The `Op`
446 * template parameter is a function object that implements the operator that
447 * this class provides. Most of these are provided by the `<functional>`
450 template<char OpChar, class Op>
451 class unary_operator : public expression
454 * The subexpression for this unary operator.
456 expression_ptr subexpr;
457 result operator()() override
460 result s = (*subexpr)();
465 return {op(s.first), true};
468 * All unary operators have the same precedence. They are all evaluated
469 * before binary expressions, but after parentheses.
471 int precedence() override
476 unary_operator(source_location l, expression_ptr p) :
477 expression(l), subexpr(std::move(p)) {}
479 void dump_impl() override
488 * Abstract base class for binary operators. Allows the tree to be modified
489 * without knowing what the operations actually are.
491 struct binary_operator_base : public expression
493 using expression::expression;
495 * The left side of the expression.
499 * The right side of the expression.
503 * Insert a node somewhere down the path of left children, until it would
504 * be preempting something that should execute first.
506 void insert_left(binary_operator_base *new_left)
508 if (lhs->precedence() < new_left->precedence())
510 new_left->rhs = std::move(lhs);
515 static_cast<binary_operator_base*>(lhs.get())->insert_left(new_left);
521 * Template class for binary operators. The precedence and the operation are
522 * provided as template parameters.
524 template<int Precedence, class Op>
525 struct binary_operator : public binary_operator_base
527 result operator()() override
532 if (!(l.second && r.second))
536 return {op(l.first, r.first), true};
538 int precedence() override
544 * Constructor. Takes the name of the operator as an argument, for
545 * debugging. Only stores it in debug mode.
547 binary_operator(source_location l, const char *) : expression(l) {}
550 binary_operator(source_location l, const char *o) :
551 binary_operator_base(l), opName(o) {}
552 void dump_impl() override
562 * Ternary conditional operators (`cond ? true : false`) are a special case -
563 * there are no other ternary operators.
565 class ternary_conditional_operator : public expression
568 * The condition for the clause.
572 * The expression that this evaluates to if the condition is true.
576 * The expression that this evaluates to if the condition is false.
579 result operator()() override
581 result c = (*cond)();
584 if (!(l.second && r.second && c.second))
588 return c.first ? l : r;
590 int precedence() override
592 // The actual precedence of a ternary conditional operator is 15, but
593 // its associativity is the opposite way around to the other operators,
594 // so we fudge it slightly.
598 void dump_impl() override
608 ternary_conditional_operator(source_location sl,
612 expression(sl), cond(std::move(c)), lhs(std::move(l)),
619 constexpr T operator()(const T &lhs, const T &rhs) const
627 constexpr T operator()(const T &lhs, const T &rhs) const
635 constexpr T operator()(const T &val) const
640 // TODO: Replace with std::bit_not once we can guarantee C++14 as a baseline.
644 constexpr T operator()(const T &val) const
651 struct divmod : public binary_operator<5, T>
653 using binary_operator<5, T>::binary_operator;
654 using binary_operator_base::result;
655 result operator()() override
657 result r = (*binary_operator_base::rhs)();
658 if (r.second && (r.first == 0))
660 expression::loc.report_error("Division by zero");
663 return binary_operator<5, T>::operator()();
667 } // anonymous namespace
670 expression_ptr text_input_buffer::parse_binary_expression(expression_ptr lhs)
673 binary_operator_base *expr = nullptr;
675 source_location l = location();
681 expr = new binary_operator<6, std::plus<valty>>(l, "+");
684 expr = new binary_operator<6, std::minus<valty>>(l, "-");
687 expr = new divmod<std::modulus<valty>>(l, "/");
690 expr = new binary_operator<5, std::multiplies<valty>>(l, "*");
693 expr = new divmod<std::divides<valty>>(l, "/");
699 parse_error("Invalid operator");
704 expr = new binary_operator<8, std::less<valty>>(l, "<");
708 expr = new binary_operator<8, std::less_equal<valty>>(l, "<=");
712 expr = new binary_operator<7, lshift<valty>>(l, "<<");
720 parse_error("Invalid operator");
725 expr = new binary_operator<8, std::greater<valty>>(l, ">");
729 expr = new binary_operator<8, std::greater_equal<valty>>(l, ">=");
733 expr = new binary_operator<7, rshift<valty>>(l, ">>");
741 parse_error("Invalid operator");
744 expr = new binary_operator<9, std::equal_to<valty>>(l, "==");
749 parse_error("Invalid operator");
753 expr = new binary_operator<9, std::not_equal_to<valty>>(l, "!=");
758 expr = new binary_operator<13, std::logical_and<valty>>(l, "&&");
762 expr = new binary_operator<10, std::bit_and<valty>>(l, "&");
768 expr = new binary_operator<12, std::logical_or<valty>>(l, "||");
772 expr = new binary_operator<14, std::bit_or<valty>>(l, "|");
778 expression_ptr true_case = parse_expression();
780 if (!true_case || !consume(':'))
782 parse_error("Expected : in ternary conditional operator");
785 expression_ptr false_case = parse_expression();
788 parse_error("Expected false condition for ternary operator");
791 return expression_ptr(new ternary_conditional_operator(l, std::move(lhs),
792 std::move(true_case), std::move(false_case)));
797 expression_ptr e(expr);
798 expression_ptr rhs(parse_expression());
803 expr->lhs = std::move(lhs);
804 if (rhs->precedence() < expr->precedence())
806 expr->rhs = std::move(rhs);
810 // If we're a normal left-to-right expression, then we need to insert
811 // this as the far-left child node of the rhs expression
812 binary_operator_base *rhs_op =
813 static_cast<binary_operator_base*>(rhs.get());
814 rhs_op->insert_left(expr);
821 expression_ptr text_input_buffer::parse_expression(bool stopAtParen)
824 unsigned long long leftVal;
826 source_location l = location();
830 if (!consume_integer(leftVal))
834 lhs.reset(new terminal_expr(l, leftVal));
839 expression_ptr &&subexpr = parse_expression();
844 lhs.reset(new paren_expression(l, std::move(subexpr)));
858 expression_ptr &&subexpr = parse_expression();
863 lhs.reset(new unary_operator<'+', unary_plus<valty>>(l, std::move(subexpr)));
869 expression_ptr &&subexpr = parse_expression();
874 lhs.reset(new unary_operator<'-', std::negate<valty>>(l, std::move(subexpr)));
880 expression_ptr &&subexpr = parse_expression();
885 lhs.reset(new unary_operator<'!', std::logical_not<valty>>(l, std::move(subexpr)));
891 expression_ptr &&subexpr = parse_expression();
896 lhs.reset(new unary_operator<'~', bit_not<valty>>(l, std::move(subexpr)));
904 return parse_binary_expression(std::move(lhs));
908 text_input_buffer::consume_integer_expression(unsigned long long &outInt)
914 expression_ptr e(parse_expression(true));
928 return consume_integer(outInt);
935 input_buffer::consume_hex_byte(uint8_t &outByte)
937 if (!ishexdigit((*this)[0]) && !ishexdigit((*this)[1]))
941 outByte = (digittoint((*this)[0]) << 4) | digittoint((*this)[1]);
947 text_input_buffer::next_token()
959 if (*self == '/' && peek() == '*')
961 // eat the start of the comment
965 // Find the ending * of */
966 while ((*self != '\0') && (*self != '*') && !finished())
972 } while ((*self != '\0') && (*self != '/') && !finished());
977 if ((*self == '/' && peek() == '/'))
979 // eat the start of the comment
982 // Find the ending of the line
983 while (*self != '\n' && !finished())
990 } while (start != cursor);
995 text_input_buffer::parse_error(const char *msg)
997 if (input_stack.empty())
999 fprintf(stderr, "Error: %s\n", msg);
1002 input_buffer &b = *input_stack.top();
1003 parse_error(msg, b, b.cursor);
1006 text_input_buffer::parse_error(const char *msg,
1013 if (loc < 0 || loc > b.size)
1017 for (int i=loc ; i>0 ; --i)
1019 if (b.buffer[i] == '\n')
1022 if (line_start == 0)
1028 for (int i=loc+1 ; i<b.size ; ++i)
1030 if (b.buffer[i] == '\n')
1036 fprintf(stderr, "Error at %s:%d:%d: %s\n", b.filename().c_str(), line_count, loc - line_start, msg);
1037 fwrite(&b.buffer[line_start], line_end-line_start, 1, stderr);
1039 for (int i=0 ; i<(loc-line_start) ; ++i)
1041 char c = (b.buffer[i+line_start] == '\t') ? '\t' : ' ';
1049 input_buffer::dump()
1051 fprintf(stderr, "Current cursor: %d\n", cursor);
1052 fwrite(&buffer[cursor], size-cursor, 1, stderr);
1060 * The source files are ASCII, so we provide a non-locale-aware version of
1061 * isalpha. This is a class so that it can be used with a template function
1062 * for parsing strings.
1066 static inline bool check(const char c)
1068 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') &&
1073 * Check whether a character is in the set allowed for node names. This is a
1074 * class so that it can be used with a template function for parsing strings.
1076 struct is_node_name_character
1078 static inline bool check(const char c)
1084 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1085 case ',': case '.': case '+': case '-':
1092 * Check whether a character is in the set allowed for property names. This is
1093 * a class so that it can be used with a template function for parsing strings.
1095 struct is_property_name_character
1097 static inline bool check(const char c)
1103 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1104 case ',': case '.': case '+': case '-':
1112 string parse(text_input_buffer &s)
1114 std::vector<char> bytes;
1115 for (char c=*s ; T::check(c) ; c=*(++s))
1119 return string(bytes.begin(), bytes.end());
1125 text_input_buffer::parse_node_name()
1127 return parse<is_node_name_character>(*this);
1131 text_input_buffer::parse_property_name()
1133 return parse<is_property_name_character>(*this);
1137 text_input_buffer::parse_node_or_property_name(bool &is_property)
1141 return parse_property_name();
1143 std::vector<char> bytes;
1144 for (char c=*(*this) ; is_node_name_character::check(c) ; c=*(++(*this)))
1148 for (char c=*(*this) ; is_property_name_character::check(c) ; c=*(++(*this)))
1153 return string(bytes.begin(), bytes.end());
1157 input_buffer::parse_to(char stop)
1159 std::vector<char> bytes;
1160 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1164 return string(bytes.begin(), bytes.end());
1168 text_input_buffer::parse_to(char stop)
1170 std::vector<char> bytes;
1171 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1179 return string(bytes.begin(), bytes.end());
1183 text_input_buffer::peek()
1185 return (*input_stack.top())[1];
1188 std::unique_ptr<input_buffer>
1189 input_buffer::buffer_for_file(const string &path, bool warn)
1193 std::unique_ptr<input_buffer> b(new stream_input_buffer());
1196 int source = open(path.c_str(), O_RDONLY);
1201 fprintf(stderr, "Unable to open file '%s'. %s\n", path.c_str(), strerror(errno));
1206 if (fstat(source, &st) == 0 && S_ISDIR(st.st_mode))
1210 fprintf(stderr, "File %s is a directory\n", path.c_str());
1215 std::unique_ptr<input_buffer> b(new mmap_input_buffer(source, std::string(path)));