DWARFDebugLine.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- DWARFDebugLine.h -----------------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_DEBUGINFO_DWARF_DWARFDEBUGLINE_H
  14. #define LLVM_DEBUGINFO_DWARF_DWARFDEBUGLINE_H
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/DebugInfo/DIContext.h"
  18. #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
  19. #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
  23. #include "llvm/Support/MD5.h"
  24. #include "llvm/Support/Path.h"
  25. #include <cstdint>
  26. #include <map>
  27. #include <string>
  28. #include <vector>
  29. namespace llvm {
  30. class DWARFUnit;
  31. class raw_ostream;
  32. class DWARFDebugLine {
  33. public:
  34. struct FileNameEntry {
  35. FileNameEntry() = default;
  36. DWARFFormValue Name;
  37. uint64_t DirIdx = 0;
  38. uint64_t ModTime = 0;
  39. uint64_t Length = 0;
  40. MD5::MD5Result Checksum;
  41. DWARFFormValue Source;
  42. };
  43. /// Tracks which optional content types are present in a DWARF file name
  44. /// entry format.
  45. struct ContentTypeTracker {
  46. ContentTypeTracker() = default;
  47. /// Whether filename entries provide a modification timestamp.
  48. bool HasModTime = false;
  49. /// Whether filename entries provide a file size.
  50. bool HasLength = false;
  51. /// For v5, whether filename entries provide an MD5 checksum.
  52. bool HasMD5 = false;
  53. /// For v5, whether filename entries provide source text.
  54. bool HasSource = false;
  55. /// Update tracked content types with \p ContentType.
  56. void trackContentType(dwarf::LineNumberEntryFormat ContentType);
  57. };
  58. struct Prologue {
  59. Prologue();
  60. /// The size in bytes of the statement information for this compilation unit
  61. /// (not including the total_length field itself).
  62. uint64_t TotalLength;
  63. /// Version, address size (starting in v5), and DWARF32/64 format; these
  64. /// parameters affect interpretation of forms (used in the directory and
  65. /// file tables starting with v5).
  66. dwarf::FormParams FormParams;
  67. /// The number of bytes following the prologue_length field to the beginning
  68. /// of the first byte of the statement program itself.
  69. uint64_t PrologueLength;
  70. /// In v5, size in bytes of a segment selector.
  71. uint8_t SegSelectorSize;
  72. /// The size in bytes of the smallest target machine instruction. Statement
  73. /// program opcodes that alter the address register first multiply their
  74. /// operands by this value.
  75. uint8_t MinInstLength;
  76. /// The maximum number of individual operations that may be encoded in an
  77. /// instruction.
  78. uint8_t MaxOpsPerInst;
  79. /// The initial value of theis_stmtregister.
  80. uint8_t DefaultIsStmt;
  81. /// This parameter affects the meaning of the special opcodes. See below.
  82. int8_t LineBase;
  83. /// This parameter affects the meaning of the special opcodes. See below.
  84. uint8_t LineRange;
  85. /// The number assigned to the first special opcode.
  86. uint8_t OpcodeBase;
  87. /// This tracks which optional file format content types are present.
  88. ContentTypeTracker ContentTypes;
  89. std::vector<uint8_t> StandardOpcodeLengths;
  90. std::vector<DWARFFormValue> IncludeDirectories;
  91. std::vector<FileNameEntry> FileNames;
  92. const dwarf::FormParams getFormParams() const { return FormParams; }
  93. uint16_t getVersion() const { return FormParams.Version; }
  94. uint8_t getAddressSize() const { return FormParams.AddrSize; }
  95. bool isDWARF64() const { return FormParams.Format == dwarf::DWARF64; }
  96. uint32_t sizeofTotalLength() const { return isDWARF64() ? 12 : 4; }
  97. uint32_t sizeofPrologueLength() const { return isDWARF64() ? 8 : 4; }
  98. bool totalLengthIsValid() const;
  99. /// Length of the prologue in bytes.
  100. uint64_t getLength() const;
  101. /// Get DWARF-version aware access to the file name entry at the provided
  102. /// index.
  103. const llvm::DWARFDebugLine::FileNameEntry &
  104. getFileNameEntry(uint64_t Index) const;
  105. bool hasFileAtIndex(uint64_t FileIndex) const;
  106. Optional<uint64_t> getLastValidFileIndex() const;
  107. bool
  108. getFileNameByIndex(uint64_t FileIndex, StringRef CompDir,
  109. DILineInfoSpecifier::FileLineInfoKind Kind,
  110. std::string &Result,
  111. sys::path::Style Style = sys::path::Style::native) const;
  112. void clear();
  113. void dump(raw_ostream &OS, DIDumpOptions DumpOptions) const;
  114. Error parse(DWARFDataExtractor Data, uint64_t *OffsetPtr,
  115. function_ref<void(Error)> RecoverableErrorHandler,
  116. const DWARFContext &Ctx, const DWARFUnit *U = nullptr);
  117. };
  118. /// Standard .debug_line state machine structure.
  119. struct Row {
  120. explicit Row(bool DefaultIsStmt = false);
  121. /// Called after a row is appended to the matrix.
  122. void postAppend();
  123. void reset(bool DefaultIsStmt);
  124. void dump(raw_ostream &OS) const;
  125. static void dumpTableHeader(raw_ostream &OS, unsigned Indent);
  126. static bool orderByAddress(const Row &LHS, const Row &RHS) {
  127. return std::tie(LHS.Address.SectionIndex, LHS.Address.Address) <
  128. std::tie(RHS.Address.SectionIndex, RHS.Address.Address);
  129. }
  130. /// The program-counter value corresponding to a machine instruction
  131. /// generated by the compiler and section index pointing to the section
  132. /// containg this PC. If relocation information is present then section
  133. /// index is the index of the section which contains above address.
  134. /// Otherwise this is object::SectionedAddress::Undef value.
  135. object::SectionedAddress Address;
  136. /// An unsigned integer indicating a source line number. Lines are numbered
  137. /// beginning at 1. The compiler may emit the value 0 in cases where an
  138. /// instruction cannot be attributed to any source line.
  139. uint32_t Line;
  140. /// An unsigned integer indicating a column number within a source line.
  141. /// Columns are numbered beginning at 1. The value 0 is reserved to indicate
  142. /// that a statement begins at the 'left edge' of the line.
  143. uint16_t Column;
  144. /// An unsigned integer indicating the identity of the source file
  145. /// corresponding to a machine instruction.
  146. uint16_t File;
  147. /// An unsigned integer representing the DWARF path discriminator value
  148. /// for this location.
  149. uint32_t Discriminator;
  150. /// An unsigned integer whose value encodes the applicable instruction set
  151. /// architecture for the current instruction.
  152. uint8_t Isa;
  153. /// A boolean indicating that the current instruction is the beginning of a
  154. /// statement.
  155. uint8_t IsStmt : 1,
  156. /// A boolean indicating that the current instruction is the
  157. /// beginning of a basic block.
  158. BasicBlock : 1,
  159. /// A boolean indicating that the current address is that of the
  160. /// first byte after the end of a sequence of target machine
  161. /// instructions.
  162. EndSequence : 1,
  163. /// A boolean indicating that the current address is one (of possibly
  164. /// many) where execution should be suspended for an entry breakpoint
  165. /// of a function.
  166. PrologueEnd : 1,
  167. /// A boolean indicating that the current address is one (of possibly
  168. /// many) where execution should be suspended for an exit breakpoint
  169. /// of a function.
  170. EpilogueBegin : 1;
  171. };
  172. /// Represents a series of contiguous machine instructions. Line table for
  173. /// each compilation unit may consist of multiple sequences, which are not
  174. /// guaranteed to be in the order of ascending instruction address.
  175. struct Sequence {
  176. Sequence();
  177. /// Sequence describes instructions at address range [LowPC, HighPC)
  178. /// and is described by line table rows [FirstRowIndex, LastRowIndex).
  179. uint64_t LowPC;
  180. uint64_t HighPC;
  181. /// If relocation information is present then this is the index of the
  182. /// section which contains above addresses. Otherwise this is
  183. /// object::SectionedAddress::Undef value.
  184. uint64_t SectionIndex;
  185. unsigned FirstRowIndex;
  186. unsigned LastRowIndex;
  187. bool Empty;
  188. void reset();
  189. static bool orderByHighPC(const Sequence &LHS, const Sequence &RHS) {
  190. return std::tie(LHS.SectionIndex, LHS.HighPC) <
  191. std::tie(RHS.SectionIndex, RHS.HighPC);
  192. }
  193. bool isValid() const {
  194. return !Empty && (LowPC < HighPC) && (FirstRowIndex < LastRowIndex);
  195. }
  196. bool containsPC(object::SectionedAddress PC) const {
  197. return SectionIndex == PC.SectionIndex &&
  198. (LowPC <= PC.Address && PC.Address < HighPC);
  199. }
  200. };
  201. struct LineTable {
  202. LineTable();
  203. /// Represents an invalid row
  204. const uint32_t UnknownRowIndex = UINT32_MAX;
  205. void appendRow(const DWARFDebugLine::Row &R) { Rows.push_back(R); }
  206. void appendSequence(const DWARFDebugLine::Sequence &S) {
  207. Sequences.push_back(S);
  208. }
  209. /// Returns the index of the row with file/line info for a given address,
  210. /// or UnknownRowIndex if there is no such row.
  211. uint32_t lookupAddress(object::SectionedAddress Address) const;
  212. bool lookupAddressRange(object::SectionedAddress Address, uint64_t Size,
  213. std::vector<uint32_t> &Result) const;
  214. bool hasFileAtIndex(uint64_t FileIndex) const {
  215. return Prologue.hasFileAtIndex(FileIndex);
  216. }
  217. Optional<uint64_t> getLastValidFileIndex() const {
  218. return Prologue.getLastValidFileIndex();
  219. }
  220. /// Extracts filename by its index in filename table in prologue.
  221. /// In Dwarf 4, the files are 1-indexed and the current compilation file
  222. /// name is not represented in the list. In DWARF v5, the files are
  223. /// 0-indexed and the primary source file has the index 0.
  224. /// Returns true on success.
  225. bool getFileNameByIndex(uint64_t FileIndex, StringRef CompDir,
  226. DILineInfoSpecifier::FileLineInfoKind Kind,
  227. std::string &Result) const {
  228. return Prologue.getFileNameByIndex(FileIndex, CompDir, Kind, Result);
  229. }
  230. /// Fills the Result argument with the file and line information
  231. /// corresponding to Address. Returns true on success.
  232. bool getFileLineInfoForAddress(object::SectionedAddress Address,
  233. const char *CompDir,
  234. DILineInfoSpecifier::FileLineInfoKind Kind,
  235. DILineInfo &Result) const;
  236. void dump(raw_ostream &OS, DIDumpOptions DumpOptions) const;
  237. void clear();
  238. /// Parse prologue and all rows.
  239. Error parse(DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr,
  240. const DWARFContext &Ctx, const DWARFUnit *U,
  241. function_ref<void(Error)> RecoverableErrorHandler,
  242. raw_ostream *OS = nullptr, bool Verbose = false);
  243. using RowVector = std::vector<Row>;
  244. using RowIter = RowVector::const_iterator;
  245. using SequenceVector = std::vector<Sequence>;
  246. using SequenceIter = SequenceVector::const_iterator;
  247. struct Prologue Prologue;
  248. RowVector Rows;
  249. SequenceVector Sequences;
  250. private:
  251. uint32_t findRowInSeq(const DWARFDebugLine::Sequence &Seq,
  252. object::SectionedAddress Address) const;
  253. Optional<StringRef>
  254. getSourceByIndex(uint64_t FileIndex,
  255. DILineInfoSpecifier::FileLineInfoKind Kind) const;
  256. uint32_t lookupAddressImpl(object::SectionedAddress Address) const;
  257. bool lookupAddressRangeImpl(object::SectionedAddress Address, uint64_t Size,
  258. std::vector<uint32_t> &Result) const;
  259. };
  260. const LineTable *getLineTable(uint64_t Offset) const;
  261. Expected<const LineTable *>
  262. getOrParseLineTable(DWARFDataExtractor &DebugLineData, uint64_t Offset,
  263. const DWARFContext &Ctx, const DWARFUnit *U,
  264. function_ref<void(Error)> RecoverableErrorHandler);
  265. /// Helper to allow for parsing of an entire .debug_line section in sequence.
  266. class SectionParser {
  267. public:
  268. using LineToUnitMap = std::map<uint64_t, DWARFUnit *>;
  269. SectionParser(DWARFDataExtractor &Data, const DWARFContext &C,
  270. DWARFUnitVector::iterator_range Units);
  271. /// Get the next line table from the section. Report any issues via the
  272. /// handlers.
  273. ///
  274. /// \param RecoverableErrorHandler - any issues that don't prevent further
  275. /// parsing of the table will be reported through this handler.
  276. /// \param UnrecoverableErrorHandler - any issues that prevent further
  277. /// parsing of the table will be reported through this handler.
  278. /// \param OS - if not null, the parser will print information about the
  279. /// table as it parses it.
  280. /// \param Verbose - if true, the parser will print verbose information when
  281. /// printing to the output.
  282. LineTable parseNext(function_ref<void(Error)> RecoverableErrorHandler,
  283. function_ref<void(Error)> UnrecoverableErrorHandler,
  284. raw_ostream *OS = nullptr, bool Verbose = false);
  285. /// Skip the current line table and go to the following line table (if
  286. /// present) immediately.
  287. ///
  288. /// \param RecoverableErrorHandler - report any recoverable prologue
  289. /// parsing issues via this handler.
  290. /// \param UnrecoverableErrorHandler - report any unrecoverable prologue
  291. /// parsing issues via this handler.
  292. void skip(function_ref<void(Error)> RecoverableErrorHandler,
  293. function_ref<void(Error)> UnrecoverableErrorHandler);
  294. /// Indicates if the parser has parsed as much as possible.
  295. ///
  296. /// \note Certain problems with the line table structure might mean that
  297. /// parsing stops before the end of the section is reached.
  298. bool done() const { return Done; }
  299. /// Get the offset the parser has reached.
  300. uint64_t getOffset() const { return Offset; }
  301. private:
  302. DWARFUnit *prepareToParse(uint64_t Offset);
  303. void moveToNextTable(uint64_t OldOffset, const Prologue &P);
  304. LineToUnitMap LineToUnit;
  305. DWARFDataExtractor &DebugLineData;
  306. const DWARFContext &Context;
  307. uint64_t Offset = 0;
  308. bool Done = false;
  309. };
  310. private:
  311. struct ParsingState {
  312. ParsingState(struct LineTable *LT, uint64_t TableOffset,
  313. function_ref<void(Error)> ErrorHandler);
  314. void resetRowAndSequence();
  315. void appendRowToMatrix();
  316. /// Advance the address by the \p OperationAdvance value. \returns the
  317. /// amount advanced by.
  318. uint64_t advanceAddr(uint64_t OperationAdvance, uint8_t Opcode,
  319. uint64_t OpcodeOffset);
  320. struct AddrAndAdjustedOpcode {
  321. uint64_t AddrDelta;
  322. uint8_t AdjustedOpcode;
  323. };
  324. /// Advance the address as required by the specified \p Opcode.
  325. /// \returns the amount advanced by and the calculated adjusted opcode.
  326. AddrAndAdjustedOpcode advanceAddrForOpcode(uint8_t Opcode,
  327. uint64_t OpcodeOffset);
  328. struct AddrAndLineDelta {
  329. uint64_t Address;
  330. int32_t Line;
  331. };
  332. /// Advance the line and address as required by the specified special \p
  333. /// Opcode. \returns the address and line delta.
  334. AddrAndLineDelta handleSpecialOpcode(uint8_t Opcode, uint64_t OpcodeOffset);
  335. /// Line table we're currently parsing.
  336. struct LineTable *LineTable;
  337. struct Row Row;
  338. struct Sequence Sequence;
  339. private:
  340. uint64_t LineTableOffset;
  341. bool ReportAdvanceAddrProblem = true;
  342. bool ReportBadLineRange = true;
  343. function_ref<void(Error)> ErrorHandler;
  344. };
  345. using LineTableMapTy = std::map<uint64_t, LineTable>;
  346. using LineTableIter = LineTableMapTy::iterator;
  347. using LineTableConstIter = LineTableMapTy::const_iterator;
  348. LineTableMapTy LineTableMap;
  349. };
  350. } // end namespace llvm
  351. #endif // LLVM_DEBUGINFO_DWARF_DWARFDEBUGLINE_H
  352. #ifdef __GNUC__
  353. #pragma GCC diagnostic pop
  354. #endif