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