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