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