RuntimeDyldChecker.cpp 33 KB

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