DWARFContext.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046
  1. //===- DWARFContext.cpp ---------------------------------------------------===//
  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/DebugInfo/DWARF/DWARFContext.h"
  9. #include "llvm/ADT/STLExtras.h"
  10. #include "llvm/ADT/SmallString.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/ADT/StringSwitch.h"
  14. #include "llvm/BinaryFormat/Dwarf.h"
  15. #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
  16. #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
  17. #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
  18. #include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
  19. #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
  20. #include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
  21. #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
  22. #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
  23. #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
  24. #include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
  25. #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
  26. #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
  27. #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
  28. #include "llvm/DebugInfo/DWARF/DWARFDie.h"
  29. #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
  30. #include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
  31. #include "llvm/DebugInfo/DWARF/DWARFSection.h"
  32. #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
  33. #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
  34. #include "llvm/MC/MCRegisterInfo.h"
  35. #include "llvm/MC/TargetRegistry.h"
  36. #include "llvm/Object/Decompressor.h"
  37. #include "llvm/Object/MachO.h"
  38. #include "llvm/Object/ObjectFile.h"
  39. #include "llvm/Object/RelocationResolver.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/DataExtractor.h"
  42. #include "llvm/Support/Error.h"
  43. #include "llvm/Support/Format.h"
  44. #include "llvm/Support/LEB128.h"
  45. #include "llvm/Support/MemoryBuffer.h"
  46. #include "llvm/Support/Path.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <algorithm>
  49. #include <cstdint>
  50. #include <deque>
  51. #include <map>
  52. #include <string>
  53. #include <utility>
  54. #include <vector>
  55. using namespace llvm;
  56. using namespace dwarf;
  57. using namespace object;
  58. #define DEBUG_TYPE "dwarf"
  59. using DWARFLineTable = DWARFDebugLine::LineTable;
  60. using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
  61. using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
  62. DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
  63. std::string DWPName,
  64. std::function<void(Error)> RecoverableErrorHandler,
  65. std::function<void(Error)> WarningHandler)
  66. : DIContext(CK_DWARF), DWPName(std::move(DWPName)),
  67. RecoverableErrorHandler(RecoverableErrorHandler),
  68. WarningHandler(WarningHandler), DObj(std::move(DObj)) {}
  69. DWARFContext::~DWARFContext() = default;
  70. /// Dump the UUID load command.
  71. static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
  72. auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
  73. if (!MachO)
  74. return;
  75. for (auto LC : MachO->load_commands()) {
  76. raw_ostream::uuid_t UUID;
  77. if (LC.C.cmd == MachO::LC_UUID) {
  78. if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
  79. OS << "error: UUID load command is too short.\n";
  80. return;
  81. }
  82. OS << "UUID: ";
  83. memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
  84. OS.write_uuid(UUID);
  85. Triple T = MachO->getArchTriple();
  86. OS << " (" << T.getArchName() << ')';
  87. OS << ' ' << MachO->getFileName() << '\n';
  88. }
  89. }
  90. }
  91. using ContributionCollection =
  92. std::vector<Optional<StrOffsetsContributionDescriptor>>;
  93. // Collect all the contributions to the string offsets table from all units,
  94. // sort them by their starting offsets and remove duplicates.
  95. static ContributionCollection
  96. collectContributionData(DWARFContext::unit_iterator_range Units) {
  97. ContributionCollection Contributions;
  98. for (const auto &U : Units)
  99. if (const auto &C = U->getStringOffsetsTableContribution())
  100. Contributions.push_back(C);
  101. // Sort the contributions so that any invalid ones are placed at
  102. // the start of the contributions vector. This way they are reported
  103. // first.
  104. llvm::sort(Contributions,
  105. [](const Optional<StrOffsetsContributionDescriptor> &L,
  106. const Optional<StrOffsetsContributionDescriptor> &R) {
  107. if (L && R)
  108. return L->Base < R->Base;
  109. return R.hasValue();
  110. });
  111. // Uniquify contributions, as it is possible that units (specifically
  112. // type units in dwo or dwp files) share contributions. We don't want
  113. // to report them more than once.
  114. Contributions.erase(
  115. std::unique(Contributions.begin(), Contributions.end(),
  116. [](const Optional<StrOffsetsContributionDescriptor> &L,
  117. const Optional<StrOffsetsContributionDescriptor> &R) {
  118. if (L && R)
  119. return L->Base == R->Base && L->Size == R->Size;
  120. return false;
  121. }),
  122. Contributions.end());
  123. return Contributions;
  124. }
  125. // Dump a DWARF string offsets section. This may be a DWARF v5 formatted
  126. // string offsets section, where each compile or type unit contributes a
  127. // number of entries (string offsets), with each contribution preceded by
  128. // a header containing size and version number. Alternatively, it may be a
  129. // monolithic series of string offsets, as generated by the pre-DWARF v5
  130. // implementation of split DWARF; however, in that case we still need to
  131. // collect contributions of units because the size of the offsets (4 or 8
  132. // bytes) depends on the format of the referencing unit (DWARF32 or DWARF64).
  133. static void dumpStringOffsetsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
  134. StringRef SectionName,
  135. const DWARFObject &Obj,
  136. const DWARFSection &StringOffsetsSection,
  137. StringRef StringSection,
  138. DWARFContext::unit_iterator_range Units,
  139. bool LittleEndian) {
  140. auto Contributions = collectContributionData(Units);
  141. DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
  142. DataExtractor StrData(StringSection, LittleEndian, 0);
  143. uint64_t SectionSize = StringOffsetsSection.Data.size();
  144. uint64_t Offset = 0;
  145. for (auto &Contribution : Contributions) {
  146. // Report an ill-formed contribution.
  147. if (!Contribution) {
  148. OS << "error: invalid contribution to string offsets table in section ."
  149. << SectionName << ".\n";
  150. return;
  151. }
  152. dwarf::DwarfFormat Format = Contribution->getFormat();
  153. int OffsetDumpWidth = 2 * dwarf::getDwarfOffsetByteSize(Format);
  154. uint16_t Version = Contribution->getVersion();
  155. uint64_t ContributionHeader = Contribution->Base;
  156. // In DWARF v5 there is a contribution header that immediately precedes
  157. // the string offsets base (the location we have previously retrieved from
  158. // the CU DIE's DW_AT_str_offsets attribute). The header is located either
  159. // 8 or 16 bytes before the base, depending on the contribution's format.
  160. if (Version >= 5)
  161. ContributionHeader -= Format == DWARF32 ? 8 : 16;
  162. // Detect overlapping contributions.
  163. if (Offset > ContributionHeader) {
  164. DumpOpts.RecoverableErrorHandler(createStringError(
  165. errc::invalid_argument,
  166. "overlapping contributions to string offsets table in section .%s.",
  167. SectionName.data()));
  168. }
  169. // Report a gap in the table.
  170. if (Offset < ContributionHeader) {
  171. OS << format("0x%8.8" PRIx64 ": Gap, length = ", Offset);
  172. OS << (ContributionHeader - Offset) << "\n";
  173. }
  174. OS << format("0x%8.8" PRIx64 ": ", ContributionHeader);
  175. // In DWARF v5 the contribution size in the descriptor does not equal
  176. // the originally encoded length (it does not contain the length of the
  177. // version field and the padding, a total of 4 bytes). Add them back in
  178. // for reporting.
  179. OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
  180. << ", Format = " << dwarf::FormatString(Format)
  181. << ", Version = " << Version << "\n";
  182. Offset = Contribution->Base;
  183. unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
  184. while (Offset - Contribution->Base < Contribution->Size) {
  185. OS << format("0x%8.8" PRIx64 ": ", Offset);
  186. uint64_t StringOffset =
  187. StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
  188. OS << format("%0*" PRIx64 " ", OffsetDumpWidth, StringOffset);
  189. const char *S = StrData.getCStr(&StringOffset);
  190. if (S)
  191. OS << format("\"%s\"", S);
  192. OS << "\n";
  193. }
  194. }
  195. // Report a gap at the end of the table.
  196. if (Offset < SectionSize) {
  197. OS << format("0x%8.8" PRIx64 ": Gap, length = ", Offset);
  198. OS << (SectionSize - Offset) << "\n";
  199. }
  200. }
  201. // Dump the .debug_addr section.
  202. static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
  203. DIDumpOptions DumpOpts, uint16_t Version,
  204. uint8_t AddrSize) {
  205. uint64_t Offset = 0;
  206. while (AddrData.isValidOffset(Offset)) {
  207. DWARFDebugAddrTable AddrTable;
  208. uint64_t TableOffset = Offset;
  209. if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
  210. DumpOpts.WarningHandler)) {
  211. DumpOpts.RecoverableErrorHandler(std::move(Err));
  212. // Keep going after an error, if we can, assuming that the length field
  213. // could be read. If it couldn't, stop reading the section.
  214. if (auto TableLength = AddrTable.getFullLength()) {
  215. Offset = TableOffset + *TableLength;
  216. continue;
  217. }
  218. break;
  219. }
  220. AddrTable.dump(OS, DumpOpts);
  221. }
  222. }
  223. // Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
  224. static void dumpRnglistsSection(
  225. raw_ostream &OS, DWARFDataExtractor &rnglistData,
  226. llvm::function_ref<Optional<object::SectionedAddress>(uint32_t)>
  227. LookupPooledAddress,
  228. DIDumpOptions DumpOpts) {
  229. uint64_t Offset = 0;
  230. while (rnglistData.isValidOffset(Offset)) {
  231. llvm::DWARFDebugRnglistTable Rnglists;
  232. uint64_t TableOffset = Offset;
  233. if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
  234. DumpOpts.RecoverableErrorHandler(std::move(Err));
  235. uint64_t Length = Rnglists.length();
  236. // Keep going after an error, if we can, assuming that the length field
  237. // could be read. If it couldn't, stop reading the section.
  238. if (Length == 0)
  239. break;
  240. Offset = TableOffset + Length;
  241. } else {
  242. Rnglists.dump(rnglistData, OS, LookupPooledAddress, DumpOpts);
  243. }
  244. }
  245. }
  246. std::unique_ptr<DWARFDebugMacro>
  247. DWARFContext::parseMacroOrMacinfo(MacroSecType SectionType) {
  248. auto Macro = std::make_unique<DWARFDebugMacro>();
  249. auto ParseAndDump = [&](DWARFDataExtractor &Data, bool IsMacro) {
  250. if (Error Err = IsMacro ? Macro->parseMacro(SectionType == MacroSection
  251. ? compile_units()
  252. : dwo_compile_units(),
  253. SectionType == MacroSection
  254. ? getStringExtractor()
  255. : getStringDWOExtractor(),
  256. Data)
  257. : Macro->parseMacinfo(Data)) {
  258. RecoverableErrorHandler(std::move(Err));
  259. Macro = nullptr;
  260. }
  261. };
  262. switch (SectionType) {
  263. case MacinfoSection: {
  264. DWARFDataExtractor Data(DObj->getMacinfoSection(), isLittleEndian(), 0);
  265. ParseAndDump(Data, /*IsMacro=*/false);
  266. break;
  267. }
  268. case MacinfoDwoSection: {
  269. DWARFDataExtractor Data(DObj->getMacinfoDWOSection(), isLittleEndian(), 0);
  270. ParseAndDump(Data, /*IsMacro=*/false);
  271. break;
  272. }
  273. case MacroSection: {
  274. DWARFDataExtractor Data(*DObj, DObj->getMacroSection(), isLittleEndian(),
  275. 0);
  276. ParseAndDump(Data, /*IsMacro=*/true);
  277. break;
  278. }
  279. case MacroDwoSection: {
  280. DWARFDataExtractor Data(DObj->getMacroDWOSection(), isLittleEndian(), 0);
  281. ParseAndDump(Data, /*IsMacro=*/true);
  282. break;
  283. }
  284. }
  285. return Macro;
  286. }
  287. static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
  288. DWARFDataExtractor Data,
  289. const MCRegisterInfo *MRI,
  290. const DWARFObject &Obj,
  291. Optional<uint64_t> DumpOffset) {
  292. uint64_t Offset = 0;
  293. while (Data.isValidOffset(Offset)) {
  294. DWARFListTableHeader Header(".debug_loclists", "locations");
  295. if (Error E = Header.extract(Data, &Offset)) {
  296. DumpOpts.RecoverableErrorHandler(std::move(E));
  297. return;
  298. }
  299. Header.dump(Data, OS, DumpOpts);
  300. uint64_t EndOffset = Header.length() + Header.getHeaderOffset();
  301. Data.setAddressSize(Header.getAddrSize());
  302. DWARFDebugLoclists Loc(Data, Header.getVersion());
  303. if (DumpOffset) {
  304. if (DumpOffset >= Offset && DumpOffset < EndOffset) {
  305. Offset = *DumpOffset;
  306. Loc.dumpLocationList(&Offset, OS, /*BaseAddr=*/None, MRI, Obj, nullptr,
  307. DumpOpts, /*Indent=*/0);
  308. OS << "\n";
  309. return;
  310. }
  311. } else {
  312. Loc.dumpRange(Offset, EndOffset - Offset, OS, MRI, Obj, DumpOpts);
  313. }
  314. Offset = EndOffset;
  315. }
  316. }
  317. static void dumpPubTableSection(raw_ostream &OS, DIDumpOptions DumpOpts,
  318. DWARFDataExtractor Data, bool GnuStyle) {
  319. DWARFDebugPubTable Table;
  320. Table.extract(Data, GnuStyle, DumpOpts.RecoverableErrorHandler);
  321. Table.dump(OS);
  322. }
  323. void DWARFContext::dump(
  324. raw_ostream &OS, DIDumpOptions DumpOpts,
  325. std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
  326. uint64_t DumpType = DumpOpts.DumpType;
  327. StringRef Extension = sys::path::extension(DObj->getFileName());
  328. bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
  329. // Print UUID header.
  330. const auto *ObjFile = DObj->getFile();
  331. if (DumpType & DIDT_UUID)
  332. dumpUUID(OS, *ObjFile);
  333. // Print a header for each explicitly-requested section.
  334. // Otherwise just print one for non-empty sections.
  335. // Only print empty .dwo section headers when dumping a .dwo file.
  336. bool Explicit = DumpType != DIDT_All && !IsDWO;
  337. bool ExplicitDWO = Explicit && IsDWO;
  338. auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
  339. StringRef Section) -> Optional<uint64_t> * {
  340. unsigned Mask = 1U << ID;
  341. bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
  342. if (!Should)
  343. return nullptr;
  344. OS << "\n" << Name << " contents:\n";
  345. return &DumpOffsets[ID];
  346. };
  347. // Dump individual sections.
  348. if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
  349. DObj->getAbbrevSection()))
  350. getDebugAbbrev()->dump(OS);
  351. if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
  352. DObj->getAbbrevDWOSection()))
  353. getDebugAbbrevDWO()->dump(OS);
  354. auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
  355. OS << '\n' << Name << " contents:\n";
  356. if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
  357. for (const auto &U : Units)
  358. U->getDIEForOffset(DumpOffset.getValue())
  359. .dump(OS, 0, DumpOpts.noImplicitRecursion());
  360. else
  361. for (const auto &U : Units)
  362. U->dump(OS, DumpOpts);
  363. };
  364. if ((DumpType & DIDT_DebugInfo)) {
  365. if (Explicit || getNumCompileUnits())
  366. dumpDebugInfo(".debug_info", info_section_units());
  367. if (ExplicitDWO || getNumDWOCompileUnits())
  368. dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
  369. }
  370. auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
  371. OS << '\n' << Name << " contents:\n";
  372. for (const auto &U : Units)
  373. if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
  374. U->getDIEForOffset(*DumpOffset)
  375. .dump(OS, 0, DumpOpts.noImplicitRecursion());
  376. else
  377. U->dump(OS, DumpOpts);
  378. };
  379. if ((DumpType & DIDT_DebugTypes)) {
  380. if (Explicit || getNumTypeUnits())
  381. dumpDebugType(".debug_types", types_section_units());
  382. if (ExplicitDWO || getNumDWOTypeUnits())
  383. dumpDebugType(".debug_types.dwo", dwo_types_section_units());
  384. }
  385. DIDumpOptions LLDumpOpts = DumpOpts;
  386. if (LLDumpOpts.Verbose)
  387. LLDumpOpts.DisplayRawContents = true;
  388. if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
  389. DObj->getLocSection().Data)) {
  390. getDebugLoc()->dump(OS, getRegisterInfo(), *DObj, LLDumpOpts, *Off);
  391. }
  392. if (const auto *Off =
  393. shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
  394. DObj->getLoclistsSection().Data)) {
  395. DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
  396. 0);
  397. dumpLoclistsSection(OS, LLDumpOpts, Data, getRegisterInfo(), *DObj, *Off);
  398. }
  399. if (const auto *Off =
  400. shouldDump(ExplicitDWO, ".debug_loclists.dwo", DIDT_ID_DebugLoclists,
  401. DObj->getLoclistsDWOSection().Data)) {
  402. DWARFDataExtractor Data(*DObj, DObj->getLoclistsDWOSection(),
  403. isLittleEndian(), 0);
  404. dumpLoclistsSection(OS, LLDumpOpts, Data, getRegisterInfo(), *DObj, *Off);
  405. }
  406. if (const auto *Off =
  407. shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
  408. DObj->getLocDWOSection().Data)) {
  409. DWARFDataExtractor Data(*DObj, DObj->getLocDWOSection(), isLittleEndian(),
  410. 4);
  411. DWARFDebugLoclists Loc(Data, /*Version=*/4);
  412. if (*Off) {
  413. uint64_t Offset = **Off;
  414. Loc.dumpLocationList(&Offset, OS,
  415. /*BaseAddr=*/None, getRegisterInfo(), *DObj, nullptr,
  416. LLDumpOpts, /*Indent=*/0);
  417. OS << "\n";
  418. } else {
  419. Loc.dumpRange(0, Data.getData().size(), OS, getRegisterInfo(), *DObj,
  420. LLDumpOpts);
  421. }
  422. }
  423. if (const Optional<uint64_t> *Off =
  424. shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
  425. DObj->getFrameSection().Data)) {
  426. if (Expected<const DWARFDebugFrame *> DF = getDebugFrame())
  427. (*DF)->dump(OS, DumpOpts, getRegisterInfo(), *Off);
  428. else
  429. RecoverableErrorHandler(DF.takeError());
  430. }
  431. if (const Optional<uint64_t> *Off =
  432. shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
  433. DObj->getEHFrameSection().Data)) {
  434. if (Expected<const DWARFDebugFrame *> DF = getEHFrame())
  435. (*DF)->dump(OS, DumpOpts, getRegisterInfo(), *Off);
  436. else
  437. RecoverableErrorHandler(DF.takeError());
  438. }
  439. if (shouldDump(Explicit, ".debug_macro", DIDT_ID_DebugMacro,
  440. DObj->getMacroSection().Data)) {
  441. if (auto Macro = getDebugMacro())
  442. Macro->dump(OS);
  443. }
  444. if (shouldDump(Explicit, ".debug_macro.dwo", DIDT_ID_DebugMacro,
  445. DObj->getMacroDWOSection())) {
  446. if (auto MacroDWO = getDebugMacroDWO())
  447. MacroDWO->dump(OS);
  448. }
  449. if (shouldDump(Explicit, ".debug_macinfo", DIDT_ID_DebugMacro,
  450. DObj->getMacinfoSection())) {
  451. if (auto Macinfo = getDebugMacinfo())
  452. Macinfo->dump(OS);
  453. }
  454. if (shouldDump(Explicit, ".debug_macinfo.dwo", DIDT_ID_DebugMacro,
  455. DObj->getMacinfoDWOSection())) {
  456. if (auto MacinfoDWO = getDebugMacinfoDWO())
  457. MacinfoDWO->dump(OS);
  458. }
  459. if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
  460. DObj->getArangesSection())) {
  461. uint64_t offset = 0;
  462. DWARFDataExtractor arangesData(DObj->getArangesSection(), isLittleEndian(),
  463. 0);
  464. DWARFDebugArangeSet set;
  465. while (arangesData.isValidOffset(offset)) {
  466. if (Error E =
  467. set.extract(arangesData, &offset, DumpOpts.WarningHandler)) {
  468. RecoverableErrorHandler(std::move(E));
  469. break;
  470. }
  471. set.dump(OS);
  472. }
  473. }
  474. auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
  475. DIDumpOptions DumpOpts,
  476. Optional<uint64_t> DumpOffset) {
  477. while (!Parser.done()) {
  478. if (DumpOffset && Parser.getOffset() != *DumpOffset) {
  479. Parser.skip(DumpOpts.WarningHandler, DumpOpts.WarningHandler);
  480. continue;
  481. }
  482. OS << "debug_line[" << format("0x%8.8" PRIx64, Parser.getOffset())
  483. << "]\n";
  484. Parser.parseNext(DumpOpts.WarningHandler, DumpOpts.WarningHandler, &OS,
  485. DumpOpts.Verbose);
  486. }
  487. };
  488. auto DumpStrSection = [&](StringRef Section) {
  489. DataExtractor StrData(Section, isLittleEndian(), 0);
  490. uint64_t Offset = 0;
  491. uint64_t StrOffset = 0;
  492. while (StrData.isValidOffset(Offset)) {
  493. Error Err = Error::success();
  494. const char *CStr = StrData.getCStr(&Offset, &Err);
  495. if (Err) {
  496. DumpOpts.WarningHandler(std::move(Err));
  497. return;
  498. }
  499. OS << format("0x%8.8" PRIx64 ": \"", StrOffset);
  500. OS.write_escaped(CStr);
  501. OS << "\"\n";
  502. StrOffset = Offset;
  503. }
  504. };
  505. if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
  506. DObj->getLineSection().Data)) {
  507. DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
  508. 0);
  509. DWARFDebugLine::SectionParser Parser(LineData, *this, normal_units());
  510. DumpLineSection(Parser, DumpOpts, *Off);
  511. }
  512. if (const auto *Off =
  513. shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
  514. DObj->getLineDWOSection().Data)) {
  515. DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
  516. isLittleEndian(), 0);
  517. DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_units());
  518. DumpLineSection(Parser, DumpOpts, *Off);
  519. }
  520. if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
  521. DObj->getCUIndexSection())) {
  522. getCUIndex().dump(OS);
  523. }
  524. if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
  525. DObj->getTUIndexSection())) {
  526. getTUIndex().dump(OS);
  527. }
  528. if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
  529. DObj->getStrSection()))
  530. DumpStrSection(DObj->getStrSection());
  531. if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
  532. DObj->getStrDWOSection()))
  533. DumpStrSection(DObj->getStrDWOSection());
  534. if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
  535. DObj->getLineStrSection()))
  536. DumpStrSection(DObj->getLineStrSection());
  537. if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
  538. DObj->getAddrSection().Data)) {
  539. DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
  540. isLittleEndian(), 0);
  541. dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
  542. }
  543. if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
  544. DObj->getRangesSection().Data)) {
  545. uint8_t savedAddressByteSize = getCUAddrSize();
  546. DWARFDataExtractor rangesData(*DObj, DObj->getRangesSection(),
  547. isLittleEndian(), savedAddressByteSize);
  548. uint64_t offset = 0;
  549. DWARFDebugRangeList rangeList;
  550. while (rangesData.isValidOffset(offset)) {
  551. if (Error E = rangeList.extract(rangesData, &offset)) {
  552. DumpOpts.RecoverableErrorHandler(std::move(E));
  553. break;
  554. }
  555. rangeList.dump(OS);
  556. }
  557. }
  558. auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
  559. const auto &CUs = compile_units();
  560. auto I = CUs.begin();
  561. if (I == CUs.end())
  562. return None;
  563. return (*I)->getAddrOffsetSectionItem(Index);
  564. };
  565. if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
  566. DObj->getRnglistsSection().Data)) {
  567. DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
  568. isLittleEndian(), 0);
  569. dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
  570. }
  571. if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
  572. DObj->getRnglistsDWOSection().Data)) {
  573. DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
  574. isLittleEndian(), 0);
  575. dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
  576. }
  577. if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
  578. DObj->getPubnamesSection().Data)) {
  579. DWARFDataExtractor PubTableData(*DObj, DObj->getPubnamesSection(),
  580. isLittleEndian(), 0);
  581. dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/false);
  582. }
  583. if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
  584. DObj->getPubtypesSection().Data)) {
  585. DWARFDataExtractor PubTableData(*DObj, DObj->getPubtypesSection(),
  586. isLittleEndian(), 0);
  587. dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/false);
  588. }
  589. if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
  590. DObj->getGnuPubnamesSection().Data)) {
  591. DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubnamesSection(),
  592. isLittleEndian(), 0);
  593. dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/true);
  594. }
  595. if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
  596. DObj->getGnuPubtypesSection().Data)) {
  597. DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubtypesSection(),
  598. isLittleEndian(), 0);
  599. dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/true);
  600. }
  601. if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
  602. DObj->getStrOffsetsSection().Data))
  603. dumpStringOffsetsSection(
  604. OS, DumpOpts, "debug_str_offsets", *DObj, DObj->getStrOffsetsSection(),
  605. DObj->getStrSection(), normal_units(), isLittleEndian());
  606. if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
  607. DObj->getStrOffsetsDWOSection().Data))
  608. dumpStringOffsetsSection(OS, DumpOpts, "debug_str_offsets.dwo", *DObj,
  609. DObj->getStrOffsetsDWOSection(),
  610. DObj->getStrDWOSection(), dwo_units(),
  611. isLittleEndian());
  612. if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
  613. DObj->getGdbIndexSection())) {
  614. getGdbIndex().dump(OS);
  615. }
  616. if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
  617. DObj->getAppleNamesSection().Data))
  618. getAppleNames().dump(OS);
  619. if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
  620. DObj->getAppleTypesSection().Data))
  621. getAppleTypes().dump(OS);
  622. if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
  623. DObj->getAppleNamespacesSection().Data))
  624. getAppleNamespaces().dump(OS);
  625. if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
  626. DObj->getAppleObjCSection().Data))
  627. getAppleObjC().dump(OS);
  628. if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
  629. DObj->getNamesSection().Data))
  630. getDebugNames().dump(OS);
  631. }
  632. DWARFTypeUnit *DWARFContext::getTypeUnitForHash(uint16_t Version, uint64_t Hash,
  633. bool IsDWO) {
  634. parseDWOUnits(LazyParse);
  635. if (const auto &TUI = getTUIndex()) {
  636. if (const auto *R = TUI.getFromHash(Hash))
  637. return dyn_cast_or_null<DWARFTypeUnit>(
  638. DWOUnits.getUnitForIndexEntry(*R));
  639. return nullptr;
  640. }
  641. struct UnitContainers {
  642. const DWARFUnitVector &Units;
  643. Optional<DenseMap<uint64_t, DWARFTypeUnit *>> &Map;
  644. };
  645. UnitContainers Units = IsDWO ? UnitContainers{DWOUnits, DWOTypeUnits}
  646. : UnitContainers{NormalUnits, NormalTypeUnits};
  647. if (!Units.Map) {
  648. Units.Map.emplace();
  649. for (const auto &U : IsDWO ? dwo_units() : normal_units()) {
  650. if (DWARFTypeUnit *TU = dyn_cast<DWARFTypeUnit>(U.get()))
  651. (*Units.Map)[TU->getTypeHash()] = TU;
  652. }
  653. }
  654. return (*Units.Map)[Hash];
  655. }
  656. DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
  657. parseDWOUnits(LazyParse);
  658. if (const auto &CUI = getCUIndex()) {
  659. if (const auto *R = CUI.getFromHash(Hash))
  660. return dyn_cast_or_null<DWARFCompileUnit>(
  661. DWOUnits.getUnitForIndexEntry(*R));
  662. return nullptr;
  663. }
  664. // If there's no index, just search through the CUs in the DWO - there's
  665. // probably only one unless this is something like LTO - though an in-process
  666. // built/cached lookup table could be used in that case to improve repeated
  667. // lookups of different CUs in the DWO.
  668. for (const auto &DWOCU : dwo_compile_units()) {
  669. // Might not have parsed DWO ID yet.
  670. if (!DWOCU->getDWOId()) {
  671. if (Optional<uint64_t> DWOId =
  672. toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
  673. DWOCU->setDWOId(*DWOId);
  674. else
  675. // No DWO ID?
  676. continue;
  677. }
  678. if (DWOCU->getDWOId() == Hash)
  679. return dyn_cast<DWARFCompileUnit>(DWOCU.get());
  680. }
  681. return nullptr;
  682. }
  683. DWARFDie DWARFContext::getDIEForOffset(uint64_t Offset) {
  684. parseNormalUnits();
  685. if (auto *CU = NormalUnits.getUnitForOffset(Offset))
  686. return CU->getDIEForOffset(Offset);
  687. return DWARFDie();
  688. }
  689. bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
  690. bool Success = true;
  691. DWARFVerifier verifier(OS, *this, DumpOpts);
  692. Success &= verifier.handleDebugAbbrev();
  693. if (DumpOpts.DumpType & DIDT_DebugInfo)
  694. Success &= verifier.handleDebugInfo();
  695. if (DumpOpts.DumpType & DIDT_DebugLine)
  696. Success &= verifier.handleDebugLine();
  697. Success &= verifier.handleAccelTables();
  698. return Success;
  699. }
  700. const DWARFUnitIndex &DWARFContext::getCUIndex() {
  701. if (CUIndex)
  702. return *CUIndex;
  703. DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
  704. CUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
  705. CUIndex->parse(CUIndexData);
  706. return *CUIndex;
  707. }
  708. const DWARFUnitIndex &DWARFContext::getTUIndex() {
  709. if (TUIndex)
  710. return *TUIndex;
  711. DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
  712. TUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_EXT_TYPES);
  713. TUIndex->parse(TUIndexData);
  714. return *TUIndex;
  715. }
  716. DWARFGdbIndex &DWARFContext::getGdbIndex() {
  717. if (GdbIndex)
  718. return *GdbIndex;
  719. DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
  720. GdbIndex = std::make_unique<DWARFGdbIndex>();
  721. GdbIndex->parse(GdbIndexData);
  722. return *GdbIndex;
  723. }
  724. const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
  725. if (Abbrev)
  726. return Abbrev.get();
  727. DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
  728. Abbrev.reset(new DWARFDebugAbbrev());
  729. Abbrev->extract(abbrData);
  730. return Abbrev.get();
  731. }
  732. const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
  733. if (AbbrevDWO)
  734. return AbbrevDWO.get();
  735. DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
  736. AbbrevDWO.reset(new DWARFDebugAbbrev());
  737. AbbrevDWO->extract(abbrData);
  738. return AbbrevDWO.get();
  739. }
  740. const DWARFDebugLoc *DWARFContext::getDebugLoc() {
  741. if (Loc)
  742. return Loc.get();
  743. // Assume all units have the same address byte size.
  744. auto LocData =
  745. getNumCompileUnits()
  746. ? DWARFDataExtractor(*DObj, DObj->getLocSection(), isLittleEndian(),
  747. getUnitAtIndex(0)->getAddressByteSize())
  748. : DWARFDataExtractor("", isLittleEndian(), 0);
  749. Loc.reset(new DWARFDebugLoc(std::move(LocData)));
  750. return Loc.get();
  751. }
  752. const DWARFDebugAranges *DWARFContext::getDebugAranges() {
  753. if (Aranges)
  754. return Aranges.get();
  755. Aranges.reset(new DWARFDebugAranges());
  756. Aranges->generate(this);
  757. return Aranges.get();
  758. }
  759. Expected<const DWARFDebugFrame *> DWARFContext::getDebugFrame() {
  760. if (DebugFrame)
  761. return DebugFrame.get();
  762. const DWARFSection &DS = DObj->getFrameSection();
  763. // There's a "bug" in the DWARFv3 standard with respect to the target address
  764. // size within debug frame sections. While DWARF is supposed to be independent
  765. // of its container, FDEs have fields with size being "target address size",
  766. // which isn't specified in DWARF in general. It's only specified for CUs, but
  767. // .eh_frame can appear without a .debug_info section. Follow the example of
  768. // other tools (libdwarf) and extract this from the container (ObjectFile
  769. // provides this information). This problem is fixed in DWARFv4
  770. // See this dwarf-discuss discussion for more details:
  771. // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
  772. DWARFDataExtractor DebugFrameData(*DObj, DS, isLittleEndian(),
  773. DObj->getAddressSize());
  774. auto DF =
  775. std::make_unique<DWARFDebugFrame>(getArch(), /*IsEH=*/false, DS.Address);
  776. if (Error E = DF->parse(DebugFrameData))
  777. return std::move(E);
  778. DebugFrame.swap(DF);
  779. return DebugFrame.get();
  780. }
  781. Expected<const DWARFDebugFrame *> DWARFContext::getEHFrame() {
  782. if (EHFrame)
  783. return EHFrame.get();
  784. const DWARFSection &DS = DObj->getEHFrameSection();
  785. DWARFDataExtractor DebugFrameData(*DObj, DS, isLittleEndian(),
  786. DObj->getAddressSize());
  787. auto DF =
  788. std::make_unique<DWARFDebugFrame>(getArch(), /*IsEH=*/true, DS.Address);
  789. if (Error E = DF->parse(DebugFrameData))
  790. return std::move(E);
  791. DebugFrame.swap(DF);
  792. return DebugFrame.get();
  793. }
  794. const DWARFDebugMacro *DWARFContext::getDebugMacro() {
  795. if (!Macro)
  796. Macro = parseMacroOrMacinfo(MacroSection);
  797. return Macro.get();
  798. }
  799. const DWARFDebugMacro *DWARFContext::getDebugMacroDWO() {
  800. if (!MacroDWO)
  801. MacroDWO = parseMacroOrMacinfo(MacroDwoSection);
  802. return MacroDWO.get();
  803. }
  804. const DWARFDebugMacro *DWARFContext::getDebugMacinfo() {
  805. if (!Macinfo)
  806. Macinfo = parseMacroOrMacinfo(MacinfoSection);
  807. return Macinfo.get();
  808. }
  809. const DWARFDebugMacro *DWARFContext::getDebugMacinfoDWO() {
  810. if (!MacinfoDWO)
  811. MacinfoDWO = parseMacroOrMacinfo(MacinfoDwoSection);
  812. return MacinfoDWO.get();
  813. }
  814. template <typename T>
  815. static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
  816. const DWARFSection &Section, StringRef StringSection,
  817. bool IsLittleEndian) {
  818. if (Cache)
  819. return *Cache;
  820. DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
  821. DataExtractor StrData(StringSection, IsLittleEndian, 0);
  822. Cache.reset(new T(AccelSection, StrData));
  823. if (Error E = Cache->extract())
  824. llvm::consumeError(std::move(E));
  825. return *Cache;
  826. }
  827. const DWARFDebugNames &DWARFContext::getDebugNames() {
  828. return getAccelTable(Names, *DObj, DObj->getNamesSection(),
  829. DObj->getStrSection(), isLittleEndian());
  830. }
  831. const AppleAcceleratorTable &DWARFContext::getAppleNames() {
  832. return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
  833. DObj->getStrSection(), isLittleEndian());
  834. }
  835. const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
  836. return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
  837. DObj->getStrSection(), isLittleEndian());
  838. }
  839. const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
  840. return getAccelTable(AppleNamespaces, *DObj,
  841. DObj->getAppleNamespacesSection(),
  842. DObj->getStrSection(), isLittleEndian());
  843. }
  844. const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
  845. return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
  846. DObj->getStrSection(), isLittleEndian());
  847. }
  848. const DWARFDebugLine::LineTable *
  849. DWARFContext::getLineTableForUnit(DWARFUnit *U) {
  850. Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
  851. getLineTableForUnit(U, WarningHandler);
  852. if (!ExpectedLineTable) {
  853. WarningHandler(ExpectedLineTable.takeError());
  854. return nullptr;
  855. }
  856. return *ExpectedLineTable;
  857. }
  858. Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
  859. DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
  860. if (!Line)
  861. Line.reset(new DWARFDebugLine);
  862. auto UnitDIE = U->getUnitDIE();
  863. if (!UnitDIE)
  864. return nullptr;
  865. auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
  866. if (!Offset)
  867. return nullptr; // No line table for this compile unit.
  868. uint64_t stmtOffset = *Offset + U->getLineTableOffset();
  869. // See if the line table is cached.
  870. if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
  871. return lt;
  872. // Make sure the offset is good before we try to parse.
  873. if (stmtOffset >= U->getLineSection().Data.size())
  874. return nullptr;
  875. // We have to parse it first.
  876. DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
  877. U->getAddressByteSize());
  878. return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
  879. RecoverableErrorHandler);
  880. }
  881. void DWARFContext::parseNormalUnits() {
  882. if (!NormalUnits.empty())
  883. return;
  884. DObj->forEachInfoSections([&](const DWARFSection &S) {
  885. NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
  886. });
  887. NormalUnits.finishedInfoUnits();
  888. DObj->forEachTypesSections([&](const DWARFSection &S) {
  889. NormalUnits.addUnitsForSection(*this, S, DW_SECT_EXT_TYPES);
  890. });
  891. }
  892. void DWARFContext::parseDWOUnits(bool Lazy) {
  893. if (!DWOUnits.empty())
  894. return;
  895. DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
  896. DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
  897. });
  898. DWOUnits.finishedInfoUnits();
  899. DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
  900. DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_EXT_TYPES, Lazy);
  901. });
  902. }
  903. DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) {
  904. parseNormalUnits();
  905. return dyn_cast_or_null<DWARFCompileUnit>(
  906. NormalUnits.getUnitForOffset(Offset));
  907. }
  908. DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
  909. // First, get the offset of the compile unit.
  910. uint64_t CUOffset = getDebugAranges()->findAddress(Address);
  911. // Retrieve the compile unit.
  912. return getCompileUnitForOffset(CUOffset);
  913. }
  914. DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
  915. DIEsForAddress Result;
  916. DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
  917. if (!CU)
  918. return Result;
  919. Result.CompileUnit = CU;
  920. Result.FunctionDIE = CU->getSubroutineForAddress(Address);
  921. std::vector<DWARFDie> Worklist;
  922. Worklist.push_back(Result.FunctionDIE);
  923. while (!Worklist.empty()) {
  924. DWARFDie DIE = Worklist.back();
  925. Worklist.pop_back();
  926. if (!DIE.isValid())
  927. continue;
  928. if (DIE.getTag() == DW_TAG_lexical_block &&
  929. DIE.addressRangeContainsAddress(Address)) {
  930. Result.BlockDIE = DIE;
  931. break;
  932. }
  933. append_range(Worklist, DIE);
  934. }
  935. return Result;
  936. }
  937. /// TODO: change input parameter from "uint64_t Address"
  938. /// into "SectionedAddress Address"
  939. static bool getFunctionNameAndStartLineForAddress(
  940. DWARFCompileUnit *CU, uint64_t Address, FunctionNameKind Kind,
  941. DILineInfoSpecifier::FileLineInfoKind FileNameKind,
  942. std::string &FunctionName, std::string &StartFile, uint32_t &StartLine,
  943. Optional<uint64_t> &StartAddress) {
  944. // The address may correspond to instruction in some inlined function,
  945. // so we have to build the chain of inlined functions and take the
  946. // name of the topmost function in it.
  947. SmallVector<DWARFDie, 4> InlinedChain;
  948. CU->getInlinedChainForAddress(Address, InlinedChain);
  949. if (InlinedChain.empty())
  950. return false;
  951. const DWARFDie &DIE = InlinedChain[0];
  952. bool FoundResult = false;
  953. const char *Name = nullptr;
  954. if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
  955. FunctionName = Name;
  956. FoundResult = true;
  957. }
  958. std::string DeclFile = DIE.getDeclFile(FileNameKind);
  959. if (!DeclFile.empty()) {
  960. StartFile = DeclFile;
  961. FoundResult = true;
  962. }
  963. if (auto DeclLineResult = DIE.getDeclLine()) {
  964. StartLine = DeclLineResult;
  965. FoundResult = true;
  966. }
  967. if (auto LowPcAddr = toSectionedAddress(DIE.find(DW_AT_low_pc)))
  968. StartAddress = LowPcAddr->Address;
  969. return FoundResult;
  970. }
  971. static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
  972. if (auto SizeAttr = Type.find(DW_AT_byte_size))
  973. if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
  974. return Size;
  975. switch (Type.getTag()) {
  976. case DW_TAG_pointer_type:
  977. case DW_TAG_reference_type:
  978. case DW_TAG_rvalue_reference_type:
  979. return PointerSize;
  980. case DW_TAG_ptr_to_member_type: {
  981. if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
  982. if (BaseType.getTag() == DW_TAG_subroutine_type)
  983. return 2 * PointerSize;
  984. return PointerSize;
  985. }
  986. case DW_TAG_const_type:
  987. case DW_TAG_immutable_type:
  988. case DW_TAG_volatile_type:
  989. case DW_TAG_restrict_type:
  990. case DW_TAG_typedef: {
  991. if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
  992. return getTypeSize(BaseType, PointerSize);
  993. break;
  994. }
  995. case DW_TAG_array_type: {
  996. DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type);
  997. if (!BaseType)
  998. return Optional<uint64_t>();
  999. Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
  1000. if (!BaseSize)
  1001. return Optional<uint64_t>();
  1002. uint64_t Size = *BaseSize;
  1003. for (DWARFDie Child : Type) {
  1004. if (Child.getTag() != DW_TAG_subrange_type)
  1005. continue;
  1006. if (auto ElemCountAttr = Child.find(DW_AT_count))
  1007. if (Optional<uint64_t> ElemCount =
  1008. ElemCountAttr->getAsUnsignedConstant())
  1009. Size *= *ElemCount;
  1010. if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
  1011. if (Optional<int64_t> UpperBound =
  1012. UpperBoundAttr->getAsSignedConstant()) {
  1013. int64_t LowerBound = 0;
  1014. if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
  1015. LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
  1016. Size *= *UpperBound - LowerBound + 1;
  1017. }
  1018. }
  1019. return Size;
  1020. }
  1021. default:
  1022. break;
  1023. }
  1024. return Optional<uint64_t>();
  1025. }
  1026. static Optional<int64_t>
  1027. getExpressionFrameOffset(ArrayRef<uint8_t> Expr,
  1028. Optional<unsigned> FrameBaseReg) {
  1029. if (!Expr.empty() &&
  1030. (Expr[0] == DW_OP_fbreg ||
  1031. (FrameBaseReg && Expr[0] == DW_OP_breg0 + *FrameBaseReg))) {
  1032. unsigned Count;
  1033. int64_t Offset = decodeSLEB128(Expr.data() + 1, &Count, Expr.end());
  1034. // A single DW_OP_fbreg or DW_OP_breg.
  1035. if (Expr.size() == Count + 1)
  1036. return Offset;
  1037. // Same + DW_OP_deref (Fortran arrays look like this).
  1038. if (Expr.size() == Count + 2 && Expr[Count + 1] == DW_OP_deref)
  1039. return Offset;
  1040. // Fallthrough. Do not accept ex. (DW_OP_breg W29, DW_OP_stack_value)
  1041. }
  1042. return None;
  1043. }
  1044. void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
  1045. DWARFDie Die, std::vector<DILocal> &Result) {
  1046. if (Die.getTag() == DW_TAG_variable ||
  1047. Die.getTag() == DW_TAG_formal_parameter) {
  1048. DILocal Local;
  1049. if (const char *Name = Subprogram.getSubroutineName(DINameKind::ShortName))
  1050. Local.FunctionName = Name;
  1051. Optional<unsigned> FrameBaseReg;
  1052. if (auto FrameBase = Subprogram.find(DW_AT_frame_base))
  1053. if (Optional<ArrayRef<uint8_t>> Expr = FrameBase->getAsBlock())
  1054. if (!Expr->empty() && (*Expr)[0] >= DW_OP_reg0 &&
  1055. (*Expr)[0] <= DW_OP_reg31) {
  1056. FrameBaseReg = (*Expr)[0] - DW_OP_reg0;
  1057. }
  1058. if (Expected<std::vector<DWARFLocationExpression>> Loc =
  1059. Die.getLocations(DW_AT_location)) {
  1060. for (const auto &Entry : *Loc) {
  1061. if (Optional<int64_t> FrameOffset =
  1062. getExpressionFrameOffset(Entry.Expr, FrameBaseReg)) {
  1063. Local.FrameOffset = *FrameOffset;
  1064. break;
  1065. }
  1066. }
  1067. } else {
  1068. // FIXME: missing DW_AT_location is OK here, but other errors should be
  1069. // reported to the user.
  1070. consumeError(Loc.takeError());
  1071. }
  1072. if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
  1073. Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
  1074. if (auto Origin =
  1075. Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
  1076. Die = Origin;
  1077. if (auto NameAttr = Die.find(DW_AT_name))
  1078. if (Optional<const char *> Name = dwarf::toString(*NameAttr))
  1079. Local.Name = *Name;
  1080. if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
  1081. Local.Size = getTypeSize(Type, getCUAddrSize());
  1082. if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
  1083. if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
  1084. LT->getFileNameByIndex(
  1085. DeclFileAttr->getAsUnsignedConstant().getValue(),
  1086. CU->getCompilationDir(),
  1087. DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
  1088. Local.DeclFile);
  1089. }
  1090. if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
  1091. Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
  1092. Result.push_back(Local);
  1093. return;
  1094. }
  1095. if (Die.getTag() == DW_TAG_inlined_subroutine)
  1096. if (auto Origin =
  1097. Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
  1098. Subprogram = Origin;
  1099. for (auto Child : Die)
  1100. addLocalsForDie(CU, Subprogram, Child, Result);
  1101. }
  1102. std::vector<DILocal>
  1103. DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
  1104. std::vector<DILocal> Result;
  1105. DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
  1106. if (!CU)
  1107. return Result;
  1108. DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
  1109. if (Subprogram.isValid())
  1110. addLocalsForDie(CU, Subprogram, Subprogram, Result);
  1111. return Result;
  1112. }
  1113. DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
  1114. DILineInfoSpecifier Spec) {
  1115. DILineInfo Result;
  1116. DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
  1117. if (!CU)
  1118. return Result;
  1119. getFunctionNameAndStartLineForAddress(
  1120. CU, Address.Address, Spec.FNKind, Spec.FLIKind, Result.FunctionName,
  1121. Result.StartFileName, Result.StartLine, Result.StartAddress);
  1122. if (Spec.FLIKind != FileLineInfoKind::None) {
  1123. if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
  1124. LineTable->getFileLineInfoForAddress(
  1125. {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
  1126. Spec.FLIKind, Result);
  1127. }
  1128. }
  1129. return Result;
  1130. }
  1131. DILineInfoTable DWARFContext::getLineInfoForAddressRange(
  1132. object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
  1133. DILineInfoTable Lines;
  1134. DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
  1135. if (!CU)
  1136. return Lines;
  1137. uint32_t StartLine = 0;
  1138. std::string StartFileName;
  1139. std::string FunctionName(DILineInfo::BadString);
  1140. Optional<uint64_t> StartAddress;
  1141. getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
  1142. Spec.FLIKind, FunctionName,
  1143. StartFileName, StartLine, StartAddress);
  1144. // If the Specifier says we don't need FileLineInfo, just
  1145. // return the top-most function at the starting address.
  1146. if (Spec.FLIKind == FileLineInfoKind::None) {
  1147. DILineInfo Result;
  1148. Result.FunctionName = FunctionName;
  1149. Result.StartFileName = StartFileName;
  1150. Result.StartLine = StartLine;
  1151. Result.StartAddress = StartAddress;
  1152. Lines.push_back(std::make_pair(Address.Address, Result));
  1153. return Lines;
  1154. }
  1155. const DWARFLineTable *LineTable = getLineTableForUnit(CU);
  1156. // Get the index of row we're looking for in the line table.
  1157. std::vector<uint32_t> RowVector;
  1158. if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
  1159. Size, RowVector)) {
  1160. return Lines;
  1161. }
  1162. for (uint32_t RowIndex : RowVector) {
  1163. // Take file number and line/column from the row.
  1164. const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
  1165. DILineInfo Result;
  1166. LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
  1167. Spec.FLIKind, Result.FileName);
  1168. Result.FunctionName = FunctionName;
  1169. Result.Line = Row.Line;
  1170. Result.Column = Row.Column;
  1171. Result.StartFileName = StartFileName;
  1172. Result.StartLine = StartLine;
  1173. Result.StartAddress = StartAddress;
  1174. Lines.push_back(std::make_pair(Row.Address.Address, Result));
  1175. }
  1176. return Lines;
  1177. }
  1178. DIInliningInfo
  1179. DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
  1180. DILineInfoSpecifier Spec) {
  1181. DIInliningInfo InliningInfo;
  1182. DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
  1183. if (!CU)
  1184. return InliningInfo;
  1185. const DWARFLineTable *LineTable = nullptr;
  1186. SmallVector<DWARFDie, 4> InlinedChain;
  1187. CU->getInlinedChainForAddress(Address.Address, InlinedChain);
  1188. if (InlinedChain.size() == 0) {
  1189. // If there is no DIE for address (e.g. it is in unavailable .dwo file),
  1190. // try to at least get file/line info from symbol table.
  1191. if (Spec.FLIKind != FileLineInfoKind::None) {
  1192. DILineInfo Frame;
  1193. LineTable = getLineTableForUnit(CU);
  1194. if (LineTable && LineTable->getFileLineInfoForAddress(
  1195. {Address.Address, Address.SectionIndex},
  1196. CU->getCompilationDir(), Spec.FLIKind, Frame))
  1197. InliningInfo.addFrame(Frame);
  1198. }
  1199. return InliningInfo;
  1200. }
  1201. uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
  1202. for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
  1203. DWARFDie &FunctionDIE = InlinedChain[i];
  1204. DILineInfo Frame;
  1205. // Get function name if necessary.
  1206. if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
  1207. Frame.FunctionName = Name;
  1208. if (auto DeclLineResult = FunctionDIE.getDeclLine())
  1209. Frame.StartLine = DeclLineResult;
  1210. Frame.StartFileName = FunctionDIE.getDeclFile(Spec.FLIKind);
  1211. if (auto LowPcAddr = toSectionedAddress(FunctionDIE.find(DW_AT_low_pc)))
  1212. Frame.StartAddress = LowPcAddr->Address;
  1213. if (Spec.FLIKind != FileLineInfoKind::None) {
  1214. if (i == 0) {
  1215. // For the topmost frame, initialize the line table of this
  1216. // compile unit and fetch file/line info from it.
  1217. LineTable = getLineTableForUnit(CU);
  1218. // For the topmost routine, get file/line info from line table.
  1219. if (LineTable)
  1220. LineTable->getFileLineInfoForAddress(
  1221. {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
  1222. Spec.FLIKind, Frame);
  1223. } else {
  1224. // Otherwise, use call file, call line and call column from
  1225. // previous DIE in inlined chain.
  1226. if (LineTable)
  1227. LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
  1228. Spec.FLIKind, Frame.FileName);
  1229. Frame.Line = CallLine;
  1230. Frame.Column = CallColumn;
  1231. Frame.Discriminator = CallDiscriminator;
  1232. }
  1233. // Get call file/line/column of a current DIE.
  1234. if (i + 1 < n) {
  1235. FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
  1236. CallDiscriminator);
  1237. }
  1238. }
  1239. InliningInfo.addFrame(Frame);
  1240. }
  1241. return InliningInfo;
  1242. }
  1243. std::shared_ptr<DWARFContext>
  1244. DWARFContext::getDWOContext(StringRef AbsolutePath) {
  1245. if (auto S = DWP.lock()) {
  1246. DWARFContext *Ctxt = S->Context.get();
  1247. return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
  1248. }
  1249. std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
  1250. if (auto S = Entry->lock()) {
  1251. DWARFContext *Ctxt = S->Context.get();
  1252. return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
  1253. }
  1254. Expected<OwningBinary<ObjectFile>> Obj = [&] {
  1255. if (!CheckedForDWP) {
  1256. SmallString<128> DWPName;
  1257. auto Obj = object::ObjectFile::createObjectFile(
  1258. this->DWPName.empty()
  1259. ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
  1260. : StringRef(this->DWPName));
  1261. if (Obj) {
  1262. Entry = &DWP;
  1263. return Obj;
  1264. } else {
  1265. CheckedForDWP = true;
  1266. // TODO: Should this error be handled (maybe in a high verbosity mode)
  1267. // before falling back to .dwo files?
  1268. consumeError(Obj.takeError());
  1269. }
  1270. }
  1271. return object::ObjectFile::createObjectFile(AbsolutePath);
  1272. }();
  1273. if (!Obj) {
  1274. // TODO: Actually report errors helpfully.
  1275. consumeError(Obj.takeError());
  1276. return nullptr;
  1277. }
  1278. auto S = std::make_shared<DWOFile>();
  1279. S->File = std::move(Obj.get());
  1280. S->Context = DWARFContext::create(*S->File.getBinary(),
  1281. ProcessDebugRelocations::Ignore);
  1282. *Entry = S;
  1283. auto *Ctxt = S->Context.get();
  1284. return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
  1285. }
  1286. static Error createError(const Twine &Reason, llvm::Error E) {
  1287. return make_error<StringError>(Reason + toString(std::move(E)),
  1288. inconvertibleErrorCode());
  1289. }
  1290. /// SymInfo contains information about symbol: it's address
  1291. /// and section index which is -1LL for absolute symbols.
  1292. struct SymInfo {
  1293. uint64_t Address;
  1294. uint64_t SectionIndex;
  1295. };
  1296. /// Returns the address of symbol relocation used against and a section index.
  1297. /// Used for futher relocations computation. Symbol's section load address is
  1298. static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
  1299. const RelocationRef &Reloc,
  1300. const LoadedObjectInfo *L,
  1301. std::map<SymbolRef, SymInfo> &Cache) {
  1302. SymInfo Ret = {0, (uint64_t)-1LL};
  1303. object::section_iterator RSec = Obj.section_end();
  1304. object::symbol_iterator Sym = Reloc.getSymbol();
  1305. std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
  1306. // First calculate the address of the symbol or section as it appears
  1307. // in the object file
  1308. if (Sym != Obj.symbol_end()) {
  1309. bool New;
  1310. std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
  1311. if (!New)
  1312. return CacheIt->second;
  1313. Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
  1314. if (!SymAddrOrErr)
  1315. return createError("failed to compute symbol address: ",
  1316. SymAddrOrErr.takeError());
  1317. // Also remember what section this symbol is in for later
  1318. auto SectOrErr = Sym->getSection();
  1319. if (!SectOrErr)
  1320. return createError("failed to get symbol section: ",
  1321. SectOrErr.takeError());
  1322. RSec = *SectOrErr;
  1323. Ret.Address = *SymAddrOrErr;
  1324. } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
  1325. RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
  1326. Ret.Address = RSec->getAddress();
  1327. }
  1328. if (RSec != Obj.section_end())
  1329. Ret.SectionIndex = RSec->getIndex();
  1330. // If we are given load addresses for the sections, we need to adjust:
  1331. // SymAddr = (Address of Symbol Or Section in File) -
  1332. // (Address of Section in File) +
  1333. // (Load Address of Section)
  1334. // RSec is now either the section being targeted or the section
  1335. // containing the symbol being targeted. In either case,
  1336. // we need to perform the same computation.
  1337. if (L && RSec != Obj.section_end())
  1338. if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
  1339. Ret.Address += SectionLoadAddress - RSec->getAddress();
  1340. if (CacheIt != Cache.end())
  1341. CacheIt->second = Ret;
  1342. return Ret;
  1343. }
  1344. static bool isRelocScattered(const object::ObjectFile &Obj,
  1345. const RelocationRef &Reloc) {
  1346. const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
  1347. if (!MachObj)
  1348. return false;
  1349. // MachO also has relocations that point to sections and
  1350. // scattered relocations.
  1351. auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
  1352. return MachObj->isRelocationScattered(RelocInfo);
  1353. }
  1354. namespace {
  1355. struct DWARFSectionMap final : public DWARFSection {
  1356. RelocAddrMap Relocs;
  1357. };
  1358. class DWARFObjInMemory final : public DWARFObject {
  1359. bool IsLittleEndian;
  1360. uint8_t AddressSize;
  1361. StringRef FileName;
  1362. const object::ObjectFile *Obj = nullptr;
  1363. std::vector<SectionName> SectionNames;
  1364. using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
  1365. std::map<object::SectionRef, unsigned>>;
  1366. InfoSectionMap InfoSections;
  1367. InfoSectionMap TypesSections;
  1368. InfoSectionMap InfoDWOSections;
  1369. InfoSectionMap TypesDWOSections;
  1370. DWARFSectionMap LocSection;
  1371. DWARFSectionMap LoclistsSection;
  1372. DWARFSectionMap LoclistsDWOSection;
  1373. DWARFSectionMap LineSection;
  1374. DWARFSectionMap RangesSection;
  1375. DWARFSectionMap RnglistsSection;
  1376. DWARFSectionMap StrOffsetsSection;
  1377. DWARFSectionMap LineDWOSection;
  1378. DWARFSectionMap FrameSection;
  1379. DWARFSectionMap EHFrameSection;
  1380. DWARFSectionMap LocDWOSection;
  1381. DWARFSectionMap StrOffsetsDWOSection;
  1382. DWARFSectionMap RangesDWOSection;
  1383. DWARFSectionMap RnglistsDWOSection;
  1384. DWARFSectionMap AddrSection;
  1385. DWARFSectionMap AppleNamesSection;
  1386. DWARFSectionMap AppleTypesSection;
  1387. DWARFSectionMap AppleNamespacesSection;
  1388. DWARFSectionMap AppleObjCSection;
  1389. DWARFSectionMap NamesSection;
  1390. DWARFSectionMap PubnamesSection;
  1391. DWARFSectionMap PubtypesSection;
  1392. DWARFSectionMap GnuPubnamesSection;
  1393. DWARFSectionMap GnuPubtypesSection;
  1394. DWARFSectionMap MacroSection;
  1395. DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
  1396. return StringSwitch<DWARFSectionMap *>(Name)
  1397. .Case("debug_loc", &LocSection)
  1398. .Case("debug_loclists", &LoclistsSection)
  1399. .Case("debug_loclists.dwo", &LoclistsDWOSection)
  1400. .Case("debug_line", &LineSection)
  1401. .Case("debug_frame", &FrameSection)
  1402. .Case("eh_frame", &EHFrameSection)
  1403. .Case("debug_str_offsets", &StrOffsetsSection)
  1404. .Case("debug_ranges", &RangesSection)
  1405. .Case("debug_rnglists", &RnglistsSection)
  1406. .Case("debug_loc.dwo", &LocDWOSection)
  1407. .Case("debug_line.dwo", &LineDWOSection)
  1408. .Case("debug_names", &NamesSection)
  1409. .Case("debug_rnglists.dwo", &RnglistsDWOSection)
  1410. .Case("debug_str_offsets.dwo", &StrOffsetsDWOSection)
  1411. .Case("debug_addr", &AddrSection)
  1412. .Case("apple_names", &AppleNamesSection)
  1413. .Case("debug_pubnames", &PubnamesSection)
  1414. .Case("debug_pubtypes", &PubtypesSection)
  1415. .Case("debug_gnu_pubnames", &GnuPubnamesSection)
  1416. .Case("debug_gnu_pubtypes", &GnuPubtypesSection)
  1417. .Case("apple_types", &AppleTypesSection)
  1418. .Case("apple_namespaces", &AppleNamespacesSection)
  1419. .Case("apple_namespac", &AppleNamespacesSection)
  1420. .Case("apple_objc", &AppleObjCSection)
  1421. .Case("debug_macro", &MacroSection)
  1422. .Default(nullptr);
  1423. }
  1424. StringRef AbbrevSection;
  1425. StringRef ArangesSection;
  1426. StringRef StrSection;
  1427. StringRef MacinfoSection;
  1428. StringRef MacinfoDWOSection;
  1429. StringRef MacroDWOSection;
  1430. StringRef AbbrevDWOSection;
  1431. StringRef StrDWOSection;
  1432. StringRef CUIndexSection;
  1433. StringRef GdbIndexSection;
  1434. StringRef TUIndexSection;
  1435. StringRef LineStrSection;
  1436. // A deque holding section data whose iterators are not invalidated when
  1437. // new decompressed sections are inserted at the end.
  1438. std::deque<SmallString<0>> UncompressedSections;
  1439. StringRef *mapSectionToMember(StringRef Name) {
  1440. if (DWARFSection *Sec = mapNameToDWARFSection(Name))
  1441. return &Sec->Data;
  1442. return StringSwitch<StringRef *>(Name)
  1443. .Case("debug_abbrev", &AbbrevSection)
  1444. .Case("debug_aranges", &ArangesSection)
  1445. .Case("debug_str", &StrSection)
  1446. .Case("debug_macinfo", &MacinfoSection)
  1447. .Case("debug_macinfo.dwo", &MacinfoDWOSection)
  1448. .Case("debug_macro.dwo", &MacroDWOSection)
  1449. .Case("debug_abbrev.dwo", &AbbrevDWOSection)
  1450. .Case("debug_str.dwo", &StrDWOSection)
  1451. .Case("debug_cu_index", &CUIndexSection)
  1452. .Case("debug_tu_index", &TUIndexSection)
  1453. .Case("gdb_index", &GdbIndexSection)
  1454. .Case("debug_line_str", &LineStrSection)
  1455. // Any more debug info sections go here.
  1456. .Default(nullptr);
  1457. }
  1458. /// If Sec is compressed section, decompresses and updates its contents
  1459. /// provided by Data. Otherwise leaves it unchanged.
  1460. Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
  1461. StringRef &Data) {
  1462. if (!Decompressor::isCompressed(Sec))
  1463. return Error::success();
  1464. Expected<Decompressor> Decompressor =
  1465. Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
  1466. if (!Decompressor)
  1467. return Decompressor.takeError();
  1468. SmallString<0> Out;
  1469. if (auto Err = Decompressor->resizeAndDecompress(Out))
  1470. return Err;
  1471. UncompressedSections.push_back(std::move(Out));
  1472. Data = UncompressedSections.back();
  1473. return Error::success();
  1474. }
  1475. public:
  1476. DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
  1477. uint8_t AddrSize, bool IsLittleEndian)
  1478. : IsLittleEndian(IsLittleEndian) {
  1479. for (const auto &SecIt : Sections) {
  1480. if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
  1481. *SectionData = SecIt.second->getBuffer();
  1482. else if (SecIt.first() == "debug_info")
  1483. // Find debug_info and debug_types data by section rather than name as
  1484. // there are multiple, comdat grouped, of these sections.
  1485. InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
  1486. else if (SecIt.first() == "debug_info.dwo")
  1487. InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
  1488. else if (SecIt.first() == "debug_types")
  1489. TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
  1490. else if (SecIt.first() == "debug_types.dwo")
  1491. TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
  1492. }
  1493. }
  1494. DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
  1495. function_ref<void(Error)> HandleError,
  1496. function_ref<void(Error)> HandleWarning,
  1497. DWARFContext::ProcessDebugRelocations RelocAction)
  1498. : IsLittleEndian(Obj.isLittleEndian()),
  1499. AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
  1500. Obj(&Obj) {
  1501. StringMap<unsigned> SectionAmountMap;
  1502. for (const SectionRef &Section : Obj.sections()) {
  1503. StringRef Name;
  1504. if (auto NameOrErr = Section.getName())
  1505. Name = *NameOrErr;
  1506. else
  1507. consumeError(NameOrErr.takeError());
  1508. ++SectionAmountMap[Name];
  1509. SectionNames.push_back({ Name, true });
  1510. // Skip BSS and Virtual sections, they aren't interesting.
  1511. if (Section.isBSS() || Section.isVirtual())
  1512. continue;
  1513. // Skip sections stripped by dsymutil.
  1514. if (Section.isStripped())
  1515. continue;
  1516. StringRef Data;
  1517. Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
  1518. if (!SecOrErr) {
  1519. HandleError(createError("failed to get relocated section: ",
  1520. SecOrErr.takeError()));
  1521. continue;
  1522. }
  1523. // Try to obtain an already relocated version of this section.
  1524. // Else use the unrelocated section from the object file. We'll have to
  1525. // apply relocations ourselves later.
  1526. section_iterator RelocatedSection =
  1527. Obj.isRelocatableObject() ? *SecOrErr : Obj.section_end();
  1528. if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) {
  1529. Expected<StringRef> E = Section.getContents();
  1530. if (E)
  1531. Data = *E;
  1532. else
  1533. // maybeDecompress below will error.
  1534. consumeError(E.takeError());
  1535. }
  1536. if (auto Err = maybeDecompress(Section, Name, Data)) {
  1537. HandleError(createError("failed to decompress '" + Name + "', ",
  1538. std::move(Err)));
  1539. continue;
  1540. }
  1541. // Compressed sections names in GNU style starts from ".z",
  1542. // at this point section is decompressed and we drop compression prefix.
  1543. Name = Name.substr(
  1544. Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
  1545. // Map platform specific debug section names to DWARF standard section
  1546. // names.
  1547. Name = Obj.mapDebugSectionName(Name);
  1548. if (StringRef *SectionData = mapSectionToMember(Name)) {
  1549. *SectionData = Data;
  1550. if (Name == "debug_ranges") {
  1551. // FIXME: Use the other dwo range section when we emit it.
  1552. RangesDWOSection.Data = Data;
  1553. } else if (Name == "debug_frame" || Name == "eh_frame") {
  1554. if (DWARFSection *S = mapNameToDWARFSection(Name))
  1555. S->Address = Section.getAddress();
  1556. }
  1557. } else if (InfoSectionMap *Sections =
  1558. StringSwitch<InfoSectionMap *>(Name)
  1559. .Case("debug_info", &InfoSections)
  1560. .Case("debug_info.dwo", &InfoDWOSections)
  1561. .Case("debug_types", &TypesSections)
  1562. .Case("debug_types.dwo", &TypesDWOSections)
  1563. .Default(nullptr)) {
  1564. // Find debug_info and debug_types data by section rather than name as
  1565. // there are multiple, comdat grouped, of these sections.
  1566. DWARFSectionMap &S = (*Sections)[Section];
  1567. S.Data = Data;
  1568. }
  1569. if (RelocatedSection != Obj.section_end() && Name.contains(".dwo"))
  1570. HandleWarning(
  1571. createError("Unexpected relocations for dwo section " + Name));
  1572. if (RelocatedSection == Obj.section_end() ||
  1573. (RelocAction == DWARFContext::ProcessDebugRelocations::Ignore))
  1574. continue;
  1575. StringRef RelSecName;
  1576. if (auto NameOrErr = RelocatedSection->getName())
  1577. RelSecName = *NameOrErr;
  1578. else
  1579. consumeError(NameOrErr.takeError());
  1580. // If the section we're relocating was relocated already by the JIT,
  1581. // then we used the relocated version above, so we do not need to process
  1582. // relocations for it now.
  1583. StringRef RelSecData;
  1584. if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
  1585. continue;
  1586. // In Mach-o files, the relocations do not need to be applied if
  1587. // there is no load offset to apply. The value read at the
  1588. // relocation point already factors in the section address
  1589. // (actually applying the relocations will produce wrong results
  1590. // as the section address will be added twice).
  1591. if (!L && isa<MachOObjectFile>(&Obj))
  1592. continue;
  1593. RelSecName = RelSecName.substr(
  1594. RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
  1595. // TODO: Add support for relocations in other sections as needed.
  1596. // Record relocations for the debug_info and debug_line sections.
  1597. DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
  1598. RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
  1599. if (!Map) {
  1600. // Find debug_info and debug_types relocs by section rather than name
  1601. // as there are multiple, comdat grouped, of these sections.
  1602. if (RelSecName == "debug_info")
  1603. Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
  1604. .Relocs;
  1605. else if (RelSecName == "debug_types")
  1606. Map =
  1607. &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
  1608. .Relocs;
  1609. else
  1610. continue;
  1611. }
  1612. if (Section.relocation_begin() == Section.relocation_end())
  1613. continue;
  1614. // Symbol to [address, section index] cache mapping.
  1615. std::map<SymbolRef, SymInfo> AddrCache;
  1616. SupportsRelocation Supports;
  1617. RelocationResolver Resolver;
  1618. std::tie(Supports, Resolver) = getRelocationResolver(Obj);
  1619. for (const RelocationRef &Reloc : Section.relocations()) {
  1620. // FIXME: it's not clear how to correctly handle scattered
  1621. // relocations.
  1622. if (isRelocScattered(Obj, Reloc))
  1623. continue;
  1624. Expected<SymInfo> SymInfoOrErr =
  1625. getSymbolInfo(Obj, Reloc, L, AddrCache);
  1626. if (!SymInfoOrErr) {
  1627. HandleError(SymInfoOrErr.takeError());
  1628. continue;
  1629. }
  1630. // Check if Resolver can handle this relocation type early so as not to
  1631. // handle invalid cases in DWARFDataExtractor.
  1632. //
  1633. // TODO Don't store Resolver in every RelocAddrEntry.
  1634. if (Supports && Supports(Reloc.getType())) {
  1635. auto I = Map->try_emplace(
  1636. Reloc.getOffset(),
  1637. RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
  1638. SymInfoOrErr->Address,
  1639. Optional<object::RelocationRef>(), 0, Resolver});
  1640. // If we didn't successfully insert that's because we already had a
  1641. // relocation for that offset. Store it as a second relocation in the
  1642. // same RelocAddrEntry instead.
  1643. if (!I.second) {
  1644. RelocAddrEntry &entry = I.first->getSecond();
  1645. if (entry.Reloc2) {
  1646. HandleError(createError(
  1647. "At most two relocations per offset are supported"));
  1648. }
  1649. entry.Reloc2 = Reloc;
  1650. entry.SymbolValue2 = SymInfoOrErr->Address;
  1651. }
  1652. } else {
  1653. SmallString<32> Type;
  1654. Reloc.getTypeName(Type);
  1655. // FIXME: Support more relocations & change this to an error
  1656. HandleWarning(
  1657. createError("failed to compute relocation: " + Type + ", ",
  1658. errorCodeToError(object_error::parse_failed)));
  1659. }
  1660. }
  1661. }
  1662. for (SectionName &S : SectionNames)
  1663. if (SectionAmountMap[S.Name] > 1)
  1664. S.IsNameUnique = false;
  1665. }
  1666. Optional<RelocAddrEntry> find(const DWARFSection &S,
  1667. uint64_t Pos) const override {
  1668. auto &Sec = static_cast<const DWARFSectionMap &>(S);
  1669. RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
  1670. if (AI == Sec.Relocs.end())
  1671. return None;
  1672. return AI->second;
  1673. }
  1674. const object::ObjectFile *getFile() const override { return Obj; }
  1675. ArrayRef<SectionName> getSectionNames() const override {
  1676. return SectionNames;
  1677. }
  1678. bool isLittleEndian() const override { return IsLittleEndian; }
  1679. StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
  1680. const DWARFSection &getLineDWOSection() const override {
  1681. return LineDWOSection;
  1682. }
  1683. const DWARFSection &getLocDWOSection() const override {
  1684. return LocDWOSection;
  1685. }
  1686. StringRef getStrDWOSection() const override { return StrDWOSection; }
  1687. const DWARFSection &getStrOffsetsDWOSection() const override {
  1688. return StrOffsetsDWOSection;
  1689. }
  1690. const DWARFSection &getRangesDWOSection() const override {
  1691. return RangesDWOSection;
  1692. }
  1693. const DWARFSection &getRnglistsDWOSection() const override {
  1694. return RnglistsDWOSection;
  1695. }
  1696. const DWARFSection &getLoclistsDWOSection() const override {
  1697. return LoclistsDWOSection;
  1698. }
  1699. const DWARFSection &getAddrSection() const override { return AddrSection; }
  1700. StringRef getCUIndexSection() const override { return CUIndexSection; }
  1701. StringRef getGdbIndexSection() const override { return GdbIndexSection; }
  1702. StringRef getTUIndexSection() const override { return TUIndexSection; }
  1703. // DWARF v5
  1704. const DWARFSection &getStrOffsetsSection() const override {
  1705. return StrOffsetsSection;
  1706. }
  1707. StringRef getLineStrSection() const override { return LineStrSection; }
  1708. // Sections for DWARF5 split dwarf proposal.
  1709. void forEachInfoDWOSections(
  1710. function_ref<void(const DWARFSection &)> F) const override {
  1711. for (auto &P : InfoDWOSections)
  1712. F(P.second);
  1713. }
  1714. void forEachTypesDWOSections(
  1715. function_ref<void(const DWARFSection &)> F) const override {
  1716. for (auto &P : TypesDWOSections)
  1717. F(P.second);
  1718. }
  1719. StringRef getAbbrevSection() const override { return AbbrevSection; }
  1720. const DWARFSection &getLocSection() const override { return LocSection; }
  1721. const DWARFSection &getLoclistsSection() const override { return LoclistsSection; }
  1722. StringRef getArangesSection() const override { return ArangesSection; }
  1723. const DWARFSection &getFrameSection() const override {
  1724. return FrameSection;
  1725. }
  1726. const DWARFSection &getEHFrameSection() const override {
  1727. return EHFrameSection;
  1728. }
  1729. const DWARFSection &getLineSection() const override { return LineSection; }
  1730. StringRef getStrSection() const override { return StrSection; }
  1731. const DWARFSection &getRangesSection() const override { return RangesSection; }
  1732. const DWARFSection &getRnglistsSection() const override {
  1733. return RnglistsSection;
  1734. }
  1735. const DWARFSection &getMacroSection() const override { return MacroSection; }
  1736. StringRef getMacroDWOSection() const override { return MacroDWOSection; }
  1737. StringRef getMacinfoSection() const override { return MacinfoSection; }
  1738. StringRef getMacinfoDWOSection() const override { return MacinfoDWOSection; }
  1739. const DWARFSection &getPubnamesSection() const override { return PubnamesSection; }
  1740. const DWARFSection &getPubtypesSection() const override { return PubtypesSection; }
  1741. const DWARFSection &getGnuPubnamesSection() const override {
  1742. return GnuPubnamesSection;
  1743. }
  1744. const DWARFSection &getGnuPubtypesSection() const override {
  1745. return GnuPubtypesSection;
  1746. }
  1747. const DWARFSection &getAppleNamesSection() const override {
  1748. return AppleNamesSection;
  1749. }
  1750. const DWARFSection &getAppleTypesSection() const override {
  1751. return AppleTypesSection;
  1752. }
  1753. const DWARFSection &getAppleNamespacesSection() const override {
  1754. return AppleNamespacesSection;
  1755. }
  1756. const DWARFSection &getAppleObjCSection() const override {
  1757. return AppleObjCSection;
  1758. }
  1759. const DWARFSection &getNamesSection() const override {
  1760. return NamesSection;
  1761. }
  1762. StringRef getFileName() const override { return FileName; }
  1763. uint8_t getAddressSize() const override { return AddressSize; }
  1764. void forEachInfoSections(
  1765. function_ref<void(const DWARFSection &)> F) const override {
  1766. for (auto &P : InfoSections)
  1767. F(P.second);
  1768. }
  1769. void forEachTypesSections(
  1770. function_ref<void(const DWARFSection &)> F) const override {
  1771. for (auto &P : TypesSections)
  1772. F(P.second);
  1773. }
  1774. };
  1775. } // namespace
  1776. std::unique_ptr<DWARFContext>
  1777. DWARFContext::create(const object::ObjectFile &Obj,
  1778. ProcessDebugRelocations RelocAction,
  1779. const LoadedObjectInfo *L, std::string DWPName,
  1780. std::function<void(Error)> RecoverableErrorHandler,
  1781. std::function<void(Error)> WarningHandler) {
  1782. auto DObj = std::make_unique<DWARFObjInMemory>(
  1783. Obj, L, RecoverableErrorHandler, WarningHandler, RelocAction);
  1784. return std::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName),
  1785. RecoverableErrorHandler,
  1786. WarningHandler);
  1787. }
  1788. std::unique_ptr<DWARFContext>
  1789. DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
  1790. uint8_t AddrSize, bool isLittleEndian,
  1791. std::function<void(Error)> RecoverableErrorHandler,
  1792. std::function<void(Error)> WarningHandler) {
  1793. auto DObj =
  1794. std::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
  1795. return std::make_unique<DWARFContext>(
  1796. std::move(DObj), "", RecoverableErrorHandler, WarningHandler);
  1797. }
  1798. Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
  1799. // Detect the architecture from the object file. We usually don't need OS
  1800. // info to lookup a target and create register info.
  1801. Triple TT;
  1802. TT.setArch(Triple::ArchType(Obj.getArch()));
  1803. TT.setVendor(Triple::UnknownVendor);
  1804. TT.setOS(Triple::UnknownOS);
  1805. std::string TargetLookupError;
  1806. const Target *TheTarget =
  1807. TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
  1808. if (!TargetLookupError.empty())
  1809. return createStringError(errc::invalid_argument,
  1810. TargetLookupError.c_str());
  1811. RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
  1812. return Error::success();
  1813. }
  1814. uint8_t DWARFContext::getCUAddrSize() {
  1815. // In theory, different compile units may have different address byte
  1816. // sizes, but for simplicity we just use the address byte size of the
  1817. // first compile unit. In practice the address size field is repeated across
  1818. // various DWARF headers (at least in version 5) to make it easier to dump
  1819. // them independently, not to enable varying the address size.
  1820. auto CUs = compile_units();
  1821. return CUs.empty() ? 0 : (*CUs.begin())->getAddressByteSize();
  1822. }