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 #include "input_buffer.hh"
55 #ifndef MAP_PREFAULT_READ
56 #define MAP_PREFAULT_READ 0
64 * Subclass of input_buffer that mmap()s a file and owns the resulting memory.
65 * When this object is destroyed, the memory is unmapped.
67 struct mmap_input_buffer : public dtc::input_buffer
70 const string &filename() const override
75 * Constructs a new buffer from the file passed in as a file
78 mmap_input_buffer(int fd, string &&filename);
80 * Unmaps the buffer, if one exists.
82 virtual ~mmap_input_buffer();
85 * Input buffer read from standard input. This is used for reading device tree
86 * blobs and source from standard input. It reads the entire input into
87 * malloc'd memory, so will be very slow for large inputs. DTS and DTB files
88 * are very rarely more than 10KB though, so this is probably not a problem.
90 struct stream_input_buffer : public dtc::input_buffer
92 const string &filename() const override
94 static string n = "<standard input>";
98 * The buffer that will store the data read from the standard input.
102 * Constructs a new buffer from the standard input.
104 stream_input_buffer();
107 mmap_input_buffer::mmap_input_buffer(int fd, string &&filename)
108 : input_buffer(0, 0), fn(filename)
113 perror("Failed to stat file");
116 buffer = (const char*)mmap(0, size, PROT_READ, MAP_PRIVATE |
117 MAP_PREFAULT_READ, fd, 0);
118 if (buffer == MAP_FAILED)
120 perror("Failed to mmap file");
125 mmap_input_buffer::~mmap_input_buffer()
129 munmap((void*)buffer, size);
133 stream_input_buffer::stream_input_buffer() : input_buffer(0, 0)
136 while ((c = fgetc(stdin)) != EOF)
144 } // Anonymous namespace
151 input_buffer::skip_to(char c)
153 while ((cursor < size) && (buffer[cursor] != c))
160 text_input_buffer::skip_to(char c)
162 while (!finished() && (*(*this) != c))
169 text_input_buffer::skip_spaces()
171 if (finished()) { return; }
173 bool last_nl = false;
174 while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\f')
175 || (c == '\v') || (c == '\r'))
177 last_nl = ((c == '\n') || (c == '\r'));
188 // Skip C preprocessor leftovers
189 if ((c == '#') && ((cursor == 0) || last_nl))
194 if (consume("/include/"))
202 text_input_buffer::handle_include()
204 bool reallyInclude = true;
208 string name = parse_property_name();
209 if (defines.count(name) > 0)
211 reallyInclude = true;
218 parse_error("Expected quoted filename");
221 auto loc = location();
222 string file = parse_to('"');
228 string include_file = dir + '/' + file;
229 auto include_buffer = input_buffer::buffer_for_file(include_file, false);
230 if (include_buffer == 0)
232 for (auto i : include_paths)
234 include_file = i + '/' + file;
235 include_buffer = input_buffer::buffer_for_file(include_file, false);
236 if (include_buffer != 0)
245 fputs(include_file.c_str(), depfile);
249 loc.report_error("Unable to locate input file");
252 input_stack.push(std::move(include_buffer));
256 input_buffer::buffer_from_offset(int offset, int s)
260 return input_buffer();
268 return input_buffer();
270 if (s > (size-offset))
272 return input_buffer();
274 return input_buffer(&buffer[offset], s);
278 input_buffer::consume(const char *str)
280 int len = strlen(str);
281 if (len > size - cursor)
287 for (int i=0 ; i<len ; ++i)
289 if (str[i] != (*this)[i])
301 input_buffer::consume_integer(unsigned long long &outInt)
303 // The first character must be a digit. Hex and octal strings
304 // are prefixed by 0 and 0x, respectively.
305 if (!isdigit((*this)[0]))
309 char *end= const_cast<char*>(&buffer[size]);
310 outInt = strtoull(&buffer[cursor], &end, 0);
311 if (end == &buffer[cursor])
315 cursor = end - buffer;
322 * Convenience typedef for the type that we use for all values.
324 typedef unsigned long long valty;
327 * Expression tree currently being parsed.
331 typedef text_input_buffer::source_location source_location;
333 * The type that is returned when computing the result. The boolean value
334 * indicates whether this is a valid expression.
336 * FIXME: Once we can use C++17, this should be `std::optional`.
338 typedef std::pair<valty, bool> result;
340 * Evaluate this node, taking into account operator precedence.
342 virtual result operator()() = 0;
344 * Returns the precedence of this node. Lower values indicate higher
347 virtual int precedence() = 0;
349 * Constructs an expression, storing the location where it was created.
351 expression(source_location l) : loc(l) {}
352 virtual ~expression() {}
355 * Dumps this expression to `std::cerr`, appending a newline if `nl` is
358 void dump(bool nl=false)
363 std::cerr << "{nullptr}\n";
374 * Method that sublcasses override to implement the behaviour of `dump()`.
376 virtual void dump_impl() = 0;
383 * Expression wrapping a single integer. Leaf nodes in the expression tree.
385 class terminal_expr : public expression
388 * The value that this wraps.
392 * Evaluate. Trivially returns the value that this class wraps.
394 result operator()() override
398 int precedence() override
406 terminal_expr(source_location l, valty v) : expression(l), val(v) {}
408 void dump_impl() override { std::cerr << val; }
413 * Parenthetical expression. Exists to make the contents opaque.
415 struct paren_expression : public expression
418 * The expression within the parentheses.
420 expression_ptr subexpr;
422 * Constructor. Takes the child expression as the only argument.
424 paren_expression(source_location l, expression_ptr p) : expression(l),
425 subexpr(std::move(p)) {}
426 int precedence() override
431 * Evaluate - just forwards to the underlying expression.
433 result operator()() override
438 void dump_impl() override
448 * Template class for unary operators. The `OpChar` template parameter is
449 * solely for debugging and makes it easy to print the expression. The `Op`
450 * template parameter is a function object that implements the operator that
451 * this class provides. Most of these are provided by the `<functional>`
454 template<char OpChar, class Op>
455 class unary_operator : public expression
458 * The subexpression for this unary operator.
460 expression_ptr subexpr;
461 result operator()() override
464 result s = (*subexpr)();
469 return {op(s.first), true};
472 * All unary operators have the same precedence. They are all evaluated
473 * before binary expressions, but after parentheses.
475 int precedence() override
480 unary_operator(source_location l, expression_ptr p) :
481 expression(l), subexpr(std::move(p)) {}
483 void dump_impl() override
492 * Abstract base class for binary operators. Allows the tree to be modified
493 * without knowing what the operations actually are.
495 struct binary_operator_base : public expression
497 using expression::expression;
499 * The left side of the expression.
503 * The right side of the expression.
507 * Insert a node somewhere down the path of left children, until it would
508 * be preempting something that should execute first.
510 void insert_left(binary_operator_base *new_left)
512 if (lhs->precedence() < new_left->precedence())
514 new_left->rhs = std::move(lhs);
519 static_cast<binary_operator_base*>(lhs.get())->insert_left(new_left);
525 * Template class for binary operators. The precedence and the operation are
526 * provided as template parameters.
528 template<int Precedence, class Op>
529 struct binary_operator : public binary_operator_base
531 result operator()() override
536 if (!(l.second && r.second))
540 return {op(l.first, r.first), true};
542 int precedence() override
548 * Constructor. Takes the name of the operator as an argument, for
549 * debugging. Only stores it in debug mode.
551 binary_operator(source_location l, const char *) :
552 binary_operator_base(l) {}
555 binary_operator(source_location l, const char *o) :
556 binary_operator_base(l), opName(o) {}
557 void dump_impl() override
567 * Ternary conditional operators (`cond ? true : false`) are a special case -
568 * there are no other ternary operators.
570 class ternary_conditional_operator : public expression
573 * The condition for the clause.
577 * The expression that this evaluates to if the condition is true.
581 * The expression that this evaluates to if the condition is false.
584 result operator()() override
586 result c = (*cond)();
589 if (!(l.second && r.second && c.second))
593 return c.first ? l : r;
595 int precedence() override
597 // The actual precedence of a ternary conditional operator is 15, but
598 // its associativity is the opposite way around to the other operators,
599 // so we fudge it slightly.
603 void dump_impl() override
613 ternary_conditional_operator(source_location sl,
617 expression(sl), cond(std::move(c)), lhs(std::move(l)),
624 constexpr T operator()(const T &lhs, const T &rhs) const
632 constexpr T operator()(const T &lhs, const T &rhs) const
640 constexpr T operator()(const T &val) const
645 // TODO: Replace with std::bit_not once we can guarantee C++14 as a baseline.
649 constexpr T operator()(const T &val) const
656 struct divmod : public binary_operator<5, T>
658 using binary_operator<5, T>::binary_operator;
659 using typename binary_operator_base::result;
660 result operator()() override
662 result r = (*binary_operator_base::rhs)();
663 if (r.second && (r.first == 0))
665 expression::loc.report_error("Division by zero");
668 return binary_operator<5, T>::operator()();
672 } // anonymous namespace
675 expression_ptr text_input_buffer::parse_binary_expression(expression_ptr lhs)
678 binary_operator_base *expr = nullptr;
680 source_location l = location();
686 expr = new binary_operator<6, std::plus<valty>>(l, "+");
689 expr = new binary_operator<6, std::minus<valty>>(l, "-");
692 expr = new divmod<std::modulus<valty>>(l, "/");
695 expr = new binary_operator<5, std::multiplies<valty>>(l, "*");
698 expr = new divmod<std::divides<valty>>(l, "/");
704 parse_error("Invalid operator");
709 expr = new binary_operator<8, std::less<valty>>(l, "<");
713 expr = new binary_operator<8, std::less_equal<valty>>(l, "<=");
717 expr = new binary_operator<7, lshift<valty>>(l, "<<");
725 parse_error("Invalid operator");
730 expr = new binary_operator<8, std::greater<valty>>(l, ">");
734 expr = new binary_operator<8, std::greater_equal<valty>>(l, ">=");
738 expr = new binary_operator<7, rshift<valty>>(l, ">>");
746 parse_error("Invalid operator");
749 expr = new binary_operator<9, std::equal_to<valty>>(l, "==");
754 parse_error("Invalid operator");
758 expr = new binary_operator<9, std::not_equal_to<valty>>(l, "!=");
763 expr = new binary_operator<13, std::logical_and<valty>>(l, "&&");
767 expr = new binary_operator<10, std::bit_and<valty>>(l, "&");
773 expr = new binary_operator<12, std::logical_or<valty>>(l, "||");
777 expr = new binary_operator<14, std::bit_or<valty>>(l, "|");
783 expression_ptr true_case = parse_expression();
785 if (!true_case || !consume(':'))
787 parse_error("Expected : in ternary conditional operator");
790 expression_ptr false_case = parse_expression();
793 parse_error("Expected false condition for ternary operator");
796 return expression_ptr(new ternary_conditional_operator(l, std::move(lhs),
797 std::move(true_case), std::move(false_case)));
802 expression_ptr e(expr);
803 expression_ptr rhs(parse_expression());
808 expr->lhs = std::move(lhs);
809 if (rhs->precedence() < expr->precedence())
811 expr->rhs = std::move(rhs);
815 // If we're a normal left-to-right expression, then we need to insert
816 // this as the far-left child node of the rhs expression
817 binary_operator_base *rhs_op =
818 static_cast<binary_operator_base*>(rhs.get());
819 rhs_op->insert_left(expr);
826 expression_ptr text_input_buffer::parse_expression(bool stopAtParen)
829 unsigned long long leftVal;
831 source_location l = location();
835 if (!consume_integer(leftVal))
839 lhs.reset(new terminal_expr(l, leftVal));
844 expression_ptr &&subexpr = parse_expression();
849 lhs.reset(new paren_expression(l, std::move(subexpr)));
863 expression_ptr &&subexpr = parse_expression();
868 lhs.reset(new unary_operator<'+', unary_plus<valty>>(l, std::move(subexpr)));
874 expression_ptr &&subexpr = parse_expression();
879 lhs.reset(new unary_operator<'-', std::negate<valty>>(l, std::move(subexpr)));
885 expression_ptr &&subexpr = parse_expression();
890 lhs.reset(new unary_operator<'!', std::logical_not<valty>>(l, std::move(subexpr)));
896 expression_ptr &&subexpr = parse_expression();
901 lhs.reset(new unary_operator<'~', bit_not<valty>>(l, std::move(subexpr)));
909 return parse_binary_expression(std::move(lhs));
913 text_input_buffer::consume_integer_expression(unsigned long long &outInt)
919 expression_ptr e(parse_expression(true));
933 return consume_integer(outInt);
940 input_buffer::consume_hex_byte(uint8_t &outByte)
942 if (!ishexdigit((*this)[0]) && !ishexdigit((*this)[1]))
946 outByte = (digittoint((*this)[0]) << 4) | digittoint((*this)[1]);
952 text_input_buffer::next_token()
964 if (*self == '/' && peek() == '*')
966 // eat the start of the comment
970 // Find the ending * of */
971 while ((*self != '\0') && (*self != '*') && !finished())
977 } while ((*self != '\0') && (*self != '/') && !finished());
982 if ((*self == '/' && peek() == '/'))
984 // eat the start of the comment
987 // Find the ending of the line
988 while (*self != '\n' && !finished())
995 } while (start != cursor);
1000 text_input_buffer::parse_error(const char *msg)
1002 if (input_stack.empty())
1004 fprintf(stderr, "Error: %s\n", msg);
1007 input_buffer &b = *input_stack.top();
1008 parse_error(msg, b, b.cursor);
1011 text_input_buffer::parse_error(const char *msg,
1018 if (loc < 0 || loc > b.size)
1022 for (int i=loc ; i>0 ; --i)
1024 if (b.buffer[i] == '\n')
1027 if (line_start == 0)
1033 for (int i=loc+1 ; i<b.size ; ++i)
1035 if (b.buffer[i] == '\n')
1041 fprintf(stderr, "Error at %s:%d:%d: %s\n", b.filename().c_str(), line_count, loc - line_start, msg);
1042 fwrite(&b.buffer[line_start], line_end-line_start, 1, stderr);
1044 for (int i=0 ; i<(loc-line_start) ; ++i)
1046 char c = (b.buffer[i+line_start] == '\t') ? '\t' : ' ';
1054 input_buffer::dump()
1056 fprintf(stderr, "Current cursor: %d\n", cursor);
1057 fwrite(&buffer[cursor], size-cursor, 1, stderr);
1065 * The source files are ASCII, so we provide a non-locale-aware version of
1066 * isalpha. This is a class so that it can be used with a template function
1067 * for parsing strings.
1071 static inline bool check(const char c)
1073 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') &&
1078 * Check whether a character is in the set allowed for node names. This is a
1079 * class so that it can be used with a template function for parsing strings.
1081 struct is_node_name_character
1083 static inline bool check(const char c)
1089 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1090 case ',': case '.': case '+': case '-':
1097 * Check whether a character is in the set allowed for property names. This is
1098 * a class so that it can be used with a template function for parsing strings.
1100 struct is_property_name_character
1102 static inline bool check(const char c)
1108 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1109 case ',': case '.': case '+': case '-':
1117 string parse(text_input_buffer &s)
1119 std::vector<char> bytes;
1120 for (char c=*s ; T::check(c) ; c=*(++s))
1124 return string(bytes.begin(), bytes.end());
1130 text_input_buffer::parse_node_name()
1132 return parse<is_node_name_character>(*this);
1136 text_input_buffer::parse_property_name()
1138 return parse<is_property_name_character>(*this);
1142 text_input_buffer::parse_node_or_property_name(bool &is_property)
1146 return parse_property_name();
1148 std::vector<char> bytes;
1149 for (char c=*(*this) ; is_node_name_character::check(c) ; c=*(++(*this)))
1153 for (char c=*(*this) ; is_property_name_character::check(c) ; c=*(++(*this)))
1158 return string(bytes.begin(), bytes.end());
1162 input_buffer::parse_to(char stop)
1164 std::vector<char> bytes;
1165 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1169 return string(bytes.begin(), bytes.end());
1173 text_input_buffer::parse_to(char stop)
1175 std::vector<char> bytes;
1176 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1184 return string(bytes.begin(), bytes.end());
1188 text_input_buffer::peek()
1190 return (*input_stack.top())[1];
1193 std::unique_ptr<input_buffer>
1194 input_buffer::buffer_for_file(const string &path, bool warn)
1198 std::unique_ptr<input_buffer> b(new stream_input_buffer());
1201 int source = open(path.c_str(), O_RDONLY);
1206 fprintf(stderr, "Unable to open file '%s'. %s\n", path.c_str(), strerror(errno));
1211 if (fstat(source, &st) == 0 && S_ISDIR(st.st_mode))
1215 fprintf(stderr, "File %s is a directory\n", path.c_str());
1220 std::unique_ptr<input_buffer> b(new mmap_input_buffer(source, string(path)));