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