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