1 //===--- RuntimeDyldChecker.cpp - RuntimeDyld tester framework --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
11 #include "RuntimeDyldCheckerImpl.h"
12 #include "RuntimeDyldImpl.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
16 #include "llvm/MC/MCInst.h"
17 #include "llvm/Support/Path.h"
22 #define DEBUG_TYPE "rtdyld"
28 // Helper class that implements the language evaluated by RuntimeDyldChecker.
29 class RuntimeDyldCheckerExprEval {
31 RuntimeDyldCheckerExprEval(const RuntimeDyldCheckerImpl &Checker,
32 raw_ostream &ErrStream)
35 bool evaluate(StringRef Expr) const {
36 // Expect equality expression of the form 'LHS = RHS'.
38 size_t EQIdx = Expr.find('=');
40 ParseContext OutsideLoad(false);
43 StringRef LHSExpr = Expr.substr(0, EQIdx).rtrim();
44 StringRef RemainingExpr;
46 std::tie(LHSResult, RemainingExpr) =
47 evalComplexExpr(evalSimpleExpr(LHSExpr, OutsideLoad), OutsideLoad);
48 if (LHSResult.hasError())
49 return handleError(Expr, LHSResult);
50 if (RemainingExpr != "")
51 return handleError(Expr, unexpectedToken(RemainingExpr, LHSExpr, ""));
54 StringRef RHSExpr = Expr.substr(EQIdx + 1).ltrim();
56 std::tie(RHSResult, RemainingExpr) =
57 evalComplexExpr(evalSimpleExpr(RHSExpr, OutsideLoad), OutsideLoad);
58 if (RHSResult.hasError())
59 return handleError(Expr, RHSResult);
60 if (RemainingExpr != "")
61 return handleError(Expr, unexpectedToken(RemainingExpr, RHSExpr, ""));
63 if (LHSResult.getValue() != RHSResult.getValue()) {
64 Checker.ErrStream << "Expression '" << Expr << "' is false: "
65 << format("0x%" PRIx64, LHSResult.getValue())
66 << " != " << format("0x%" PRIx64, RHSResult.getValue())
74 // RuntimeDyldCheckerExprEval requires some context when parsing exprs. In
75 // particular, it needs to know whether a symbol is being evaluated in the
76 // context of a load, in which case we want the linker's local address for
77 // the symbol, or outside of a load, in which case we want the symbol's
78 // address in the remote target.
82 ParseContext(bool IsInsideLoad) : IsInsideLoad(IsInsideLoad) {}
85 const RuntimeDyldCheckerImpl &Checker;
87 enum class BinOpToken : unsigned {
99 EvalResult() : Value(0), ErrorMsg("") {}
100 EvalResult(uint64_t Value) : Value(Value), ErrorMsg("") {}
101 EvalResult(std::string ErrorMsg)
102 : Value(0), ErrorMsg(std::move(ErrorMsg)) {}
103 uint64_t getValue() const { return Value; }
104 bool hasError() const { return ErrorMsg != ""; }
105 const std::string &getErrorMsg() const { return ErrorMsg; }
109 std::string ErrorMsg;
112 StringRef getTokenForError(StringRef Expr) const {
116 StringRef Token, Remaining;
117 if (isalpha(Expr[0]))
118 std::tie(Token, Remaining) = parseSymbol(Expr);
119 else if (isdigit(Expr[0]))
120 std::tie(Token, Remaining) = parseNumberString(Expr);
123 if (Expr.startswith("<<") || Expr.startswith(">>"))
125 Token = Expr.substr(0, TokLen);
130 EvalResult unexpectedToken(StringRef TokenStart, StringRef SubExpr,
131 StringRef ErrText) const {
132 std::string ErrorMsg("Encountered unexpected token '");
133 ErrorMsg += getTokenForError(TokenStart);
135 ErrorMsg += "' while parsing subexpression '";
143 return EvalResult(std::move(ErrorMsg));
146 bool handleError(StringRef Expr, const EvalResult &R) const {
147 assert(R.hasError() && "Not an error result.");
148 Checker.ErrStream << "Error evaluating expression '" << Expr
149 << "': " << R.getErrorMsg() << "\n";
153 std::pair<BinOpToken, StringRef> parseBinOpToken(StringRef Expr) const {
155 return std::make_pair(BinOpToken::Invalid, "");
157 // Handle the two 2-character tokens.
158 if (Expr.startswith("<<"))
159 return std::make_pair(BinOpToken::ShiftLeft, Expr.substr(2).ltrim());
160 if (Expr.startswith(">>"))
161 return std::make_pair(BinOpToken::ShiftRight, Expr.substr(2).ltrim());
163 // Handle one-character tokens.
167 return std::make_pair(BinOpToken::Invalid, Expr);
169 Op = BinOpToken::Add;
172 Op = BinOpToken::Sub;
175 Op = BinOpToken::BitwiseAnd;
178 Op = BinOpToken::BitwiseOr;
182 return std::make_pair(Op, Expr.substr(1).ltrim());
185 EvalResult computeBinOpResult(BinOpToken Op, const EvalResult &LHSResult,
186 const EvalResult &RHSResult) const {
189 llvm_unreachable("Tried to evaluate unrecognized operation.");
190 case BinOpToken::Add:
191 return EvalResult(LHSResult.getValue() + RHSResult.getValue());
192 case BinOpToken::Sub:
193 return EvalResult(LHSResult.getValue() - RHSResult.getValue());
194 case BinOpToken::BitwiseAnd:
195 return EvalResult(LHSResult.getValue() & RHSResult.getValue());
196 case BinOpToken::BitwiseOr:
197 return EvalResult(LHSResult.getValue() | RHSResult.getValue());
198 case BinOpToken::ShiftLeft:
199 return EvalResult(LHSResult.getValue() << RHSResult.getValue());
200 case BinOpToken::ShiftRight:
201 return EvalResult(LHSResult.getValue() >> RHSResult.getValue());
205 // Parse a symbol and return a (string, string) pair representing the symbol
206 // name and expression remaining to be parsed.
207 std::pair<StringRef, StringRef> parseSymbol(StringRef Expr) const {
208 size_t FirstNonSymbol = Expr.find_first_not_of("0123456789"
209 "abcdefghijklmnopqrstuvwxyz"
210 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
212 return std::make_pair(Expr.substr(0, FirstNonSymbol),
213 Expr.substr(FirstNonSymbol).ltrim());
216 // Evaluate a call to decode_operand. Decode the instruction operand at the
217 // given symbol and get the value of the requested operand.
218 // Returns an error if the instruction cannot be decoded, or the requested
219 // operand is not an immediate.
220 // On success, returns a pair containing the value of the operand, plus
221 // the expression remaining to be evaluated.
222 std::pair<EvalResult, StringRef> evalDecodeOperand(StringRef Expr) const {
223 if (!Expr.startswith("("))
224 return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
225 StringRef RemainingExpr = Expr.substr(1).ltrim();
227 std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
229 if (!Checker.isSymbolValid(Symbol))
230 return std::make_pair(
231 EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()),
234 if (!RemainingExpr.startswith(","))
235 return std::make_pair(
236 unexpectedToken(RemainingExpr, RemainingExpr, "expected ','"), "");
237 RemainingExpr = RemainingExpr.substr(1).ltrim();
239 EvalResult OpIdxExpr;
240 std::tie(OpIdxExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
241 if (OpIdxExpr.hasError())
242 return std::make_pair(OpIdxExpr, "");
244 if (!RemainingExpr.startswith(")"))
245 return std::make_pair(
246 unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), "");
247 RemainingExpr = RemainingExpr.substr(1).ltrim();
251 if (!decodeInst(Symbol, Inst, Size))
252 return std::make_pair(
253 EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()),
256 unsigned OpIdx = OpIdxExpr.getValue();
257 if (OpIdx >= Inst.getNumOperands()) {
259 raw_string_ostream ErrMsgStream(ErrMsg);
260 ErrMsgStream << "Invalid operand index '" << format("%i", OpIdx)
261 << "' for instruction '" << Symbol
262 << "'. Instruction has only "
263 << format("%i", Inst.getNumOperands())
264 << " operands.\nInstruction is:\n ";
265 Inst.dump_pretty(ErrMsgStream, Checker.InstPrinter);
266 return std::make_pair(EvalResult(ErrMsgStream.str()), "");
269 const MCOperand &Op = Inst.getOperand(OpIdx);
272 raw_string_ostream ErrMsgStream(ErrMsg);
273 ErrMsgStream << "Operand '" << format("%i", OpIdx) << "' of instruction '"
274 << Symbol << "' is not an immediate.\nInstruction is:\n ";
275 Inst.dump_pretty(ErrMsgStream, Checker.InstPrinter);
277 return std::make_pair(EvalResult(ErrMsgStream.str()), "");
280 return std::make_pair(EvalResult(Op.getImm()), RemainingExpr);
283 // Evaluate a call to next_pc.
284 // Decode the instruction at the given symbol and return the following program
286 // Returns an error if the instruction cannot be decoded.
287 // On success, returns a pair containing the next PC, plus of the
288 // expression remaining to be evaluated.
289 std::pair<EvalResult, StringRef> evalNextPC(StringRef Expr,
290 ParseContext PCtx) const {
291 if (!Expr.startswith("("))
292 return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
293 StringRef RemainingExpr = Expr.substr(1).ltrim();
295 std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
297 if (!Checker.isSymbolValid(Symbol))
298 return std::make_pair(
299 EvalResult(("Cannot decode unknown symbol '" + Symbol + "'").str()),
302 if (!RemainingExpr.startswith(")"))
303 return std::make_pair(
304 unexpectedToken(RemainingExpr, RemainingExpr, "expected ')'"), "");
305 RemainingExpr = RemainingExpr.substr(1).ltrim();
309 if (!decodeInst(Symbol, Inst, InstSize))
310 return std::make_pair(
311 EvalResult(("Couldn't decode instruction at '" + Symbol + "'").str()),
314 uint64_t SymbolAddr = PCtx.IsInsideLoad
315 ? Checker.getSymbolLocalAddr(Symbol)
316 : Checker.getSymbolRemoteAddr(Symbol);
317 uint64_t NextPC = SymbolAddr + InstSize;
319 return std::make_pair(EvalResult(NextPC), RemainingExpr);
322 // Evaluate a call to stub_addr.
323 // Look up and return the address of the stub for the given
324 // (<file name>, <section name>, <symbol name>) tuple.
325 // On success, returns a pair containing the stub address, plus the expression
326 // remaining to be evaluated.
327 std::pair<EvalResult, StringRef> evalStubAddr(StringRef Expr,
328 ParseContext PCtx) const {
329 if (!Expr.startswith("("))
330 return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
331 StringRef RemainingExpr = Expr.substr(1).ltrim();
333 // Handle file-name specially, as it may contain characters that aren't
334 // legal for symbols.
336 size_t ComaIdx = RemainingExpr.find(',');
337 FileName = RemainingExpr.substr(0, ComaIdx).rtrim();
338 RemainingExpr = RemainingExpr.substr(ComaIdx).ltrim();
340 if (!RemainingExpr.startswith(","))
341 return std::make_pair(
342 unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
343 RemainingExpr = RemainingExpr.substr(1).ltrim();
345 StringRef SectionName;
346 std::tie(SectionName, RemainingExpr) = parseSymbol(RemainingExpr);
348 if (!RemainingExpr.startswith(","))
349 return std::make_pair(
350 unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
351 RemainingExpr = RemainingExpr.substr(1).ltrim();
354 std::tie(Symbol, RemainingExpr) = parseSymbol(RemainingExpr);
356 if (!RemainingExpr.startswith(")"))
357 return std::make_pair(
358 unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
359 RemainingExpr = RemainingExpr.substr(1).ltrim();
362 std::string ErrorMsg = "";
363 std::tie(StubAddr, ErrorMsg) = Checker.getStubAddrFor(
364 FileName, SectionName, Symbol, PCtx.IsInsideLoad);
367 return std::make_pair(EvalResult(ErrorMsg), "");
369 return std::make_pair(EvalResult(StubAddr), RemainingExpr);
372 std::pair<EvalResult, StringRef> evalSectionAddr(StringRef Expr,
373 ParseContext PCtx) const {
374 if (!Expr.startswith("("))
375 return std::make_pair(unexpectedToken(Expr, Expr, "expected '('"), "");
376 StringRef RemainingExpr = Expr.substr(1).ltrim();
378 // Handle file-name specially, as it may contain characters that aren't
379 // legal for symbols.
381 size_t ComaIdx = RemainingExpr.find(',');
382 FileName = RemainingExpr.substr(0, ComaIdx).rtrim();
383 RemainingExpr = RemainingExpr.substr(ComaIdx).ltrim();
385 if (!RemainingExpr.startswith(","))
386 return std::make_pair(
387 unexpectedToken(RemainingExpr, Expr, "expected ','"), "");
388 RemainingExpr = RemainingExpr.substr(1).ltrim();
390 StringRef SectionName;
391 std::tie(SectionName, RemainingExpr) = parseSymbol(RemainingExpr);
393 if (!RemainingExpr.startswith(")"))
394 return std::make_pair(
395 unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
396 RemainingExpr = RemainingExpr.substr(1).ltrim();
399 std::string ErrorMsg = "";
400 std::tie(StubAddr, ErrorMsg) = Checker.getSectionAddr(
401 FileName, SectionName, PCtx.IsInsideLoad);
404 return std::make_pair(EvalResult(ErrorMsg), "");
406 return std::make_pair(EvalResult(StubAddr), RemainingExpr);
409 // Evaluate an identiefer expr, which may be a symbol, or a call to
410 // one of the builtin functions: get_insn_opcode or get_insn_length.
411 // Return the result, plus the expression remaining to be parsed.
412 std::pair<EvalResult, StringRef> evalIdentifierExpr(StringRef Expr,
413 ParseContext PCtx) const {
415 StringRef RemainingExpr;
416 std::tie(Symbol, RemainingExpr) = parseSymbol(Expr);
418 // Check for builtin function calls.
419 if (Symbol == "decode_operand")
420 return evalDecodeOperand(RemainingExpr);
421 else if (Symbol == "next_pc")
422 return evalNextPC(RemainingExpr, PCtx);
423 else if (Symbol == "stub_addr")
424 return evalStubAddr(RemainingExpr, PCtx);
425 else if (Symbol == "section_addr")
426 return evalSectionAddr(RemainingExpr, PCtx);
428 if (!Checker.isSymbolValid(Symbol)) {
429 std::string ErrMsg("No known address for symbol '");
432 if (Symbol.startswith("L"))
433 ErrMsg += " (this appears to be an assembler local label - "
434 " perhaps drop the 'L'?)";
436 return std::make_pair(EvalResult(ErrMsg), "");
439 // The value for the symbol depends on the context we're evaluating in:
440 // Inside a load this is the address in the linker's memory, outside a
441 // load it's the address in the target processes memory.
442 uint64_t Value = PCtx.IsInsideLoad ? Checker.getSymbolLocalAddr(Symbol)
443 : Checker.getSymbolRemoteAddr(Symbol);
445 // Looks like a plain symbol reference.
446 return std::make_pair(EvalResult(Value), RemainingExpr);
449 // Parse a number (hexadecimal or decimal) and return a (string, string)
450 // pair representing the number and the expression remaining to be parsed.
451 std::pair<StringRef, StringRef> parseNumberString(StringRef Expr) const {
452 size_t FirstNonDigit = StringRef::npos;
453 if (Expr.startswith("0x")) {
454 FirstNonDigit = Expr.find_first_not_of("0123456789abcdefABCDEF", 2);
455 if (FirstNonDigit == StringRef::npos)
456 FirstNonDigit = Expr.size();
458 FirstNonDigit = Expr.find_first_not_of("0123456789");
459 if (FirstNonDigit == StringRef::npos)
460 FirstNonDigit = Expr.size();
462 return std::make_pair(Expr.substr(0, FirstNonDigit),
463 Expr.substr(FirstNonDigit));
466 // Evaluate a constant numeric expression (hexadecimal or decimal) and
467 // return a pair containing the result, and the expression remaining to be
469 std::pair<EvalResult, StringRef> evalNumberExpr(StringRef Expr) const {
471 StringRef RemainingExpr;
472 std::tie(ValueStr, RemainingExpr) = parseNumberString(Expr);
474 if (ValueStr.empty() || !isdigit(ValueStr[0]))
475 return std::make_pair(
476 unexpectedToken(RemainingExpr, RemainingExpr, "expected number"), "");
478 ValueStr.getAsInteger(0, Value);
479 return std::make_pair(EvalResult(Value), RemainingExpr);
482 // Evaluate an expression of the form "(<expr>)" and return a pair
483 // containing the result of evaluating <expr>, plus the expression
484 // remaining to be parsed.
485 std::pair<EvalResult, StringRef> evalParensExpr(StringRef Expr,
486 ParseContext PCtx) const {
487 assert(Expr.startswith("(") && "Not a parenthesized expression");
488 EvalResult SubExprResult;
489 StringRef RemainingExpr;
490 std::tie(SubExprResult, RemainingExpr) =
491 evalComplexExpr(evalSimpleExpr(Expr.substr(1).ltrim(), PCtx), PCtx);
492 if (SubExprResult.hasError())
493 return std::make_pair(SubExprResult, "");
494 if (!RemainingExpr.startswith(")"))
495 return std::make_pair(
496 unexpectedToken(RemainingExpr, Expr, "expected ')'"), "");
497 RemainingExpr = RemainingExpr.substr(1).ltrim();
498 return std::make_pair(SubExprResult, RemainingExpr);
501 // Evaluate an expression in one of the following forms:
503 // Return a pair containing the result, plus the expression remaining to be
505 std::pair<EvalResult, StringRef> evalLoadExpr(StringRef Expr) const {
506 assert(Expr.startswith("*") && "Not a load expression");
507 StringRef RemainingExpr = Expr.substr(1).ltrim();
510 if (!RemainingExpr.startswith("{"))
511 return std::make_pair(EvalResult("Expected '{' following '*'."), "");
512 RemainingExpr = RemainingExpr.substr(1).ltrim();
513 EvalResult ReadSizeExpr;
514 std::tie(ReadSizeExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
515 if (ReadSizeExpr.hasError())
516 return std::make_pair(ReadSizeExpr, RemainingExpr);
517 uint64_t ReadSize = ReadSizeExpr.getValue();
518 if (ReadSize < 1 || ReadSize > 8)
519 return std::make_pair(EvalResult("Invalid size for dereference."), "");
520 if (!RemainingExpr.startswith("}"))
521 return std::make_pair(EvalResult("Missing '}' for dereference."), "");
522 RemainingExpr = RemainingExpr.substr(1).ltrim();
524 // Evaluate the expression representing the load address.
525 ParseContext LoadCtx(true);
526 EvalResult LoadAddrExprResult;
527 std::tie(LoadAddrExprResult, RemainingExpr) =
528 evalComplexExpr(evalSimpleExpr(RemainingExpr, LoadCtx), LoadCtx);
530 if (LoadAddrExprResult.hasError())
531 return std::make_pair(LoadAddrExprResult, "");
533 uint64_t LoadAddr = LoadAddrExprResult.getValue();
535 return std::make_pair(
536 EvalResult(Checker.readMemoryAtAddr(LoadAddr, ReadSize)),
540 // Evaluate a "simple" expression. This is any expression that _isn't_ an
541 // un-parenthesized binary expression.
543 // "Simple" expressions can be optionally bit-sliced. See evalSlicedExpr.
545 // Returns a pair containing the result of the evaluation, plus the
546 // expression remaining to be parsed.
547 std::pair<EvalResult, StringRef> evalSimpleExpr(StringRef Expr,
548 ParseContext PCtx) const {
549 EvalResult SubExprResult;
550 StringRef RemainingExpr;
553 return std::make_pair(EvalResult("Unexpected end of expression"), "");
556 std::tie(SubExprResult, RemainingExpr) = evalParensExpr(Expr, PCtx);
557 else if (Expr[0] == '*')
558 std::tie(SubExprResult, RemainingExpr) = evalLoadExpr(Expr);
559 else if (isalpha(Expr[0]) || Expr[0] == '_')
560 std::tie(SubExprResult, RemainingExpr) = evalIdentifierExpr(Expr, PCtx);
561 else if (isdigit(Expr[0]))
562 std::tie(SubExprResult, RemainingExpr) = evalNumberExpr(Expr);
564 return std::make_pair(
565 unexpectedToken(Expr, Expr,
566 "expected '(', '*', identifier, or number"), "");
568 if (SubExprResult.hasError())
569 return std::make_pair(SubExprResult, RemainingExpr);
571 // Evaluate bit-slice if present.
572 if (RemainingExpr.startswith("["))
573 std::tie(SubExprResult, RemainingExpr) =
574 evalSliceExpr(std::make_pair(SubExprResult, RemainingExpr));
576 return std::make_pair(SubExprResult, RemainingExpr);
579 // Evaluate a bit-slice of an expression.
580 // A bit-slice has the form "<expr>[high:low]". The result of evaluating a
581 // slice is the bits between high and low (inclusive) in the original
582 // expression, right shifted so that the "low" bit is in position 0 in the
584 // Returns a pair containing the result of the slice operation, plus the
585 // expression remaining to be parsed.
586 std::pair<EvalResult, StringRef>
587 evalSliceExpr(const std::pair<EvalResult, StringRef> &Ctx) const {
588 EvalResult SubExprResult;
589 StringRef RemainingExpr;
590 std::tie(SubExprResult, RemainingExpr) = Ctx;
592 assert(RemainingExpr.startswith("[") && "Not a slice expr.");
593 RemainingExpr = RemainingExpr.substr(1).ltrim();
595 EvalResult HighBitExpr;
596 std::tie(HighBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
598 if (HighBitExpr.hasError())
599 return std::make_pair(HighBitExpr, RemainingExpr);
601 if (!RemainingExpr.startswith(":"))
602 return std::make_pair(
603 unexpectedToken(RemainingExpr, RemainingExpr, "expected ':'"), "");
604 RemainingExpr = RemainingExpr.substr(1).ltrim();
606 EvalResult LowBitExpr;
607 std::tie(LowBitExpr, RemainingExpr) = evalNumberExpr(RemainingExpr);
609 if (LowBitExpr.hasError())
610 return std::make_pair(LowBitExpr, RemainingExpr);
612 if (!RemainingExpr.startswith("]"))
613 return std::make_pair(
614 unexpectedToken(RemainingExpr, RemainingExpr, "expected ']'"), "");
615 RemainingExpr = RemainingExpr.substr(1).ltrim();
617 unsigned HighBit = HighBitExpr.getValue();
618 unsigned LowBit = LowBitExpr.getValue();
619 uint64_t Mask = ((uint64_t)1 << (HighBit - LowBit + 1)) - 1;
620 uint64_t SlicedValue = (SubExprResult.getValue() >> LowBit) & Mask;
621 return std::make_pair(EvalResult(SlicedValue), RemainingExpr);
624 // Evaluate a "complex" expression.
625 // Takes an already evaluated subexpression and checks for the presence of a
626 // binary operator, computing the result of the binary operation if one is
627 // found. Used to make arithmetic expressions left-associative.
628 // Returns a pair containing the ultimate result of evaluating the
629 // expression, plus the expression remaining to be evaluated.
630 std::pair<EvalResult, StringRef>
631 evalComplexExpr(const std::pair<EvalResult, StringRef> &LHSAndRemaining,
632 ParseContext PCtx) const {
633 EvalResult LHSResult;
634 StringRef RemainingExpr;
635 std::tie(LHSResult, RemainingExpr) = LHSAndRemaining;
637 // If there was an error, or there's nothing left to evaluate, return the
639 if (LHSResult.hasError() || RemainingExpr == "")
640 return std::make_pair(LHSResult, RemainingExpr);
642 // Otherwise check if this is a binary expressioan.
644 std::tie(BinOp, RemainingExpr) = parseBinOpToken(RemainingExpr);
646 // If this isn't a recognized expression just return.
647 if (BinOp == BinOpToken::Invalid)
648 return std::make_pair(LHSResult, RemainingExpr);
650 // This is a recognized bin-op. Evaluate the RHS, then evaluate the binop.
651 EvalResult RHSResult;
652 std::tie(RHSResult, RemainingExpr) = evalSimpleExpr(RemainingExpr, PCtx);
654 // If there was an error evaluating the RHS, return it.
655 if (RHSResult.hasError())
656 return std::make_pair(RHSResult, RemainingExpr);
658 // This is a binary expression - evaluate and try to continue as a
660 EvalResult ThisResult(computeBinOpResult(BinOp, LHSResult, RHSResult));
662 return evalComplexExpr(std::make_pair(ThisResult, RemainingExpr), PCtx);
665 bool decodeInst(StringRef Symbol, MCInst &Inst, uint64_t &Size) const {
666 MCDisassembler *Dis = Checker.Disassembler;
667 StringRef SectionMem = Checker.getSubsectionStartingAt(Symbol);
668 ArrayRef<uint8_t> SectionBytes(
669 reinterpret_cast<const uint8_t *>(SectionMem.data()),
672 MCDisassembler::DecodeStatus S =
673 Dis->getInstruction(Inst, Size, SectionBytes, 0, nulls(), nulls());
675 return (S == MCDisassembler::Success);
680 RuntimeDyldCheckerImpl::RuntimeDyldCheckerImpl(RuntimeDyld &RTDyld,
681 MCDisassembler *Disassembler,
682 MCInstPrinter *InstPrinter,
683 raw_ostream &ErrStream)
684 : RTDyld(RTDyld), Disassembler(Disassembler), InstPrinter(InstPrinter),
685 ErrStream(ErrStream) {
686 RTDyld.Checker = this;
689 bool RuntimeDyldCheckerImpl::check(StringRef CheckExpr) const {
690 CheckExpr = CheckExpr.trim();
691 DEBUG(dbgs() << "RuntimeDyldChecker: Checking '" << CheckExpr << "'...\n");
692 RuntimeDyldCheckerExprEval P(*this, ErrStream);
693 bool Result = P.evaluate(CheckExpr);
695 DEBUG(dbgs() << "RuntimeDyldChecker: '" << CheckExpr << "' "
696 << (Result ? "passed" : "FAILED") << ".\n");
700 bool RuntimeDyldCheckerImpl::checkAllRulesInBuffer(StringRef RulePrefix,
701 MemoryBuffer *MemBuf) const {
702 bool DidAllTestsPass = true;
703 unsigned NumRules = 0;
705 const char *LineStart = MemBuf->getBufferStart();
708 while (LineStart != MemBuf->getBufferEnd() && std::isspace(*LineStart))
711 while (LineStart != MemBuf->getBufferEnd() && *LineStart != '\0') {
712 const char *LineEnd = LineStart;
713 while (LineEnd != MemBuf->getBufferEnd() && *LineEnd != '\r' &&
717 StringRef Line(LineStart, LineEnd - LineStart);
718 if (Line.startswith(RulePrefix)) {
719 DidAllTestsPass &= check(Line.substr(RulePrefix.size()));
725 while (LineStart != MemBuf->getBufferEnd() && std::isspace(*LineStart))
728 return DidAllTestsPass && (NumRules != 0);
731 bool RuntimeDyldCheckerImpl::isSymbolValid(StringRef Symbol) const {
732 if (getRTDyld().getSymbol(Symbol))
734 return !!getRTDyld().Resolver.findSymbol(Symbol);
737 uint64_t RuntimeDyldCheckerImpl::getSymbolLocalAddr(StringRef Symbol) const {
738 return static_cast<uint64_t>(
739 reinterpret_cast<uintptr_t>(getRTDyld().getSymbolLocalAddress(Symbol)));
742 uint64_t RuntimeDyldCheckerImpl::getSymbolRemoteAddr(StringRef Symbol) const {
743 if (auto InternalSymbol = getRTDyld().getSymbol(Symbol))
744 return InternalSymbol.getAddress();
745 return cantFail(getRTDyld().Resolver.findSymbol(Symbol).getAddress());
748 uint64_t RuntimeDyldCheckerImpl::readMemoryAtAddr(uint64_t SrcAddr,
749 unsigned Size) const {
750 uintptr_t PtrSizedAddr = static_cast<uintptr_t>(SrcAddr);
751 assert(PtrSizedAddr == SrcAddr && "Linker memory pointer out-of-range.");
752 uint8_t *Src = reinterpret_cast<uint8_t*>(PtrSizedAddr);
753 return getRTDyld().readBytesUnaligned(Src, Size);
757 std::pair<const RuntimeDyldCheckerImpl::SectionAddressInfo*, std::string>
758 RuntimeDyldCheckerImpl::findSectionAddrInfo(StringRef FileName,
759 StringRef SectionName) const {
761 auto SectionMapItr = Stubs.find(FileName);
762 if (SectionMapItr == Stubs.end()) {
763 std::string ErrorMsg = "File '";
764 ErrorMsg += FileName;
765 ErrorMsg += "' not found. ";
767 ErrorMsg += "No stubs registered.";
769 ErrorMsg += "Available files are:";
770 for (const auto& StubEntry : Stubs) {
772 ErrorMsg += StubEntry.first;
777 return std::make_pair(nullptr, ErrorMsg);
780 auto SectionInfoItr = SectionMapItr->second.find(SectionName);
781 if (SectionInfoItr == SectionMapItr->second.end())
782 return std::make_pair(nullptr,
783 ("Section '" + SectionName + "' not found in file '" +
784 FileName + "'\n").str());
786 return std::make_pair(&SectionInfoItr->second, std::string(""));
789 std::pair<uint64_t, std::string> RuntimeDyldCheckerImpl::getSectionAddr(
790 StringRef FileName, StringRef SectionName, bool IsInsideLoad) const {
792 const SectionAddressInfo *SectionInfo = nullptr;
794 std::string ErrorMsg;
795 std::tie(SectionInfo, ErrorMsg) =
796 findSectionAddrInfo(FileName, SectionName);
798 return std::make_pair(0, ErrorMsg);
801 unsigned SectionID = SectionInfo->SectionID;
804 Addr = static_cast<uint64_t>(reinterpret_cast<uintptr_t>(
805 getRTDyld().Sections[SectionID].getAddress()));
807 Addr = getRTDyld().Sections[SectionID].getLoadAddress();
809 return std::make_pair(Addr, std::string(""));
812 std::pair<uint64_t, std::string> RuntimeDyldCheckerImpl::getStubAddrFor(
813 StringRef FileName, StringRef SectionName, StringRef SymbolName,
814 bool IsInsideLoad) const {
816 const SectionAddressInfo *SectionInfo = nullptr;
818 std::string ErrorMsg;
819 std::tie(SectionInfo, ErrorMsg) =
820 findSectionAddrInfo(FileName, SectionName);
822 return std::make_pair(0, ErrorMsg);
825 unsigned SectionID = SectionInfo->SectionID;
826 const StubOffsetsMap &SymbolStubs = SectionInfo->StubOffsets;
827 auto StubOffsetItr = SymbolStubs.find(SymbolName);
828 if (StubOffsetItr == SymbolStubs.end())
829 return std::make_pair(0,
830 ("Stub for symbol '" + SymbolName + "' not found. "
831 "If '" + SymbolName + "' is an internal symbol this "
832 "may indicate that the stub target offset is being "
833 "computed incorrectly.\n").str());
835 uint64_t StubOffset = StubOffsetItr->second;
839 uintptr_t SectionBase = reinterpret_cast<uintptr_t>(
840 getRTDyld().Sections[SectionID].getAddress());
841 Addr = static_cast<uint64_t>(SectionBase) + StubOffset;
843 uint64_t SectionBase = getRTDyld().Sections[SectionID].getLoadAddress();
844 Addr = SectionBase + StubOffset;
847 return std::make_pair(Addr, std::string(""));
851 RuntimeDyldCheckerImpl::getSubsectionStartingAt(StringRef Name) const {
852 RTDyldSymbolTable::const_iterator pos =
853 getRTDyld().GlobalSymbolTable.find(Name);
854 if (pos == getRTDyld().GlobalSymbolTable.end())
856 const auto &SymInfo = pos->second;
857 uint8_t *SectionAddr = getRTDyld().getSectionAddress(SymInfo.getSectionID());
858 return StringRef(reinterpret_cast<const char *>(SectionAddr) +
860 getRTDyld().Sections[SymInfo.getSectionID()].getSize() -
861 SymInfo.getOffset());
865 RuntimeDyldCheckerImpl::getSectionLoadAddress(void *LocalAddress) const {
866 for (auto &S : getRTDyld().Sections) {
867 if (S.getAddress() == LocalAddress)
868 return S.getLoadAddress();
870 return Optional<uint64_t>();
873 void RuntimeDyldCheckerImpl::registerSection(
874 StringRef FilePath, unsigned SectionID) {
875 StringRef FileName = sys::path::filename(FilePath);
876 const SectionEntry &Section = getRTDyld().Sections[SectionID];
877 StringRef SectionName = Section.getName();
879 Stubs[FileName][SectionName].SectionID = SectionID;
882 void RuntimeDyldCheckerImpl::registerStubMap(
883 StringRef FilePath, unsigned SectionID,
884 const RuntimeDyldImpl::StubMap &RTDyldStubs) {
885 StringRef FileName = sys::path::filename(FilePath);
886 const SectionEntry &Section = getRTDyld().Sections[SectionID];
887 StringRef SectionName = Section.getName();
889 Stubs[FileName][SectionName].SectionID = SectionID;
891 for (auto &StubMapEntry : RTDyldStubs) {
892 std::string SymbolName = "";
894 if (StubMapEntry.first.SymbolName)
895 SymbolName = StubMapEntry.first.SymbolName;
897 // If this is a (Section, Offset) pair, do a reverse lookup in the
898 // global symbol table to find the name.
899 for (auto &GSTEntry : getRTDyld().GlobalSymbolTable) {
900 const auto &SymInfo = GSTEntry.second;
901 if (SymInfo.getSectionID() == StubMapEntry.first.SectionID &&
902 SymInfo.getOffset() ==
903 static_cast<uint64_t>(StubMapEntry.first.Offset)) {
904 SymbolName = GSTEntry.first();
910 if (SymbolName != "")
911 Stubs[FileName][SectionName].StubOffsets[SymbolName] =
916 RuntimeDyldChecker::RuntimeDyldChecker(RuntimeDyld &RTDyld,
917 MCDisassembler *Disassembler,
918 MCInstPrinter *InstPrinter,
919 raw_ostream &ErrStream)
920 : Impl(make_unique<RuntimeDyldCheckerImpl>(RTDyld, Disassembler,
921 InstPrinter, ErrStream)) {}
923 RuntimeDyldChecker::~RuntimeDyldChecker() {}
925 RuntimeDyld& RuntimeDyldChecker::getRTDyld() {
929 const RuntimeDyld& RuntimeDyldChecker::getRTDyld() const {
933 bool RuntimeDyldChecker::check(StringRef CheckExpr) const {
934 return Impl->check(CheckExpr);
937 bool RuntimeDyldChecker::checkAllRulesInBuffer(StringRef RulePrefix,
938 MemoryBuffer *MemBuf) const {
939 return Impl->checkAllRulesInBuffer(RulePrefix, MemBuf);
942 std::pair<uint64_t, std::string>
943 RuntimeDyldChecker::getSectionAddr(StringRef FileName, StringRef SectionName,
945 return Impl->getSectionAddr(FileName, SectionName, LocalAddress);
949 RuntimeDyldChecker::getSectionLoadAddress(void *LocalAddress) const {
950 return Impl->getSectionLoadAddress(LocalAddress);