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