3ac4dd6b4f04f5c036e689cb4b03977206ed6b4a
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldChecker.cpp
1 //===--- RuntimeDyldChecker.cpp - RuntimeDyld tester framework --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
12 #include "llvm/MC/MCContext.h"
13 #include "llvm/MC/MCDisassembler.h"
14 #include "llvm/MC/MCInst.h"
15 #include "llvm/Support/StringRefMemoryObject.h"
16 #include "RuntimeDyldCheckerImpl.h"
17 #include "RuntimeDyldImpl.h"
18 #include <cctype>
19 #include <memory>
20
21 #define DEBUG_TYPE "rtdyld"
22
23 using namespace llvm;
24
25 namespace llvm {
26
27 // Helper class that implements the language evaluated by RuntimeDyldChecker.
28 class RuntimeDyldCheckerExprEval {
29 public:
30   RuntimeDyldCheckerExprEval(const RuntimeDyldCheckerImpl &Checker,
31                              raw_ostream &ErrStream)
32       : Checker(Checker) {}
33
34   bool evaluate(StringRef Expr) const {
35     // Expect equality expression of the form 'LHS = RHS'.
36     Expr = Expr.trim();
37     size_t EQIdx = Expr.find('=');
38
39     ParseContext OutsideLoad(false);
40
41     // Evaluate LHS.
42     StringRef LHSExpr = Expr.substr(0, EQIdx).rtrim();
43     StringRef RemainingExpr;
44     EvalResult LHSResult;
45     std::tie(LHSResult, RemainingExpr) =
46         evalComplexExpr(evalSimpleExpr(LHSExpr, OutsideLoad), OutsideLoad);
47     if (LHSResult.hasError())
48       return handleError(Expr, LHSResult);
49     if (RemainingExpr != "")
50       return handleError(Expr, unexpectedToken(RemainingExpr, LHSExpr, ""));
51
52     // Evaluate RHS.
53     StringRef RHSExpr = Expr.substr(EQIdx + 1).ltrim();
54     EvalResult RHSResult;
55     std::tie(RHSResult, RemainingExpr) =
56         evalComplexExpr(evalSimpleExpr(RHSExpr, OutsideLoad), OutsideLoad);
57     if (RHSResult.hasError())
58       return handleError(Expr, RHSResult);
59     if (RemainingExpr != "")
60       return handleError(Expr, unexpectedToken(RemainingExpr, RHSExpr, ""));
61
62     if (LHSResult.getValue() != RHSResult.getValue()) {
63       Checker.ErrStream << "Expression '" << Expr << "' is false: "
64                         << format("0x%lx", LHSResult.getValue())
65                         << " != " << format("0x%lx", RHSResult.getValue())
66                         << "\n";
67       return false;
68     }
69     return true;
70   }
71
72 private:
73   // RuntimeDyldCheckerExprEval requires some context when parsing exprs. In
74   // particular, it needs to know whether a symbol is being evaluated in the
75   // context of a load, in which case we want the linker's local address for
76   // the symbol, or outside of a load, in which case we want the symbol's
77   // address in the remote target.
78
79   struct ParseContext {
80     bool IsInsideLoad;
81     ParseContext(bool IsInsideLoad) : IsInsideLoad(IsInsideLoad) {}
82   };
83
84   const RuntimeDyldCheckerImpl &Checker;
85
86   enum class BinOpToken : unsigned {
87     Invalid,
88     Add,
89     Sub,
90     BitwiseAnd,
91     BitwiseOr,
92     ShiftLeft,
93     ShiftRight
94   };
95
96   class EvalResult {
97   public:
98     EvalResult() : Value(0), ErrorMsg("") {}
99     EvalResult(uint64_t Value) : Value(Value), ErrorMsg("") {}
100     EvalResult(std::string ErrorMsg) : Value(0), ErrorMsg(ErrorMsg) {}
101     uint64_t getValue() const { return Value; }
102     bool hasError() const { return ErrorMsg != ""; }
103     const std::string &getErrorMsg() const { return ErrorMsg; }
104
105   private:
106     uint64_t Value;
107     std::string ErrorMsg;
108   };
109
110   StringRef getTokenForError(StringRef Expr) const {
111     if (Expr.empty())
112       return "";
113
114     StringRef Token, Remaining;
115     if (isalpha(Expr[0]))
116       std::tie(Token, Remaining) = parseSymbol(Expr);
117     else if (isdigit(Expr[0]))
118       std::tie(Token, Remaining) = parseNumberString(Expr);
119     else {
120       unsigned TokLen = 1;
121       if (Expr.startswith("<<") || Expr.startswith(">>"))
122         TokLen = 2;
123       Token = Expr.substr(0, TokLen);
124     }
125     return Token;
126   }
127
128   EvalResult unexpectedToken(StringRef TokenStart, StringRef SubExpr,
129                              StringRef ErrText) const {
130     std::string ErrorMsg("Encountered unexpected token '");
131     ErrorMsg += getTokenForError(TokenStart);
132     if (SubExpr != "") {
133       ErrorMsg += "' while parsing subexpression '";
134       ErrorMsg += SubExpr;
135     }
136     ErrorMsg += "'";
137     if (ErrText != "") {
138       ErrorMsg += " ";
139       ErrorMsg += ErrText;
140     }
141     return EvalResult(std::move(ErrorMsg));
142   }
143
144   bool handleError(StringRef Expr, const EvalResult &R) const {
145     assert(R.hasError() && "Not an error result.");
146     Checker.ErrStream << "Error evaluating expression '" << Expr
147                       << "': " << R.getErrorMsg() << "\n";
148     return false;
149   }
150
151   std::pair<BinOpToken, StringRef> parseBinOpToken(StringRef Expr) const {
152     if (Expr.empty())
153       return std::make_pair(BinOpToken::Invalid, "");
154
155     // Handle the two 2-character tokens.
156     if (Expr.startswith("<<"))
157       return std::make_pair(BinOpToken::ShiftLeft, Expr.substr(2).ltrim());
158     if (Expr.startswith(">>"))
159       return std::make_pair(BinOpToken::ShiftRight, Expr.substr(2).ltrim());
160
161     // Handle one-character tokens.
162     BinOpToken Op;
163     switch (Expr[0]) {
164     default:
165       return std::make_pair(BinOpToken::Invalid, Expr);
166     case '+':
167       Op = BinOpToken::Add;
168       break;
169     case '-':
170       Op = BinOpToken::Sub;
171       break;
172     case '&':
173       Op = BinOpToken::BitwiseAnd;
174       break;
175     case '|':
176       Op = BinOpToken::BitwiseOr;
177       break;
178     }
179
180     return std::make_pair(Op, Expr.substr(1).ltrim());
181   }
182
183   EvalResult computeBinOpResult(BinOpToken Op, const EvalResult &LHSResult,
184                                 const EvalResult &RHSResult) const {
185     switch (Op) {
186     default:
187       llvm_unreachable("Tried to evaluate unrecognized operation.");
188     case BinOpToken::Add:
189       return EvalResult(LHSResult.getValue() + RHSResult.getValue());
190     case BinOpToken::Sub:
191       return EvalResult(LHSResult.getValue() - RHSResult.getValue());
192     case BinOpToken::BitwiseAnd:
193       return EvalResult(LHSResult.getValue() & RHSResult.getValue());
194     case BinOpToken::BitwiseOr:
195       return EvalResult(LHSResult.getValue() | RHSResult.getValue());
196     case BinOpToken::ShiftLeft:
197       return EvalResult(LHSResult.getValue() << RHSResult.getValue());
198     case BinOpToken::ShiftRight:
199       return EvalResult(LHSResult.getValue() >> RHSResult.getValue());
200     }
201   }
202
203   // Parse a symbol and return a (string, string) pair representing the symbol
204   // name and expression remaining to be parsed.
205   std::pair<StringRef, StringRef> parseSymbol(StringRef Expr) const {
206     size_t FirstNonSymbol = Expr.find_first_not_of("0123456789"
207                                                    "abcdefghijklmnopqrstuvwxyz"
208                                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
209                                                    ":_.");
210     return std::make_pair(Expr.substr(0, FirstNonSymbol),
211                           Expr.substr(FirstNonSymbol).ltrim());
212   }
213
214   // Evaluate a call to decode_operand. Decode the instruction operand at the
215   // given symbol and get the value of the requested operand.
216   // Returns an error if the instruction cannot be decoded, or the requested
217   // operand is not an immediate.
218   // On success, retuns a pair containing the value of the operand, plus
219   // the expression remaining to be evaluated.
220   std::pair<EvalResult, StringRef> evalDecodeOperand(StringRef Expr) const {
221     if (!Expr.startswith("("))
222       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
223     StringRef RemainingExpr = Expr.substr(1).ltrim();
224     StringRef Symbol;
225     std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
226
227     if (!Checker.isSymbolValid(Symbol))
228       return std::make_pair(
229           EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()),
230           "");
231
232     if (!RemainingExpr.startswith(","))
233       return std::make_pair(
234           unexpectedToken(RemainingExpr, RemainingExpr, "expected ','"), "");
235     RemainingExpr = RemainingExpr.substr(1).ltrim();
236
237     EvalResult OpIdxExpr;
238     std::tie(OpIdxExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
239     if (OpIdxExpr.hasError())
240       return std::make_pair(OpIdxExpr, "");
241
242     if (!RemainingExpr.startswith(")"))
243       return std::make_pair(
244           unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), "");
245     RemainingExpr = RemainingExpr.substr(1).ltrim();
246
247     MCInst Inst;
248     uint64_t Size;
249     if (!decodeInst(Symbol, Inst, Size))
250       return std::make_pair(
251           EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()),
252           "");
253
254     unsigned OpIdx = OpIdxExpr.getValue();
255     if (OpIdx >= Inst.getNumOperands()) {
256       std::string ErrMsg;
257       raw_string_ostream ErrMsgStream(ErrMsg);
258       ErrMsgStream << "Invalid operand index '" << format("%i", OpIdx)
259                    << "' for instruction '" << Symbol
260                    << "'. Instruction has only "
261                    << format("%i", Inst.getNumOperands())
262                    << " operands.\nInstruction is:\n  ";
263       Inst.dump_pretty(ErrMsgStream,
264                        Checker.Disassembler->getContext().getAsmInfo(),
265                        Checker.InstPrinter);
266       return std::make_pair(EvalResult(ErrMsgStream.str()), "");
267     }
268
269     const MCOperand &Op = Inst.getOperand(OpIdx);
270     if (!Op.isImm()) {
271       std::string ErrMsg;
272       raw_string_ostream ErrMsgStream(ErrMsg);
273       ErrMsgStream << "Operand '" << format("%i", OpIdx) << "' of instruction '"
274                    << Symbol << "' is not an immediate.\nInstruction is:\n  ";
275       Inst.dump_pretty(ErrMsgStream,
276                        Checker.Disassembler->getContext().getAsmInfo(),
277                        Checker.InstPrinter);
278
279       return std::make_pair(EvalResult(ErrMsgStream.str()), "");
280     }
281
282     return std::make_pair(EvalResult(Op.getImm()), RemainingExpr);
283   }
284
285   // Evaluate a call to next_pc.
286   // Decode the instruction at the given symbol and return the following program
287   // counter.
288   // Returns an error if the instruction cannot be decoded.
289   // On success, returns a pair containing the next PC, plus of the
290   // expression remaining to be evaluated.
291   std::pair<EvalResult, StringRef> evalNextPC(StringRef Expr,
292                                               ParseContext PCtx) const {
293     if (!Expr.startswith("("))
294       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
295     StringRef RemainingExpr = Expr.substr(1).ltrim();
296     StringRef Symbol;
297     std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
298
299     if (!Checker.isSymbolValid(Symbol))
300       return std::make_pair(
301           EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()),
302           "");
303
304     if (!RemainingExpr.startswith(")"))
305       return std::make_pair(
306           unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), "");
307     RemainingExpr = RemainingExpr.substr(1).ltrim();
308
309     MCInst Inst;
310     uint64_t InstSize;
311     if (!decodeInst(Symbol, Inst, InstSize))
312       return std::make_pair(
313           EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()),
314           "");
315
316     uint64_t SymbolAddr = PCtx.IsInsideLoad
317                               ? Checker.getSymbolLinkerAddr(Symbol)
318                               : Checker.getSymbolRemoteAddr(Symbol);
319     uint64_t NextPC = SymbolAddr + InstSize;
320
321     return std::make_pair(EvalResult(NextPC), RemainingExpr);
322   }
323
324   // Evaluate a call to stub_addr.
325   // Look up and return the address of the stub for the given
326   // (<file name>, <section name>, <symbol name>) tuple.
327   // On success, returns a pair containing the stub address, plus the expression
328   // remaining to be evaluated.
329   std::pair<EvalResult, StringRef> evalStubAddr(StringRef Expr,
330                                                 ParseContext PCtx) const {
331     if (!Expr.startswith("("))
332       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
333     StringRef RemainingExpr = Expr.substr(1).ltrim();
334
335     // Handle file-name specially, as it may contain characters that aren't
336     // legal for symbols.
337     StringRef FileName;
338     size_t ComaIdx = RemainingExpr.find(',');
339     FileName = RemainingExpr.substr(0, ComaIdx).rtrim();
340     RemainingExpr = RemainingExpr.substr(ComaIdx).ltrim();
341
342     if (!RemainingExpr.startswith(","))
343       return std::make_pair(
344           unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
345     RemainingExpr = RemainingExpr.substr(1).ltrim();
346
347     StringRef SectionName;
348     std::tie(SectionName, RemainingExpr) = parseSymbol(RemainingExpr);
349
350     if (!RemainingExpr.startswith(","))
351       return std::make_pair(
352           unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
353     RemainingExpr = RemainingExpr.substr(1).ltrim();
354
355     StringRef Symbol;
356     std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
357
358     if (!RemainingExpr.startswith(")"))
359       return std::make_pair(
360           unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
361     RemainingExpr = RemainingExpr.substr(1).ltrim();
362
363     uint64_t StubAddr;
364     std::string ErrorMsg = "";
365     std::tie(StubAddr, ErrorMsg) = Checker.getStubAddrFor(
366         FileName, SectionName, Symbol, PCtx.IsInsideLoad);
367
368     if (ErrorMsg != "")
369       return std::make_pair(EvalResult(ErrorMsg), "");
370
371     return std::make_pair(EvalResult(StubAddr), RemainingExpr);
372   }
373
374   // Evaluate an identiefer expr, which may be a symbol, or a call to
375   // one of the builtin functions: get_insn_opcode or get_insn_length.
376   // Return the result, plus the expression remaining to be parsed.
377   std::pair<EvalResult, StringRef> evalIdentifierExpr(StringRef Expr,
378                                                       ParseContext PCtx) const {
379     StringRef Symbol;
380     StringRef RemainingExpr;
381     std::tie(Symbol, RemainingExpr) = parseSymbol(Expr);
382
383     // Check for builtin function calls.
384     if (Symbol == "decode_operand")
385       return evalDecodeOperand(RemainingExpr);
386     else if (Symbol == "next_pc")
387       return evalNextPC(RemainingExpr, PCtx);
388     else if (Symbol == "stub_addr")
389       return evalStubAddr(RemainingExpr, PCtx);
390
391     if (!Checker.isSymbolValid(Symbol)) {
392       std::string ErrMsg("No known address for symbol '");
393       ErrMsg += Symbol;
394       ErrMsg += "'";
395       if (Symbol.startswith("L"))
396         ErrMsg += " (this appears to be an assembler local label - "
397                   " perhaps drop the 'L'?)";
398
399       return std::make_pair(EvalResult(ErrMsg), "");
400     }
401
402     // The value for the symbol depends on the context we're evaluating in:
403     // Inside a load this is the address in the linker's memory, outside a
404     // load it's the address in the target processes memory.
405     uint64_t Value = PCtx.IsInsideLoad ? Checker.getSymbolLinkerAddr(Symbol)
406                                        : Checker.getSymbolRemoteAddr(Symbol);
407
408     // Looks like a plain symbol reference.
409     return std::make_pair(EvalResult(Value), RemainingExpr);
410   }
411
412   // Parse a number (hexadecimal or decimal) and return a (string, string)
413   // pair representing the number and the expression remaining to be parsed.
414   std::pair<StringRef, StringRef> parseNumberString(StringRef Expr) const {
415     size_t FirstNonDigit = StringRef::npos;
416     if (Expr.startswith("0x")) {
417       FirstNonDigit = Expr.find_first_not_of("0123456789abcdefABCDEF", 2);
418       if (FirstNonDigit == StringRef::npos)
419         FirstNonDigit = Expr.size();
420     } else {
421       FirstNonDigit = Expr.find_first_not_of("0123456789");
422       if (FirstNonDigit == StringRef::npos)
423         FirstNonDigit = Expr.size();
424     }
425     return std::make_pair(Expr.substr(0, FirstNonDigit),
426                           Expr.substr(FirstNonDigit));
427   }
428
429   // Evaluate a constant numeric expression (hexidecimal or decimal) and
430   // return a pair containing the result, and the expression remaining to be
431   // evaluated.
432   std::pair<EvalResult, StringRef> evalNumberExpr(StringRef Expr) const {
433     StringRef ValueStr;
434     StringRef RemainingExpr;
435     std::tie(ValueStr, RemainingExpr) = parseNumberString(Expr);
436
437     if (ValueStr.empty() || !isdigit(ValueStr[0]))
438       return std::make_pair(
439           unexpectedToken(RemainingExpr, RemainingExpr, "expected number"), "");
440     uint64_t Value;
441     ValueStr.getAsInteger(0, Value);
442     return std::make_pair(EvalResult(Value), RemainingExpr);
443   }
444
445   // Evaluate an expression of the form "(<expr>)" and return a pair
446   // containing the result of evaluating <expr>, plus the expression
447   // remaining to be parsed.
448   std::pair<EvalResult, StringRef> evalParensExpr(StringRef Expr,
449                                                   ParseContext PCtx) const {
450     assert(Expr.startswith("(") && "Not a parenthesized expression");
451     EvalResult SubExprResult;
452     StringRef RemainingExpr;
453     std::tie(SubExprResult, RemainingExpr) =
454         evalComplexExpr(evalSimpleExpr(Expr.substr(1).ltrim(), PCtx), PCtx);
455     if (SubExprResult.hasError())
456       return std::make_pair(SubExprResult, "");
457     if (!RemainingExpr.startswith(")"))
458       return std::make_pair(
459           unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
460     RemainingExpr = RemainingExpr.substr(1).ltrim();
461     return std::make_pair(SubExprResult, RemainingExpr);
462   }
463
464   // Evaluate an expression in one of the following forms:
465   //   *{<number>}<expr>
466   // Return a pair containing the result, plus the expression remaining to be
467   // parsed.
468   std::pair<EvalResult, StringRef> evalLoadExpr(StringRef Expr) const {
469     assert(Expr.startswith("*") && "Not a load expression");
470     StringRef RemainingExpr = Expr.substr(1).ltrim();
471
472     // Parse read size.
473     if (!RemainingExpr.startswith("{"))
474       return std::make_pair(EvalResult("Expected '{' following '*'."), "");
475     RemainingExpr = RemainingExpr.substr(1).ltrim();
476     EvalResult ReadSizeExpr;
477     std::tie(ReadSizeExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
478     if (ReadSizeExpr.hasError())
479       return std::make_pair(ReadSizeExpr, RemainingExpr);
480     uint64_t ReadSize = ReadSizeExpr.getValue();
481     if (ReadSize < 1 || ReadSize > 8)
482       return std::make_pair(EvalResult("Invalid size for dereference."), "");
483     if (!RemainingExpr.startswith("}"))
484       return std::make_pair(EvalResult("Missing '}' for dereference."), "");
485     RemainingExpr = RemainingExpr.substr(1).ltrim();
486
487     // Evaluate the expression representing the load address.
488     ParseContext LoadCtx(true);
489     EvalResult LoadAddrExprResult;
490     std::tie(LoadAddrExprResult, RemainingExpr) =
491         evalComplexExpr(evalSimpleExpr(RemainingExpr, LoadCtx), LoadCtx);
492
493     if (LoadAddrExprResult.hasError())
494       return std::make_pair(LoadAddrExprResult, "");
495
496     uint64_t LoadAddr = LoadAddrExprResult.getValue();
497
498     return std::make_pair(
499         EvalResult(Checker.readMemoryAtAddr(LoadAddr, ReadSize)),
500         RemainingExpr);
501   }
502
503   // Evaluate a "simple" expression. This is any expression that _isn't_ an
504   // un-parenthesized binary expression.
505   //
506   // "Simple" expressions can be optionally bit-sliced. See evalSlicedExpr.
507   //
508   // Returns a pair containing the result of the evaluation, plus the
509   // expression remaining to be parsed.
510   std::pair<EvalResult, StringRef> evalSimpleExpr(StringRef Expr,
511                                                   ParseContext PCtx) const {
512     EvalResult SubExprResult;
513     StringRef RemainingExpr;
514
515     if (Expr.empty())
516       return std::make_pair(EvalResult("Unexpected end of expression"), "");
517
518     if (Expr[0] == '(')
519       std::tie(SubExprResult, RemainingExpr) = evalParensExpr(Expr, PCtx);
520     else if (Expr[0] == '*')
521       std::tie(SubExprResult, RemainingExpr) = evalLoadExpr(Expr);
522     else if (isalpha(Expr[0]))
523       std::tie(SubExprResult, RemainingExpr) = evalIdentifierExpr(Expr, PCtx);
524     else if (isdigit(Expr[0]))
525       std::tie(SubExprResult, RemainingExpr) = evalNumberExpr(Expr);
526
527     if (SubExprResult.hasError())
528       return std::make_pair(SubExprResult, RemainingExpr);
529
530     // Evaluate bit-slice if present.
531     if (RemainingExpr.startswith("["))
532       std::tie(SubExprResult, RemainingExpr) =
533           evalSliceExpr(std::make_pair(SubExprResult, RemainingExpr));
534
535     return std::make_pair(SubExprResult, RemainingExpr);
536   }
537
538   // Evaluate a bit-slice of an expression.
539   // A bit-slice has the form "<expr>[high:low]". The result of evaluating a
540   // slice is the bits between high and low (inclusive) in the original
541   // expression, right shifted so that the "low" bit is in position 0 in the
542   // result.
543   // Returns a pair containing the result of the slice operation, plus the
544   // expression remaining to be parsed.
545   std::pair<EvalResult, StringRef>
546   evalSliceExpr(std::pair<EvalResult, StringRef> Ctx) const {
547     EvalResult SubExprResult;
548     StringRef RemainingExpr;
549     std::tie(SubExprResult, RemainingExpr) = Ctx;
550
551     assert(RemainingExpr.startswith("[") && "Not a slice expr.");
552     RemainingExpr = RemainingExpr.substr(1).ltrim();
553
554     EvalResult HighBitExpr;
555     std::tie(HighBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
556
557     if (HighBitExpr.hasError())
558       return std::make_pair(HighBitExpr, RemainingExpr);
559
560     if (!RemainingExpr.startswith(":"))
561       return std::make_pair(
562           unexpectedToken(RemainingExpr, RemainingExpr, "expected ':'"), "");
563     RemainingExpr = RemainingExpr.substr(1).ltrim();
564
565     EvalResult LowBitExpr;
566     std::tie(LowBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
567
568     if (LowBitExpr.hasError())
569       return std::make_pair(LowBitExpr, RemainingExpr);
570
571     if (!RemainingExpr.startswith("]"))
572       return std::make_pair(
573           unexpectedToken(RemainingExpr, RemainingExpr, "expected ']'"), "");
574     RemainingExpr = RemainingExpr.substr(1).ltrim();
575
576     unsigned HighBit = HighBitExpr.getValue();
577     unsigned LowBit = LowBitExpr.getValue();
578     uint64_t Mask = ((uint64_t)1 << (HighBit - LowBit + 1)) - 1;
579     uint64_t SlicedValue = (SubExprResult.getValue() >> LowBit) & Mask;
580     return std::make_pair(EvalResult(SlicedValue), RemainingExpr);
581   }
582
583   // Evaluate a "complex" expression.
584   // Takes an already evaluated subexpression and checks for the presence of a
585   // binary operator, computing the result of the binary operation if one is
586   // found. Used to make arithmetic expressions left-associative.
587   // Returns a pair containing the ultimate result of evaluating the
588   // expression, plus the expression remaining to be evaluated.
589   std::pair<EvalResult, StringRef>
590   evalComplexExpr(std::pair<EvalResult, StringRef> LHSAndRemaining,
591                   ParseContext PCtx) const {
592     EvalResult LHSResult;
593     StringRef RemainingExpr;
594     std::tie(LHSResult, RemainingExpr) = LHSAndRemaining;
595
596     // If there was an error, or there's nothing left to evaluate, return the
597     // result.
598     if (LHSResult.hasError() || RemainingExpr == "")
599       return std::make_pair(LHSResult, RemainingExpr);
600
601     // Otherwise check if this is a binary expressioan.
602     BinOpToken BinOp;
603     std::tie(BinOp, RemainingExpr) = parseBinOpToken(RemainingExpr);
604
605     // If this isn't a recognized expression just return.
606     if (BinOp == BinOpToken::Invalid)
607       return std::make_pair(LHSResult, RemainingExpr);
608
609     // This is a recognized bin-op. Evaluate the RHS, then evaluate the binop.
610     EvalResult RHSResult;
611     std::tie(RHSResult, RemainingExpr) = evalSimpleExpr(RemainingExpr, PCtx);
612
613     // If there was an error evaluating the RHS, return it.
614     if (RHSResult.hasError())
615       return std::make_pair(RHSResult, RemainingExpr);
616
617     // This is a binary expression - evaluate and try to continue as a
618     // complex expr.
619     EvalResult ThisResult(computeBinOpResult(BinOp, LHSResult, RHSResult));
620
621     return evalComplexExpr(std::make_pair(ThisResult, RemainingExpr), PCtx);
622   }
623
624   bool decodeInst(StringRef Symbol, MCInst &Inst, uint64_t &Size) const {
625     MCDisassembler *Dis = Checker.Disassembler;
626     StringRef SectionMem = Checker.getSubsectionStartingAt(Symbol);
627     StringRefMemoryObject SectionBytes(SectionMem, 0);
628
629     MCDisassembler::DecodeStatus S =
630         Dis->getInstruction(Inst, Size, SectionBytes, 0, nulls(), nulls());
631
632     return (S == MCDisassembler::Success);
633   }
634 };
635 }
636
637 RuntimeDyldCheckerImpl::RuntimeDyldCheckerImpl(RuntimeDyld &RTDyld,
638                                                MCDisassembler *Disassembler,
639                                                MCInstPrinter *InstPrinter,
640                                                raw_ostream &ErrStream)
641     : RTDyld(RTDyld), Disassembler(Disassembler), InstPrinter(InstPrinter),
642       ErrStream(ErrStream) {
643   RTDyld.Checker = this;
644 }
645
646 bool RuntimeDyldCheckerImpl::check(StringRef CheckExpr) const {
647   CheckExpr = CheckExpr.trim();
648   DEBUG(dbgs() << "RuntimeDyldChecker: Checking '" << CheckExpr << "'...\n");
649   RuntimeDyldCheckerExprEval P(*this, ErrStream);
650   bool Result = P.evaluate(CheckExpr);
651   (void)Result;
652   DEBUG(dbgs() << "RuntimeDyldChecker: '" << CheckExpr << "' "
653                << (Result ? "passed" : "FAILED") << ".\n");
654   return Result;
655 }
656
657 bool RuntimeDyldCheckerImpl::checkAllRulesInBuffer(StringRef RulePrefix,
658                                                    MemoryBuffer *MemBuf) const {
659   bool DidAllTestsPass = true;
660   unsigned NumRules = 0;
661
662   const char *LineStart = MemBuf->getBufferStart();
663
664   // Eat whitespace.
665   while (LineStart != MemBuf->getBufferEnd() && std::isspace(*LineStart))
666     ++LineStart;
667
668   while (LineStart != MemBuf->getBufferEnd() && *LineStart != '\0') {
669     const char *LineEnd = LineStart;
670     while (LineEnd != MemBuf->getBufferEnd() && *LineEnd != '\r' &&
671            *LineEnd != '\n')
672       ++LineEnd;
673
674     StringRef Line(LineStart, LineEnd - LineStart);
675     if (Line.startswith(RulePrefix)) {
676       DidAllTestsPass &= check(Line.substr(RulePrefix.size()));
677       ++NumRules;
678     }
679
680     // Eat whitespace.
681     LineStart = LineEnd;
682     while (LineStart != MemBuf->getBufferEnd() && std::isspace(*LineStart))
683       ++LineStart;
684   }
685   return DidAllTestsPass && (NumRules != 0);
686 }
687
688 bool RuntimeDyldCheckerImpl::isSymbolValid(StringRef Symbol) const {
689   return getRTDyld().getSymbolAddress(Symbol) != nullptr;
690 }
691
692 uint64_t RuntimeDyldCheckerImpl::getSymbolLinkerAddr(StringRef Symbol) const {
693   return static_cast<uint64_t>(
694       reinterpret_cast<uintptr_t>(getRTDyld().getSymbolAddress(Symbol)));
695 }
696
697 uint64_t RuntimeDyldCheckerImpl::getSymbolRemoteAddr(StringRef Symbol) const {
698   return getRTDyld().getAnySymbolRemoteAddress(Symbol);
699 }
700
701 uint64_t RuntimeDyldCheckerImpl::readMemoryAtAddr(uint64_t SrcAddr,
702                                                   unsigned Size) const {
703   uintptr_t PtrSizedAddr = static_cast<uintptr_t>(SrcAddr);
704   assert(PtrSizedAddr == SrcAddr && "Linker memory pointer out-of-range.");
705   uint8_t *Src = reinterpret_cast<uint8_t *>(PtrSizedAddr);
706   uint64_t Result = 0;
707   memcpy(&Result, Src, Size);
708   return Result;
709 }
710
711 std::pair<uint64_t, std::string> RuntimeDyldCheckerImpl::getStubAddrFor(
712     StringRef FileName, StringRef SectionName, StringRef SymbolName,
713     bool IsInsideLoad) const {
714
715   auto SI1 = Stubs.find(FileName);
716   if (SI1 == Stubs.end())
717     return std::make_pair(0, ("File '" + FileName + "' not found.\n").str());
718
719   const SectionStubMap &SectionStubs = SI1->second;
720   auto SI2 = SectionStubs.find(SectionName);
721   if (SI2 == SectionStubs.end())
722     return std::make_pair(0,
723                           ("Section '" + SectionName + "' not found.\n").str());
724
725   const SymbolStubMap &SymbolStubs = SI2->second;
726   auto SI3 = SymbolStubs.find(SymbolName);
727   if (SI3 == SymbolStubs.end())
728     return std::make_pair(0,
729                           ("Symbol '" + SymbolName + "' not found.\n").str());
730
731   unsigned SectionID = SI3->second.first;
732   uint64_t StubOffset = SI3->second.second;
733
734   uint64_t Addr;
735   if (IsInsideLoad) {
736     uint64_t SectionBase = getRTDyld().Sections[SectionID].LoadAddress;
737     Addr = SectionBase + StubOffset;
738   } else {
739     uintptr_t SectionBase =
740         reinterpret_cast<uintptr_t>(getRTDyld().Sections[SectionID].Address);
741     Addr = static_cast<uint64_t>(SectionBase) + StubOffset;
742   }
743
744   return std::make_pair(Addr, std::string(""));
745 }
746
747 StringRef
748 RuntimeDyldCheckerImpl::getSubsectionStartingAt(StringRef Name) const {
749   RuntimeDyldImpl::SymbolTableMap::const_iterator pos =
750       getRTDyld().GlobalSymbolTable.find(Name);
751   if (pos == getRTDyld().GlobalSymbolTable.end())
752     return StringRef();
753   RuntimeDyldImpl::SymbolLoc Loc = pos->second;
754   uint8_t *SectionAddr = getRTDyld().getSectionAddress(Loc.first);
755   return StringRef(reinterpret_cast<const char *>(SectionAddr) + Loc.second,
756                    getRTDyld().Sections[Loc.first].Size - Loc.second);
757 }
758
759 void RuntimeDyldCheckerImpl::registerStubMap(
760     StringRef FileName, unsigned SectionID,
761     const RuntimeDyldImpl::StubMap &RTDyldStubs) {
762   const SectionEntry &Section = getRTDyld().Sections[SectionID];
763   StringRef SectionName = Section.Name;
764   for (auto &StubMapEntry : RTDyldStubs) {
765     std::string SymbolName = "";
766
767     if (StubMapEntry.first.SymbolName)
768       SymbolName = StubMapEntry.first.SymbolName;
769     else {
770       // If this is a (Section, Offset) pair, do a reverse lookup in the
771       // global symbol table to find the name.
772       for (auto &GSTEntry : getRTDyld().GlobalSymbolTable) {
773         if (GSTEntry.second.first == StubMapEntry.first.SectionID &&
774             GSTEntry.second.second ==
775                 static_cast<uint64_t>(StubMapEntry.first.Addend)) {
776           SymbolName = GSTEntry.first();
777           break;
778         }
779       }
780     }
781
782     if (SymbolName != "")
783       Stubs[FileName][SectionName][SymbolName] =
784           StubLoc(SectionID, StubMapEntry.second);
785   }
786 }
787
788 RuntimeDyldChecker::RuntimeDyldChecker(RuntimeDyld &RTDyld,
789                                        MCDisassembler *Disassembler,
790                                        MCInstPrinter *InstPrinter,
791                                        raw_ostream &ErrStream)
792     : Impl(make_unique<RuntimeDyldCheckerImpl>(RTDyld, Disassembler,
793                                                InstPrinter, ErrStream)) {}
794
795 RuntimeDyldChecker::~RuntimeDyldChecker() {}
796
797 bool RuntimeDyldChecker::check(StringRef CheckExpr) const {
798   return Impl->check(CheckExpr);
799 }
800
801 bool RuntimeDyldChecker::checkAllRulesInBuffer(StringRef RulePrefix,
802                                                MemoryBuffer *MemBuf) const {
803   return Impl->checkAllRulesInBuffer(RulePrefix, MemBuf);
804 }