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