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