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