RuntimeDyldChecker.cpp 34 KB

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