[RuntimeDyld] Improve error diagnostic in RuntimeDyldChecker.
[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/ExecutionEngine/RuntimeDyldChecker.h"
11 #include "llvm/MC/MCContext.h"
12 #include "llvm/MC/MCDisassembler.h"
13 #include "llvm/MC/MCInst.h"
14 #include "llvm/Support/StringRefMemoryObject.h"
15 #include "RuntimeDyldImpl.h"
16 #include <cctype>
17 #include <memory>
18
19 #define DEBUG_TYPE "rtdyld"
20
21 using namespace llvm;
22
23 namespace llvm {
24
25   // Helper class that implements the language evaluated by RuntimeDyldChecker.
26   class RuntimeDyldCheckerExprEval {
27   public:
28
29     RuntimeDyldCheckerExprEval(const RuntimeDyldChecker &Checker,
30                                llvm::raw_ostream &ErrStream)
31       : Checker(Checker), ErrStream(ErrStream) {}
32
33     bool evaluate(StringRef Expr) const {
34       // Expect equality expression of the form 'LHS = RHS'.
35       Expr = Expr.trim();
36       size_t EQIdx = Expr.find('=');
37
38       // Evaluate LHS.
39       StringRef LHSExpr = Expr.substr(0, EQIdx).rtrim();
40       StringRef RemainingExpr;
41       EvalResult LHSResult;
42       std::tie(LHSResult, RemainingExpr) =
43         evalComplexExpr(evalSimpleExpr(LHSExpr));
44       if (LHSResult.hasError())
45         return handleError(Expr, LHSResult);
46       if (RemainingExpr != "")
47         return handleError(Expr, unexpectedToken(RemainingExpr, LHSExpr, ""));
48
49       // Evaluate RHS.
50       StringRef RHSExpr = Expr.substr(EQIdx + 1).ltrim();
51       EvalResult RHSResult;
52       std::tie(RHSResult, RemainingExpr) =
53         evalComplexExpr(evalSimpleExpr(RHSExpr));
54       if (RHSResult.hasError())
55         return handleError(Expr, RHSResult);
56       if (RemainingExpr != "")
57         return handleError(Expr, unexpectedToken(RemainingExpr, RHSExpr, ""));
58
59       if (LHSResult.getValue() != RHSResult.getValue()) {
60         ErrStream << "Expression '" << Expr << "' is false: "
61                   << format("0x%lx", LHSResult.getValue()) << " != "
62                   << format("0x%lx", RHSResult.getValue()) << "\n";
63         return false;
64       }
65       return true;
66     }
67
68   private:
69     const RuntimeDyldChecker &Checker;
70     llvm::raw_ostream &ErrStream;
71
72     enum class BinOpToken : unsigned { Invalid, Add, Sub, BitwiseAnd,
73                                        BitwiseOr, ShiftLeft, ShiftRight };
74
75     class EvalResult {
76     public:
77       EvalResult()
78         : Value(0), ErrorMsg("") {}
79       EvalResult(uint64_t Value)
80         : Value(Value), ErrorMsg("") {}
81       EvalResult(std::string ErrorMsg)
82         : Value(0), ErrorMsg(ErrorMsg) {}
83       uint64_t getValue() const { return Value; }
84       bool hasError() const { return ErrorMsg != ""; }
85       const std::string& getErrorMsg() const { return ErrorMsg; }
86     private:
87       uint64_t Value;
88       std::string ErrorMsg;
89     };
90
91     StringRef getTokenForError(StringRef Expr) const {
92       if (Expr.empty())
93         return "";
94
95       StringRef Token, Remaining;
96       if (isalpha(Expr[0]))
97         std::tie(Token, Remaining) = parseSymbol(Expr);
98       else if (isdigit(Expr[0]))
99         std::tie(Token, Remaining) = parseNumberString(Expr);
100       else {
101         unsigned TokLen = 1;
102         if (Expr.startswith("<<") || Expr.startswith(">>"))
103           TokLen = 2;
104         Token = Expr.substr(0, TokLen);
105       }
106       return Token;
107     }
108
109     EvalResult unexpectedToken(StringRef TokenStart,
110                                StringRef SubExpr,
111                                StringRef ErrText) const {
112       std::string ErrorMsg("Encountered unexpected token '");
113       ErrorMsg += getTokenForError(TokenStart);
114       if (SubExpr != "") {
115         ErrorMsg += "' while parsing subexpression '";
116         ErrorMsg += SubExpr;
117       }
118       ErrorMsg += "'";
119       if (ErrText != "") {
120         ErrorMsg += " ";
121         ErrorMsg += ErrText;
122       }
123       return EvalResult(std::move(ErrorMsg));
124     }
125
126     bool handleError(StringRef Expr, const EvalResult &R) const {
127       assert(R.hasError() && "Not an error result.");
128       ErrStream << "Error evaluating expression '" << Expr << "': "
129                 << R.getErrorMsg() << "\n";
130       return false;
131     }
132
133     std::pair<BinOpToken, StringRef> parseBinOpToken(StringRef Expr) const {
134       if (Expr.empty())
135         return std::make_pair(BinOpToken::Invalid, "");
136
137       // Handle the two 2-character tokens.
138       if (Expr.startswith("<<"))
139         return std::make_pair(BinOpToken::ShiftLeft,
140                               Expr.substr(2).ltrim());
141       if (Expr.startswith(">>"))
142         return std::make_pair(BinOpToken::ShiftRight,
143                               Expr.substr(2).ltrim());
144
145       // Handle one-character tokens.
146       BinOpToken Op;
147       switch (Expr[0]) {
148         default: return std::make_pair(BinOpToken::Invalid, Expr);
149         case '+': Op = BinOpToken::Add; break;
150         case '-': Op = BinOpToken::Sub; break;
151         case '&': Op = BinOpToken::BitwiseAnd; break;
152         case '|': Op = BinOpToken::BitwiseOr; break;
153       }
154
155       return std::make_pair(Op, Expr.substr(1).ltrim());
156     }
157
158     EvalResult computeBinOpResult(BinOpToken Op, const EvalResult &LHSResult,
159                                   const EvalResult &RHSResult) const {
160       switch (Op) {
161       default: llvm_unreachable("Tried to evaluate unrecognized operation.");
162       case BinOpToken::Add:
163         return EvalResult(LHSResult.getValue() + RHSResult.getValue());
164       case BinOpToken::Sub:
165         return EvalResult(LHSResult.getValue() - RHSResult.getValue());
166       case BinOpToken::BitwiseAnd:
167         return EvalResult(LHSResult.getValue() & RHSResult.getValue());
168       case BinOpToken::BitwiseOr:
169         return EvalResult(LHSResult.getValue() | RHSResult.getValue());
170       case BinOpToken::ShiftLeft:
171         return EvalResult(LHSResult.getValue() << RHSResult.getValue());
172       case BinOpToken::ShiftRight:
173         return EvalResult(LHSResult.getValue() >> RHSResult.getValue());
174       }
175     }
176
177     // Parse a symbol and return a (string, string) pair representing the symbol
178     // name and expression remaining to be parsed.
179     std::pair<StringRef, StringRef> parseSymbol(StringRef Expr) const {
180       size_t FirstNonSymbol =
181         Expr.find_first_not_of("0123456789"
182                                "abcdefghijklmnopqrstuvwxyz"
183                                "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
184                                ":_");
185       return std::make_pair(Expr.substr(0, FirstNonSymbol),
186                             Expr.substr(FirstNonSymbol).ltrim());
187     }
188
189     // Evaluate a call to decode_operand. Decode the instruction operand at the
190     // given symbol and get the value of the requested operand.
191     // Returns an error if the instruction cannot be decoded, or the requested
192     // operand is not an immediate.
193     // On success, retuns a pair containing the value of the operand, plus
194     // the expression remaining to be evaluated.
195     std::pair<EvalResult, StringRef> evalDecodeOperand(StringRef Expr) const {
196       if (!Expr.startswith("("))
197         return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
198       StringRef RemainingExpr = Expr.substr(1).ltrim();
199       StringRef Symbol;
200       std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
201
202       if (!Checker.isSymbolValid(Symbol))
203         return std::make_pair(EvalResult(("Cannot decode unknown symbol '" +
204                                           Symbol + "'").str()),
205                               "");
206
207       if (!RemainingExpr.startswith(","))
208         return std::make_pair(unexpectedToken(RemainingExpr, RemainingExpr,
209                                               "expected ','"),
210                               "");
211       RemainingExpr = RemainingExpr.substr(1).ltrim();
212
213       EvalResult OpIdxExpr;
214       std::tie(OpIdxExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
215       if (OpIdxExpr.hasError())
216         return std::make_pair(OpIdxExpr, "");
217
218       if (!RemainingExpr.startswith(")"))
219         return std::make_pair(unexpectedToken(RemainingExpr, RemainingExpr,
220                                               "expected ')'"),
221                               "");
222       RemainingExpr = RemainingExpr.substr(1).ltrim();
223
224       MCInst Inst;
225       uint64_t Size;
226       if (!decodeInst(Symbol, Inst, Size))
227         return std::make_pair(EvalResult(("Couldn't decode instruction at '" +
228                                           Symbol + "'").str()),
229                               "");
230
231       unsigned OpIdx = OpIdxExpr.getValue();
232       if (OpIdx >= Inst.getNumOperands()) {
233         std::string ErrMsg;
234         raw_string_ostream ErrMsgStream(ErrMsg);
235         ErrMsgStream << "Invalid operand index '" << format("%i", OpIdx)
236                      << " for instruction '" << Symbol
237                      << ". Instruction has only "
238                      << format("%i", Inst.getNumOperands()) << " operands.";
239         return std::make_pair(EvalResult(ErrMsgStream.str()), "");
240       }
241
242       const MCOperand &Op = Inst.getOperand(OpIdx);
243       if (!Op.isImm()) {
244         std::string ErrMsg;
245         raw_string_ostream ErrMsgStream(ErrMsg);
246         ErrMsgStream << "Operand '" << format("%i", OpIdx)
247                      << "' of instruction '" << Symbol
248                      << "' is not an immediate.\nInstruction is:\n  ";
249         Inst.dump_pretty(ErrMsgStream,
250                          Checker.Disassembler->getContext().getAsmInfo(),
251                          Checker.InstPrinter);
252
253         return std::make_pair(EvalResult(ErrMsgStream.str()), "");
254       }
255
256       return std::make_pair(EvalResult(Op.getImm()), RemainingExpr);
257     }
258
259     // Evaluate a call to next_pc. Decode the instruction at the given
260     // symbol and return the following program counter..
261     // Returns an error if the instruction cannot be decoded.
262     // On success, returns a pair containing the next PC, plus the length of the
263     // expression remaining to be evaluated.
264     std::pair<EvalResult, StringRef> evalNextPC(StringRef Expr) const {
265       if (!Expr.startswith("("))
266         return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
267       StringRef RemainingExpr = Expr.substr(1).ltrim();
268       StringRef Symbol;
269       std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
270
271       if (!Checker.isSymbolValid(Symbol))
272         return std::make_pair(EvalResult(("Cannot decode unknown symbol '"
273                                           + Symbol + "'").str()),
274                               "");
275
276       if (!RemainingExpr.startswith(")"))
277         return std::make_pair(unexpectedToken(RemainingExpr, RemainingExpr,
278                                               "expected ')'"),
279                               "");
280       RemainingExpr = RemainingExpr.substr(1).ltrim();
281
282       MCInst Inst;
283       uint64_t Size;
284       if (!decodeInst(Symbol, Inst, Size))
285         return std::make_pair(EvalResult(("Couldn't decode instruction at '" +
286                                           Symbol + "'").str()),
287                               "");
288       uint64_t NextPC = Checker.getSymbolAddress(Symbol) + Size;
289
290       return std::make_pair(EvalResult(NextPC), RemainingExpr);
291     }
292
293     // Evaluate an identiefer expr, which may be a symbol, or a call to
294     // one of the builtin functions: get_insn_opcode or get_insn_length.
295     // Return the result, plus the expression remaining to be parsed.
296     std::pair<EvalResult, StringRef> evalIdentifierExpr(StringRef Expr) const {
297       StringRef Symbol;
298       StringRef RemainingExpr;
299       std::tie(Symbol, RemainingExpr) = parseSymbol(Expr);
300
301       // Check for builtin function calls.
302       if (Symbol == "decode_operand")
303         return evalDecodeOperand(RemainingExpr);
304       else if (Symbol == "next_pc")
305         return evalNextPC(RemainingExpr);
306
307       if (!Checker.isSymbolValid(Symbol)) {
308         std::string ErrMsg("No known address for symbol '");
309         ErrMsg += Symbol;
310         ErrMsg += "'";
311         if (Symbol.startswith("L"))
312           ErrMsg += " (this appears to be an assembler local label - "
313                     " perhaps drop the 'L'?)";
314
315         return std::make_pair(EvalResult(ErrMsg), "");
316       }
317
318       // Looks like a plain symbol reference.
319       return std::make_pair(EvalResult(Checker.getSymbolAddress(Symbol)),
320                             RemainingExpr);
321     }
322
323     // Parse a number (hexadecimal or decimal) and return a (string, string)
324     // pair representing the number and the expression remaining to be parsed.
325     std::pair<StringRef, StringRef> parseNumberString(StringRef Expr) const {
326       size_t FirstNonDigit = StringRef::npos;
327       if (Expr.startswith("0x")) {
328         FirstNonDigit = Expr.find_first_not_of("0123456789abcdefABCDEF", 2);
329         if (FirstNonDigit == StringRef::npos)
330           FirstNonDigit = Expr.size();
331       } else {
332         FirstNonDigit = Expr.find_first_not_of("0123456789");
333         if (FirstNonDigit == StringRef::npos)
334           FirstNonDigit = Expr.size();
335       }
336       return std::make_pair(Expr.substr(0, FirstNonDigit),
337                             Expr.substr(FirstNonDigit));
338     }
339
340     // Evaluate a constant numeric expression (hexidecimal or decimal) and
341     // return a pair containing the result, and the expression remaining to be
342     // evaluated.
343     std::pair<EvalResult, StringRef> evalNumberExpr(StringRef Expr) const {
344       StringRef ValueStr;
345       StringRef RemainingExpr;
346       std::tie(ValueStr, RemainingExpr) = parseNumberString(Expr);
347
348       if (ValueStr.empty() || !isdigit(ValueStr[0]))
349         return std::make_pair(unexpectedToken(RemainingExpr, RemainingExpr,
350                                               "expected number"),
351                               "");
352       uint64_t Value;
353       ValueStr.getAsInteger(0, Value);
354       return std::make_pair(EvalResult(Value), RemainingExpr);
355     }
356
357     // Evaluate an expression of the form "(<expr>)" and return a pair
358     // containing the result of evaluating <expr>, plus the expression
359     // remaining to be parsed.
360     std::pair<EvalResult, StringRef> evalParensExpr(StringRef Expr) const {
361       assert(Expr.startswith("(") && "Not a parenthesized expression");
362       EvalResult SubExprResult;
363       StringRef RemainingExpr;
364       std::tie(SubExprResult, RemainingExpr) =
365         evalComplexExpr(evalSimpleExpr(Expr.substr(1).ltrim()));
366       if (SubExprResult.hasError())
367         return std::make_pair(SubExprResult, "");
368       if (!RemainingExpr.startswith(")"))
369         return std::make_pair(unexpectedToken(RemainingExpr, Expr,
370                                               "expected ')'"),
371                               "");
372       RemainingExpr = RemainingExpr.substr(1).ltrim();
373       return std::make_pair(SubExprResult, RemainingExpr);
374     }
375
376     // Evaluate an expression in one of the following forms:
377     //   *{<number>}<symbol>
378     //   *{<number>}(<symbol> + <number>)
379     //   *{<number>}(<symbol> - <number>)
380     // Return a pair containing the result, plus the expression remaining to be
381     // parsed.
382     std::pair<EvalResult, StringRef> evalLoadExpr(StringRef Expr) const {
383       assert(Expr.startswith("*") && "Not a load expression");
384       StringRef RemainingExpr = Expr.substr(1).ltrim();
385       // Parse read size.
386       if (!RemainingExpr.startswith("{"))
387         return std::make_pair(EvalResult("Expected '{' following '*'."), "");
388       RemainingExpr = RemainingExpr.substr(1).ltrim();
389       EvalResult ReadSizeExpr;
390       std::tie(ReadSizeExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
391       if (ReadSizeExpr.hasError())
392         return std::make_pair(ReadSizeExpr, RemainingExpr);
393       uint64_t ReadSize = ReadSizeExpr.getValue();
394       if (ReadSize < 1 || ReadSize > 8)
395         return std::make_pair(EvalResult("Invalid size for dereference."), "");
396       if (!RemainingExpr.startswith("}"))
397         return std::make_pair(EvalResult("Missing '}' for dereference."), "");
398       RemainingExpr = RemainingExpr.substr(1).ltrim();
399
400       // Check for '(symbol +/- constant)' form.
401       bool SymbolPlusConstant = false;
402       if (RemainingExpr.startswith("(")) {
403         SymbolPlusConstant = true;
404         RemainingExpr = RemainingExpr.substr(1).ltrim();
405       }
406
407       // Read symbol.
408       StringRef Symbol;
409       std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
410
411       if (!Checker.isSymbolValid(Symbol))
412         return std::make_pair(EvalResult(("Cannot dereference unknown symbol '"
413                                           + Symbol + "'").str()),
414                               "");
415
416       // Set up defaut offset.
417       int64_t Offset = 0;
418
419       // Handle "+/- constant)" portion if necessary.
420       if (SymbolPlusConstant) {
421         char OpChar = RemainingExpr[0];
422         if (OpChar != '+' && OpChar != '-')
423           return std::make_pair(EvalResult("Invalid operator in load address."),
424                                 "");
425         RemainingExpr = RemainingExpr.substr(1).ltrim();
426
427         EvalResult OffsetExpr;
428         std::tie(OffsetExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
429
430         Offset = (OpChar == '+') ?
431                    OffsetExpr.getValue() : -1 * OffsetExpr.getValue();
432
433         if (!RemainingExpr.startswith(")"))
434           return std::make_pair(EvalResult("Missing ')' in load address."),
435                                 "");
436
437         RemainingExpr = RemainingExpr.substr(1).ltrim();
438       }
439
440       return std::make_pair(
441                EvalResult(Checker.readMemoryAtSymbol(Symbol, Offset, ReadSize)),
442                RemainingExpr);
443     }
444
445     // Evaluate a "simple" expression. This is any expression that _isn't_ an
446     // un-parenthesized binary expression.
447     //
448     // "Simple" expressions can be optionally bit-sliced. See evalSlicedExpr.
449     //
450     // Returns a pair containing the result of the evaluation, plus the
451     // expression remaining to be parsed.
452     std::pair<EvalResult, StringRef> evalSimpleExpr(StringRef Expr) const {
453       EvalResult SubExprResult;
454       StringRef RemainingExpr;
455
456       if (Expr.empty())
457         return std::make_pair(EvalResult("Unexpected end of expression"), "");
458
459       if (Expr[0] == '(')
460         std::tie(SubExprResult, RemainingExpr) = evalParensExpr(Expr);
461       else if (Expr[0] == '*')
462         std::tie(SubExprResult, RemainingExpr) = evalLoadExpr(Expr);
463       else if (isalpha(Expr[0]))
464         std::tie(SubExprResult, RemainingExpr) = evalIdentifierExpr(Expr);
465       else if (isdigit(Expr[0]))
466         std::tie(SubExprResult, RemainingExpr) = evalNumberExpr(Expr);
467
468       if (SubExprResult.hasError())
469         return std::make_pair(SubExprResult, RemainingExpr);
470
471       // Evaluate bit-slice if present.
472       if (RemainingExpr.startswith("["))
473         std::tie(SubExprResult, RemainingExpr) =
474           evalSliceExpr(std::make_pair(SubExprResult, RemainingExpr));
475
476       return std::make_pair(SubExprResult, RemainingExpr);
477     }
478
479     // Evaluate a bit-slice of an expression.
480     // A bit-slice has the form "<expr>[high:low]". The result of evaluating a
481     // slice is the bits between high and low (inclusive) in the original
482     // expression, right shifted so that the "low" bit is in position 0 in the
483     // result.
484     // Returns a pair containing the result of the slice operation, plus the
485     // expression remaining to be parsed.
486     std::pair<EvalResult, StringRef> evalSliceExpr(
487                                     std::pair<EvalResult, StringRef> Ctx) const{
488       EvalResult SubExprResult;
489       StringRef RemainingExpr;
490       std::tie(SubExprResult, RemainingExpr) = Ctx;
491
492       assert(RemainingExpr.startswith("[") && "Not a slice expr.");
493       RemainingExpr = RemainingExpr.substr(1).ltrim();
494
495       EvalResult HighBitExpr;
496       std::tie(HighBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
497
498       if (HighBitExpr.hasError())
499         return std::make_pair(HighBitExpr, RemainingExpr);
500
501       if (!RemainingExpr.startswith(":"))
502         return std::make_pair(unexpectedToken(RemainingExpr, RemainingExpr,
503                                               "expected ':'"),
504                               "");
505       RemainingExpr = RemainingExpr.substr(1).ltrim();
506
507       EvalResult LowBitExpr;
508       std::tie(LowBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
509
510       if (LowBitExpr.hasError())
511         return std::make_pair(LowBitExpr, RemainingExpr);
512
513       if (!RemainingExpr.startswith("]"))
514         return std::make_pair(unexpectedToken(RemainingExpr, RemainingExpr,
515                                               "expected ']'"),
516                               "");
517       RemainingExpr = RemainingExpr.substr(1).ltrim();
518
519       unsigned HighBit = HighBitExpr.getValue();
520       unsigned LowBit = LowBitExpr.getValue();
521       uint64_t Mask = ((uint64_t)1 << (HighBit - LowBit + 1)) - 1;
522       uint64_t SlicedValue = (SubExprResult.getValue() >> LowBit) & Mask;
523       return std::make_pair(EvalResult(SlicedValue), RemainingExpr);
524     }
525
526     // Evaluate a "complex" expression.
527     // Takes an already evaluated subexpression and checks for the presence of a
528     // binary operator, computing the result of the binary operation if one is
529     // found. Used to make arithmetic expressions left-associative.
530     // Returns a pair containing the ultimate result of evaluating the
531     // expression, plus the expression remaining to be evaluated.
532     std::pair<EvalResult, StringRef> evalComplexExpr(
533                                    std::pair<EvalResult, StringRef> Ctx) const {
534       EvalResult LHSResult;
535       StringRef RemainingExpr;
536       std::tie(LHSResult, RemainingExpr) = Ctx;
537
538       // If there was an error, or there's nothing left to evaluate, return the
539       // result.
540       if (LHSResult.hasError() || RemainingExpr == "")
541         return std::make_pair(LHSResult, RemainingExpr);
542
543       // Otherwise check if this is a binary expressioan.
544       BinOpToken BinOp;
545       std::tie(BinOp, RemainingExpr) = parseBinOpToken(RemainingExpr);
546
547       // If this isn't a recognized expression just return.
548       if (BinOp == BinOpToken::Invalid)
549         return std::make_pair(LHSResult, RemainingExpr);
550
551       // This is a recognized bin-op. Evaluate the RHS, then evaluate the binop.
552       EvalResult RHSResult;
553       std::tie(RHSResult, RemainingExpr) = evalSimpleExpr(RemainingExpr);
554
555       // If there was an error evaluating the RHS, return it.
556       if (RHSResult.hasError())
557         return std::make_pair(RHSResult, RemainingExpr);
558
559       // This is a binary expression - evaluate and try to continue as a
560       // complex expr.
561       EvalResult ThisResult(computeBinOpResult(BinOp, LHSResult, RHSResult));
562
563       return evalComplexExpr(std::make_pair(ThisResult, RemainingExpr));
564     }
565
566     bool decodeInst(StringRef Symbol, MCInst &Inst, uint64_t &Size) const {
567       MCDisassembler *Dis = Checker.Disassembler;
568       StringRef SectionMem = Checker.getSubsectionStartingAt(Symbol);
569       StringRefMemoryObject SectionBytes(SectionMem, 0);
570
571       MCDisassembler::DecodeStatus S =
572         Dis->getInstruction(Inst, Size, SectionBytes, 0, nulls(), nulls());
573
574       return (S == MCDisassembler::Success);
575     }
576
577   };
578
579 }
580
581 bool RuntimeDyldChecker::check(StringRef CheckExpr) const {
582   CheckExpr = CheckExpr.trim();
583   DEBUG(llvm::dbgs() << "RuntimeDyldChecker: Checking '" << CheckExpr
584                      << "'...\n");
585   RuntimeDyldCheckerExprEval P(*this, ErrStream);
586   bool Result = P.evaluate(CheckExpr);
587   (void)Result;
588   DEBUG(llvm::dbgs() << "RuntimeDyldChecker: '" << CheckExpr << "' "
589                      << (Result ? "passed" : "FAILED") << ".\n");
590   return Result;
591 }
592
593 bool RuntimeDyldChecker::checkAllRulesInBuffer(StringRef RulePrefix,
594                                                MemoryBuffer* MemBuf) const {
595   bool DidAllTestsPass = true;
596   unsigned NumRules = 0;
597
598   const char *LineStart = MemBuf->getBufferStart();
599
600   // Eat whitespace.
601   while (LineStart != MemBuf->getBufferEnd() &&
602          std::isspace(*LineStart))
603     ++LineStart;
604
605   while (LineStart != MemBuf->getBufferEnd() && *LineStart != '\0') {
606     const char *LineEnd = LineStart;
607     while (LineEnd != MemBuf->getBufferEnd() &&
608            *LineEnd != '\r' && *LineEnd != '\n')
609       ++LineEnd;
610
611     StringRef Line(LineStart, LineEnd - LineStart);
612     if (Line.startswith(RulePrefix)) {
613       DidAllTestsPass &= check(Line.substr(RulePrefix.size()));
614       ++NumRules;
615     }
616
617     // Eat whitespace.
618     LineStart = LineEnd;
619     while (LineStart != MemBuf->getBufferEnd() &&
620            std::isspace(*LineStart))
621       ++LineStart;
622   }
623   return DidAllTestsPass && (NumRules != 0);
624 }
625
626 bool RuntimeDyldChecker::isSymbolValid(StringRef Symbol) const {
627   return RTDyld.getSymbolAddress(Symbol) != nullptr;
628 }
629
630 uint64_t RuntimeDyldChecker::getSymbolAddress(StringRef Symbol) const {
631   return RTDyld.getAnySymbolRemoteAddress(Symbol);
632 }
633
634 uint64_t RuntimeDyldChecker::readMemoryAtSymbol(StringRef Symbol,
635                                                 int64_t Offset,
636                                                 unsigned Size) const {
637   uint8_t *Src = RTDyld.getSymbolAddress(Symbol);
638   uint64_t Result = 0;
639   memcpy(&Result, Src + Offset, Size);
640   return Result;
641 }
642
643 StringRef RuntimeDyldChecker::getSubsectionStartingAt(StringRef Name) const {
644   RuntimeDyldImpl::SymbolTableMap::const_iterator pos =
645     RTDyld.GlobalSymbolTable.find(Name);
646   if (pos == RTDyld.GlobalSymbolTable.end())
647     return StringRef();
648   RuntimeDyldImpl::SymbolLoc Loc = pos->second;
649   uint8_t *SectionAddr = RTDyld.getSectionAddress(Loc.first);
650   return StringRef(reinterpret_cast<const char*>(SectionAddr) + Loc.second,
651                    RTDyld.Sections[Loc.first].Size - Loc.second);
652 }