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