DWARFDebugLine.h 16 KB

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