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(const_cast<char*>(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 = false;
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));
255 bool text_input_buffer::read_binary_file(const std::string &filename, byte_buffer &b)
257 bool try_include_paths = true;
259 if (filename[0] == '/')
261 include_file = filename;
262 // Don't try include paths if we're given an absolute path.
263 // Failing is better so that we don't accidentally do the wrong thing,
264 // but make it seem like everything is alright.
265 try_include_paths = false;
269 include_file = dir + '/' + filename;
271 auto include_buffer = input_buffer::buffer_for_file(include_file, false);
272 if (include_buffer == 0 && try_include_paths)
274 for (auto i : include_paths)
276 include_file = i + '/' + filename;
277 include_buffer = input_buffer::buffer_for_file(include_file, false);
278 if (include_buffer != 0)
291 fputs(include_file.c_str(), depfile);
293 b.insert(b.begin(), include_buffer->begin(), include_buffer->end());
298 input_buffer::buffer_from_offset(int offset, int s)
302 return input_buffer();
310 return input_buffer();
312 if (s > (size-offset))
314 return input_buffer();
316 return input_buffer(&buffer[offset], s);
320 input_buffer::consume(const char *str)
322 int len = strlen(str);
323 if (len > size - cursor)
329 for (int i=0 ; i<len ; ++i)
331 if (str[i] != (*this)[i])
343 input_buffer::consume_integer(unsigned long long &outInt)
345 // The first character must be a digit. Hex and octal strings
346 // are prefixed by 0 and 0x, respectively.
347 if (!isdigit((*this)[0]))
351 char *end= const_cast<char*>(&buffer[size]);
352 outInt = strtoull(&buffer[cursor], &end, 0);
353 if (end == &buffer[cursor])
357 cursor = end - buffer;
364 * Convenience typedef for the type that we use for all values.
366 typedef unsigned long long valty;
369 * Expression tree currently being parsed.
373 typedef text_input_buffer::source_location source_location;
375 * The type that is returned when computing the result. The boolean value
376 * indicates whether this is a valid expression.
378 * FIXME: Once we can use C++17, this should be `std::optional`.
380 typedef std::pair<valty, bool> result;
382 * Evaluate this node, taking into account operator precedence.
384 virtual result operator()() = 0;
386 * Returns the precedence of this node. Lower values indicate higher
389 virtual int precedence() = 0;
391 * Constructs an expression, storing the location where it was created.
393 expression(source_location l) : loc(l) {}
394 virtual ~expression() {}
397 * Dumps this expression to `std::cerr`, appending a newline if `nl` is
400 void dump(bool nl=false)
405 std::cerr << "{nullptr}\n";
416 * Method that sublcasses override to implement the behaviour of `dump()`.
418 virtual void dump_impl() = 0;
425 * Expression wrapping a single integer. Leaf nodes in the expression tree.
427 class terminal_expr : public expression
430 * The value that this wraps.
434 * Evaluate. Trivially returns the value that this class wraps.
436 result operator()() override
440 int precedence() override
448 terminal_expr(source_location l, valty v) : expression(l), val(v) {}
450 void dump_impl() override { std::cerr << val; }
455 * Parenthetical expression. Exists to make the contents opaque.
457 struct paren_expression : public expression
460 * The expression within the parentheses.
462 expression_ptr subexpr;
464 * Constructor. Takes the child expression as the only argument.
466 paren_expression(source_location l, expression_ptr p) : expression(l),
467 subexpr(std::move(p)) {}
468 int precedence() override
473 * Evaluate - just forwards to the underlying expression.
475 result operator()() override
480 void dump_impl() override
490 * Template class for unary operators. The `OpChar` template parameter is
491 * solely for debugging and makes it easy to print the expression. The `Op`
492 * template parameter is a function object that implements the operator that
493 * this class provides. Most of these are provided by the `<functional>`
496 template<char OpChar, class Op>
497 class unary_operator : public expression
500 * The subexpression for this unary operator.
502 expression_ptr subexpr;
503 result operator()() override
506 result s = (*subexpr)();
511 return {op(s.first), true};
514 * All unary operators have the same precedence. They are all evaluated
515 * before binary expressions, but after parentheses.
517 int precedence() override
522 unary_operator(source_location l, expression_ptr p) :
523 expression(l), subexpr(std::move(p)) {}
525 void dump_impl() override
534 * Abstract base class for binary operators. Allows the tree to be modified
535 * without knowing what the operations actually are.
537 struct binary_operator_base : public expression
539 using expression::expression;
541 * The left side of the expression.
545 * The right side of the expression.
549 * Insert a node somewhere down the path of left children, until it would
550 * be preempting something that should execute first.
552 void insert_left(binary_operator_base *new_left)
554 if (lhs->precedence() < new_left->precedence())
556 new_left->rhs = std::move(lhs);
561 static_cast<binary_operator_base*>(lhs.get())->insert_left(new_left);
567 * Template class for binary operators. The precedence and the operation are
568 * provided as template parameters.
570 template<int Precedence, class Op>
571 struct binary_operator : public binary_operator_base
573 result operator()() override
578 if (!(l.second && r.second))
582 return {op(l.first, r.first), true};
584 int precedence() override
590 * Constructor. Takes the name of the operator as an argument, for
591 * debugging. Only stores it in debug mode.
593 binary_operator(source_location l, const char *) :
594 binary_operator_base(l) {}
597 binary_operator(source_location l, const char *o) :
598 binary_operator_base(l), opName(o) {}
599 void dump_impl() override
609 * Ternary conditional operators (`cond ? true : false`) are a special case -
610 * there are no other ternary operators.
612 class ternary_conditional_operator : public expression
615 * The condition for the clause.
619 * The expression that this evaluates to if the condition is true.
623 * The expression that this evaluates to if the condition is false.
626 result operator()() override
628 result c = (*cond)();
631 if (!(l.second && r.second && c.second))
635 return c.first ? l : r;
637 int precedence() override
639 // The actual precedence of a ternary conditional operator is 15, but
640 // its associativity is the opposite way around to the other operators,
641 // so we fudge it slightly.
645 void dump_impl() override
655 ternary_conditional_operator(source_location sl,
659 expression(sl), cond(std::move(c)), lhs(std::move(l)),
666 constexpr T operator()(const T &lhs, const T &rhs) const
674 constexpr T operator()(const T &lhs, const T &rhs) const
682 constexpr T operator()(const T &val) const
687 // TODO: Replace with std::bit_not once we can guarantee C++14 as a baseline.
691 constexpr T operator()(const T &val) const
698 struct divmod : public binary_operator<5, T>
700 using binary_operator<5, T>::binary_operator;
701 using typename binary_operator_base::result;
702 result operator()() override
704 result r = (*binary_operator_base::rhs)();
705 if (r.second && (r.first == 0))
707 expression::loc.report_error("Division by zero");
710 return binary_operator<5, T>::operator()();
714 } // anonymous namespace
717 expression_ptr text_input_buffer::parse_binary_expression(expression_ptr lhs)
720 binary_operator_base *expr = nullptr;
722 source_location l = location();
728 expr = new binary_operator<6, std::plus<valty>>(l, "+");
731 expr = new binary_operator<6, std::minus<valty>>(l, "-");
734 expr = new divmod<std::modulus<valty>>(l, "/");
737 expr = new binary_operator<5, std::multiplies<valty>>(l, "*");
740 expr = new divmod<std::divides<valty>>(l, "/");
746 parse_error("Invalid operator");
751 expr = new binary_operator<8, std::less<valty>>(l, "<");
755 expr = new binary_operator<8, std::less_equal<valty>>(l, "<=");
759 expr = new binary_operator<7, lshift<valty>>(l, "<<");
767 parse_error("Invalid operator");
772 expr = new binary_operator<8, std::greater<valty>>(l, ">");
776 expr = new binary_operator<8, std::greater_equal<valty>>(l, ">=");
780 expr = new binary_operator<7, rshift<valty>>(l, ">>");
788 parse_error("Invalid operator");
791 expr = new binary_operator<9, std::equal_to<valty>>(l, "==");
796 parse_error("Invalid operator");
800 expr = new binary_operator<9, std::not_equal_to<valty>>(l, "!=");
805 expr = new binary_operator<13, std::logical_and<valty>>(l, "&&");
809 expr = new binary_operator<10, std::bit_and<valty>>(l, "&");
815 expr = new binary_operator<12, std::logical_or<valty>>(l, "||");
819 expr = new binary_operator<14, std::bit_or<valty>>(l, "|");
825 expression_ptr true_case = parse_expression();
827 if (!true_case || !consume(':'))
829 parse_error("Expected : in ternary conditional operator");
832 expression_ptr false_case = parse_expression();
835 parse_error("Expected false condition for ternary operator");
838 return expression_ptr(new ternary_conditional_operator(l, std::move(lhs),
839 std::move(true_case), std::move(false_case)));
844 expression_ptr e(expr);
845 expression_ptr rhs(parse_expression());
850 expr->lhs = std::move(lhs);
851 if (rhs->precedence() < expr->precedence())
853 expr->rhs = std::move(rhs);
857 // If we're a normal left-to-right expression, then we need to insert
858 // this as the far-left child node of the rhs expression
859 binary_operator_base *rhs_op =
860 static_cast<binary_operator_base*>(rhs.get());
861 rhs_op->insert_left(expr);
868 expression_ptr text_input_buffer::parse_expression(bool stopAtParen)
871 unsigned long long leftVal;
873 source_location l = location();
877 if (!consume_integer(leftVal))
881 lhs.reset(new terminal_expr(l, leftVal));
886 expression_ptr &&subexpr = parse_expression();
891 lhs.reset(new paren_expression(l, std::move(subexpr)));
905 expression_ptr &&subexpr = parse_expression();
910 lhs.reset(new unary_operator<'+', unary_plus<valty>>(l, std::move(subexpr)));
916 expression_ptr &&subexpr = parse_expression();
921 lhs.reset(new unary_operator<'-', std::negate<valty>>(l, std::move(subexpr)));
927 expression_ptr &&subexpr = parse_expression();
932 lhs.reset(new unary_operator<'!', std::logical_not<valty>>(l, std::move(subexpr)));
938 expression_ptr &&subexpr = parse_expression();
943 lhs.reset(new unary_operator<'~', bit_not<valty>>(l, std::move(subexpr)));
951 return parse_binary_expression(std::move(lhs));
955 text_input_buffer::consume_integer_expression(unsigned long long &outInt)
961 expression_ptr e(parse_expression(true));
975 return consume_integer(outInt);
982 input_buffer::consume_hex_byte(uint8_t &outByte)
984 if (!ishexdigit((*this)[0]) && !ishexdigit((*this)[1]))
988 outByte = (digittoint((*this)[0]) << 4) | digittoint((*this)[1]);
994 text_input_buffer::next_token()
1005 // Parse /* comments
1006 if (*self == '/' && peek() == '*')
1008 // eat the start of the comment
1012 // Find the ending * of */
1013 while ((*self != '\0') && (*self != '*') && !finished())
1019 } while ((*self != '\0') && (*self != '/') && !finished());
1023 // Parse // comments
1024 if ((*self == '/' && peek() == '/'))
1026 // eat the start of the comment
1029 // Find the ending of the line
1030 while (*self != '\n' && !finished())
1037 } while (start != cursor);
1042 text_input_buffer::parse_error(const char *msg)
1044 if (input_stack.empty())
1046 fprintf(stderr, "Error: %s\n", msg);
1049 input_buffer &b = *input_stack.top();
1050 parse_error(msg, b, b.cursor);
1053 text_input_buffer::parse_error(const char *msg,
1060 if (loc < 0 || loc > b.size)
1064 for (int i=loc ; i>0 ; --i)
1066 if (b.buffer[i] == '\n')
1069 if (line_start == 0)
1075 for (int i=loc+1 ; i<b.size ; ++i)
1077 if (b.buffer[i] == '\n')
1083 fprintf(stderr, "Error at %s:%d:%d: %s\n", b.filename().c_str(), line_count, loc - line_start, msg);
1084 fwrite(&b.buffer[line_start], line_end-line_start, 1, stderr);
1086 for (int i=0 ; i<(loc-line_start) ; ++i)
1088 char c = (b.buffer[i+line_start] == '\t') ? '\t' : ' ';
1096 input_buffer::dump()
1098 fprintf(stderr, "Current cursor: %d\n", cursor);
1099 fwrite(&buffer[cursor], size-cursor, 1, stderr);
1107 * The source files are ASCII, so we provide a non-locale-aware version of
1108 * isalpha. This is a class so that it can be used with a template function
1109 * for parsing strings.
1113 static inline bool check(const char c)
1115 return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') &&
1120 * Check whether a character is in the set allowed for node names. This is a
1121 * class so that it can be used with a template function for parsing strings.
1123 struct is_node_name_character
1125 static inline bool check(const char c)
1131 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1132 case ',': case '.': case '+': case '-':
1139 * Check whether a character is in the set allowed for property names. This is
1140 * a class so that it can be used with a template function for parsing strings.
1142 struct is_property_name_character
1144 static inline bool check(const char c)
1150 case 'a'...'z': case 'A'...'Z': case '0'...'9':
1151 case ',': case '.': case '+': case '-':
1159 string parse(text_input_buffer &s)
1161 std::vector<char> bytes;
1162 for (char c=*s ; T::check(c) ; c=*(++s))
1166 return string(bytes.begin(), bytes.end());
1172 text_input_buffer::parse_node_name()
1174 return parse<is_node_name_character>(*this);
1178 text_input_buffer::parse_property_name()
1180 return parse<is_property_name_character>(*this);
1184 text_input_buffer::parse_node_or_property_name(bool &is_property)
1188 return parse_property_name();
1190 std::vector<char> bytes;
1191 for (char c=*(*this) ; is_node_name_character::check(c) ; c=*(++(*this)))
1195 for (char c=*(*this) ; is_property_name_character::check(c) ; c=*(++(*this)))
1200 return string(bytes.begin(), bytes.end());
1204 input_buffer::parse_to(char stop)
1206 std::vector<char> bytes;
1207 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1211 return string(bytes.begin(), bytes.end());
1215 text_input_buffer::parse_to(char stop)
1217 std::vector<char> bytes;
1218 for (char c=*(*this) ; c != stop ; c=*(++(*this)))
1226 return string(bytes.begin(), bytes.end());
1230 text_input_buffer::peek()
1232 return (*input_stack.top())[1];
1235 std::unique_ptr<input_buffer>
1236 input_buffer::buffer_for_file(const string &path, bool warn)
1240 std::unique_ptr<input_buffer> b(new stream_input_buffer());
1243 int source = open(path.c_str(), O_RDONLY);
1248 fprintf(stderr, "Unable to open file '%s'. %s\n", path.c_str(), strerror(errno));
1253 if (fstat(source, &st) == 0 && S_ISDIR(st.st_mode))
1257 fprintf(stderr, "File %s is a directory\n", path.c_str());
1262 std::unique_ptr<input_buffer> b(new mmap_input_buffer(source, string(path)));