xref: /freebsd/contrib/llvm-project/llvm/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldChecker.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
10b57cec5SDimitry Andric //===--- RuntimeDyldChecker.cpp - RuntimeDyld tester framework --*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
100b57cec5SDimitry Andric #include "RuntimeDyldCheckerImpl.h"
110b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
120b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
130b57cec5SDimitry Andric #include "llvm/MC/MCDisassembler/MCDisassembler.h"
140b57cec5SDimitry Andric #include "llvm/MC/MCInst.h"
150b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
160b57cec5SDimitry Andric #include "llvm/Support/MSVCErrorWorkarounds.h"
170b57cec5SDimitry Andric #include "llvm/Support/Path.h"
180b57cec5SDimitry Andric #include <cctype>
190b57cec5SDimitry Andric #include <memory>
200b57cec5SDimitry Andric #include <utility>
210b57cec5SDimitry Andric 
220b57cec5SDimitry Andric #define DEBUG_TYPE "rtdyld"
230b57cec5SDimitry Andric 
240b57cec5SDimitry Andric using namespace llvm;
250b57cec5SDimitry Andric 
260b57cec5SDimitry Andric namespace llvm {
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric // Helper class that implements the language evaluated by RuntimeDyldChecker.
290b57cec5SDimitry Andric class RuntimeDyldCheckerExprEval {
300b57cec5SDimitry Andric public:
310b57cec5SDimitry Andric   RuntimeDyldCheckerExprEval(const RuntimeDyldCheckerImpl &Checker,
320b57cec5SDimitry Andric                              raw_ostream &ErrStream)
330b57cec5SDimitry Andric       : Checker(Checker) {}
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric   bool evaluate(StringRef Expr) const {
360b57cec5SDimitry Andric     // Expect equality expression of the form 'LHS = RHS'.
370b57cec5SDimitry Andric     Expr = Expr.trim();
380b57cec5SDimitry Andric     size_t EQIdx = Expr.find('=');
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric     ParseContext OutsideLoad(false);
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric     // Evaluate LHS.
430b57cec5SDimitry Andric     StringRef LHSExpr = Expr.substr(0, EQIdx).rtrim();
440b57cec5SDimitry Andric     StringRef RemainingExpr;
450b57cec5SDimitry Andric     EvalResult LHSResult;
460b57cec5SDimitry Andric     std::tie(LHSResult, RemainingExpr) =
470b57cec5SDimitry Andric         evalComplexExpr(evalSimpleExpr(LHSExpr, OutsideLoad), OutsideLoad);
480b57cec5SDimitry Andric     if (LHSResult.hasError())
490b57cec5SDimitry Andric       return handleError(Expr, LHSResult);
500b57cec5SDimitry Andric     if (RemainingExpr != "")
510b57cec5SDimitry Andric       return handleError(Expr, unexpectedToken(RemainingExpr, LHSExpr, ""));
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric     // Evaluate RHS.
540b57cec5SDimitry Andric     StringRef RHSExpr = Expr.substr(EQIdx + 1).ltrim();
550b57cec5SDimitry Andric     EvalResult RHSResult;
560b57cec5SDimitry Andric     std::tie(RHSResult, RemainingExpr) =
570b57cec5SDimitry Andric         evalComplexExpr(evalSimpleExpr(RHSExpr, OutsideLoad), OutsideLoad);
580b57cec5SDimitry Andric     if (RHSResult.hasError())
590b57cec5SDimitry Andric       return handleError(Expr, RHSResult);
600b57cec5SDimitry Andric     if (RemainingExpr != "")
610b57cec5SDimitry Andric       return handleError(Expr, unexpectedToken(RemainingExpr, RHSExpr, ""));
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric     if (LHSResult.getValue() != RHSResult.getValue()) {
640b57cec5SDimitry Andric       Checker.ErrStream << "Expression '" << Expr << "' is false: "
650b57cec5SDimitry Andric                         << format("0x%" PRIx64, LHSResult.getValue())
660b57cec5SDimitry Andric                         << " != " << format("0x%" PRIx64, RHSResult.getValue())
670b57cec5SDimitry Andric                         << "\n";
680b57cec5SDimitry Andric       return false;
690b57cec5SDimitry Andric     }
700b57cec5SDimitry Andric     return true;
710b57cec5SDimitry Andric   }
720b57cec5SDimitry Andric 
730b57cec5SDimitry Andric private:
740b57cec5SDimitry Andric   // RuntimeDyldCheckerExprEval requires some context when parsing exprs. In
750b57cec5SDimitry Andric   // particular, it needs to know whether a symbol is being evaluated in the
760b57cec5SDimitry Andric   // context of a load, in which case we want the linker's local address for
770b57cec5SDimitry Andric   // the symbol, or outside of a load, in which case we want the symbol's
780b57cec5SDimitry Andric   // address in the remote target.
790b57cec5SDimitry Andric 
800b57cec5SDimitry Andric   struct ParseContext {
810b57cec5SDimitry Andric     bool IsInsideLoad;
820b57cec5SDimitry Andric     ParseContext(bool IsInsideLoad) : IsInsideLoad(IsInsideLoad) {}
830b57cec5SDimitry Andric   };
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric   const RuntimeDyldCheckerImpl &Checker;
860b57cec5SDimitry Andric 
870b57cec5SDimitry Andric   enum class BinOpToken : unsigned {
880b57cec5SDimitry Andric     Invalid,
890b57cec5SDimitry Andric     Add,
900b57cec5SDimitry Andric     Sub,
910b57cec5SDimitry Andric     BitwiseAnd,
920b57cec5SDimitry Andric     BitwiseOr,
930b57cec5SDimitry Andric     ShiftLeft,
940b57cec5SDimitry Andric     ShiftRight
950b57cec5SDimitry Andric   };
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric   class EvalResult {
980b57cec5SDimitry Andric   public:
990b57cec5SDimitry Andric     EvalResult() : Value(0), ErrorMsg("") {}
1000b57cec5SDimitry Andric     EvalResult(uint64_t Value) : Value(Value), ErrorMsg("") {}
1010b57cec5SDimitry Andric     EvalResult(std::string ErrorMsg)
1020b57cec5SDimitry Andric         : Value(0), ErrorMsg(std::move(ErrorMsg)) {}
1030b57cec5SDimitry Andric     uint64_t getValue() const { return Value; }
1040b57cec5SDimitry Andric     bool hasError() const { return ErrorMsg != ""; }
1050b57cec5SDimitry Andric     const std::string &getErrorMsg() const { return ErrorMsg; }
1060b57cec5SDimitry Andric 
1070b57cec5SDimitry Andric   private:
1080b57cec5SDimitry Andric     uint64_t Value;
1090b57cec5SDimitry Andric     std::string ErrorMsg;
1100b57cec5SDimitry Andric   };
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   StringRef getTokenForError(StringRef Expr) const {
1130b57cec5SDimitry Andric     if (Expr.empty())
1140b57cec5SDimitry Andric       return "";
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric     StringRef Token, Remaining;
1170b57cec5SDimitry Andric     if (isalpha(Expr[0]))
1180b57cec5SDimitry Andric       std::tie(Token, Remaining) = parseSymbol(Expr);
1190b57cec5SDimitry Andric     else if (isdigit(Expr[0]))
1200b57cec5SDimitry Andric       std::tie(Token, Remaining) = parseNumberString(Expr);
1210b57cec5SDimitry Andric     else {
1220b57cec5SDimitry Andric       unsigned TokLen = 1;
1230b57cec5SDimitry Andric       if (Expr.startswith("<<") || Expr.startswith(">>"))
1240b57cec5SDimitry Andric         TokLen = 2;
1250b57cec5SDimitry Andric       Token = Expr.substr(0, TokLen);
1260b57cec5SDimitry Andric     }
1270b57cec5SDimitry Andric     return Token;
1280b57cec5SDimitry Andric   }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric   EvalResult unexpectedToken(StringRef TokenStart, StringRef SubExpr,
1310b57cec5SDimitry Andric                              StringRef ErrText) const {
1320b57cec5SDimitry Andric     std::string ErrorMsg("Encountered unexpected token '");
1330b57cec5SDimitry Andric     ErrorMsg += getTokenForError(TokenStart);
1340b57cec5SDimitry Andric     if (SubExpr != "") {
1350b57cec5SDimitry Andric       ErrorMsg += "' while parsing subexpression '";
1360b57cec5SDimitry Andric       ErrorMsg += SubExpr;
1370b57cec5SDimitry Andric     }
1380b57cec5SDimitry Andric     ErrorMsg += "'";
1390b57cec5SDimitry Andric     if (ErrText != "") {
1400b57cec5SDimitry Andric       ErrorMsg += " ";
1410b57cec5SDimitry Andric       ErrorMsg += ErrText;
1420b57cec5SDimitry Andric     }
1430b57cec5SDimitry Andric     return EvalResult(std::move(ErrorMsg));
1440b57cec5SDimitry Andric   }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   bool handleError(StringRef Expr, const EvalResult &R) const {
1470b57cec5SDimitry Andric     assert(R.hasError() && "Not an error result.");
1480b57cec5SDimitry Andric     Checker.ErrStream << "Error evaluating expression '" << Expr
1490b57cec5SDimitry Andric                       << "': " << R.getErrorMsg() << "\n";
1500b57cec5SDimitry Andric     return false;
1510b57cec5SDimitry Andric   }
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   std::pair<BinOpToken, StringRef> parseBinOpToken(StringRef Expr) const {
1540b57cec5SDimitry Andric     if (Expr.empty())
1550b57cec5SDimitry Andric       return std::make_pair(BinOpToken::Invalid, "");
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric     // Handle the two 2-character tokens.
1580b57cec5SDimitry Andric     if (Expr.startswith("<<"))
1590b57cec5SDimitry Andric       return std::make_pair(BinOpToken::ShiftLeft, Expr.substr(2).ltrim());
1600b57cec5SDimitry Andric     if (Expr.startswith(">>"))
1610b57cec5SDimitry Andric       return std::make_pair(BinOpToken::ShiftRight, Expr.substr(2).ltrim());
1620b57cec5SDimitry Andric 
1630b57cec5SDimitry Andric     // Handle one-character tokens.
1640b57cec5SDimitry Andric     BinOpToken Op;
1650b57cec5SDimitry Andric     switch (Expr[0]) {
1660b57cec5SDimitry Andric     default:
1670b57cec5SDimitry Andric       return std::make_pair(BinOpToken::Invalid, Expr);
1680b57cec5SDimitry Andric     case '+':
1690b57cec5SDimitry Andric       Op = BinOpToken::Add;
1700b57cec5SDimitry Andric       break;
1710b57cec5SDimitry Andric     case '-':
1720b57cec5SDimitry Andric       Op = BinOpToken::Sub;
1730b57cec5SDimitry Andric       break;
1740b57cec5SDimitry Andric     case '&':
1750b57cec5SDimitry Andric       Op = BinOpToken::BitwiseAnd;
1760b57cec5SDimitry Andric       break;
1770b57cec5SDimitry Andric     case '|':
1780b57cec5SDimitry Andric       Op = BinOpToken::BitwiseOr;
1790b57cec5SDimitry Andric       break;
1800b57cec5SDimitry Andric     }
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric     return std::make_pair(Op, Expr.substr(1).ltrim());
1830b57cec5SDimitry Andric   }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   EvalResult computeBinOpResult(BinOpToken Op, const EvalResult &LHSResult,
1860b57cec5SDimitry Andric                                 const EvalResult &RHSResult) const {
1870b57cec5SDimitry Andric     switch (Op) {
1880b57cec5SDimitry Andric     default:
1890b57cec5SDimitry Andric       llvm_unreachable("Tried to evaluate unrecognized operation.");
1900b57cec5SDimitry Andric     case BinOpToken::Add:
1910b57cec5SDimitry Andric       return EvalResult(LHSResult.getValue() + RHSResult.getValue());
1920b57cec5SDimitry Andric     case BinOpToken::Sub:
1930b57cec5SDimitry Andric       return EvalResult(LHSResult.getValue() - RHSResult.getValue());
1940b57cec5SDimitry Andric     case BinOpToken::BitwiseAnd:
1950b57cec5SDimitry Andric       return EvalResult(LHSResult.getValue() & RHSResult.getValue());
1960b57cec5SDimitry Andric     case BinOpToken::BitwiseOr:
1970b57cec5SDimitry Andric       return EvalResult(LHSResult.getValue() | RHSResult.getValue());
1980b57cec5SDimitry Andric     case BinOpToken::ShiftLeft:
1990b57cec5SDimitry Andric       return EvalResult(LHSResult.getValue() << RHSResult.getValue());
2000b57cec5SDimitry Andric     case BinOpToken::ShiftRight:
2010b57cec5SDimitry Andric       return EvalResult(LHSResult.getValue() >> RHSResult.getValue());
2020b57cec5SDimitry Andric     }
2030b57cec5SDimitry Andric   }
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric   // Parse a symbol and return a (string, string) pair representing the symbol
2060b57cec5SDimitry Andric   // name and expression remaining to be parsed.
2070b57cec5SDimitry Andric   std::pair<StringRef, StringRef> parseSymbol(StringRef Expr) const {
2080b57cec5SDimitry Andric     size_t FirstNonSymbol = Expr.find_first_not_of("0123456789"
2090b57cec5SDimitry Andric                                                    "abcdefghijklmnopqrstuvwxyz"
2100b57cec5SDimitry Andric                                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2110b57cec5SDimitry Andric                                                    ":_.$");
2120b57cec5SDimitry Andric     return std::make_pair(Expr.substr(0, FirstNonSymbol),
2130b57cec5SDimitry Andric                           Expr.substr(FirstNonSymbol).ltrim());
2140b57cec5SDimitry Andric   }
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   // Evaluate a call to decode_operand. Decode the instruction operand at the
2170b57cec5SDimitry Andric   // given symbol and get the value of the requested operand.
2180b57cec5SDimitry Andric   // Returns an error if the instruction cannot be decoded, or the requested
2190b57cec5SDimitry Andric   // operand is not an immediate.
2200b57cec5SDimitry Andric   // On success, returns a pair containing the value of the operand, plus
2210b57cec5SDimitry Andric   // the expression remaining to be evaluated.
2220b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalDecodeOperand(StringRef Expr) const {
2230b57cec5SDimitry Andric     if (!Expr.startswith("("))
2240b57cec5SDimitry Andric       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
2250b57cec5SDimitry Andric     StringRef RemainingExpr = Expr.substr(1).ltrim();
2260b57cec5SDimitry Andric     StringRef Symbol;
2270b57cec5SDimitry Andric     std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     if (!Checker.isSymbolValid(Symbol))
2300b57cec5SDimitry Andric       return std::make_pair(
2310b57cec5SDimitry Andric           EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()),
2320b57cec5SDimitry Andric           "");
2330b57cec5SDimitry Andric 
2340b57cec5SDimitry Andric     if (!RemainingExpr.startswith(","))
2350b57cec5SDimitry Andric       return std::make_pair(
2360b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, RemainingExpr, "expected ','"), "");
2370b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric     EvalResult OpIdxExpr;
2400b57cec5SDimitry Andric     std::tie(OpIdxExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
2410b57cec5SDimitry Andric     if (OpIdxExpr.hasError())
2420b57cec5SDimitry Andric       return std::make_pair(OpIdxExpr, "");
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric     if (!RemainingExpr.startswith(")"))
2450b57cec5SDimitry Andric       return std::make_pair(
2460b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), "");
2470b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric     MCInst Inst;
2500b57cec5SDimitry Andric     uint64_t Size;
2510b57cec5SDimitry Andric     if (!decodeInst(Symbol, Inst, Size))
2520b57cec5SDimitry Andric       return std::make_pair(
2530b57cec5SDimitry Andric           EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()),
2540b57cec5SDimitry Andric           "");
2550b57cec5SDimitry Andric 
2560b57cec5SDimitry Andric     unsigned OpIdx = OpIdxExpr.getValue();
2570b57cec5SDimitry Andric     if (OpIdx >= Inst.getNumOperands()) {
2580b57cec5SDimitry Andric       std::string ErrMsg;
2590b57cec5SDimitry Andric       raw_string_ostream ErrMsgStream(ErrMsg);
2600b57cec5SDimitry Andric       ErrMsgStream << "Invalid operand index '" << format("%i", OpIdx)
2610b57cec5SDimitry Andric                    << "' for instruction '" << Symbol
2620b57cec5SDimitry Andric                    << "'. Instruction has only "
2630b57cec5SDimitry Andric                    << format("%i", Inst.getNumOperands())
2640b57cec5SDimitry Andric                    << " operands.\nInstruction is:\n  ";
2650b57cec5SDimitry Andric       Inst.dump_pretty(ErrMsgStream, Checker.InstPrinter);
2660b57cec5SDimitry Andric       return std::make_pair(EvalResult(ErrMsgStream.str()), "");
2670b57cec5SDimitry Andric     }
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric     const MCOperand &Op = Inst.getOperand(OpIdx);
2700b57cec5SDimitry Andric     if (!Op.isImm()) {
2710b57cec5SDimitry Andric       std::string ErrMsg;
2720b57cec5SDimitry Andric       raw_string_ostream ErrMsgStream(ErrMsg);
2730b57cec5SDimitry Andric       ErrMsgStream << "Operand '" << format("%i", OpIdx) << "' of instruction '"
2740b57cec5SDimitry Andric                    << Symbol << "' is not an immediate.\nInstruction is:\n  ";
2750b57cec5SDimitry Andric       Inst.dump_pretty(ErrMsgStream, Checker.InstPrinter);
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric       return std::make_pair(EvalResult(ErrMsgStream.str()), "");
2780b57cec5SDimitry Andric     }
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric     return std::make_pair(EvalResult(Op.getImm()), RemainingExpr);
2810b57cec5SDimitry Andric   }
2820b57cec5SDimitry Andric 
2830b57cec5SDimitry Andric   // Evaluate a call to next_pc.
2840b57cec5SDimitry Andric   // Decode the instruction at the given symbol and return the following program
2850b57cec5SDimitry Andric   // counter.
2860b57cec5SDimitry Andric   // Returns an error if the instruction cannot be decoded.
2870b57cec5SDimitry Andric   // On success, returns a pair containing the next PC, plus of the
2880b57cec5SDimitry Andric   // expression remaining to be evaluated.
2890b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalNextPC(StringRef Expr,
2900b57cec5SDimitry Andric                                               ParseContext PCtx) const {
2910b57cec5SDimitry Andric     if (!Expr.startswith("("))
2920b57cec5SDimitry Andric       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
2930b57cec5SDimitry Andric     StringRef RemainingExpr = Expr.substr(1).ltrim();
2940b57cec5SDimitry Andric     StringRef Symbol;
2950b57cec5SDimitry Andric     std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric     if (!Checker.isSymbolValid(Symbol))
2980b57cec5SDimitry Andric       return std::make_pair(
2990b57cec5SDimitry Andric           EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()),
3000b57cec5SDimitry Andric           "");
3010b57cec5SDimitry Andric 
3020b57cec5SDimitry Andric     if (!RemainingExpr.startswith(")"))
3030b57cec5SDimitry Andric       return std::make_pair(
3040b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), "");
3050b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric     MCInst Inst;
3080b57cec5SDimitry Andric     uint64_t InstSize;
3090b57cec5SDimitry Andric     if (!decodeInst(Symbol, Inst, InstSize))
3100b57cec5SDimitry Andric       return std::make_pair(
3110b57cec5SDimitry Andric           EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()),
3120b57cec5SDimitry Andric           "");
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric     uint64_t SymbolAddr = PCtx.IsInsideLoad
3150b57cec5SDimitry Andric                               ? Checker.getSymbolLocalAddr(Symbol)
3160b57cec5SDimitry Andric                               : Checker.getSymbolRemoteAddr(Symbol);
3170b57cec5SDimitry Andric     uint64_t NextPC = SymbolAddr + InstSize;
3180b57cec5SDimitry Andric 
3190b57cec5SDimitry Andric     return std::make_pair(EvalResult(NextPC), RemainingExpr);
3200b57cec5SDimitry Andric   }
3210b57cec5SDimitry Andric 
3220b57cec5SDimitry Andric   // Evaluate a call to stub_addr/got_addr.
3230b57cec5SDimitry Andric   // Look up and return the address of the stub for the given
3240b57cec5SDimitry Andric   // (<file name>, <section name>, <symbol name>) tuple.
3250b57cec5SDimitry Andric   // On success, returns a pair containing the stub address, plus the expression
3260b57cec5SDimitry Andric   // remaining to be evaluated.
3270b57cec5SDimitry Andric   std::pair<EvalResult, StringRef>
3280b57cec5SDimitry Andric   evalStubOrGOTAddr(StringRef Expr, ParseContext PCtx, bool IsStubAddr) const {
3290b57cec5SDimitry Andric     if (!Expr.startswith("("))
3300b57cec5SDimitry Andric       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
3310b57cec5SDimitry Andric     StringRef RemainingExpr = Expr.substr(1).ltrim();
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric     // Handle file-name specially, as it may contain characters that aren't
3340b57cec5SDimitry Andric     // legal for symbols.
3350b57cec5SDimitry Andric     StringRef StubContainerName;
3360b57cec5SDimitry Andric     size_t ComaIdx = RemainingExpr.find(',');
3370b57cec5SDimitry Andric     StubContainerName = RemainingExpr.substr(0, ComaIdx).rtrim();
3380b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(ComaIdx).ltrim();
3390b57cec5SDimitry Andric 
3400b57cec5SDimitry Andric     if (!RemainingExpr.startswith(","))
3410b57cec5SDimitry Andric       return std::make_pair(
3420b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
3430b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric     StringRef Symbol;
3460b57cec5SDimitry Andric     std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
3470b57cec5SDimitry Andric 
3480b57cec5SDimitry Andric     if (!RemainingExpr.startswith(")"))
3490b57cec5SDimitry Andric       return std::make_pair(
3500b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
3510b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     uint64_t StubAddr;
3540b57cec5SDimitry Andric     std::string ErrorMsg = "";
3550b57cec5SDimitry Andric     std::tie(StubAddr, ErrorMsg) = Checker.getStubOrGOTAddrFor(
3560b57cec5SDimitry Andric         StubContainerName, Symbol, PCtx.IsInsideLoad, IsStubAddr);
3570b57cec5SDimitry Andric 
3580b57cec5SDimitry Andric     if (ErrorMsg != "")
3590b57cec5SDimitry Andric       return std::make_pair(EvalResult(ErrorMsg), "");
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric     return std::make_pair(EvalResult(StubAddr), RemainingExpr);
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalSectionAddr(StringRef Expr,
3650b57cec5SDimitry Andric                                                    ParseContext PCtx) const {
3660b57cec5SDimitry Andric     if (!Expr.startswith("("))
3670b57cec5SDimitry Andric       return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
3680b57cec5SDimitry Andric     StringRef RemainingExpr = Expr.substr(1).ltrim();
3690b57cec5SDimitry Andric 
3700b57cec5SDimitry Andric     // Handle file-name specially, as it may contain characters that aren't
3710b57cec5SDimitry Andric     // legal for symbols.
3720b57cec5SDimitry Andric     StringRef FileName;
3730b57cec5SDimitry Andric     size_t ComaIdx = RemainingExpr.find(',');
3740b57cec5SDimitry Andric     FileName = RemainingExpr.substr(0, ComaIdx).rtrim();
3750b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(ComaIdx).ltrim();
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric     if (!RemainingExpr.startswith(","))
3780b57cec5SDimitry Andric       return std::make_pair(
3790b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
3800b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
3810b57cec5SDimitry Andric 
3820b57cec5SDimitry Andric     StringRef SectionName;
3830b57cec5SDimitry Andric     std::tie(SectionName, RemainingExpr) = parseSymbol(RemainingExpr);
3840b57cec5SDimitry Andric 
3850b57cec5SDimitry Andric     if (!RemainingExpr.startswith(")"))
3860b57cec5SDimitry Andric       return std::make_pair(
3870b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
3880b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
3890b57cec5SDimitry Andric 
3900b57cec5SDimitry Andric     uint64_t StubAddr;
3910b57cec5SDimitry Andric     std::string ErrorMsg = "";
3920b57cec5SDimitry Andric     std::tie(StubAddr, ErrorMsg) = Checker.getSectionAddr(
3930b57cec5SDimitry Andric         FileName, SectionName, PCtx.IsInsideLoad);
3940b57cec5SDimitry Andric 
3950b57cec5SDimitry Andric     if (ErrorMsg != "")
3960b57cec5SDimitry Andric       return std::make_pair(EvalResult(ErrorMsg), "");
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     return std::make_pair(EvalResult(StubAddr), RemainingExpr);
3990b57cec5SDimitry Andric   }
4000b57cec5SDimitry Andric 
4010b57cec5SDimitry Andric   // Evaluate an identiefer expr, which may be a symbol, or a call to
4020b57cec5SDimitry Andric   // one of the builtin functions: get_insn_opcode or get_insn_length.
4030b57cec5SDimitry Andric   // Return the result, plus the expression remaining to be parsed.
4040b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalIdentifierExpr(StringRef Expr,
4050b57cec5SDimitry Andric                                                       ParseContext PCtx) const {
4060b57cec5SDimitry Andric     StringRef Symbol;
4070b57cec5SDimitry Andric     StringRef RemainingExpr;
4080b57cec5SDimitry Andric     std::tie(Symbol, RemainingExpr) = parseSymbol(Expr);
4090b57cec5SDimitry Andric 
4100b57cec5SDimitry Andric     // Check for builtin function calls.
4110b57cec5SDimitry Andric     if (Symbol == "decode_operand")
4120b57cec5SDimitry Andric       return evalDecodeOperand(RemainingExpr);
4130b57cec5SDimitry Andric     else if (Symbol == "next_pc")
4140b57cec5SDimitry Andric       return evalNextPC(RemainingExpr, PCtx);
4150b57cec5SDimitry Andric     else if (Symbol == "stub_addr")
4160b57cec5SDimitry Andric       return evalStubOrGOTAddr(RemainingExpr, PCtx, true);
4170b57cec5SDimitry Andric     else if (Symbol == "got_addr")
4180b57cec5SDimitry Andric       return evalStubOrGOTAddr(RemainingExpr, PCtx, false);
4190b57cec5SDimitry Andric     else if (Symbol == "section_addr")
4200b57cec5SDimitry Andric       return evalSectionAddr(RemainingExpr, PCtx);
4210b57cec5SDimitry Andric 
4220b57cec5SDimitry Andric     if (!Checker.isSymbolValid(Symbol)) {
4230b57cec5SDimitry Andric       std::string ErrMsg("No known address for symbol '");
4240b57cec5SDimitry Andric       ErrMsg += Symbol;
4250b57cec5SDimitry Andric       ErrMsg += "'";
4260b57cec5SDimitry Andric       if (Symbol.startswith("L"))
4270b57cec5SDimitry Andric         ErrMsg += " (this appears to be an assembler local label - "
4280b57cec5SDimitry Andric                   " perhaps drop the 'L'?)";
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric       return std::make_pair(EvalResult(ErrMsg), "");
4310b57cec5SDimitry Andric     }
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric     // The value for the symbol depends on the context we're evaluating in:
4340b57cec5SDimitry Andric     // Inside a load this is the address in the linker's memory, outside a
4350b57cec5SDimitry Andric     // load it's the address in the target processes memory.
4360b57cec5SDimitry Andric     uint64_t Value = PCtx.IsInsideLoad ? Checker.getSymbolLocalAddr(Symbol)
4370b57cec5SDimitry Andric                                        : Checker.getSymbolRemoteAddr(Symbol);
4380b57cec5SDimitry Andric 
4390b57cec5SDimitry Andric     // Looks like a plain symbol reference.
4400b57cec5SDimitry Andric     return std::make_pair(EvalResult(Value), RemainingExpr);
4410b57cec5SDimitry Andric   }
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Parse a number (hexadecimal or decimal) and return a (string, string)
4440b57cec5SDimitry Andric   // pair representing the number and the expression remaining to be parsed.
4450b57cec5SDimitry Andric   std::pair<StringRef, StringRef> parseNumberString(StringRef Expr) const {
4460b57cec5SDimitry Andric     size_t FirstNonDigit = StringRef::npos;
4470b57cec5SDimitry Andric     if (Expr.startswith("0x")) {
4480b57cec5SDimitry Andric       FirstNonDigit = Expr.find_first_not_of("0123456789abcdefABCDEF", 2);
4490b57cec5SDimitry Andric       if (FirstNonDigit == StringRef::npos)
4500b57cec5SDimitry Andric         FirstNonDigit = Expr.size();
4510b57cec5SDimitry Andric     } else {
4520b57cec5SDimitry Andric       FirstNonDigit = Expr.find_first_not_of("0123456789");
4530b57cec5SDimitry Andric       if (FirstNonDigit == StringRef::npos)
4540b57cec5SDimitry Andric         FirstNonDigit = Expr.size();
4550b57cec5SDimitry Andric     }
4560b57cec5SDimitry Andric     return std::make_pair(Expr.substr(0, FirstNonDigit),
4570b57cec5SDimitry Andric                           Expr.substr(FirstNonDigit));
4580b57cec5SDimitry Andric   }
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   // Evaluate a constant numeric expression (hexadecimal or decimal) and
4610b57cec5SDimitry Andric   // return a pair containing the result, and the expression remaining to be
4620b57cec5SDimitry Andric   // evaluated.
4630b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalNumberExpr(StringRef Expr) const {
4640b57cec5SDimitry Andric     StringRef ValueStr;
4650b57cec5SDimitry Andric     StringRef RemainingExpr;
4660b57cec5SDimitry Andric     std::tie(ValueStr, RemainingExpr) = parseNumberString(Expr);
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric     if (ValueStr.empty() || !isdigit(ValueStr[0]))
4690b57cec5SDimitry Andric       return std::make_pair(
4700b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, RemainingExpr, "expected number"), "");
4710b57cec5SDimitry Andric     uint64_t Value;
4720b57cec5SDimitry Andric     ValueStr.getAsInteger(0, Value);
4730b57cec5SDimitry Andric     return std::make_pair(EvalResult(Value), RemainingExpr);
4740b57cec5SDimitry Andric   }
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   // Evaluate an expression of the form "(<expr>)" and return a pair
4770b57cec5SDimitry Andric   // containing the result of evaluating <expr>, plus the expression
4780b57cec5SDimitry Andric   // remaining to be parsed.
4790b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalParensExpr(StringRef Expr,
4800b57cec5SDimitry Andric                                                   ParseContext PCtx) const {
4810b57cec5SDimitry Andric     assert(Expr.startswith("(") && "Not a parenthesized expression");
4820b57cec5SDimitry Andric     EvalResult SubExprResult;
4830b57cec5SDimitry Andric     StringRef RemainingExpr;
4840b57cec5SDimitry Andric     std::tie(SubExprResult, RemainingExpr) =
4850b57cec5SDimitry Andric         evalComplexExpr(evalSimpleExpr(Expr.substr(1).ltrim(), PCtx), PCtx);
4860b57cec5SDimitry Andric     if (SubExprResult.hasError())
4870b57cec5SDimitry Andric       return std::make_pair(SubExprResult, "");
4880b57cec5SDimitry Andric     if (!RemainingExpr.startswith(")"))
4890b57cec5SDimitry Andric       return std::make_pair(
4900b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
4910b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
4920b57cec5SDimitry Andric     return std::make_pair(SubExprResult, RemainingExpr);
4930b57cec5SDimitry Andric   }
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   // Evaluate an expression in one of the following forms:
4960b57cec5SDimitry Andric   //   *{<number>}<expr>
4970b57cec5SDimitry Andric   // Return a pair containing the result, plus the expression remaining to be
4980b57cec5SDimitry Andric   // parsed.
4990b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalLoadExpr(StringRef Expr) const {
5000b57cec5SDimitry Andric     assert(Expr.startswith("*") && "Not a load expression");
5010b57cec5SDimitry Andric     StringRef RemainingExpr = Expr.substr(1).ltrim();
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric     // Parse read size.
5040b57cec5SDimitry Andric     if (!RemainingExpr.startswith("{"))
5050b57cec5SDimitry Andric       return std::make_pair(EvalResult("Expected '{' following '*'."), "");
5060b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
5070b57cec5SDimitry Andric     EvalResult ReadSizeExpr;
5080b57cec5SDimitry Andric     std::tie(ReadSizeExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
5090b57cec5SDimitry Andric     if (ReadSizeExpr.hasError())
5100b57cec5SDimitry Andric       return std::make_pair(ReadSizeExpr, RemainingExpr);
5110b57cec5SDimitry Andric     uint64_t ReadSize = ReadSizeExpr.getValue();
5120b57cec5SDimitry Andric     if (ReadSize < 1 || ReadSize > 8)
5130b57cec5SDimitry Andric       return std::make_pair(EvalResult("Invalid size for dereference."), "");
5140b57cec5SDimitry Andric     if (!RemainingExpr.startswith("}"))
5150b57cec5SDimitry Andric       return std::make_pair(EvalResult("Missing '}' for dereference."), "");
5160b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric     // Evaluate the expression representing the load address.
5190b57cec5SDimitry Andric     ParseContext LoadCtx(true);
5200b57cec5SDimitry Andric     EvalResult LoadAddrExprResult;
5210b57cec5SDimitry Andric     std::tie(LoadAddrExprResult, RemainingExpr) =
5220b57cec5SDimitry Andric         evalComplexExpr(evalSimpleExpr(RemainingExpr, LoadCtx), LoadCtx);
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric     if (LoadAddrExprResult.hasError())
5250b57cec5SDimitry Andric       return std::make_pair(LoadAddrExprResult, "");
5260b57cec5SDimitry Andric 
5270b57cec5SDimitry Andric     uint64_t LoadAddr = LoadAddrExprResult.getValue();
5280b57cec5SDimitry Andric 
5290b57cec5SDimitry Andric     // If there is no error but the content pointer is null then this is a
5300b57cec5SDimitry Andric     // zero-fill symbol/section.
5310b57cec5SDimitry Andric     if (LoadAddr == 0)
5320b57cec5SDimitry Andric       return std::make_pair(0, RemainingExpr);
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric     return std::make_pair(
5350b57cec5SDimitry Andric         EvalResult(Checker.readMemoryAtAddr(LoadAddr, ReadSize)),
5360b57cec5SDimitry Andric         RemainingExpr);
5370b57cec5SDimitry Andric   }
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   // Evaluate a "simple" expression. This is any expression that _isn't_ an
5400b57cec5SDimitry Andric   // un-parenthesized binary expression.
5410b57cec5SDimitry Andric   //
5420b57cec5SDimitry Andric   // "Simple" expressions can be optionally bit-sliced. See evalSlicedExpr.
5430b57cec5SDimitry Andric   //
5440b57cec5SDimitry Andric   // Returns a pair containing the result of the evaluation, plus the
5450b57cec5SDimitry Andric   // expression remaining to be parsed.
5460b57cec5SDimitry Andric   std::pair<EvalResult, StringRef> evalSimpleExpr(StringRef Expr,
5470b57cec5SDimitry Andric                                                   ParseContext PCtx) const {
5480b57cec5SDimitry Andric     EvalResult SubExprResult;
5490b57cec5SDimitry Andric     StringRef RemainingExpr;
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric     if (Expr.empty())
5520b57cec5SDimitry Andric       return std::make_pair(EvalResult("Unexpected end of expression"), "");
5530b57cec5SDimitry Andric 
5540b57cec5SDimitry Andric     if (Expr[0] == '(')
5550b57cec5SDimitry Andric       std::tie(SubExprResult, RemainingExpr) = evalParensExpr(Expr, PCtx);
5560b57cec5SDimitry Andric     else if (Expr[0] == '*')
5570b57cec5SDimitry Andric       std::tie(SubExprResult, RemainingExpr) = evalLoadExpr(Expr);
5580b57cec5SDimitry Andric     else if (isalpha(Expr[0]) || Expr[0] == '_')
5590b57cec5SDimitry Andric       std::tie(SubExprResult, RemainingExpr) = evalIdentifierExpr(Expr, PCtx);
5600b57cec5SDimitry Andric     else if (isdigit(Expr[0]))
5610b57cec5SDimitry Andric       std::tie(SubExprResult, RemainingExpr) = evalNumberExpr(Expr);
5620b57cec5SDimitry Andric     else
5630b57cec5SDimitry Andric       return std::make_pair(
5640b57cec5SDimitry Andric           unexpectedToken(Expr, Expr,
5650b57cec5SDimitry Andric                           "expected '(', '*', identifier, or number"), "");
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric     if (SubExprResult.hasError())
5680b57cec5SDimitry Andric       return std::make_pair(SubExprResult, RemainingExpr);
5690b57cec5SDimitry Andric 
5700b57cec5SDimitry Andric     // Evaluate bit-slice if present.
5710b57cec5SDimitry Andric     if (RemainingExpr.startswith("["))
5720b57cec5SDimitry Andric       std::tie(SubExprResult, RemainingExpr) =
5730b57cec5SDimitry Andric           evalSliceExpr(std::make_pair(SubExprResult, RemainingExpr));
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric     return std::make_pair(SubExprResult, RemainingExpr);
5760b57cec5SDimitry Andric   }
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   // Evaluate a bit-slice of an expression.
5790b57cec5SDimitry Andric   // A bit-slice has the form "<expr>[high:low]". The result of evaluating a
5800b57cec5SDimitry Andric   // slice is the bits between high and low (inclusive) in the original
5810b57cec5SDimitry Andric   // expression, right shifted so that the "low" bit is in position 0 in the
5820b57cec5SDimitry Andric   // result.
5830b57cec5SDimitry Andric   // Returns a pair containing the result of the slice operation, plus the
5840b57cec5SDimitry Andric   // expression remaining to be parsed.
5850b57cec5SDimitry Andric   std::pair<EvalResult, StringRef>
5860b57cec5SDimitry Andric   evalSliceExpr(const std::pair<EvalResult, StringRef> &Ctx) const {
5870b57cec5SDimitry Andric     EvalResult SubExprResult;
5880b57cec5SDimitry Andric     StringRef RemainingExpr;
5890b57cec5SDimitry Andric     std::tie(SubExprResult, RemainingExpr) = Ctx;
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric     assert(RemainingExpr.startswith("[") && "Not a slice expr.");
5920b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric     EvalResult HighBitExpr;
5950b57cec5SDimitry Andric     std::tie(HighBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
5960b57cec5SDimitry Andric 
5970b57cec5SDimitry Andric     if (HighBitExpr.hasError())
5980b57cec5SDimitry Andric       return std::make_pair(HighBitExpr, RemainingExpr);
5990b57cec5SDimitry Andric 
6000b57cec5SDimitry Andric     if (!RemainingExpr.startswith(":"))
6010b57cec5SDimitry Andric       return std::make_pair(
6020b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, RemainingExpr, "expected ':'"), "");
6030b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
6040b57cec5SDimitry Andric 
6050b57cec5SDimitry Andric     EvalResult LowBitExpr;
6060b57cec5SDimitry Andric     std::tie(LowBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric     if (LowBitExpr.hasError())
6090b57cec5SDimitry Andric       return std::make_pair(LowBitExpr, RemainingExpr);
6100b57cec5SDimitry Andric 
6110b57cec5SDimitry Andric     if (!RemainingExpr.startswith("]"))
6120b57cec5SDimitry Andric       return std::make_pair(
6130b57cec5SDimitry Andric           unexpectedToken(RemainingExpr, RemainingExpr, "expected ']'"), "");
6140b57cec5SDimitry Andric     RemainingExpr = RemainingExpr.substr(1).ltrim();
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric     unsigned HighBit = HighBitExpr.getValue();
6170b57cec5SDimitry Andric     unsigned LowBit = LowBitExpr.getValue();
6180b57cec5SDimitry Andric     uint64_t Mask = ((uint64_t)1 << (HighBit - LowBit + 1)) - 1;
6190b57cec5SDimitry Andric     uint64_t SlicedValue = (SubExprResult.getValue() >> LowBit) & Mask;
6200b57cec5SDimitry Andric     return std::make_pair(EvalResult(SlicedValue), RemainingExpr);
6210b57cec5SDimitry Andric   }
6220b57cec5SDimitry Andric 
6230b57cec5SDimitry Andric   // Evaluate a "complex" expression.
6240b57cec5SDimitry Andric   // Takes an already evaluated subexpression and checks for the presence of a
6250b57cec5SDimitry Andric   // binary operator, computing the result of the binary operation if one is
6260b57cec5SDimitry Andric   // found. Used to make arithmetic expressions left-associative.
6270b57cec5SDimitry Andric   // Returns a pair containing the ultimate result of evaluating the
6280b57cec5SDimitry Andric   // expression, plus the expression remaining to be evaluated.
6290b57cec5SDimitry Andric   std::pair<EvalResult, StringRef>
6300b57cec5SDimitry Andric   evalComplexExpr(const std::pair<EvalResult, StringRef> &LHSAndRemaining,
6310b57cec5SDimitry Andric                   ParseContext PCtx) const {
6320b57cec5SDimitry Andric     EvalResult LHSResult;
6330b57cec5SDimitry Andric     StringRef RemainingExpr;
6340b57cec5SDimitry Andric     std::tie(LHSResult, RemainingExpr) = LHSAndRemaining;
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric     // If there was an error, or there's nothing left to evaluate, return the
6370b57cec5SDimitry Andric     // result.
6380b57cec5SDimitry Andric     if (LHSResult.hasError() || RemainingExpr == "")
6390b57cec5SDimitry Andric       return std::make_pair(LHSResult, RemainingExpr);
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric     // Otherwise check if this is a binary expressioan.
6420b57cec5SDimitry Andric     BinOpToken BinOp;
6430b57cec5SDimitry Andric     std::tie(BinOp, RemainingExpr) = parseBinOpToken(RemainingExpr);
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric     // If this isn't a recognized expression just return.
6460b57cec5SDimitry Andric     if (BinOp == BinOpToken::Invalid)
6470b57cec5SDimitry Andric       return std::make_pair(LHSResult, RemainingExpr);
6480b57cec5SDimitry Andric 
6490b57cec5SDimitry Andric     // This is a recognized bin-op. Evaluate the RHS, then evaluate the binop.
6500b57cec5SDimitry Andric     EvalResult RHSResult;
6510b57cec5SDimitry Andric     std::tie(RHSResult, RemainingExpr) = evalSimpleExpr(RemainingExpr, PCtx);
6520b57cec5SDimitry Andric 
6530b57cec5SDimitry Andric     // If there was an error evaluating the RHS, return it.
6540b57cec5SDimitry Andric     if (RHSResult.hasError())
6550b57cec5SDimitry Andric       return std::make_pair(RHSResult, RemainingExpr);
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric     // This is a binary expression - evaluate and try to continue as a
6580b57cec5SDimitry Andric     // complex expr.
6590b57cec5SDimitry Andric     EvalResult ThisResult(computeBinOpResult(BinOp, LHSResult, RHSResult));
6600b57cec5SDimitry Andric 
6610b57cec5SDimitry Andric     return evalComplexExpr(std::make_pair(ThisResult, RemainingExpr), PCtx);
6620b57cec5SDimitry Andric   }
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric   bool decodeInst(StringRef Symbol, MCInst &Inst, uint64_t &Size) const {
6650b57cec5SDimitry Andric     MCDisassembler *Dis = Checker.Disassembler;
6660b57cec5SDimitry Andric     StringRef SymbolMem = Checker.getSymbolContent(Symbol);
6670b57cec5SDimitry Andric     ArrayRef<uint8_t> SymbolBytes(SymbolMem.bytes_begin(), SymbolMem.size());
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric     MCDisassembler::DecodeStatus S =
670*480093f4SDimitry Andric         Dis->getInstruction(Inst, Size, SymbolBytes, 0, nulls());
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric     return (S == MCDisassembler::Success);
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric };
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric RuntimeDyldCheckerImpl::RuntimeDyldCheckerImpl(
6780b57cec5SDimitry Andric     IsSymbolValidFunction IsSymbolValid, GetSymbolInfoFunction GetSymbolInfo,
6790b57cec5SDimitry Andric     GetSectionInfoFunction GetSectionInfo, GetStubInfoFunction GetStubInfo,
6800b57cec5SDimitry Andric     GetGOTInfoFunction GetGOTInfo, support::endianness Endianness,
6810b57cec5SDimitry Andric     MCDisassembler *Disassembler, MCInstPrinter *InstPrinter,
6820b57cec5SDimitry Andric     raw_ostream &ErrStream)
6830b57cec5SDimitry Andric     : IsSymbolValid(std::move(IsSymbolValid)),
6840b57cec5SDimitry Andric       GetSymbolInfo(std::move(GetSymbolInfo)),
6850b57cec5SDimitry Andric       GetSectionInfo(std::move(GetSectionInfo)),
6860b57cec5SDimitry Andric       GetStubInfo(std::move(GetStubInfo)), GetGOTInfo(std::move(GetGOTInfo)),
6870b57cec5SDimitry Andric       Endianness(Endianness), Disassembler(Disassembler),
6880b57cec5SDimitry Andric       InstPrinter(InstPrinter), ErrStream(ErrStream) {}
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric bool RuntimeDyldCheckerImpl::check(StringRef CheckExpr) const {
6910b57cec5SDimitry Andric   CheckExpr = CheckExpr.trim();
6920b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "RuntimeDyldChecker: Checking '" << CheckExpr
6930b57cec5SDimitry Andric                     << "'...\n");
6940b57cec5SDimitry Andric   RuntimeDyldCheckerExprEval P(*this, ErrStream);
6950b57cec5SDimitry Andric   bool Result = P.evaluate(CheckExpr);
6960b57cec5SDimitry Andric   (void)Result;
6970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "RuntimeDyldChecker: '" << CheckExpr << "' "
6980b57cec5SDimitry Andric                     << (Result ? "passed" : "FAILED") << ".\n");
6990b57cec5SDimitry Andric   return Result;
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric bool RuntimeDyldCheckerImpl::checkAllRulesInBuffer(StringRef RulePrefix,
7030b57cec5SDimitry Andric                                                    MemoryBuffer *MemBuf) const {
7040b57cec5SDimitry Andric   bool DidAllTestsPass = true;
7050b57cec5SDimitry Andric   unsigned NumRules = 0;
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   const char *LineStart = MemBuf->getBufferStart();
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   // Eat whitespace.
7100b57cec5SDimitry Andric   while (LineStart != MemBuf->getBufferEnd() && std::isspace(*LineStart))
7110b57cec5SDimitry Andric     ++LineStart;
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric   while (LineStart != MemBuf->getBufferEnd() && *LineStart != '\0') {
7140b57cec5SDimitry Andric     const char *LineEnd = LineStart;
7150b57cec5SDimitry Andric     while (LineEnd != MemBuf->getBufferEnd() && *LineEnd != '\r' &&
7160b57cec5SDimitry Andric            *LineEnd != '\n')
7170b57cec5SDimitry Andric       ++LineEnd;
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric     StringRef Line(LineStart, LineEnd - LineStart);
7200b57cec5SDimitry Andric     if (Line.startswith(RulePrefix)) {
7210b57cec5SDimitry Andric       DidAllTestsPass &= check(Line.substr(RulePrefix.size()));
7220b57cec5SDimitry Andric       ++NumRules;
7230b57cec5SDimitry Andric     }
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric     // Eat whitespace.
7260b57cec5SDimitry Andric     LineStart = LineEnd;
7270b57cec5SDimitry Andric     while (LineStart != MemBuf->getBufferEnd() && std::isspace(*LineStart))
7280b57cec5SDimitry Andric       ++LineStart;
7290b57cec5SDimitry Andric   }
7300b57cec5SDimitry Andric   return DidAllTestsPass && (NumRules != 0);
7310b57cec5SDimitry Andric }
7320b57cec5SDimitry Andric 
7330b57cec5SDimitry Andric bool RuntimeDyldCheckerImpl::isSymbolValid(StringRef Symbol) const {
7340b57cec5SDimitry Andric   return IsSymbolValid(Symbol);
7350b57cec5SDimitry Andric }
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric uint64_t RuntimeDyldCheckerImpl::getSymbolLocalAddr(StringRef Symbol) const {
7380b57cec5SDimitry Andric   auto SymInfo = GetSymbolInfo(Symbol);
7390b57cec5SDimitry Andric   if (!SymInfo) {
7400b57cec5SDimitry Andric     logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
7410b57cec5SDimitry Andric     return 0;
7420b57cec5SDimitry Andric   }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   if (SymInfo->isZeroFill())
7450b57cec5SDimitry Andric     return 0;
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric   return static_cast<uint64_t>(
7480b57cec5SDimitry Andric       reinterpret_cast<uintptr_t>(SymInfo->getContent().data()));
7490b57cec5SDimitry Andric }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric uint64_t RuntimeDyldCheckerImpl::getSymbolRemoteAddr(StringRef Symbol) const {
7520b57cec5SDimitry Andric   auto SymInfo = GetSymbolInfo(Symbol);
7530b57cec5SDimitry Andric   if (!SymInfo) {
7540b57cec5SDimitry Andric     logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
7550b57cec5SDimitry Andric     return 0;
7560b57cec5SDimitry Andric   }
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   return SymInfo->getTargetAddress();
7590b57cec5SDimitry Andric }
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric uint64_t RuntimeDyldCheckerImpl::readMemoryAtAddr(uint64_t SrcAddr,
7620b57cec5SDimitry Andric                                                   unsigned Size) const {
7630b57cec5SDimitry Andric   uintptr_t PtrSizedAddr = static_cast<uintptr_t>(SrcAddr);
7640b57cec5SDimitry Andric   assert(PtrSizedAddr == SrcAddr && "Linker memory pointer out-of-range.");
7650b57cec5SDimitry Andric   void *Ptr = reinterpret_cast<void*>(PtrSizedAddr);
7660b57cec5SDimitry Andric 
7670b57cec5SDimitry Andric   switch (Size) {
7680b57cec5SDimitry Andric   case 1:
7690b57cec5SDimitry Andric     return support::endian::read<uint8_t>(Ptr, Endianness);
7700b57cec5SDimitry Andric   case 2:
7710b57cec5SDimitry Andric     return support::endian::read<uint16_t>(Ptr, Endianness);
7720b57cec5SDimitry Andric   case 4:
7730b57cec5SDimitry Andric     return support::endian::read<uint32_t>(Ptr, Endianness);
7740b57cec5SDimitry Andric   case 8:
7750b57cec5SDimitry Andric     return support::endian::read<uint64_t>(Ptr, Endianness);
7760b57cec5SDimitry Andric   }
7770b57cec5SDimitry Andric   llvm_unreachable("Unsupported read size");
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric StringRef RuntimeDyldCheckerImpl::getSymbolContent(StringRef Symbol) const {
7810b57cec5SDimitry Andric   auto SymInfo = GetSymbolInfo(Symbol);
7820b57cec5SDimitry Andric   if (!SymInfo) {
7830b57cec5SDimitry Andric     logAllUnhandledErrors(SymInfo.takeError(), errs(), "RTDyldChecker: ");
7840b57cec5SDimitry Andric     return StringRef();
7850b57cec5SDimitry Andric   }
7860b57cec5SDimitry Andric   return SymInfo->getContent();
7870b57cec5SDimitry Andric }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric std::pair<uint64_t, std::string> RuntimeDyldCheckerImpl::getSectionAddr(
7900b57cec5SDimitry Andric     StringRef FileName, StringRef SectionName, bool IsInsideLoad) const {
7910b57cec5SDimitry Andric 
7920b57cec5SDimitry Andric   auto SecInfo = GetSectionInfo(FileName, SectionName);
7930b57cec5SDimitry Andric   if (!SecInfo) {
7940b57cec5SDimitry Andric     std::string ErrMsg;
7950b57cec5SDimitry Andric     {
7960b57cec5SDimitry Andric       raw_string_ostream ErrMsgStream(ErrMsg);
7970b57cec5SDimitry Andric       logAllUnhandledErrors(SecInfo.takeError(), ErrMsgStream,
7980b57cec5SDimitry Andric                             "RTDyldChecker: ");
7990b57cec5SDimitry Andric     }
8000b57cec5SDimitry Andric     return std::make_pair(0, std::move(ErrMsg));
8010b57cec5SDimitry Andric   }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric   // If this address is being looked up in "load" mode, return the content
8040b57cec5SDimitry Andric   // pointer, otherwise return the target address.
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric   uint64_t Addr = 0;
8070b57cec5SDimitry Andric 
8080b57cec5SDimitry Andric   if (IsInsideLoad) {
8090b57cec5SDimitry Andric     if (SecInfo->isZeroFill())
8100b57cec5SDimitry Andric       Addr = 0;
8110b57cec5SDimitry Andric     else
8120b57cec5SDimitry Andric       Addr = pointerToJITTargetAddress(SecInfo->getContent().data());
8130b57cec5SDimitry Andric   } else
8140b57cec5SDimitry Andric     Addr = SecInfo->getTargetAddress();
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric   return std::make_pair(Addr, "");
8170b57cec5SDimitry Andric }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric std::pair<uint64_t, std::string> RuntimeDyldCheckerImpl::getStubOrGOTAddrFor(
8200b57cec5SDimitry Andric     StringRef StubContainerName, StringRef SymbolName, bool IsInsideLoad,
8210b57cec5SDimitry Andric     bool IsStubAddr) const {
8220b57cec5SDimitry Andric 
8230b57cec5SDimitry Andric   auto StubInfo = IsStubAddr ? GetStubInfo(StubContainerName, SymbolName)
8240b57cec5SDimitry Andric                              : GetGOTInfo(StubContainerName, SymbolName);
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric   if (!StubInfo) {
8270b57cec5SDimitry Andric     std::string ErrMsg;
8280b57cec5SDimitry Andric     {
8290b57cec5SDimitry Andric       raw_string_ostream ErrMsgStream(ErrMsg);
8300b57cec5SDimitry Andric       logAllUnhandledErrors(StubInfo.takeError(), ErrMsgStream,
8310b57cec5SDimitry Andric                             "RTDyldChecker: ");
8320b57cec5SDimitry Andric     }
8330b57cec5SDimitry Andric     return std::make_pair((uint64_t)0, std::move(ErrMsg));
8340b57cec5SDimitry Andric   }
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric   uint64_t Addr = 0;
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   if (IsInsideLoad) {
8390b57cec5SDimitry Andric     if (StubInfo->isZeroFill())
8400b57cec5SDimitry Andric       return std::make_pair((uint64_t)0, "Detected zero-filled stub/GOT entry");
8410b57cec5SDimitry Andric     Addr = pointerToJITTargetAddress(StubInfo->getContent().data());
8420b57cec5SDimitry Andric   } else
8430b57cec5SDimitry Andric     Addr = StubInfo->getTargetAddress();
8440b57cec5SDimitry Andric 
8450b57cec5SDimitry Andric   return std::make_pair(Addr, "");
8460b57cec5SDimitry Andric }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric RuntimeDyldChecker::RuntimeDyldChecker(
8490b57cec5SDimitry Andric     IsSymbolValidFunction IsSymbolValid, GetSymbolInfoFunction GetSymbolInfo,
8500b57cec5SDimitry Andric     GetSectionInfoFunction GetSectionInfo, GetStubInfoFunction GetStubInfo,
8510b57cec5SDimitry Andric     GetGOTInfoFunction GetGOTInfo, support::endianness Endianness,
8520b57cec5SDimitry Andric     MCDisassembler *Disassembler, MCInstPrinter *InstPrinter,
8530b57cec5SDimitry Andric     raw_ostream &ErrStream)
8548bcb0991SDimitry Andric     : Impl(::std::make_unique<RuntimeDyldCheckerImpl>(
8550b57cec5SDimitry Andric           std::move(IsSymbolValid), std::move(GetSymbolInfo),
8560b57cec5SDimitry Andric           std::move(GetSectionInfo), std::move(GetStubInfo),
8570b57cec5SDimitry Andric           std::move(GetGOTInfo), Endianness, Disassembler, InstPrinter,
8580b57cec5SDimitry Andric           ErrStream)) {}
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric RuntimeDyldChecker::~RuntimeDyldChecker() {}
8610b57cec5SDimitry Andric 
8620b57cec5SDimitry Andric bool RuntimeDyldChecker::check(StringRef CheckExpr) const {
8630b57cec5SDimitry Andric   return Impl->check(CheckExpr);
8640b57cec5SDimitry Andric }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric bool RuntimeDyldChecker::checkAllRulesInBuffer(StringRef RulePrefix,
8670b57cec5SDimitry Andric                                                MemoryBuffer *MemBuf) const {
8680b57cec5SDimitry Andric   return Impl->checkAllRulesInBuffer(RulePrefix, MemBuf);
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
8710b57cec5SDimitry Andric std::pair<uint64_t, std::string>
8720b57cec5SDimitry Andric RuntimeDyldChecker::getSectionAddr(StringRef FileName, StringRef SectionName,
8730b57cec5SDimitry Andric                                    bool LocalAddress) {
8740b57cec5SDimitry Andric   return Impl->getSectionAddr(FileName, SectionName, LocalAddress);
8750b57cec5SDimitry Andric }
876