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/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/TargetRegistry.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, 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, 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, compile_units(),
552                                          type_units());
553     DumpLineSection(Parser, DumpOpts, *Off);
554   }
555 
556   if (const auto *Off =
557           shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
558                      DObj->getLineDWOSection().Data)) {
559     DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
560                                 isLittleEndian(), 0);
561     DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
562                                          dwo_type_units());
563     DumpLineSection(Parser, DumpOpts, *Off);
564   }
565 
566   if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
567                  DObj->getCUIndexSection())) {
568     getCUIndex().dump(OS);
569   }
570 
571   if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
572                  DObj->getTUIndexSection())) {
573     getTUIndex().dump(OS);
574   }
575 
576   if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
577                  DObj->getStrSection()))
578     DumpStrSection(DObj->getStrSection());
579 
580   if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
581                  DObj->getStrDWOSection()))
582     DumpStrSection(DObj->getStrDWOSection());
583 
584   if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
585                  DObj->getLineStrSection()))
586     DumpStrSection(DObj->getLineStrSection());
587 
588   if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
589                  DObj->getAddrSection().Data)) {
590     DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
591                                    isLittleEndian(), 0);
592     dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
593   }
594 
595   if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
596                  DObj->getRangesSection().Data)) {
597     uint8_t savedAddressByteSize = getCUAddrSize();
598     DWARFDataExtractor rangesData(*DObj, DObj->getRangesSection(),
599                                   isLittleEndian(), savedAddressByteSize);
600     uint64_t offset = 0;
601     DWARFDebugRangeList rangeList;
602     while (rangesData.isValidOffset(offset)) {
603       if (Error E = rangeList.extract(rangesData, &offset)) {
604         DumpOpts.RecoverableErrorHandler(std::move(E));
605         break;
606       }
607       rangeList.dump(OS);
608     }
609   }
610 
611   auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
612     const auto &CUs = compile_units();
613     auto I = CUs.begin();
614     if (I == CUs.end())
615       return None;
616     return (*I)->getAddrOffsetSectionItem(Index);
617   };
618 
619   if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
620                  DObj->getRnglistsSection().Data)) {
621     DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
622                                    isLittleEndian(), 0);
623     dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
624   }
625 
626   if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
627                  DObj->getRnglistsDWOSection().Data)) {
628     DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
629                                    isLittleEndian(), 0);
630     dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
631   }
632 
633   if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
634                  DObj->getPubnamesSection().Data)) {
635     DWARFDataExtractor PubTableData(*DObj, DObj->getPubnamesSection(),
636                                     isLittleEndian(), 0);
637     dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/false);
638   }
639 
640   if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
641                  DObj->getPubtypesSection().Data)) {
642     DWARFDataExtractor PubTableData(*DObj, DObj->getPubtypesSection(),
643                                     isLittleEndian(), 0);
644     dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/false);
645   }
646 
647   if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
648                  DObj->getGnuPubnamesSection().Data)) {
649     DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubnamesSection(),
650                                     isLittleEndian(), 0);
651     dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/true);
652   }
653 
654   if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
655                  DObj->getGnuPubtypesSection().Data)) {
656     DWARFDataExtractor PubTableData(*DObj, DObj->getGnuPubtypesSection(),
657                                     isLittleEndian(), 0);
658     dumpPubTableSection(OS, DumpOpts, PubTableData, /*GnuStyle=*/true);
659   }
660 
661   if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
662                  DObj->getStrOffsetsSection().Data))
663     dumpStringOffsetsSection(
664         OS, DumpOpts, "debug_str_offsets", *DObj, DObj->getStrOffsetsSection(),
665         DObj->getStrSection(), normal_units(), isLittleEndian());
666   if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
667                  DObj->getStrOffsetsDWOSection().Data))
668     dumpStringOffsetsSection(OS, DumpOpts, "debug_str_offsets.dwo", *DObj,
669                              DObj->getStrOffsetsDWOSection(),
670                              DObj->getStrDWOSection(), dwo_units(),
671                              isLittleEndian());
672 
673   if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
674                  DObj->getGdbIndexSection())) {
675     getGdbIndex().dump(OS);
676   }
677 
678   if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
679                  DObj->getAppleNamesSection().Data))
680     getAppleNames().dump(OS);
681 
682   if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
683                  DObj->getAppleTypesSection().Data))
684     getAppleTypes().dump(OS);
685 
686   if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
687                  DObj->getAppleNamespacesSection().Data))
688     getAppleNamespaces().dump(OS);
689 
690   if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
691                  DObj->getAppleObjCSection().Data))
692     getAppleObjC().dump(OS);
693   if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
694                  DObj->getNamesSection().Data))
695     getDebugNames().dump(OS);
696 }
697 
698 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
699   parseDWOUnits(LazyParse);
700 
701   if (const auto &CUI = getCUIndex()) {
702     if (const auto *R = CUI.getFromHash(Hash))
703       return dyn_cast_or_null<DWARFCompileUnit>(
704           DWOUnits.getUnitForIndexEntry(*R));
705     return nullptr;
706   }
707 
708   // If there's no index, just search through the CUs in the DWO - there's
709   // probably only one unless this is something like LTO - though an in-process
710   // built/cached lookup table could be used in that case to improve repeated
711   // lookups of different CUs in the DWO.
712   for (const auto &DWOCU : dwo_compile_units()) {
713     // Might not have parsed DWO ID yet.
714     if (!DWOCU->getDWOId()) {
715       if (Optional<uint64_t> DWOId =
716           toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
717         DWOCU->setDWOId(*DWOId);
718       else
719         // No DWO ID?
720         continue;
721     }
722     if (DWOCU->getDWOId() == Hash)
723       return dyn_cast<DWARFCompileUnit>(DWOCU.get());
724   }
725   return nullptr;
726 }
727 
728 DWARFDie DWARFContext::getDIEForOffset(uint64_t Offset) {
729   parseNormalUnits();
730   if (auto *CU = NormalUnits.getUnitForOffset(Offset))
731     return CU->getDIEForOffset(Offset);
732   return DWARFDie();
733 }
734 
735 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
736   bool Success = true;
737   DWARFVerifier verifier(OS, *this, DumpOpts);
738 
739   Success &= verifier.handleDebugAbbrev();
740   if (DumpOpts.DumpType & DIDT_DebugInfo)
741     Success &= verifier.handleDebugInfo();
742   if (DumpOpts.DumpType & DIDT_DebugLine)
743     Success &= verifier.handleDebugLine();
744   Success &= verifier.handleAccelTables();
745   return Success;
746 }
747 
748 const DWARFUnitIndex &DWARFContext::getCUIndex() {
749   if (CUIndex)
750     return *CUIndex;
751 
752   DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
753 
754   CUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
755   CUIndex->parse(CUIndexData);
756   return *CUIndex;
757 }
758 
759 const DWARFUnitIndex &DWARFContext::getTUIndex() {
760   if (TUIndex)
761     return *TUIndex;
762 
763   DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
764 
765   TUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_EXT_TYPES);
766   TUIndex->parse(TUIndexData);
767   return *TUIndex;
768 }
769 
770 DWARFGdbIndex &DWARFContext::getGdbIndex() {
771   if (GdbIndex)
772     return *GdbIndex;
773 
774   DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
775   GdbIndex = std::make_unique<DWARFGdbIndex>();
776   GdbIndex->parse(GdbIndexData);
777   return *GdbIndex;
778 }
779 
780 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
781   if (Abbrev)
782     return Abbrev.get();
783 
784   DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
785 
786   Abbrev.reset(new DWARFDebugAbbrev());
787   Abbrev->extract(abbrData);
788   return Abbrev.get();
789 }
790 
791 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
792   if (AbbrevDWO)
793     return AbbrevDWO.get();
794 
795   DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
796   AbbrevDWO.reset(new DWARFDebugAbbrev());
797   AbbrevDWO->extract(abbrData);
798   return AbbrevDWO.get();
799 }
800 
801 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
802   if (Loc)
803     return Loc.get();
804 
805   // Assume all units have the same address byte size.
806   auto LocData =
807       getNumCompileUnits()
808           ? DWARFDataExtractor(*DObj, DObj->getLocSection(), isLittleEndian(),
809                                getUnitAtIndex(0)->getAddressByteSize())
810           : DWARFDataExtractor("", isLittleEndian(), 0);
811   Loc.reset(new DWARFDebugLoc(std::move(LocData)));
812   return Loc.get();
813 }
814 
815 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
816   if (Aranges)
817     return Aranges.get();
818 
819   Aranges.reset(new DWARFDebugAranges());
820   Aranges->generate(this);
821   return Aranges.get();
822 }
823 
824 Expected<const DWARFDebugFrame *> DWARFContext::getDebugFrame() {
825   if (DebugFrame)
826     return DebugFrame.get();
827 
828   // There's a "bug" in the DWARFv3 standard with respect to the target address
829   // size within debug frame sections. While DWARF is supposed to be independent
830   // of its container, FDEs have fields with size being "target address size",
831   // which isn't specified in DWARF in general. It's only specified for CUs, but
832   // .eh_frame can appear without a .debug_info section. Follow the example of
833   // other tools (libdwarf) and extract this from the container (ObjectFile
834   // provides this information). This problem is fixed in DWARFv4
835   // See this dwarf-discuss discussion for more details:
836   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
837   DWARFDataExtractor debugFrameData(*DObj, DObj->getFrameSection(),
838                                     isLittleEndian(), DObj->getAddressSize());
839   auto DF = std::make_unique<DWARFDebugFrame>(getArch(), /*IsEH=*/false);
840   if (Error E = DF->parse(debugFrameData))
841     return std::move(E);
842 
843   DebugFrame.swap(DF);
844   return DebugFrame.get();
845 }
846 
847 Expected<const DWARFDebugFrame *> DWARFContext::getEHFrame() {
848   if (EHFrame)
849     return EHFrame.get();
850 
851   DWARFDataExtractor debugFrameData(*DObj, DObj->getEHFrameSection(),
852                                     isLittleEndian(), DObj->getAddressSize());
853 
854   auto DF = std::make_unique<DWARFDebugFrame>(getArch(), /*IsEH=*/true);
855   if (Error E = DF->parse(debugFrameData))
856     return std::move(E);
857   DebugFrame.swap(DF);
858   return DebugFrame.get();
859 }
860 
861 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
862   if (!Macro)
863     Macro = parseMacroOrMacinfo(MacroSection);
864   return Macro.get();
865 }
866 
867 const DWARFDebugMacro *DWARFContext::getDebugMacroDWO() {
868   if (!MacroDWO)
869     MacroDWO = parseMacroOrMacinfo(MacroDwoSection);
870   return MacroDWO.get();
871 }
872 
873 const DWARFDebugMacro *DWARFContext::getDebugMacinfo() {
874   if (!Macinfo)
875     Macinfo = parseMacroOrMacinfo(MacinfoSection);
876   return Macinfo.get();
877 }
878 
879 const DWARFDebugMacro *DWARFContext::getDebugMacinfoDWO() {
880   if (!MacinfoDWO)
881     MacinfoDWO = parseMacroOrMacinfo(MacinfoDwoSection);
882   return MacinfoDWO.get();
883 }
884 
885 template <typename T>
886 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
887                         const DWARFSection &Section, StringRef StringSection,
888                         bool IsLittleEndian) {
889   if (Cache)
890     return *Cache;
891   DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
892   DataExtractor StrData(StringSection, IsLittleEndian, 0);
893   Cache.reset(new T(AccelSection, StrData));
894   if (Error E = Cache->extract())
895     llvm::consumeError(std::move(E));
896   return *Cache;
897 }
898 
899 const DWARFDebugNames &DWARFContext::getDebugNames() {
900   return getAccelTable(Names, *DObj, DObj->getNamesSection(),
901                        DObj->getStrSection(), isLittleEndian());
902 }
903 
904 const AppleAcceleratorTable &DWARFContext::getAppleNames() {
905   return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
906                        DObj->getStrSection(), isLittleEndian());
907 }
908 
909 const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
910   return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
911                        DObj->getStrSection(), isLittleEndian());
912 }
913 
914 const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
915   return getAccelTable(AppleNamespaces, *DObj,
916                        DObj->getAppleNamespacesSection(),
917                        DObj->getStrSection(), isLittleEndian());
918 }
919 
920 const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
921   return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
922                        DObj->getStrSection(), isLittleEndian());
923 }
924 
925 const DWARFDebugLine::LineTable *
926 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
927   Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
928       getLineTableForUnit(U, WarningHandler);
929   if (!ExpectedLineTable) {
930     WarningHandler(ExpectedLineTable.takeError());
931     return nullptr;
932   }
933   return *ExpectedLineTable;
934 }
935 
936 Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
937     DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
938   if (!Line)
939     Line.reset(new DWARFDebugLine);
940 
941   auto UnitDIE = U->getUnitDIE();
942   if (!UnitDIE)
943     return nullptr;
944 
945   auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
946   if (!Offset)
947     return nullptr; // No line table for this compile unit.
948 
949   uint64_t stmtOffset = *Offset + U->getLineTableOffset();
950   // See if the line table is cached.
951   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
952     return lt;
953 
954   // Make sure the offset is good before we try to parse.
955   if (stmtOffset >= U->getLineSection().Data.size())
956     return nullptr;
957 
958   // We have to parse it first.
959   DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
960                               U->getAddressByteSize());
961   return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
962                                    RecoverableErrorHandler);
963 }
964 
965 void DWARFContext::parseNormalUnits() {
966   if (!NormalUnits.empty())
967     return;
968   DObj->forEachInfoSections([&](const DWARFSection &S) {
969     NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
970   });
971   NormalUnits.finishedInfoUnits();
972   DObj->forEachTypesSections([&](const DWARFSection &S) {
973     NormalUnits.addUnitsForSection(*this, S, DW_SECT_EXT_TYPES);
974   });
975 }
976 
977 void DWARFContext::parseDWOUnits(bool Lazy) {
978   if (!DWOUnits.empty())
979     return;
980   DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
981     DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
982   });
983   DWOUnits.finishedInfoUnits();
984   DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
985     DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_EXT_TYPES, Lazy);
986   });
987 }
988 
989 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) {
990   parseNormalUnits();
991   return dyn_cast_or_null<DWARFCompileUnit>(
992       NormalUnits.getUnitForOffset(Offset));
993 }
994 
995 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
996   // First, get the offset of the compile unit.
997   uint64_t CUOffset = getDebugAranges()->findAddress(Address);
998   // Retrieve the compile unit.
999   return getCompileUnitForOffset(CUOffset);
1000 }
1001 
1002 DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
1003   DIEsForAddress Result;
1004 
1005   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
1006   if (!CU)
1007     return Result;
1008 
1009   Result.CompileUnit = CU;
1010   Result.FunctionDIE = CU->getSubroutineForAddress(Address);
1011 
1012   std::vector<DWARFDie> Worklist;
1013   Worklist.push_back(Result.FunctionDIE);
1014   while (!Worklist.empty()) {
1015     DWARFDie DIE = Worklist.back();
1016     Worklist.pop_back();
1017 
1018     if (!DIE.isValid())
1019       continue;
1020 
1021     if (DIE.getTag() == DW_TAG_lexical_block &&
1022         DIE.addressRangeContainsAddress(Address)) {
1023       Result.BlockDIE = DIE;
1024       break;
1025     }
1026 
1027     for (auto Child : DIE)
1028       Worklist.push_back(Child);
1029   }
1030 
1031   return Result;
1032 }
1033 
1034 /// TODO: change input parameter from "uint64_t Address"
1035 ///       into "SectionedAddress Address"
1036 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
1037                                                   uint64_t Address,
1038                                                   FunctionNameKind Kind,
1039                                                   DILineInfoSpecifier::FileLineInfoKind FileNameKind,
1040                                                   std::string &FunctionName,
1041                                                   std::string &StartFile,
1042                                                   uint32_t &StartLine) {
1043   // The address may correspond to instruction in some inlined function,
1044   // so we have to build the chain of inlined functions and take the
1045   // name of the topmost function in it.
1046   SmallVector<DWARFDie, 4> InlinedChain;
1047   CU->getInlinedChainForAddress(Address, InlinedChain);
1048   if (InlinedChain.empty())
1049     return false;
1050 
1051   const DWARFDie &DIE = InlinedChain[0];
1052   bool FoundResult = false;
1053   const char *Name = nullptr;
1054   if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
1055     FunctionName = Name;
1056     FoundResult = true;
1057   }
1058   std::string DeclFile = DIE.getDeclFile(FileNameKind);
1059   if (!DeclFile.empty()) {
1060     StartFile = DeclFile;
1061     FoundResult = true;
1062   }
1063   if (auto DeclLineResult = DIE.getDeclLine()) {
1064     StartLine = DeclLineResult;
1065     FoundResult = true;
1066   }
1067 
1068   return FoundResult;
1069 }
1070 
1071 static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
1072   if (auto SizeAttr = Type.find(DW_AT_byte_size))
1073     if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
1074       return Size;
1075 
1076   switch (Type.getTag()) {
1077   case DW_TAG_pointer_type:
1078   case DW_TAG_reference_type:
1079   case DW_TAG_rvalue_reference_type:
1080     return PointerSize;
1081   case DW_TAG_ptr_to_member_type: {
1082     if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
1083       if (BaseType.getTag() == DW_TAG_subroutine_type)
1084         return 2 * PointerSize;
1085     return PointerSize;
1086   }
1087   case DW_TAG_const_type:
1088   case DW_TAG_volatile_type:
1089   case DW_TAG_restrict_type:
1090   case DW_TAG_typedef: {
1091     if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
1092       return getTypeSize(BaseType, PointerSize);
1093     break;
1094   }
1095   case DW_TAG_array_type: {
1096     DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type);
1097     if (!BaseType)
1098       return Optional<uint64_t>();
1099     Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
1100     if (!BaseSize)
1101       return Optional<uint64_t>();
1102     uint64_t Size = *BaseSize;
1103     for (DWARFDie Child : Type) {
1104       if (Child.getTag() != DW_TAG_subrange_type)
1105         continue;
1106 
1107       if (auto ElemCountAttr = Child.find(DW_AT_count))
1108         if (Optional<uint64_t> ElemCount =
1109                 ElemCountAttr->getAsUnsignedConstant())
1110           Size *= *ElemCount;
1111       if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
1112         if (Optional<int64_t> UpperBound =
1113                 UpperBoundAttr->getAsSignedConstant()) {
1114           int64_t LowerBound = 0;
1115           if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
1116             LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
1117           Size *= *UpperBound - LowerBound + 1;
1118         }
1119     }
1120     return Size;
1121   }
1122   default:
1123     break;
1124   }
1125   return Optional<uint64_t>();
1126 }
1127 
1128 static Optional<int64_t>
1129 getExpressionFrameOffset(ArrayRef<uint8_t> Expr,
1130                          Optional<unsigned> FrameBaseReg) {
1131   if (!Expr.empty() &&
1132       (Expr[0] == DW_OP_fbreg ||
1133        (FrameBaseReg && Expr[0] == DW_OP_breg0 + *FrameBaseReg))) {
1134     unsigned Count;
1135     int64_t Offset = decodeSLEB128(Expr.data() + 1, &Count, Expr.end());
1136     // A single DW_OP_fbreg or DW_OP_breg.
1137     if (Expr.size() == Count + 1)
1138       return Offset;
1139     // Same + DW_OP_deref (Fortran arrays look like this).
1140     if (Expr.size() == Count + 2 && Expr[Count + 1] == DW_OP_deref)
1141       return Offset;
1142     // Fallthrough. Do not accept ex. (DW_OP_breg W29, DW_OP_stack_value)
1143   }
1144   return None;
1145 }
1146 
1147 void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1148                                    DWARFDie Die, std::vector<DILocal> &Result) {
1149   if (Die.getTag() == DW_TAG_variable ||
1150       Die.getTag() == DW_TAG_formal_parameter) {
1151     DILocal Local;
1152     if (const char *Name = Subprogram.getSubroutineName(DINameKind::ShortName))
1153       Local.FunctionName = Name;
1154 
1155     Optional<unsigned> FrameBaseReg;
1156     if (auto FrameBase = Subprogram.find(DW_AT_frame_base))
1157       if (Optional<ArrayRef<uint8_t>> Expr = FrameBase->getAsBlock())
1158         if (!Expr->empty() && (*Expr)[0] >= DW_OP_reg0 &&
1159             (*Expr)[0] <= DW_OP_reg31) {
1160           FrameBaseReg = (*Expr)[0] - DW_OP_reg0;
1161         }
1162 
1163     if (Expected<std::vector<DWARFLocationExpression>> Loc =
1164             Die.getLocations(DW_AT_location)) {
1165       for (const auto &Entry : *Loc) {
1166         if (Optional<int64_t> FrameOffset =
1167                 getExpressionFrameOffset(Entry.Expr, FrameBaseReg)) {
1168           Local.FrameOffset = *FrameOffset;
1169           break;
1170         }
1171       }
1172     } else {
1173       // FIXME: missing DW_AT_location is OK here, but other errors should be
1174       // reported to the user.
1175       consumeError(Loc.takeError());
1176     }
1177 
1178     if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
1179       Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1180 
1181     if (auto Origin =
1182             Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1183       Die = Origin;
1184     if (auto NameAttr = Die.find(DW_AT_name))
1185       if (Optional<const char *> Name = NameAttr->getAsCString())
1186         Local.Name = *Name;
1187     if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
1188       Local.Size = getTypeSize(Type, getCUAddrSize());
1189     if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
1190       if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
1191         LT->getFileNameByIndex(
1192             DeclFileAttr->getAsUnsignedConstant().getValue(),
1193             CU->getCompilationDir(),
1194             DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1195             Local.DeclFile);
1196     }
1197     if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
1198       Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
1199 
1200     Result.push_back(Local);
1201     return;
1202   }
1203 
1204   if (Die.getTag() == DW_TAG_inlined_subroutine)
1205     if (auto Origin =
1206             Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1207       Subprogram = Origin;
1208 
1209   for (auto Child : Die)
1210     addLocalsForDie(CU, Subprogram, Child, Result);
1211 }
1212 
1213 std::vector<DILocal>
1214 DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
1215   std::vector<DILocal> Result;
1216   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1217   if (!CU)
1218     return Result;
1219 
1220   DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
1221   if (Subprogram.isValid())
1222     addLocalsForDie(CU, Subprogram, Subprogram, Result);
1223   return Result;
1224 }
1225 
1226 DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
1227                                                DILineInfoSpecifier Spec) {
1228   DILineInfo Result;
1229 
1230   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1231   if (!CU)
1232     return Result;
1233 
1234   getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind, Spec.FLIKind,
1235                                         Result.FunctionName,
1236                                         Result.StartFileName, Result.StartLine);
1237   if (Spec.FLIKind != FileLineInfoKind::None) {
1238     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
1239       LineTable->getFileLineInfoForAddress(
1240           {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1241           Spec.FLIKind, Result);
1242     }
1243   }
1244   return Result;
1245 }
1246 
1247 DILineInfoTable DWARFContext::getLineInfoForAddressRange(
1248     object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
1249   DILineInfoTable  Lines;
1250   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1251   if (!CU)
1252     return Lines;
1253 
1254   uint32_t StartLine = 0;
1255   std::string StartFileName;
1256   std::string FunctionName(DILineInfo::BadString);
1257   getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind, Spec.FLIKind,
1258                                         FunctionName, StartFileName, StartLine);
1259 
1260   // If the Specifier says we don't need FileLineInfo, just
1261   // return the top-most function at the starting address.
1262   if (Spec.FLIKind == FileLineInfoKind::None) {
1263     DILineInfo Result;
1264     Result.FunctionName = FunctionName;
1265     Result.StartFileName = StartFileName;
1266     Result.StartLine = StartLine;
1267     Lines.push_back(std::make_pair(Address.Address, Result));
1268     return Lines;
1269   }
1270 
1271   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
1272 
1273   // Get the index of row we're looking for in the line table.
1274   std::vector<uint32_t> RowVector;
1275   if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
1276                                      Size, RowVector)) {
1277     return Lines;
1278   }
1279 
1280   for (uint32_t RowIndex : RowVector) {
1281     // Take file number and line/column from the row.
1282     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
1283     DILineInfo Result;
1284     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1285                                   Spec.FLIKind, Result.FileName);
1286     Result.FunctionName = FunctionName;
1287     Result.Line = Row.Line;
1288     Result.Column = Row.Column;
1289     Result.StartFileName = StartFileName;
1290     Result.StartLine = StartLine;
1291     Lines.push_back(std::make_pair(Row.Address.Address, Result));
1292   }
1293 
1294   return Lines;
1295 }
1296 
1297 DIInliningInfo
1298 DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
1299                                         DILineInfoSpecifier Spec) {
1300   DIInliningInfo InliningInfo;
1301 
1302   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1303   if (!CU)
1304     return InliningInfo;
1305 
1306   const DWARFLineTable *LineTable = nullptr;
1307   SmallVector<DWARFDie, 4> InlinedChain;
1308   CU->getInlinedChainForAddress(Address.Address, InlinedChain);
1309   if (InlinedChain.size() == 0) {
1310     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1311     // try to at least get file/line info from symbol table.
1312     if (Spec.FLIKind != FileLineInfoKind::None) {
1313       DILineInfo Frame;
1314       LineTable = getLineTableForUnit(CU);
1315       if (LineTable && LineTable->getFileLineInfoForAddress(
1316                            {Address.Address, Address.SectionIndex},
1317                            CU->getCompilationDir(), Spec.FLIKind, Frame))
1318         InliningInfo.addFrame(Frame);
1319     }
1320     return InliningInfo;
1321   }
1322 
1323   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
1324   for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1325     DWARFDie &FunctionDIE = InlinedChain[i];
1326     DILineInfo Frame;
1327     // Get function name if necessary.
1328     if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
1329       Frame.FunctionName = Name;
1330     if (auto DeclLineResult = FunctionDIE.getDeclLine())
1331       Frame.StartLine = DeclLineResult;
1332     Frame.StartFileName = FunctionDIE.getDeclFile(Spec.FLIKind);
1333     if (Spec.FLIKind != FileLineInfoKind::None) {
1334       if (i == 0) {
1335         // For the topmost frame, initialize the line table of this
1336         // compile unit and fetch file/line info from it.
1337         LineTable = getLineTableForUnit(CU);
1338         // For the topmost routine, get file/line info from line table.
1339         if (LineTable)
1340           LineTable->getFileLineInfoForAddress(
1341               {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1342               Spec.FLIKind, Frame);
1343       } else {
1344         // Otherwise, use call file, call line and call column from
1345         // previous DIE in inlined chain.
1346         if (LineTable)
1347           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1348                                         Spec.FLIKind, Frame.FileName);
1349         Frame.Line = CallLine;
1350         Frame.Column = CallColumn;
1351         Frame.Discriminator = CallDiscriminator;
1352       }
1353       // Get call file/line/column of a current DIE.
1354       if (i + 1 < n) {
1355         FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1356                                    CallDiscriminator);
1357       }
1358     }
1359     InliningInfo.addFrame(Frame);
1360   }
1361   return InliningInfo;
1362 }
1363 
1364 std::shared_ptr<DWARFContext>
1365 DWARFContext::getDWOContext(StringRef AbsolutePath) {
1366   if (auto S = DWP.lock()) {
1367     DWARFContext *Ctxt = S->Context.get();
1368     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1369   }
1370 
1371   std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1372 
1373   if (auto S = Entry->lock()) {
1374     DWARFContext *Ctxt = S->Context.get();
1375     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1376   }
1377 
1378   Expected<OwningBinary<ObjectFile>> Obj = [&] {
1379     if (!CheckedForDWP) {
1380       SmallString<128> DWPName;
1381       auto Obj = object::ObjectFile::createObjectFile(
1382           this->DWPName.empty()
1383               ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1384               : StringRef(this->DWPName));
1385       if (Obj) {
1386         Entry = &DWP;
1387         return Obj;
1388       } else {
1389         CheckedForDWP = true;
1390         // TODO: Should this error be handled (maybe in a high verbosity mode)
1391         // before falling back to .dwo files?
1392         consumeError(Obj.takeError());
1393       }
1394     }
1395 
1396     return object::ObjectFile::createObjectFile(AbsolutePath);
1397   }();
1398 
1399   if (!Obj) {
1400     // TODO: Actually report errors helpfully.
1401     consumeError(Obj.takeError());
1402     return nullptr;
1403   }
1404 
1405   auto S = std::make_shared<DWOFile>();
1406   S->File = std::move(Obj.get());
1407   S->Context = DWARFContext::create(*S->File.getBinary());
1408   *Entry = S;
1409   auto *Ctxt = S->Context.get();
1410   return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1411 }
1412 
1413 static Error createError(const Twine &Reason, llvm::Error E) {
1414   return make_error<StringError>(Reason + toString(std::move(E)),
1415                                  inconvertibleErrorCode());
1416 }
1417 
1418 /// SymInfo contains information about symbol: it's address
1419 /// and section index which is -1LL for absolute symbols.
1420 struct SymInfo {
1421   uint64_t Address;
1422   uint64_t SectionIndex;
1423 };
1424 
1425 /// Returns the address of symbol relocation used against and a section index.
1426 /// Used for futher relocations computation. Symbol's section load address is
1427 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1428                                        const RelocationRef &Reloc,
1429                                        const LoadedObjectInfo *L,
1430                                        std::map<SymbolRef, SymInfo> &Cache) {
1431   SymInfo Ret = {0, (uint64_t)-1LL};
1432   object::section_iterator RSec = Obj.section_end();
1433   object::symbol_iterator Sym = Reloc.getSymbol();
1434 
1435   std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1436   // First calculate the address of the symbol or section as it appears
1437   // in the object file
1438   if (Sym != Obj.symbol_end()) {
1439     bool New;
1440     std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
1441     if (!New)
1442       return CacheIt->second;
1443 
1444     Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1445     if (!SymAddrOrErr)
1446       return createError("failed to compute symbol address: ",
1447                          SymAddrOrErr.takeError());
1448 
1449     // Also remember what section this symbol is in for later
1450     auto SectOrErr = Sym->getSection();
1451     if (!SectOrErr)
1452       return createError("failed to get symbol section: ",
1453                          SectOrErr.takeError());
1454 
1455     RSec = *SectOrErr;
1456     Ret.Address = *SymAddrOrErr;
1457   } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1458     RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
1459     Ret.Address = RSec->getAddress();
1460   }
1461 
1462   if (RSec != Obj.section_end())
1463     Ret.SectionIndex = RSec->getIndex();
1464 
1465   // If we are given load addresses for the sections, we need to adjust:
1466   // SymAddr = (Address of Symbol Or Section in File) -
1467   //           (Address of Section in File) +
1468   //           (Load Address of Section)
1469   // RSec is now either the section being targeted or the section
1470   // containing the symbol being targeted. In either case,
1471   // we need to perform the same computation.
1472   if (L && RSec != Obj.section_end())
1473     if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
1474       Ret.Address += SectionLoadAddress - RSec->getAddress();
1475 
1476   if (CacheIt != Cache.end())
1477     CacheIt->second = Ret;
1478 
1479   return Ret;
1480 }
1481 
1482 static bool isRelocScattered(const object::ObjectFile &Obj,
1483                              const RelocationRef &Reloc) {
1484   const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1485   if (!MachObj)
1486     return false;
1487   // MachO also has relocations that point to sections and
1488   // scattered relocations.
1489   auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1490   return MachObj->isRelocationScattered(RelocInfo);
1491 }
1492 
1493 namespace {
1494 struct DWARFSectionMap final : public DWARFSection {
1495   RelocAddrMap Relocs;
1496 };
1497 
1498 class DWARFObjInMemory final : public DWARFObject {
1499   bool IsLittleEndian;
1500   uint8_t AddressSize;
1501   StringRef FileName;
1502   const object::ObjectFile *Obj = nullptr;
1503   std::vector<SectionName> SectionNames;
1504 
1505   using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1506                                    std::map<object::SectionRef, unsigned>>;
1507 
1508   InfoSectionMap InfoSections;
1509   InfoSectionMap TypesSections;
1510   InfoSectionMap InfoDWOSections;
1511   InfoSectionMap TypesDWOSections;
1512 
1513   DWARFSectionMap LocSection;
1514   DWARFSectionMap LoclistsSection;
1515   DWARFSectionMap LoclistsDWOSection;
1516   DWARFSectionMap LineSection;
1517   DWARFSectionMap RangesSection;
1518   DWARFSectionMap RnglistsSection;
1519   DWARFSectionMap StrOffsetsSection;
1520   DWARFSectionMap LineDWOSection;
1521   DWARFSectionMap FrameSection;
1522   DWARFSectionMap EHFrameSection;
1523   DWARFSectionMap LocDWOSection;
1524   DWARFSectionMap StrOffsetsDWOSection;
1525   DWARFSectionMap RangesDWOSection;
1526   DWARFSectionMap RnglistsDWOSection;
1527   DWARFSectionMap AddrSection;
1528   DWARFSectionMap AppleNamesSection;
1529   DWARFSectionMap AppleTypesSection;
1530   DWARFSectionMap AppleNamespacesSection;
1531   DWARFSectionMap AppleObjCSection;
1532   DWARFSectionMap NamesSection;
1533   DWARFSectionMap PubnamesSection;
1534   DWARFSectionMap PubtypesSection;
1535   DWARFSectionMap GnuPubnamesSection;
1536   DWARFSectionMap GnuPubtypesSection;
1537   DWARFSectionMap MacroSection;
1538 
1539   DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1540     return StringSwitch<DWARFSectionMap *>(Name)
1541         .Case("debug_loc", &LocSection)
1542         .Case("debug_loclists", &LoclistsSection)
1543         .Case("debug_loclists.dwo", &LoclistsDWOSection)
1544         .Case("debug_line", &LineSection)
1545         .Case("debug_frame", &FrameSection)
1546         .Case("eh_frame", &EHFrameSection)
1547         .Case("debug_str_offsets", &StrOffsetsSection)
1548         .Case("debug_ranges", &RangesSection)
1549         .Case("debug_rnglists", &RnglistsSection)
1550         .Case("debug_loc.dwo", &LocDWOSection)
1551         .Case("debug_line.dwo", &LineDWOSection)
1552         .Case("debug_names", &NamesSection)
1553         .Case("debug_rnglists.dwo", &RnglistsDWOSection)
1554         .Case("debug_str_offsets.dwo", &StrOffsetsDWOSection)
1555         .Case("debug_addr", &AddrSection)
1556         .Case("apple_names", &AppleNamesSection)
1557         .Case("debug_pubnames", &PubnamesSection)
1558         .Case("debug_pubtypes", &PubtypesSection)
1559         .Case("debug_gnu_pubnames", &GnuPubnamesSection)
1560         .Case("debug_gnu_pubtypes", &GnuPubtypesSection)
1561         .Case("apple_types", &AppleTypesSection)
1562         .Case("apple_namespaces", &AppleNamespacesSection)
1563         .Case("apple_namespac", &AppleNamespacesSection)
1564         .Case("apple_objc", &AppleObjCSection)
1565         .Case("debug_macro", &MacroSection)
1566         .Default(nullptr);
1567   }
1568 
1569   StringRef AbbrevSection;
1570   StringRef ArangesSection;
1571   StringRef StrSection;
1572   StringRef MacinfoSection;
1573   StringRef MacinfoDWOSection;
1574   StringRef MacroDWOSection;
1575   StringRef AbbrevDWOSection;
1576   StringRef StrDWOSection;
1577   StringRef CUIndexSection;
1578   StringRef GdbIndexSection;
1579   StringRef TUIndexSection;
1580   StringRef LineStrSection;
1581 
1582   // A deque holding section data whose iterators are not invalidated when
1583   // new decompressed sections are inserted at the end.
1584   std::deque<SmallString<0>> UncompressedSections;
1585 
1586   StringRef *mapSectionToMember(StringRef Name) {
1587     if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1588       return &Sec->Data;
1589     return StringSwitch<StringRef *>(Name)
1590         .Case("debug_abbrev", &AbbrevSection)
1591         .Case("debug_aranges", &ArangesSection)
1592         .Case("debug_str", &StrSection)
1593         .Case("debug_macinfo", &MacinfoSection)
1594         .Case("debug_macinfo.dwo", &MacinfoDWOSection)
1595         .Case("debug_macro.dwo", &MacroDWOSection)
1596         .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1597         .Case("debug_str.dwo", &StrDWOSection)
1598         .Case("debug_cu_index", &CUIndexSection)
1599         .Case("debug_tu_index", &TUIndexSection)
1600         .Case("gdb_index", &GdbIndexSection)
1601         .Case("debug_line_str", &LineStrSection)
1602         // Any more debug info sections go here.
1603         .Default(nullptr);
1604   }
1605 
1606   /// If Sec is compressed section, decompresses and updates its contents
1607   /// provided by Data. Otherwise leaves it unchanged.
1608   Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1609                         StringRef &Data) {
1610     if (!Decompressor::isCompressed(Sec))
1611       return Error::success();
1612 
1613     Expected<Decompressor> Decompressor =
1614         Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1615     if (!Decompressor)
1616       return Decompressor.takeError();
1617 
1618     SmallString<0> Out;
1619     if (auto Err = Decompressor->resizeAndDecompress(Out))
1620       return Err;
1621 
1622     UncompressedSections.push_back(std::move(Out));
1623     Data = UncompressedSections.back();
1624 
1625     return Error::success();
1626   }
1627 
1628 public:
1629   DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1630                    uint8_t AddrSize, bool IsLittleEndian)
1631       : IsLittleEndian(IsLittleEndian) {
1632     for (const auto &SecIt : Sections) {
1633       if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1634         *SectionData = SecIt.second->getBuffer();
1635       else if (SecIt.first() == "debug_info")
1636         // Find debug_info and debug_types data by section rather than name as
1637         // there are multiple, comdat grouped, of these sections.
1638         InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1639       else if (SecIt.first() == "debug_info.dwo")
1640         InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1641       else if (SecIt.first() == "debug_types")
1642         TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1643       else if (SecIt.first() == "debug_types.dwo")
1644         TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1645     }
1646   }
1647   DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1648                    function_ref<void(Error)> HandleError, function_ref<void(Error)> HandleWarning )
1649       : IsLittleEndian(Obj.isLittleEndian()),
1650         AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1651         Obj(&Obj) {
1652 
1653     StringMap<unsigned> SectionAmountMap;
1654     for (const SectionRef &Section : Obj.sections()) {
1655       StringRef Name;
1656       if (auto NameOrErr = Section.getName())
1657         Name = *NameOrErr;
1658       else
1659         consumeError(NameOrErr.takeError());
1660 
1661       ++SectionAmountMap[Name];
1662       SectionNames.push_back({ Name, true });
1663 
1664       // Skip BSS and Virtual sections, they aren't interesting.
1665       if (Section.isBSS() || Section.isVirtual())
1666         continue;
1667 
1668       // Skip sections stripped by dsymutil.
1669       if (Section.isStripped())
1670         continue;
1671 
1672       StringRef Data;
1673       Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1674       if (!SecOrErr) {
1675         HandleError(createError("failed to get relocated section: ",
1676                                 SecOrErr.takeError()));
1677         continue;
1678       }
1679 
1680       // Try to obtain an already relocated version of this section.
1681       // Else use the unrelocated section from the object file. We'll have to
1682       // apply relocations ourselves later.
1683       section_iterator RelocatedSection = *SecOrErr;
1684       if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) {
1685         Expected<StringRef> E = Section.getContents();
1686         if (E)
1687           Data = *E;
1688         else
1689           // maybeDecompress below will error.
1690           consumeError(E.takeError());
1691       }
1692 
1693       if (auto Err = maybeDecompress(Section, Name, Data)) {
1694         HandleError(createError("failed to decompress '" + Name + "', ",
1695                                 std::move(Err)));
1696         continue;
1697       }
1698 
1699       // Compressed sections names in GNU style starts from ".z",
1700       // at this point section is decompressed and we drop compression prefix.
1701       Name = Name.substr(
1702           Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1703 
1704       // Map platform specific debug section names to DWARF standard section
1705       // names.
1706       Name = Obj.mapDebugSectionName(Name);
1707 
1708       if (StringRef *SectionData = mapSectionToMember(Name)) {
1709         *SectionData = Data;
1710         if (Name == "debug_ranges") {
1711           // FIXME: Use the other dwo range section when we emit it.
1712           RangesDWOSection.Data = Data;
1713         }
1714       } else if (Name == "debug_info") {
1715         // Find debug_info and debug_types data by section rather than name as
1716         // there are multiple, comdat grouped, of these sections.
1717         InfoSections[Section].Data = Data;
1718       } else if (Name == "debug_info.dwo") {
1719         InfoDWOSections[Section].Data = Data;
1720       } else if (Name == "debug_types") {
1721         TypesSections[Section].Data = Data;
1722       } else if (Name == "debug_types.dwo") {
1723         TypesDWOSections[Section].Data = Data;
1724       }
1725 
1726       if (RelocatedSection == Obj.section_end())
1727         continue;
1728 
1729       StringRef RelSecName;
1730       if (auto NameOrErr = RelocatedSection->getName())
1731         RelSecName = *NameOrErr;
1732       else
1733         consumeError(NameOrErr.takeError());
1734 
1735       // If the section we're relocating was relocated already by the JIT,
1736       // then we used the relocated version above, so we do not need to process
1737       // relocations for it now.
1738       StringRef RelSecData;
1739       if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1740         continue;
1741 
1742       // In Mach-o files, the relocations do not need to be applied if
1743       // there is no load offset to apply. The value read at the
1744       // relocation point already factors in the section address
1745       // (actually applying the relocations will produce wrong results
1746       // as the section address will be added twice).
1747       if (!L && isa<MachOObjectFile>(&Obj))
1748         continue;
1749 
1750       RelSecName = RelSecName.substr(
1751           RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1752 
1753       // TODO: Add support for relocations in other sections as needed.
1754       // Record relocations for the debug_info and debug_line sections.
1755       DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1756       RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1757       if (!Map) {
1758         // Find debug_info and debug_types relocs by section rather than name
1759         // as there are multiple, comdat grouped, of these sections.
1760         if (RelSecName == "debug_info")
1761           Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1762                      .Relocs;
1763         else if (RelSecName == "debug_info.dwo")
1764           Map = &static_cast<DWARFSectionMap &>(
1765                      InfoDWOSections[*RelocatedSection])
1766                      .Relocs;
1767         else if (RelSecName == "debug_types")
1768           Map =
1769               &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1770                    .Relocs;
1771         else if (RelSecName == "debug_types.dwo")
1772           Map = &static_cast<DWARFSectionMap &>(
1773                      TypesDWOSections[*RelocatedSection])
1774                      .Relocs;
1775         else
1776           continue;
1777       }
1778 
1779       if (Section.relocation_begin() == Section.relocation_end())
1780         continue;
1781 
1782       // Symbol to [address, section index] cache mapping.
1783       std::map<SymbolRef, SymInfo> AddrCache;
1784       bool (*Supports)(uint64_t);
1785       RelocationResolver Resolver;
1786       std::tie(Supports, Resolver) = getRelocationResolver(Obj);
1787       for (const RelocationRef &Reloc : Section.relocations()) {
1788         // FIXME: it's not clear how to correctly handle scattered
1789         // relocations.
1790         if (isRelocScattered(Obj, Reloc))
1791           continue;
1792 
1793         Expected<SymInfo> SymInfoOrErr =
1794             getSymbolInfo(Obj, Reloc, L, AddrCache);
1795         if (!SymInfoOrErr) {
1796           HandleError(SymInfoOrErr.takeError());
1797           continue;
1798         }
1799 
1800         // Check if Resolver can handle this relocation type early so as not to
1801         // handle invalid cases in DWARFDataExtractor.
1802         //
1803         // TODO Don't store Resolver in every RelocAddrEntry.
1804         if (Supports && Supports(Reloc.getType())) {
1805           auto I = Map->try_emplace(
1806               Reloc.getOffset(),
1807               RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
1808                              SymInfoOrErr->Address,
1809                              Optional<object::RelocationRef>(), 0, Resolver});
1810           // If we didn't successfully insert that's because we already had a
1811           // relocation for that offset. Store it as a second relocation in the
1812           // same RelocAddrEntry instead.
1813           if (!I.second) {
1814             RelocAddrEntry &entry = I.first->getSecond();
1815             if (entry.Reloc2) {
1816               HandleError(createError(
1817                   "At most two relocations per offset are supported"));
1818             }
1819             entry.Reloc2 = Reloc;
1820             entry.SymbolValue2 = SymInfoOrErr->Address;
1821           }
1822         } else {
1823           SmallString<32> Type;
1824           Reloc.getTypeName(Type);
1825           // FIXME: Support more relocations & change this to an error
1826           HandleWarning(
1827               createError("failed to compute relocation: " + Type + ", ",
1828                           errorCodeToError(object_error::parse_failed)));
1829         }
1830       }
1831     }
1832 
1833     for (SectionName &S : SectionNames)
1834       if (SectionAmountMap[S.Name] > 1)
1835         S.IsNameUnique = false;
1836   }
1837 
1838   Optional<RelocAddrEntry> find(const DWARFSection &S,
1839                                 uint64_t Pos) const override {
1840     auto &Sec = static_cast<const DWARFSectionMap &>(S);
1841     RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1842     if (AI == Sec.Relocs.end())
1843       return None;
1844     return AI->second;
1845   }
1846 
1847   const object::ObjectFile *getFile() const override { return Obj; }
1848 
1849   ArrayRef<SectionName> getSectionNames() const override {
1850     return SectionNames;
1851   }
1852 
1853   bool isLittleEndian() const override { return IsLittleEndian; }
1854   StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1855   const DWARFSection &getLineDWOSection() const override {
1856     return LineDWOSection;
1857   }
1858   const DWARFSection &getLocDWOSection() const override {
1859     return LocDWOSection;
1860   }
1861   StringRef getStrDWOSection() const override { return StrDWOSection; }
1862   const DWARFSection &getStrOffsetsDWOSection() const override {
1863     return StrOffsetsDWOSection;
1864   }
1865   const DWARFSection &getRangesDWOSection() const override {
1866     return RangesDWOSection;
1867   }
1868   const DWARFSection &getRnglistsDWOSection() const override {
1869     return RnglistsDWOSection;
1870   }
1871   const DWARFSection &getLoclistsDWOSection() const override {
1872     return LoclistsDWOSection;
1873   }
1874   const DWARFSection &getAddrSection() const override { return AddrSection; }
1875   StringRef getCUIndexSection() const override { return CUIndexSection; }
1876   StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1877   StringRef getTUIndexSection() const override { return TUIndexSection; }
1878 
1879   // DWARF v5
1880   const DWARFSection &getStrOffsetsSection() const override {
1881     return StrOffsetsSection;
1882   }
1883   StringRef getLineStrSection() const override { return LineStrSection; }
1884 
1885   // Sections for DWARF5 split dwarf proposal.
1886   void forEachInfoDWOSections(
1887       function_ref<void(const DWARFSection &)> F) const override {
1888     for (auto &P : InfoDWOSections)
1889       F(P.second);
1890   }
1891   void forEachTypesDWOSections(
1892       function_ref<void(const DWARFSection &)> F) const override {
1893     for (auto &P : TypesDWOSections)
1894       F(P.second);
1895   }
1896 
1897   StringRef getAbbrevSection() const override { return AbbrevSection; }
1898   const DWARFSection &getLocSection() const override { return LocSection; }
1899   const DWARFSection &getLoclistsSection() const override { return LoclistsSection; }
1900   StringRef getArangesSection() const override { return ArangesSection; }
1901   const DWARFSection &getFrameSection() const override {
1902     return FrameSection;
1903   }
1904   const DWARFSection &getEHFrameSection() const override {
1905     return EHFrameSection;
1906   }
1907   const DWARFSection &getLineSection() const override { return LineSection; }
1908   StringRef getStrSection() const override { return StrSection; }
1909   const DWARFSection &getRangesSection() const override { return RangesSection; }
1910   const DWARFSection &getRnglistsSection() const override {
1911     return RnglistsSection;
1912   }
1913   const DWARFSection &getMacroSection() const override { return MacroSection; }
1914   StringRef getMacroDWOSection() const override { return MacroDWOSection; }
1915   StringRef getMacinfoSection() const override { return MacinfoSection; }
1916   StringRef getMacinfoDWOSection() const override { return MacinfoDWOSection; }
1917   const DWARFSection &getPubnamesSection() const override { return PubnamesSection; }
1918   const DWARFSection &getPubtypesSection() const override { return PubtypesSection; }
1919   const DWARFSection &getGnuPubnamesSection() const override {
1920     return GnuPubnamesSection;
1921   }
1922   const DWARFSection &getGnuPubtypesSection() const override {
1923     return GnuPubtypesSection;
1924   }
1925   const DWARFSection &getAppleNamesSection() const override {
1926     return AppleNamesSection;
1927   }
1928   const DWARFSection &getAppleTypesSection() const override {
1929     return AppleTypesSection;
1930   }
1931   const DWARFSection &getAppleNamespacesSection() const override {
1932     return AppleNamespacesSection;
1933   }
1934   const DWARFSection &getAppleObjCSection() const override {
1935     return AppleObjCSection;
1936   }
1937   const DWARFSection &getNamesSection() const override {
1938     return NamesSection;
1939   }
1940 
1941   StringRef getFileName() const override { return FileName; }
1942   uint8_t getAddressSize() const override { return AddressSize; }
1943   void forEachInfoSections(
1944       function_ref<void(const DWARFSection &)> F) const override {
1945     for (auto &P : InfoSections)
1946       F(P.second);
1947   }
1948   void forEachTypesSections(
1949       function_ref<void(const DWARFSection &)> F) const override {
1950     for (auto &P : TypesSections)
1951       F(P.second);
1952   }
1953 };
1954 } // namespace
1955 
1956 std::unique_ptr<DWARFContext>
1957 DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1958                      std::string DWPName,
1959                      std::function<void(Error)> RecoverableErrorHandler,
1960                      std::function<void(Error)> WarningHandler) {
1961   auto DObj =
1962       std::make_unique<DWARFObjInMemory>(Obj, L, RecoverableErrorHandler, WarningHandler);
1963   return std::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName),
1964                                         RecoverableErrorHandler,
1965                                         WarningHandler);
1966 }
1967 
1968 std::unique_ptr<DWARFContext>
1969 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1970                      uint8_t AddrSize, bool isLittleEndian,
1971                      std::function<void(Error)> RecoverableErrorHandler,
1972                      std::function<void(Error)> WarningHandler) {
1973   auto DObj =
1974       std::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1975   return std::make_unique<DWARFContext>(
1976       std::move(DObj), "", RecoverableErrorHandler, WarningHandler);
1977 }
1978 
1979 Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1980   // Detect the architecture from the object file. We usually don't need OS
1981   // info to lookup a target and create register info.
1982   Triple TT;
1983   TT.setArch(Triple::ArchType(Obj.getArch()));
1984   TT.setVendor(Triple::UnknownVendor);
1985   TT.setOS(Triple::UnknownOS);
1986   std::string TargetLookupError;
1987   const Target *TheTarget =
1988       TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1989   if (!TargetLookupError.empty())
1990     return createStringError(errc::invalid_argument,
1991                              TargetLookupError.c_str());
1992   RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1993   return Error::success();
1994 }
1995 
1996 uint8_t DWARFContext::getCUAddrSize() {
1997   // In theory, different compile units may have different address byte
1998   // sizes, but for simplicity we just use the address byte size of the
1999   // first compile unit. In practice the address size field is repeated across
2000   // various DWARF headers (at least in version 5) to make it easier to dump
2001   // them independently, not to enable varying the address size.
2002   unit_iterator_range CUs = compile_units();
2003   return CUs.empty() ? 0 : (*CUs.begin())->getAddressByteSize();
2004 }
2005