1 //===- DWARFContext.cpp ---------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/BinaryFormat/Dwarf.h"
17 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
18 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.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/DWARFDie.h"
29 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
30 #include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
31 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
32 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
33 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/Object/Decompressor.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Object/RelocVisitor.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/DataExtractor.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include <algorithm>
48 #include <cstdint>
49 #include <map>
50 #include <string>
51 #include <tuple>
52 #include <utility>
53 #include <vector>
54 
55 using namespace llvm;
56 using namespace dwarf;
57 using namespace object;
58 
59 #define DEBUG_TYPE "dwarf"
60 
61 using DWARFLineTable = DWARFDebugLine::LineTable;
62 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
63 using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
64 
65 DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
66                            std::string DWPName)
67     : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
68 
69 DWARFContext::~DWARFContext() = default;
70 
71 /// Dump the UUID load command.
72 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
73   auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
74   if (!MachO)
75     return;
76   for (auto LC : MachO->load_commands()) {
77     raw_ostream::uuid_t UUID;
78     if (LC.C.cmd == MachO::LC_UUID) {
79       if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
80         OS << "error: UUID load command is too short.\n";
81         return;
82       }
83       OS << "UUID: ";
84       memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
85       OS.write_uuid(UUID);
86       OS << ' ' << MachO->getFileFormatName();
87       OS << ' ' << MachO->getFileName() << '\n';
88     }
89   }
90 }
91 
92 static void
93 dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
94                                 const DWARFObject &Obj,
95                                 const DWARFSection &StringOffsetsSection,
96                                 StringRef StringSection, bool LittleEndian) {
97   DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
98   uint32_t Offset = 0;
99   uint64_t SectionSize = StringOffsetsSection.Data.size();
100 
101   while (Offset < SectionSize) {
102     unsigned Version = 0;
103     DwarfFormat Format = DWARF32;
104     unsigned EntrySize = 4;
105     // Perform validation and extract the segment size from the header.
106     if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
107       OS << "error: invalid contribution to string offsets table in section ."
108          << SectionName << ".\n";
109       return;
110     }
111     uint32_t ContributionStart = Offset;
112     uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
113     // A contribution size of 0xffffffff indicates DWARF64, with the actual size
114     // in the following 8 bytes. Otherwise, the DWARF standard mandates that
115     // the contribution size must be at most 0xfffffff0.
116     if (ContributionSize == 0xffffffff) {
117       if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
118         OS << "error: invalid contribution to string offsets table in section ."
119            << SectionName << ".\n";
120         return;
121       }
122       Format = DWARF64;
123       EntrySize = 8;
124       ContributionSize = StrOffsetExt.getU64(&Offset);
125     } else if (ContributionSize > 0xfffffff0) {
126       OS << "error: invalid contribution to string offsets table in section ."
127          << SectionName << ".\n";
128       return;
129     }
130 
131     // We must ensure that we don't read a partial record at the end, so we
132     // validate for a multiple of EntrySize. Also, we're expecting a version
133     // number and padding, which adds an additional 4 bytes.
134     uint64_t ValidationSize =
135         4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
136     if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
137       OS << "error: contribution to string offsets table in section ."
138          << SectionName << " has invalid length.\n";
139       return;
140     }
141 
142     Version = StrOffsetExt.getU16(&Offset);
143     Offset += 2;
144     OS << format("0x%8.8x: ", ContributionStart);
145     OS << "Contribution size = " << ContributionSize
146        << ", Version = " << Version << "\n";
147 
148     uint32_t ContributionBase = Offset;
149     DataExtractor StrData(StringSection, LittleEndian, 0);
150     while (Offset - ContributionBase < ContributionSize) {
151       OS << format("0x%8.8x: ", Offset);
152       // FIXME: We can only extract strings in DWARF32 format at the moment.
153       uint64_t StringOffset =
154           StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
155       if (Format == DWARF32) {
156         uint32_t StringOffset32 = (uint32_t)StringOffset;
157         OS << format("%8.8x ", StringOffset32);
158         const char *S = StrData.getCStr(&StringOffset32);
159         if (S)
160           OS << format("\"%s\"", S);
161       } else
162         OS << format("%16.16" PRIx64 " ", StringOffset);
163       OS << "\n";
164     }
165   }
166 }
167 
168 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted
169 // string offsets section, where each compile or type unit contributes a
170 // number of entries (string offsets), with each contribution preceded by
171 // a header containing size and version number. Alternatively, it may be a
172 // monolithic series of string offsets, as generated by the pre-DWARF v5
173 // implementation of split DWARF.
174 static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
175                                      const DWARFObject &Obj,
176                                      const DWARFSection &StringOffsetsSection,
177                                      StringRef StringSection, bool LittleEndian,
178                                      unsigned MaxVersion) {
179   // If we have at least one (compile or type) unit with DWARF v5 or greater,
180   // we assume that the section is formatted like a DWARF v5 string offsets
181   // section.
182   if (MaxVersion >= 5)
183     dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
184                                     StringSection, LittleEndian);
185   else {
186     DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
187     uint32_t offset = 0;
188     uint64_t size = StringOffsetsSection.Data.size();
189     // Ensure that size is a multiple of the size of an entry.
190     if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
191       OS << "error: size of ." << SectionName << " is not a multiple of "
192          << sizeof(uint32_t) << ".\n";
193       size &= -(uint64_t)sizeof(uint32_t);
194     }
195     DataExtractor StrData(StringSection, LittleEndian, 0);
196     while (offset < size) {
197       OS << format("0x%8.8x: ", offset);
198       uint32_t StringOffset = strOffsetExt.getU32(&offset);
199       OS << format("%8.8x  ", StringOffset);
200       const char *S = StrData.getCStr(&StringOffset);
201       if (S)
202         OS << format("\"%s\"", S);
203       OS << "\n";
204     }
205   }
206 }
207 
208 void DWARFContext::dump(
209     raw_ostream &OS, DIDumpOptions DumpOpts,
210     std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
211 
212   Optional<uint64_t> DumpOffset;
213   uint64_t DumpType = DumpOpts.DumpType;
214 
215   StringRef Extension = sys::path::extension(DObj->getFileName());
216   bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
217 
218   // Print UUID header.
219   const auto *ObjFile = DObj->getFile();
220   if (DumpType & DIDT_UUID)
221     dumpUUID(OS, *ObjFile);
222 
223   // Print a header for each explicitly-requested section.
224   // Otherwise just print one for non-empty sections.
225   // Only print empty .dwo section headers when dumping a .dwo file.
226   bool Explicit = DumpType != DIDT_All && !IsDWO;
227   bool ExplicitDWO = Explicit && IsDWO;
228   auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
229                         StringRef Section) {
230     DumpOffset = DumpOffsets[ID];
231     unsigned Mask = 1U << ID;
232     bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
233     if (Should)
234       OS << "\n" << Name << " contents:\n";
235     return Should;
236   };
237 
238   // Dump individual sections.
239   if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
240                  DObj->getAbbrevSection()))
241     getDebugAbbrev()->dump(OS);
242   if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
243                  DObj->getAbbrevDWOSection()))
244     getDebugAbbrevDWO()->dump(OS);
245 
246   auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
247                            DWARFSection Section, cu_iterator_range CUs) {
248     if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
249       if (DumpOffset)
250         getDIEForOffset(DumpOffset.getValue())
251             .dump(OS, 0, DumpOpts.noImplicitRecursion());
252       else
253         for (const auto &CU : CUs)
254           CU->dump(OS, DumpOpts);
255     }
256   };
257   dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
258                 compile_units());
259   dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
260                 dwo_compile_units());
261 
262   auto dumpDebugType = [&](const char *Name,
263                            tu_section_iterator_range TUSections) {
264     OS << '\n' << Name << " contents:\n";
265     DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
266     for (const auto &TUS : TUSections)
267       for (const auto &TU : TUS)
268         if (DumpOffset)
269           TU->getDIEForOffset(*DumpOffset)
270               .dump(OS, 0, DumpOpts.noImplicitRecursion());
271         else
272           TU->dump(OS, DumpOpts);
273   };
274   if ((DumpType & DIDT_DebugTypes)) {
275     if (Explicit || getNumTypeUnits())
276       dumpDebugType(".debug_types", type_unit_sections());
277     if (ExplicitDWO || getNumDWOTypeUnits())
278       dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
279   }
280 
281   if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
282                  DObj->getLocSection().Data)) {
283     getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset);
284   }
285   if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
286                  DObj->getLocDWOSection().Data)) {
287     getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset);
288   }
289 
290   if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
291                  DObj->getDebugFrameSection()))
292     getDebugFrame()->dump(OS, DumpOffset);
293 
294   if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
295                  DObj->getEHFrameSection()))
296     getEHFrame()->dump(OS, DumpOffset);
297 
298   if (DumpType & DIDT_DebugMacro) {
299     if (Explicit || !getDebugMacro()->empty()) {
300       OS << "\n.debug_macinfo contents:\n";
301       getDebugMacro()->dump(OS);
302     }
303   }
304 
305   if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
306                  DObj->getARangeSection())) {
307     uint32_t offset = 0;
308     DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
309     DWARFDebugArangeSet set;
310     while (set.extract(arangesData, &offset))
311       set.dump(OS);
312   }
313 
314   uint8_t savedAddressByteSize = 0;
315   if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
316                  DObj->getLineSection().Data)) {
317     for (const auto &CU : compile_units()) {
318       savedAddressByteSize = CU->getAddressByteSize();
319       auto CUDIE = CU->getUnitDIE();
320       if (!CUDIE)
321         continue;
322       if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
323         if (DumpOffset && *StmtOffset != *DumpOffset)
324           continue;
325         DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
326                                     isLittleEndian(), savedAddressByteSize);
327         DWARFDebugLine::LineTable LineTable;
328         uint32_t Offset = *StmtOffset;
329         // Verbose dumping is done during parsing and not on the intermediate
330         // representation.
331         OS << "debug_line[" << format("0x%8.8x", Offset) << "]\n";
332         if (DumpOpts.Verbose) {
333           LineTable.parse(lineData, &Offset, &OS);
334         } else {
335           LineTable.parse(lineData, &Offset);
336           LineTable.dump(OS);
337         }
338       }
339     }
340   }
341 
342   // FIXME: This seems sketchy.
343   for (const auto &CU : compile_units()) {
344     savedAddressByteSize = CU->getAddressByteSize();
345     break;
346   }
347   if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
348                  DObj->getLineDWOSection().Data)) {
349     unsigned stmtOffset = 0;
350     DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
351                                 isLittleEndian(), savedAddressByteSize);
352     DWARFDebugLine::LineTable LineTable;
353     while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
354       LineTable.dump(OS);
355       LineTable.clear();
356     }
357   }
358 
359   if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
360                  DObj->getCUIndexSection())) {
361     getCUIndex().dump(OS);
362   }
363 
364   if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
365                  DObj->getTUIndexSection())) {
366     getTUIndex().dump(OS);
367   }
368 
369   if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
370                  DObj->getStringSection())) {
371     DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
372     uint32_t offset = 0;
373     uint32_t strOffset = 0;
374     while (const char *s = strData.getCStr(&offset)) {
375       OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
376       strOffset = offset;
377     }
378   }
379   if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
380                  DObj->getStringDWOSection())) {
381     DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
382     uint32_t offset = 0;
383     uint32_t strDWOOffset = 0;
384     while (const char *s = strDWOData.getCStr(&offset)) {
385       OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
386       strDWOOffset = offset;
387     }
388   }
389 
390   if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
391                  DObj->getRangeSection().Data)) {
392     // In fact, different compile units may have different address byte
393     // sizes, but for simplicity we just use the address byte size of the
394     // last compile unit (there is no easy and fast way to associate address
395     // range list and the compile unit it describes).
396     // FIXME: savedAddressByteSize seems sketchy.
397     DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
398                                   isLittleEndian(), savedAddressByteSize);
399     uint32_t offset = 0;
400     DWARFDebugRangeList rangeList;
401     while (rangeList.extract(rangesData, &offset))
402       rangeList.dump(OS);
403   }
404 
405   if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
406                  DObj->getPubNamesSection()))
407     DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
408         .dump(OS);
409 
410   if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
411                  DObj->getPubTypesSection()))
412     DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
413         .dump(OS);
414 
415   if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
416                  DObj->getGnuPubNamesSection()))
417     DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
418                        true /* GnuStyle */)
419         .dump(OS);
420 
421   if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
422                  DObj->getGnuPubTypesSection()))
423     DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
424                        true /* GnuStyle */)
425         .dump(OS);
426 
427   if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
428                  DObj->getStringOffsetSection().Data))
429     dumpStringOffsetsSection(
430         OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
431         DObj->getStringSection(), isLittleEndian(), getMaxVersion());
432   if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
433                  DObj->getStringOffsetDWOSection().Data))
434     dumpStringOffsetsSection(
435         OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
436         DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
437 
438   if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
439                  DObj->getGdbIndexSection())) {
440     getGdbIndex().dump(OS);
441   }
442 
443   if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
444                  DObj->getAppleNamesSection().Data))
445     getAppleNames().dump(OS);
446 
447   if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
448                  DObj->getAppleTypesSection().Data))
449     getAppleTypes().dump(OS);
450 
451   if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
452                  DObj->getAppleNamespacesSection().Data))
453     getAppleNamespaces().dump(OS);
454 
455   if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
456                  DObj->getAppleObjCSection().Data))
457     getAppleObjC().dump(OS);
458 }
459 
460 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
461   DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
462 
463   if (const auto &CUI = getCUIndex()) {
464     if (const auto *R = CUI.getFromHash(Hash))
465       return DWOCUs.getUnitForIndexEntry(*R);
466     return nullptr;
467   }
468 
469   // If there's no index, just search through the CUs in the DWO - there's
470   // probably only one unless this is something like LTO - though an in-process
471   // built/cached lookup table could be used in that case to improve repeated
472   // lookups of different CUs in the DWO.
473   for (const auto &DWOCU : dwo_compile_units())
474     if (DWOCU->getDWOId() == Hash)
475       return DWOCU.get();
476   return nullptr;
477 }
478 
479 DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
480   parseCompileUnits();
481   if (auto *CU = CUs.getUnitForOffset(Offset))
482     return CU->getDIEForOffset(Offset);
483   return DWARFDie();
484 }
485 
486 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
487   bool Success = true;
488   DWARFVerifier verifier(OS, *this, DumpOpts);
489 
490   Success &= verifier.handleDebugAbbrev();
491   if (DumpOpts.DumpType & DIDT_DebugInfo)
492     Success &= verifier.handleDebugInfo();
493   if (DumpOpts.DumpType & DIDT_DebugLine)
494     Success &= verifier.handleDebugLine();
495   Success &= verifier.handleAccelTables();
496   return Success;
497 }
498 
499 const DWARFUnitIndex &DWARFContext::getCUIndex() {
500   if (CUIndex)
501     return *CUIndex;
502 
503   DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
504 
505   CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
506   CUIndex->parse(CUIndexData);
507   return *CUIndex;
508 }
509 
510 const DWARFUnitIndex &DWARFContext::getTUIndex() {
511   if (TUIndex)
512     return *TUIndex;
513 
514   DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
515 
516   TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
517   TUIndex->parse(TUIndexData);
518   return *TUIndex;
519 }
520 
521 DWARFGdbIndex &DWARFContext::getGdbIndex() {
522   if (GdbIndex)
523     return *GdbIndex;
524 
525   DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
526   GdbIndex = llvm::make_unique<DWARFGdbIndex>();
527   GdbIndex->parse(GdbIndexData);
528   return *GdbIndex;
529 }
530 
531 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
532   if (Abbrev)
533     return Abbrev.get();
534 
535   DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
536 
537   Abbrev.reset(new DWARFDebugAbbrev());
538   Abbrev->extract(abbrData);
539   return Abbrev.get();
540 }
541 
542 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
543   if (AbbrevDWO)
544     return AbbrevDWO.get();
545 
546   DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
547   AbbrevDWO.reset(new DWARFDebugAbbrev());
548   AbbrevDWO->extract(abbrData);
549   return AbbrevDWO.get();
550 }
551 
552 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
553   if (Loc)
554     return Loc.get();
555 
556   Loc.reset(new DWARFDebugLoc);
557   // assume all compile units have the same address byte size
558   if (getNumCompileUnits()) {
559     DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
560                                getCompileUnitAtIndex(0)->getAddressByteSize());
561     Loc->parse(LocData);
562   }
563   return Loc.get();
564 }
565 
566 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
567   if (LocDWO)
568     return LocDWO.get();
569 
570   DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
571   LocDWO.reset(new DWARFDebugLocDWO());
572   LocDWO->parse(LocData);
573   return LocDWO.get();
574 }
575 
576 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
577   if (Aranges)
578     return Aranges.get();
579 
580   Aranges.reset(new DWARFDebugAranges());
581   Aranges->generate(this);
582   return Aranges.get();
583 }
584 
585 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
586   if (DebugFrame)
587     return DebugFrame.get();
588 
589   // There's a "bug" in the DWARFv3 standard with respect to the target address
590   // size within debug frame sections. While DWARF is supposed to be independent
591   // of its container, FDEs have fields with size being "target address size",
592   // which isn't specified in DWARF in general. It's only specified for CUs, but
593   // .eh_frame can appear without a .debug_info section. Follow the example of
594   // other tools (libdwarf) and extract this from the container (ObjectFile
595   // provides this information). This problem is fixed in DWARFv4
596   // See this dwarf-discuss discussion for more details:
597   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
598   DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
599                                DObj->getAddressSize());
600   DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
601   DebugFrame->parse(debugFrameData);
602   return DebugFrame.get();
603 }
604 
605 const DWARFDebugFrame *DWARFContext::getEHFrame() {
606   if (EHFrame)
607     return EHFrame.get();
608 
609   DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
610                                DObj->getAddressSize());
611   DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
612   DebugFrame->parse(debugFrameData);
613   return DebugFrame.get();
614 }
615 
616 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
617   if (Macro)
618     return Macro.get();
619 
620   DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
621   Macro.reset(new DWARFDebugMacro());
622   Macro->parse(MacinfoData);
623   return Macro.get();
624 }
625 
626 static DWARFAcceleratorTable &
627 getAccelTable(std::unique_ptr<DWARFAcceleratorTable> &Cache,
628               const DWARFObject &Obj, const DWARFSection &Section,
629               StringRef StringSection, bool IsLittleEndian) {
630   if (Cache)
631     return *Cache;
632   DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
633   DataExtractor StrData(StringSection, IsLittleEndian, 0);
634   Cache.reset(new DWARFAcceleratorTable(AccelSection, StrData));
635   Cache->extract();
636   return *Cache;
637 }
638 
639 const DWARFAcceleratorTable &DWARFContext::getAppleNames() {
640   return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
641                        DObj->getStringSection(), isLittleEndian());
642 }
643 
644 const DWARFAcceleratorTable &DWARFContext::getAppleTypes() {
645   return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
646                        DObj->getStringSection(), isLittleEndian());
647 }
648 
649 const DWARFAcceleratorTable &DWARFContext::getAppleNamespaces() {
650   return getAccelTable(AppleNamespaces, *DObj,
651                        DObj->getAppleNamespacesSection(),
652                        DObj->getStringSection(), isLittleEndian());
653 }
654 
655 const DWARFAcceleratorTable &DWARFContext::getAppleObjC() {
656   return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
657                        DObj->getStringSection(), isLittleEndian());
658 }
659 
660 const DWARFLineTable *
661 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
662   if (!Line)
663     Line.reset(new DWARFDebugLine);
664 
665   auto UnitDIE = U->getUnitDIE();
666   if (!UnitDIE)
667     return nullptr;
668 
669   auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
670   if (!Offset)
671     return nullptr; // No line table for this compile unit.
672 
673   uint32_t stmtOffset = *Offset + U->getLineTableOffset();
674   // See if the line table is cached.
675   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
676     return lt;
677 
678   // Make sure the offset is good before we try to parse.
679   if (stmtOffset >= U->getLineSection().Data.size())
680     return nullptr;
681 
682   // We have to parse it first.
683   DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
684                               U->getAddressByteSize());
685   return Line->getOrParseLineTable(lineData, stmtOffset);
686 }
687 
688 void DWARFContext::parseCompileUnits() {
689   CUs.parse(*this, DObj->getInfoSection());
690 }
691 
692 void DWARFContext::parseTypeUnits() {
693   if (!TUs.empty())
694     return;
695   DObj->forEachTypesSections([&](const DWARFSection &S) {
696     TUs.emplace_back();
697     TUs.back().parse(*this, S);
698   });
699 }
700 
701 void DWARFContext::parseDWOCompileUnits() {
702   DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
703 }
704 
705 void DWARFContext::parseDWOTypeUnits() {
706   if (!DWOTUs.empty())
707     return;
708   DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
709     DWOTUs.emplace_back();
710     DWOTUs.back().parseDWO(*this, S);
711   });
712 }
713 
714 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
715   parseCompileUnits();
716   return CUs.getUnitForOffset(Offset);
717 }
718 
719 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
720   // First, get the offset of the compile unit.
721   uint32_t CUOffset = getDebugAranges()->findAddress(Address);
722   // Retrieve the compile unit.
723   return getCompileUnitForOffset(CUOffset);
724 }
725 
726 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
727                                                   uint64_t Address,
728                                                   FunctionNameKind Kind,
729                                                   std::string &FunctionName,
730                                                   uint32_t &StartLine) {
731   // The address may correspond to instruction in some inlined function,
732   // so we have to build the chain of inlined functions and take the
733   // name of the topmost function in it.
734   SmallVector<DWARFDie, 4> InlinedChain;
735   CU->getInlinedChainForAddress(Address, InlinedChain);
736   if (InlinedChain.empty())
737     return false;
738 
739   const DWARFDie &DIE = InlinedChain[0];
740   bool FoundResult = false;
741   const char *Name = nullptr;
742   if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
743     FunctionName = Name;
744     FoundResult = true;
745   }
746   if (auto DeclLineResult = DIE.getDeclLine()) {
747     StartLine = DeclLineResult;
748     FoundResult = true;
749   }
750 
751   return FoundResult;
752 }
753 
754 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
755                                                DILineInfoSpecifier Spec) {
756   DILineInfo Result;
757 
758   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
759   if (!CU)
760     return Result;
761   getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
762                                         Result.FunctionName,
763                                         Result.StartLine);
764   if (Spec.FLIKind != FileLineInfoKind::None) {
765     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
766       LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
767                                            Spec.FLIKind, Result);
768   }
769   return Result;
770 }
771 
772 DILineInfoTable
773 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
774                                          DILineInfoSpecifier Spec) {
775   DILineInfoTable  Lines;
776   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
777   if (!CU)
778     return Lines;
779 
780   std::string FunctionName = "<invalid>";
781   uint32_t StartLine = 0;
782   getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
783                                         StartLine);
784 
785   // If the Specifier says we don't need FileLineInfo, just
786   // return the top-most function at the starting address.
787   if (Spec.FLIKind == FileLineInfoKind::None) {
788     DILineInfo Result;
789     Result.FunctionName = FunctionName;
790     Result.StartLine = StartLine;
791     Lines.push_back(std::make_pair(Address, Result));
792     return Lines;
793   }
794 
795   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
796 
797   // Get the index of row we're looking for in the line table.
798   std::vector<uint32_t> RowVector;
799   if (!LineTable->lookupAddressRange(Address, Size, RowVector))
800     return Lines;
801 
802   for (uint32_t RowIndex : RowVector) {
803     // Take file number and line/column from the row.
804     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
805     DILineInfo Result;
806     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
807                                   Spec.FLIKind, Result.FileName);
808     Result.FunctionName = FunctionName;
809     Result.Line = Row.Line;
810     Result.Column = Row.Column;
811     Result.StartLine = StartLine;
812     Lines.push_back(std::make_pair(Row.Address, Result));
813   }
814 
815   return Lines;
816 }
817 
818 DIInliningInfo
819 DWARFContext::getInliningInfoForAddress(uint64_t Address,
820                                         DILineInfoSpecifier Spec) {
821   DIInliningInfo InliningInfo;
822 
823   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
824   if (!CU)
825     return InliningInfo;
826 
827   const DWARFLineTable *LineTable = nullptr;
828   SmallVector<DWARFDie, 4> InlinedChain;
829   CU->getInlinedChainForAddress(Address, InlinedChain);
830   if (InlinedChain.size() == 0) {
831     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
832     // try to at least get file/line info from symbol table.
833     if (Spec.FLIKind != FileLineInfoKind::None) {
834       DILineInfo Frame;
835       LineTable = getLineTableForUnit(CU);
836       if (LineTable &&
837           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
838                                                Spec.FLIKind, Frame))
839         InliningInfo.addFrame(Frame);
840     }
841     return InliningInfo;
842   }
843 
844   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
845   for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
846     DWARFDie &FunctionDIE = InlinedChain[i];
847     DILineInfo Frame;
848     // Get function name if necessary.
849     if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
850       Frame.FunctionName = Name;
851     if (auto DeclLineResult = FunctionDIE.getDeclLine())
852       Frame.StartLine = DeclLineResult;
853     if (Spec.FLIKind != FileLineInfoKind::None) {
854       if (i == 0) {
855         // For the topmost frame, initialize the line table of this
856         // compile unit and fetch file/line info from it.
857         LineTable = getLineTableForUnit(CU);
858         // For the topmost routine, get file/line info from line table.
859         if (LineTable)
860           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
861                                                Spec.FLIKind, Frame);
862       } else {
863         // Otherwise, use call file, call line and call column from
864         // previous DIE in inlined chain.
865         if (LineTable)
866           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
867                                         Spec.FLIKind, Frame.FileName);
868         Frame.Line = CallLine;
869         Frame.Column = CallColumn;
870         Frame.Discriminator = CallDiscriminator;
871       }
872       // Get call file/line/column of a current DIE.
873       if (i + 1 < n) {
874         FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
875                                    CallDiscriminator);
876       }
877     }
878     InliningInfo.addFrame(Frame);
879   }
880   return InliningInfo;
881 }
882 
883 std::shared_ptr<DWARFContext>
884 DWARFContext::getDWOContext(StringRef AbsolutePath) {
885   if (auto S = DWP.lock()) {
886     DWARFContext *Ctxt = S->Context.get();
887     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
888   }
889 
890   std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
891 
892   if (auto S = Entry->lock()) {
893     DWARFContext *Ctxt = S->Context.get();
894     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
895   }
896 
897   Expected<OwningBinary<ObjectFile>> Obj = [&] {
898     if (!CheckedForDWP) {
899       SmallString<128> DWPName;
900       auto Obj = object::ObjectFile::createObjectFile(
901           this->DWPName.empty()
902               ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
903               : StringRef(this->DWPName));
904       if (Obj) {
905         Entry = &DWP;
906         return Obj;
907       } else {
908         CheckedForDWP = true;
909         // TODO: Should this error be handled (maybe in a high verbosity mode)
910         // before falling back to .dwo files?
911         consumeError(Obj.takeError());
912       }
913     }
914 
915     return object::ObjectFile::createObjectFile(AbsolutePath);
916   }();
917 
918   if (!Obj) {
919     // TODO: Actually report errors helpfully.
920     consumeError(Obj.takeError());
921     return nullptr;
922   }
923 
924   auto S = std::make_shared<DWOFile>();
925   S->File = std::move(Obj.get());
926   S->Context = DWARFContext::create(*S->File.getBinary());
927   *Entry = S;
928   auto *Ctxt = S->Context.get();
929   return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
930 }
931 
932 static Error createError(const Twine &Reason, llvm::Error E) {
933   return make_error<StringError>(Reason + toString(std::move(E)),
934                                  inconvertibleErrorCode());
935 }
936 
937 /// SymInfo contains information about symbol: it's address
938 /// and section index which is -1LL for absolute symbols.
939 struct SymInfo {
940   uint64_t Address;
941   uint64_t SectionIndex;
942 };
943 
944 /// Returns the address of symbol relocation used against and a section index.
945 /// Used for futher relocations computation. Symbol's section load address is
946 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
947                                        const RelocationRef &Reloc,
948                                        const LoadedObjectInfo *L,
949                                        std::map<SymbolRef, SymInfo> &Cache) {
950   SymInfo Ret = {0, (uint64_t)-1LL};
951   object::section_iterator RSec = Obj.section_end();
952   object::symbol_iterator Sym = Reloc.getSymbol();
953 
954   std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
955   // First calculate the address of the symbol or section as it appears
956   // in the object file
957   if (Sym != Obj.symbol_end()) {
958     bool New;
959     std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
960     if (!New)
961       return CacheIt->second;
962 
963     Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
964     if (!SymAddrOrErr)
965       return createError("failed to compute symbol address: ",
966                          SymAddrOrErr.takeError());
967 
968     // Also remember what section this symbol is in for later
969     auto SectOrErr = Sym->getSection();
970     if (!SectOrErr)
971       return createError("failed to get symbol section: ",
972                          SectOrErr.takeError());
973 
974     RSec = *SectOrErr;
975     Ret.Address = *SymAddrOrErr;
976   } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
977     RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
978     Ret.Address = RSec->getAddress();
979   }
980 
981   if (RSec != Obj.section_end())
982     Ret.SectionIndex = RSec->getIndex();
983 
984   // If we are given load addresses for the sections, we need to adjust:
985   // SymAddr = (Address of Symbol Or Section in File) -
986   //           (Address of Section in File) +
987   //           (Load Address of Section)
988   // RSec is now either the section being targeted or the section
989   // containing the symbol being targeted. In either case,
990   // we need to perform the same computation.
991   if (L && RSec != Obj.section_end())
992     if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
993       Ret.Address += SectionLoadAddress - RSec->getAddress();
994 
995   if (CacheIt != Cache.end())
996     CacheIt->second = Ret;
997 
998   return Ret;
999 }
1000 
1001 static bool isRelocScattered(const object::ObjectFile &Obj,
1002                              const RelocationRef &Reloc) {
1003   const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1004   if (!MachObj)
1005     return false;
1006   // MachO also has relocations that point to sections and
1007   // scattered relocations.
1008   auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1009   return MachObj->isRelocationScattered(RelocInfo);
1010 }
1011 
1012 ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
1013   errs() << "error: " + toString(std::move(E)) << '\n';
1014   return ErrorPolicy::Continue;
1015 }
1016 
1017 namespace {
1018 struct DWARFSectionMap final : public DWARFSection {
1019   RelocAddrMap Relocs;
1020 };
1021 
1022 class DWARFObjInMemory final : public DWARFObject {
1023   bool IsLittleEndian;
1024   uint8_t AddressSize;
1025   StringRef FileName;
1026   const object::ObjectFile *Obj = nullptr;
1027   std::vector<SectionName> SectionNames;
1028 
1029   using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1030                                    std::map<object::SectionRef, unsigned>>;
1031 
1032   TypeSectionMap TypesSections;
1033   TypeSectionMap TypesDWOSections;
1034 
1035   DWARFSectionMap InfoSection;
1036   DWARFSectionMap LocSection;
1037   DWARFSectionMap LineSection;
1038   DWARFSectionMap RangeSection;
1039   DWARFSectionMap StringOffsetSection;
1040   DWARFSectionMap InfoDWOSection;
1041   DWARFSectionMap LineDWOSection;
1042   DWARFSectionMap LocDWOSection;
1043   DWARFSectionMap StringOffsetDWOSection;
1044   DWARFSectionMap RangeDWOSection;
1045   DWARFSectionMap AddrSection;
1046   DWARFSectionMap AppleNamesSection;
1047   DWARFSectionMap AppleTypesSection;
1048   DWARFSectionMap AppleNamespacesSection;
1049   DWARFSectionMap AppleObjCSection;
1050 
1051   DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1052     return StringSwitch<DWARFSectionMap *>(Name)
1053         .Case("debug_info", &InfoSection)
1054         .Case("debug_loc", &LocSection)
1055         .Case("debug_line", &LineSection)
1056         .Case("debug_str_offsets", &StringOffsetSection)
1057         .Case("debug_ranges", &RangeSection)
1058         .Case("debug_info.dwo", &InfoDWOSection)
1059         .Case("debug_loc.dwo", &LocDWOSection)
1060         .Case("debug_line.dwo", &LineDWOSection)
1061         .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1062         .Case("debug_addr", &AddrSection)
1063         .Case("apple_names", &AppleNamesSection)
1064         .Case("apple_types", &AppleTypesSection)
1065         .Case("apple_namespaces", &AppleNamespacesSection)
1066         .Case("apple_namespac", &AppleNamespacesSection)
1067         .Case("apple_objc", &AppleObjCSection)
1068         .Default(nullptr);
1069   }
1070 
1071   StringRef AbbrevSection;
1072   StringRef ARangeSection;
1073   StringRef DebugFrameSection;
1074   StringRef EHFrameSection;
1075   StringRef StringSection;
1076   StringRef MacinfoSection;
1077   StringRef PubNamesSection;
1078   StringRef PubTypesSection;
1079   StringRef GnuPubNamesSection;
1080   StringRef AbbrevDWOSection;
1081   StringRef StringDWOSection;
1082   StringRef GnuPubTypesSection;
1083   StringRef CUIndexSection;
1084   StringRef GdbIndexSection;
1085   StringRef TUIndexSection;
1086 
1087   SmallVector<SmallString<32>, 4> UncompressedSections;
1088 
1089   StringRef *mapSectionToMember(StringRef Name) {
1090     if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1091       return &Sec->Data;
1092     return StringSwitch<StringRef *>(Name)
1093         .Case("debug_abbrev", &AbbrevSection)
1094         .Case("debug_aranges", &ARangeSection)
1095         .Case("debug_frame", &DebugFrameSection)
1096         .Case("eh_frame", &EHFrameSection)
1097         .Case("debug_str", &StringSection)
1098         .Case("debug_macinfo", &MacinfoSection)
1099         .Case("debug_pubnames", &PubNamesSection)
1100         .Case("debug_pubtypes", &PubTypesSection)
1101         .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1102         .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1103         .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1104         .Case("debug_str.dwo", &StringDWOSection)
1105         .Case("debug_cu_index", &CUIndexSection)
1106         .Case("debug_tu_index", &TUIndexSection)
1107         .Case("gdb_index", &GdbIndexSection)
1108         // Any more debug info sections go here.
1109         .Default(nullptr);
1110   }
1111 
1112   /// If Sec is compressed section, decompresses and updates its contents
1113   /// provided by Data. Otherwise leaves it unchanged.
1114   Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1115                         StringRef &Data) {
1116     if (!Decompressor::isCompressed(Sec))
1117       return Error::success();
1118 
1119     Expected<Decompressor> Decompressor =
1120         Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1121     if (!Decompressor)
1122       return Decompressor.takeError();
1123 
1124     SmallString<32> Out;
1125     if (auto Err = Decompressor->resizeAndDecompress(Out))
1126       return Err;
1127 
1128     UncompressedSections.emplace_back(std::move(Out));
1129     Data = UncompressedSections.back();
1130 
1131     return Error::success();
1132   }
1133 
1134 public:
1135   DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1136                    uint8_t AddrSize, bool IsLittleEndian)
1137       : IsLittleEndian(IsLittleEndian) {
1138     for (const auto &SecIt : Sections) {
1139       if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1140         *SectionData = SecIt.second->getBuffer();
1141     }
1142   }
1143   DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1144                    function_ref<ErrorPolicy(Error)> HandleError)
1145       : IsLittleEndian(Obj.isLittleEndian()),
1146         AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1147         Obj(&Obj) {
1148 
1149     StringMap<unsigned> SectionAmountMap;
1150     for (const SectionRef &Section : Obj.sections()) {
1151       StringRef Name;
1152       Section.getName(Name);
1153       ++SectionAmountMap[Name];
1154       SectionNames.push_back({ Name, true });
1155 
1156       // Skip BSS and Virtual sections, they aren't interesting.
1157       if (Section.isBSS() || Section.isVirtual())
1158         continue;
1159 
1160       // Skip sections stripped by dsymutil.
1161       if (Section.isStripped())
1162         continue;
1163 
1164       StringRef Data;
1165       section_iterator RelocatedSection = Section.getRelocatedSection();
1166       // Try to obtain an already relocated version of this section.
1167       // Else use the unrelocated section from the object file. We'll have to
1168       // apply relocations ourselves later.
1169       if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1170         Section.getContents(Data);
1171 
1172       if (auto Err = maybeDecompress(Section, Name, Data)) {
1173         ErrorPolicy EP = HandleError(createError(
1174             "failed to decompress '" + Name + "', ", std::move(Err)));
1175         if (EP == ErrorPolicy::Halt)
1176           return;
1177         continue;
1178       }
1179 
1180       // Compressed sections names in GNU style starts from ".z",
1181       // at this point section is decompressed and we drop compression prefix.
1182       Name = Name.substr(
1183           Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1184 
1185       // Map platform specific debug section names to DWARF standard section
1186       // names.
1187       Name = Obj.mapDebugSectionName(Name);
1188 
1189       if (StringRef *SectionData = mapSectionToMember(Name)) {
1190         *SectionData = Data;
1191         if (Name == "debug_ranges") {
1192           // FIXME: Use the other dwo range section when we emit it.
1193           RangeDWOSection.Data = Data;
1194         }
1195       } else if (Name == "debug_types") {
1196         // Find debug_types data by section rather than name as there are
1197         // multiple, comdat grouped, debug_types sections.
1198         TypesSections[Section].Data = Data;
1199       } else if (Name == "debug_types.dwo") {
1200         TypesDWOSections[Section].Data = Data;
1201       }
1202 
1203       if (RelocatedSection == Obj.section_end())
1204         continue;
1205 
1206       StringRef RelSecName;
1207       StringRef RelSecData;
1208       RelocatedSection->getName(RelSecName);
1209 
1210       // If the section we're relocating was relocated already by the JIT,
1211       // then we used the relocated version above, so we do not need to process
1212       // relocations for it now.
1213       if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1214         continue;
1215 
1216       // In Mach-o files, the relocations do not need to be applied if
1217       // there is no load offset to apply. The value read at the
1218       // relocation point already factors in the section address
1219       // (actually applying the relocations will produce wrong results
1220       // as the section address will be added twice).
1221       if (!L && isa<MachOObjectFile>(&Obj))
1222         continue;
1223 
1224       RelSecName = RelSecName.substr(
1225           RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1226 
1227       // TODO: Add support for relocations in other sections as needed.
1228       // Record relocations for the debug_info and debug_line sections.
1229       DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1230       RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1231       if (!Map) {
1232         // Find debug_types relocs by section rather than name as there are
1233         // multiple, comdat grouped, debug_types sections.
1234         if (RelSecName == "debug_types")
1235           Map =
1236               &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1237                    .Relocs;
1238         else if (RelSecName == "debug_types.dwo")
1239           Map = &static_cast<DWARFSectionMap &>(
1240                      TypesDWOSections[*RelocatedSection])
1241                      .Relocs;
1242         else
1243           continue;
1244       }
1245 
1246       if (Section.relocation_begin() == Section.relocation_end())
1247         continue;
1248 
1249       // Symbol to [address, section index] cache mapping.
1250       std::map<SymbolRef, SymInfo> AddrCache;
1251       for (const RelocationRef &Reloc : Section.relocations()) {
1252         // FIXME: it's not clear how to correctly handle scattered
1253         // relocations.
1254         if (isRelocScattered(Obj, Reloc))
1255           continue;
1256 
1257         Expected<SymInfo> SymInfoOrErr =
1258             getSymbolInfo(Obj, Reloc, L, AddrCache);
1259         if (!SymInfoOrErr) {
1260           if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1261             return;
1262           continue;
1263         }
1264 
1265         object::RelocVisitor V(Obj);
1266         uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1267         if (V.error()) {
1268           SmallString<32> Type;
1269           Reloc.getTypeName(Type);
1270           ErrorPolicy EP = HandleError(
1271               createError("failed to compute relocation: " + Type + ", ",
1272                           errorCodeToError(object_error::parse_failed)));
1273           if (EP == ErrorPolicy::Halt)
1274             return;
1275           continue;
1276         }
1277         RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1278         Map->insert({Reloc.getOffset(), Rel});
1279       }
1280     }
1281 
1282     for (SectionName &S : SectionNames)
1283       if (SectionAmountMap[S.Name] > 1)
1284         S.IsNameUnique = false;
1285   }
1286 
1287   Optional<RelocAddrEntry> find(const DWARFSection &S,
1288                                 uint64_t Pos) const override {
1289     auto &Sec = static_cast<const DWARFSectionMap &>(S);
1290     RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1291     if (AI == Sec.Relocs.end())
1292       return None;
1293     return AI->second;
1294   }
1295 
1296   const object::ObjectFile *getFile() const override { return Obj; }
1297 
1298   ArrayRef<SectionName> getSectionNames() const override {
1299     return SectionNames;
1300   }
1301 
1302   bool isLittleEndian() const override { return IsLittleEndian; }
1303   StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1304   const DWARFSection &getLineDWOSection() const override {
1305     return LineDWOSection;
1306   }
1307   const DWARFSection &getLocDWOSection() const override {
1308     return LocDWOSection;
1309   }
1310   StringRef getStringDWOSection() const override { return StringDWOSection; }
1311   const DWARFSection &getStringOffsetDWOSection() const override {
1312     return StringOffsetDWOSection;
1313   }
1314   const DWARFSection &getRangeDWOSection() const override {
1315     return RangeDWOSection;
1316   }
1317   const DWARFSection &getAddrSection() const override { return AddrSection; }
1318   StringRef getCUIndexSection() const override { return CUIndexSection; }
1319   StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1320   StringRef getTUIndexSection() const override { return TUIndexSection; }
1321 
1322   // DWARF v5
1323   const DWARFSection &getStringOffsetSection() const override {
1324     return StringOffsetSection;
1325   }
1326 
1327   // Sections for DWARF5 split dwarf proposal.
1328   const DWARFSection &getInfoDWOSection() const override {
1329     return InfoDWOSection;
1330   }
1331   void forEachTypesDWOSections(
1332       function_ref<void(const DWARFSection &)> F) const override {
1333     for (auto &P : TypesDWOSections)
1334       F(P.second);
1335   }
1336 
1337   StringRef getAbbrevSection() const override { return AbbrevSection; }
1338   const DWARFSection &getLocSection() const override { return LocSection; }
1339   StringRef getARangeSection() const override { return ARangeSection; }
1340   StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1341   StringRef getEHFrameSection() const override { return EHFrameSection; }
1342   const DWARFSection &getLineSection() const override { return LineSection; }
1343   StringRef getStringSection() const override { return StringSection; }
1344   const DWARFSection &getRangeSection() const override { return RangeSection; }
1345   StringRef getMacinfoSection() const override { return MacinfoSection; }
1346   StringRef getPubNamesSection() const override { return PubNamesSection; }
1347   StringRef getPubTypesSection() const override { return PubTypesSection; }
1348   StringRef getGnuPubNamesSection() const override {
1349     return GnuPubNamesSection;
1350   }
1351   StringRef getGnuPubTypesSection() const override {
1352     return GnuPubTypesSection;
1353   }
1354   const DWARFSection &getAppleNamesSection() const override {
1355     return AppleNamesSection;
1356   }
1357   const DWARFSection &getAppleTypesSection() const override {
1358     return AppleTypesSection;
1359   }
1360   const DWARFSection &getAppleNamespacesSection() const override {
1361     return AppleNamespacesSection;
1362   }
1363   const DWARFSection &getAppleObjCSection() const override {
1364     return AppleObjCSection;
1365   }
1366 
1367   StringRef getFileName() const override { return FileName; }
1368   uint8_t getAddressSize() const override { return AddressSize; }
1369   const DWARFSection &getInfoSection() const override { return InfoSection; }
1370   void forEachTypesSections(
1371       function_ref<void(const DWARFSection &)> F) const override {
1372     for (auto &P : TypesSections)
1373       F(P.second);
1374   }
1375 };
1376 } // namespace
1377 
1378 std::unique_ptr<DWARFContext>
1379 DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1380                      function_ref<ErrorPolicy(Error)> HandleError,
1381                      std::string DWPName) {
1382   auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
1383   return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
1384 }
1385 
1386 std::unique_ptr<DWARFContext>
1387 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1388                      uint8_t AddrSize, bool isLittleEndian) {
1389   auto DObj =
1390       llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1391   return llvm::make_unique<DWARFContext>(std::move(DObj), "");
1392 }
1393 
1394 Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1395   // Detect the architecture from the object file. We usually don't need OS
1396   // info to lookup a target and create register info.
1397   Triple TT;
1398   TT.setArch(Triple::ArchType(Obj.getArch()));
1399   TT.setVendor(Triple::UnknownVendor);
1400   TT.setOS(Triple::UnknownOS);
1401   std::string TargetLookupError;
1402   const Target *TheTarget =
1403       TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1404   if (!TargetLookupError.empty())
1405     return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1406   RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1407   return Error::success();
1408 }
1409