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