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"
53 #ifndef MAP_PREFAULT_READ
54 #define MAP_PREFAULT_READ 0
62 * Subclass of input_buffer that mmap()s a file and owns the resulting memory.
63 * When this object is destroyed, the memory is unmapped.
65 struct mmap_input_buffer : public dtc::input_buffer
68 const string &filename() const override
73 * Constructs a new buffer from the file passed in as a file
76 mmap_input_buffer(int fd, string &&filename);
78 * Unmaps the buffer, if one exists.
80 virtual ~mmap_input_buffer();
83 * Input buffer read from standard input. This is used for reading device tree
84 * blobs and source from standard input. It reads the entire input into
85 * malloc'd memory, so will be very slow for large inputs. DTS and DTB files
86 * are very rarely more than 10KB though, so this is probably not a problem.
88 struct stream_input_buffer : public dtc::input_buffer
90 const string &filename() const override
92 static string n = "<standard input>";
96 * The buffer that will store the data read from the standard input.
100 * Constructs a new buffer from the standard input.
102 stream_input_buffer();
105 mmap_input_buffer::mmap_input_buffer(int fd, string &&filename)
106 : input_buffer(0, 0), fn(filename)
111 perror("Failed to stat file");
114 buffer = (const char*)mmap(0, size, PROT_READ, MAP_PRIVATE |
115 MAP_PREFAULT_READ, fd, 0);
116 if (buffer == MAP_FAILED)
118 perror("Failed to mmap file");
123 mmap_input_buffer::~mmap_input_buffer()
127 munmap((void*)buffer, size);
131 stream_input_buffer::stream_input_buffer() : input_buffer(0, 0)
134 while ((c = fgetc(stdin)) != EOF)
142 } // Anonymous namespace
149 input_buffer::skip_to(char c)
151 while ((cursor < size) && (buffer[cursor] != c))
158 text_input_buffer::skip_to(char c)
160 while (!finished() && (*(*this) != c))
167 text_input_buffer::skip_spaces()
169 if (finished()) { return; }
171 bool last_nl = false;
172 while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\f')
173 || (c == '\v') || (c == '\r'))
175 last_nl = ((c == '\n') || (c == '\r'));
186 // Skip C preprocessor leftovers
187 if ((c == '#') && ((cursor == 0) || last_nl))
192 if (consume("/include/"))
200 text_input_buffer::handle_include()
202 bool reallyInclude = true;
206 string name = parse_property_name();
207 if (defines.count(name) > 0)
209 reallyInclude = true;
216 parse_error("Expected quoted filename");
219 auto loc = location();
220 string file = parse_to('"');
226 string include_file = dir + '/' + file;
227 auto include_buffer = input_buffer::buffer_for_file(include_file, false);
228 if (include_buffer == 0)
230 for (auto i : include_paths)
232 include_file = i + '/' + file;
233 include_buffer = input_buffer::buffer_for_file(include_file, false);
234 if (include_buffer != 0)
243 fputs(include_file.c_str(), depfile);
247 loc.report_error("Unable to locate input file");
250 input_stack.push(std::move(include_buffer));
254 input_buffer::buffer_from_offset(int offset, int s)
258 return input_buffer();
266 return input_buffer();
268 if (s > (size-offset))
270 return input_buffer();
272 return input_buffer(&buffer[offset], s);
276 input_buffer::consume(const char *str)
278 int len = strlen(str);
279 if (len > size - cursor)
285 for (int i=0 ; i<len ; ++i)
287 if (str[i] != (*this)[i])
299 input_buffer::consume_integer(unsigned long long &outInt)
301 // The first character must be a digit. Hex and octal strings
302 // are prefixed by 0 and 0x, respectively.
303 if (!isdigit((*this)[0]))
307 char *end= const_cast<char*>(&buffer[size]);
308 outInt = strtoull(&buffer[cursor], &end, 0);
309 if (end == &buffer[cursor])
313 cursor = end - buffer;
320 * Convenience typedef for the type that we use for all values.
322 typedef unsigned long long valty;
325 * Expression tree currently being parsed.
329 typedef text_input_buffer::source_location source_location;
331 * The type that is returned when computing the result. The boolean value
332 * indicates whether this is a valid expression.
334 * FIXME: Once we can use C++17, this should be `std::optional`.
336 typedef std::pair<valty, bool> result;
338 * Evaluate this node, taking into account operator precedence.
340 virtual result operator()() = 0;
342 * Returns the precedence of this node. Lower values indicate higher
345 virtual int precedence() = 0;
347 * Constructs an expression, storing the location where it was created.
349 expression(source_location l) : loc(l) {}
350 virtual ~expression() {}
353 * Dumps this expression to `std::cerr`, appending a newline if `nl` is
356 void dump(bool nl=false)
361 std::cerr << "{nullptr}\n";
372 * Method that sublcasses override to implement the behaviour of `dump()`.
374 virtual void dump_impl() = 0;
381 * Expression wrapping a single integer. Leaf nodes in the expression tree.
383 class terminal_expr : public expression
386 * The value that this wraps.
390 * Evaluate. Trivially returns the value that this class wraps.
392 result operator()() override
396 int precedence() override
404 terminal_expr(source_location l, valty v) : expression(l), val(v) {}
406 void dump_impl() override { std::cerr << val; }
411 * Parenthetical expression. Exists to make the contents opaque.
413 struct paren_expression : public expression
416 * The expression within the parentheses.
418 expression_ptr subexpr;
420 * Constructor. Takes the child expression as the only argument.
422 paren_expression(source_location l, expression_ptr p) : expression(l),
423 subexpr(std::move(p)) {}
424 int precedence() override
429 * Evaluate - just forwards to the underlying expression.
431 result operator()() override
436 void dump_impl() override
446 * Template class for unary operators. The `OpChar` template parameter is
447 * solely for debugging and makes it easy to print the expression. The `Op`
448 * template parameter is a function object that implements the operator that
449 * this class provides. Most of these are provided by the `<functional>`
452 template<char OpChar, class Op>
453 class unary_operator : public expression
456 * The subexpression for this unary operator.
458 expression_ptr subexpr;
459 result operator()() override
462 result s = (*subexpr)();
467 return {op(s.first), true};
470 * All unary operators have the same precedence. They are all evaluated
471 * before binary expressions, but after parentheses.
473 int precedence() override
478 unary_operator(source_location l, expression_ptr p) :
479 expression(l), subexpr(std::move(p)) {}
481 void dump_impl() override
490 * Abstract base class for binary operators. Allows the tree to be modified
491 * without knowing what the operations actually are.
493 struct binary_operator_base : public expression
495 using expression::expression;
497 * The left side of the expression.
501 * The right side of the expression.
505 * Insert a node somewhere down the path of left children, until it would
506 * be preempting something that should execute first.
508 void insert_left(binary_operator_base *new_left)
510 if (lhs->precedence() < new_left->precedence())
512 new_left->rhs = std::move(lhs);
517 static_cast<binary_operator_base*>(lhs.get())->insert_left(new_left);
523 * Template class for binary operators. The precedence and the operation are
524 * provided as template parameters.
526 template<int Precedence, class Op>
527 struct binary_operator : public binary_operator_base
529 result operator()() override
534 if (!(l.second && r.second))
538 return {op(l.first, r.first), true};
540 int precedence() override
546 * Constructor. Takes the name of the operator as an argument, for
547 * debugging. Only stores it in debug mode.
549 binary_operator(source_location l, const char *) :
550 binary_operator_base(l) {}
553 binary_operator(source_location l, const char *o) :
554 binary_operator_base(l), opName(o) {}
555 void dump_impl() override
565 * Ternary conditional operators (`cond ? true : false`) are a special case -
566 * there are no other ternary operators.
568 class ternary_conditional_operator : public expression
571 * The condition for the clause.
575 * The expression that this evaluates to if the condition is true.
579 * The expression that this evaluates to if the condition is false.
582 result operator()() override
584 result c = (*cond)();
587 if (!(l.second && r.second && c.second))
591 return c.first ? l : r;
593 int precedence() override
595 // The actual precedence of a ternary conditional operator is 15, but
596 // its associativity is the opposite way around to the other operators,
597 // so we fudge it slightly.
601 void dump_impl() override
611 ternary_conditional_operator(source_location sl,
615 expression(sl), cond(std::move(c)), lhs(std::move(l)),
622 constexpr T operator()(const T &lhs, const T &rhs) const
630 constexpr T operator()(const T &lhs, const T &rhs) const
638 constexpr T operator()(const T &val) const
643 // TODO: Replace with std::bit_not once we can guarantee C++14 as a baseline.
647 constexpr T operator()(const T &val) const
654 struct divmod : public binary_operator<5, T>
656 using binary_operator<5, T>::binary_operator;
657 using typename binary_operator_base::result;
658 result operator()() override
660 result r = (*binary_operator_base::rhs)();
661 if (r.second && (r.first == 0))
663 expression::loc.report_error("Division by zero");
666 return binary_operator<5, T>::operator()();
670 } // anonymous namespace
673 expression_ptr text_input_buffer::parse_binary_expression(expression_ptr lhs)
676 binary_operator_base *expr = nullptr;
678 source_location l = location();
684 expr = new binary_operator<6, std::plus<valty>>(l, "+");
687 expr = new binary_operator<6, std::minus<valty>>(l, "-");
690 expr = new divmod<std::modulus<valty>>(l, "/");
693 expr = new binary_operator<5, std::multiplies<valty>>(l, "*");
696 expr = new divmod<std::divides<valty>>(l, "/");
702 parse_error("Invalid operator");
707 expr = new binary_operator<8, std::less<valty>>(l, "<");
711 expr = new binary_operator<8, std::less_equal<valty>>(l, "<=");
715 expr = new binary_operator<7, lshift<valty>>(l, "<<");
723 parse_error("Invalid operator");
728 expr = new binary_operator<8, std::greater<valty>>(l, ">");
732 expr = new binary_operator<8, std::greater_equal<valty>>(l, ">=");
736 expr = new binary_operator<7, rshift<valty>>(l, ">>");
744 parse_error("Invalid operator");
747 expr = new binary_operator<9, std::equal_to<valty>>(l, "==");
752 parse_error("Invalid operator");
756 expr = new binary_operator<9, std::not_equal_to<valty>>(l, "!=");
761 expr = new binary_operator<13, std::logical_and<valty>>(l, "&&");
765 expr = new binary_operator<10, std::bit_and<valty>>(l, "&");
771 expr = new binary_operator<12, std::logical_or<valty>>(l, "||");
775 expr = new binary_operator<14, std::bit_or<valty>>(l, "|");
781 expression_ptr true_case = parse_expression();
783 if (!true_case || !consume(':'))
785 parse_error("Expected : in ternary conditional operator");
788 expression_ptr false_case = parse_expression();
791 parse_error("Expected false condition for ternary operator");
794 return expression_ptr(new ternary_conditional_operator(l, std::move(lhs),
795 std::move(true_case), std::move(false_case)));
800 expression_ptr e(expr);
801 expression_ptr rhs(parse_expression());
806 expr->lhs = std::move(lhs);
807 if (rhs->precedence() < expr->precedence())
809 expr->rhs = std::move(rhs);
813 // If we're a normal left-to-right expression, then we need to insert
814 // this as the far-left child node of the rhs expression
815 binary_operator_base *rhs_op =
816 static_cast<binary_operator_base*>(rhs.get());
817 rhs_op->insert_left(expr);
824 expression_ptr text_input_buffer::parse_expression(bool stopAtParen)
827 unsigned long long leftVal;
829 source_location l = location();
833 if (!consume_integer(leftVal))
837 lhs.reset(new terminal_expr(l, leftVal));
842 expression_ptr &&subexpr = parse_expression();
847 lhs.reset(new paren_expression(l, std::move(subexpr)));
861 expression_ptr &&subexpr = parse_expression();
866 lhs.reset(new unary_operator<'+', unary_plus<valty>>(l, std::move(subexpr)));
872 expression_ptr &&subexpr = parse_expression();
877 lhs.reset(new unary_operator<'-', std::negate<valty>>(l, std::move(subexpr)));
883 expression_ptr &&subexpr = parse_expression();
888 lhs.reset(new unary_operator<'!', std::logical_not<valty>>(l, std::move(subexpr)));
894 expression_ptr &&subexpr = parse_expression();
899 lhs.reset(new unary_operator<'~', bit_not<valty>>(l, std::move(subexpr)));
907 return parse_binary_expression(std::move(lhs));
911 text_input_buffer::consume_integer_expression(unsigned long long &outInt)
917 expression_ptr e(parse_expression(true));
931 return consume_integer(outInt);
938 input_buffer::consume_hex_byte(uint8_t &outByte)
940 if (!ishexdigit((*this)[0]) && !ishexdigit((*this)[1]))
944 outByte = (digittoint((*this)[0]) << 4) | digittoint((*this)[1]);
950 text_input_buffer::next_token()
962 if (*self == '/' && peek() == '*')
964 // eat the start of the comment
968 // Find the ending * of */
969 while ((*self != '\0') && (*self != '*') && !finished())
975 } while ((*self != '\0') && (*self != '/') && !finished());
980 if ((*self == '/' && peek() == '/'))
982 // eat the start of the comment
985 // Find the ending of the line
986 while (*self != '\n' && !finished())
993 } while (start != cursor);
998 text_input_buffer::parse_error(const char *msg)
1000 if (input_stack.empty())
1002 fprintf(stderr, "Error: %s\n", msg);
1005 input_buffer &b = *input_stack.top();
1006 parse_error(msg, b, b.cursor);
1009 text_input_buffer::parse_error(const char *msg,
1016 if (loc < 0 || loc > b.size)
1020 for (int i=loc ; i>0 ; --i)
1022 if (b.buffer[i] == '\n')
1025 if (line_start == 0)
1031 for (int i=loc+1 ; i<b.size ; ++i)
1033 if (b.buffer[i] == '\n')
1039 fprintf(stderr, "Error at %s:%d:%d: %s\n", b.filename().c_str(), line_count, loc - line_start, msg);
1040 fwrite(&b.buffer[line_start], line_end-line_start, 1, stderr);
1042 for (int i=0 ; i<(loc-line_start) ; ++i)
1044 char c = (b.buffer[i+line_start] == '\t') ? '\t' : ' ';
1052 input_buffer::dump()
1054 fprintf(stderr, "Current cursor: %d\n", cursor);
1055 fwrite(&buffer[cursor], size-cursor, 1, stderr);
1063 * The source files are ASCII, so we provide a non-locale-aware version of
1064 * isalpha. This is a class so that it can be used with a template function
1065 * for parsing strings.
1069 static inline bool check(const char c)
1071 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') &&
1076 * Check whether a character is in the set allowed for node names. This is a
1077 * class so that it can be used with a template function for parsing strings.
1079 struct is_node_name_character
1081 static inline bool check(const char c)
1087 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1088 case ',': case '.': case '+': case '-':
1095 * Check whether a character is in the set allowed for property names. This is
1096 * a class so that it can be used with a template function for parsing strings.
1098 struct is_property_name_character
1100 static inline bool check(const char c)
1106 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1107 case ',': case '.': case '+': case '-':
1115 string parse(text_input_buffer &s)
1117 std::vector<char> bytes;
1118 for (char c=*s ; T::check(c) ; c=*(++s))
1122 return string(bytes.begin(), bytes.end());
1128 text_input_buffer::parse_node_name()
1130 return parse<is_node_name_character>(*this);
1134 text_input_buffer::parse_property_name()
1136 return parse<is_property_name_character>(*this);
1140 text_input_buffer::parse_node_or_property_name(bool &is_property)
1144 return parse_property_name();
1146 std::vector<char> bytes;
1147 for (char c=*(*this) ; is_node_name_character::check(c) ; c=*(++(*this)))
1151 for (char c=*(*this) ; is_property_name_character::check(c) ; c=*(++(*this)))
1156 return string(bytes.begin(), bytes.end());
1160 input_buffer::parse_to(char stop)
1162 std::vector<char> bytes;
1163 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1167 return string(bytes.begin(), bytes.end());
1171 text_input_buffer::parse_to(char stop)
1173 std::vector<char> bytes;
1174 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1182 return string(bytes.begin(), bytes.end());
1186 text_input_buffer::peek()
1188 return (*input_stack.top())[1];
1191 std::unique_ptr<input_buffer>
1192 input_buffer::buffer_for_file(const string &path, bool warn)
1196 std::unique_ptr<input_buffer> b(new stream_input_buffer());
1199 int source = open(path.c_str(), O_RDONLY);
1204 fprintf(stderr, "Unable to open file '%s'. %s\n", path.c_str(), strerror(errno));
1209 if (fstat(source, &st) == 0 && S_ISDIR(st.st_mode))
1213 fprintf(stderr, "File %s is a directory\n", path.c_str());
1218 std::unique_ptr<input_buffer> b(new mmap_input_buffer(source, string(path)));