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