1 //===- DWARFContext.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/BinaryFormat/Dwarf.h"
16 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
17 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugAddr.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/DWARFDebugRnglists.h"
29 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
30 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
31 #include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
32 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
33 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
34 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
35 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/Object/Decompressor.h"
37 #include "llvm/Object/MachO.h"
38 #include "llvm/Object/ObjectFile.h"
39 #include "llvm/Object/RelocationResolver.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/DataExtractor.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/Format.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cstdint>
51 #include <deque>
52 #include <map>
53 #include <string>
54 #include <utility>
55 #include <vector>
56 
57 using namespace llvm;
58 using namespace dwarf;
59 using namespace object;
60 
61 #define DEBUG_TYPE "dwarf"
62 
63 using DWARFLineTable = DWARFDebugLine::LineTable;
64 using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
65 using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
66 
67 DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
68                            std::string DWPName,
69                            std::function<void(Error)> RecoverableErrorHandler,
70                            std::function<void(Error)> WarningHandler)
71     : DIContext(CK_DWARF), DWPName(std::move(DWPName)),
72       RecoverableErrorHandler(RecoverableErrorHandler),
73       WarningHandler(WarningHandler), DObj(std::move(DObj)) {}
74 
75 DWARFContext::~DWARFContext() = default;
76 
77 /// Dump the UUID load command.
78 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
79   auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
80   if (!MachO)
81     return;
82   for (auto LC : MachO->load_commands()) {
83     raw_ostream::uuid_t UUID;
84     if (LC.C.cmd == MachO::LC_UUID) {
85       if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
86         OS << "error: UUID load command is too short.\n";
87         return;
88       }
89       OS << "UUID: ";
90       memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
91       OS.write_uuid(UUID);
92       Triple T = MachO->getArchTriple();
93       OS << " (" << T.getArchName() << ')';
94       OS << ' ' << MachO->getFileName() << '\n';
95     }
96   }
97 }
98 
99 using ContributionCollection =
100     std::vector<Optional<StrOffsetsContributionDescriptor>>;
101 
102 // Collect all the contributions to the string offsets table from all units,
103 // sort them by their starting offsets and remove duplicates.
104 static ContributionCollection
105 collectContributionData(DWARFContext::unit_iterator_range Units) {
106   ContributionCollection Contributions;
107   for (const auto &U : Units)
108     if (const auto &C = U->getStringOffsetsTableContribution())
109       Contributions.push_back(C);
110   // Sort the contributions so that any invalid ones are placed at
111   // the start of the contributions vector. This way they are reported
112   // first.
113   llvm::sort(Contributions,
114              [](const Optional<StrOffsetsContributionDescriptor> &L,
115                 const Optional<StrOffsetsContributionDescriptor> &R) {
116                if (L && R)
117                  return L->Base < R->Base;
118                return R.hasValue();
119              });
120 
121   // Uniquify contributions, as it is possible that units (specifically
122   // type units in dwo or dwp files) share contributions. We don't want
123   // to report them more than once.
124   Contributions.erase(
125       std::unique(Contributions.begin(), Contributions.end(),
126                   [](const Optional<StrOffsetsContributionDescriptor> &L,
127                      const Optional<StrOffsetsContributionDescriptor> &R) {
128                     if (L && R)
129                       return L->Base == R->Base && L->Size == R->Size;
130                     return false;
131                   }),
132       Contributions.end());
133   return Contributions;
134 }
135 
136 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted
137 // string offsets section, where each compile or type unit contributes a
138 // number of entries (string offsets), with each contribution preceded by
139 // a header containing size and version number. Alternatively, it may be a
140 // monolithic series of string offsets, as generated by the pre-DWARF v5
141 // implementation of split DWARF; however, in that case we still need to
142 // collect contributions of units because the size of the offsets (4 or 8
143 // bytes) depends on the format of the referencing unit (DWARF32 or DWARF64).
144 static void dumpStringOffsetsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
145                                      StringRef SectionName,
146                                      const DWARFObject &Obj,
147                                      const DWARFSection &StringOffsetsSection,
148                                      StringRef StringSection,
149                                      DWARFContext::unit_iterator_range Units,
150                                      bool LittleEndian) {
151   auto Contributions = collectContributionData(Units);
152   DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
153   DataExtractor StrData(StringSection, LittleEndian, 0);
154   uint64_t SectionSize = StringOffsetsSection.Data.size();
155   uint64_t Offset = 0;
156   for (auto &Contribution : Contributions) {
157     // Report an ill-formed contribution.
158     if (!Contribution) {
159       OS << "error: invalid contribution to string offsets table in section ."
160          << SectionName << ".\n";
161       return;
162     }
163 
164     dwarf::DwarfFormat Format = Contribution->getFormat();
165     uint16_t Version = Contribution->getVersion();
166     uint64_t ContributionHeader = Contribution->Base;
167     // In DWARF v5 there is a contribution header that immediately precedes
168     // the string offsets base (the location we have previously retrieved from
169     // the CU DIE's DW_AT_str_offsets attribute). The header is located either
170     // 8 or 16 bytes before the base, depending on the contribution's format.
171     if (Version >= 5)
172       ContributionHeader -= Format == DWARF32 ? 8 : 16;
173 
174     // Detect overlapping contributions.
175     if (Offset > ContributionHeader) {
176       DumpOpts.RecoverableErrorHandler(createStringError(
177           errc::invalid_argument,
178           "overlapping contributions to string offsets table in section .%s.",
179           SectionName.data()));
180     }
181     // Report a gap in the table.
182     if (Offset < ContributionHeader) {
183       OS << format("0x%8.8" PRIx64 ": Gap, length = ", Offset);
184       OS << (ContributionHeader - Offset) << "\n";
185     }
186     OS << format("0x%8.8" PRIx64 ": ", ContributionHeader);
187     // In DWARF v5 the contribution size in the descriptor does not equal
188     // the originally encoded length (it does not contain the length of the
189     // version field and the padding, a total of 4 bytes). Add them back in
190     // for reporting.
191     OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
192        << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
193        << ", Version = " << Version << "\n";
194 
195     Offset = Contribution->Base;
196     unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
197     while (Offset - Contribution->Base < Contribution->Size) {
198       OS << format("0x%8.8" PRIx64 ": ", Offset);
199       uint64_t StringOffset =
200           StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
201       OS << format("%8.8" PRIx64 " ", StringOffset);
202       const char *S = StrData.getCStr(&StringOffset);
203       if (S)
204         OS << format("\"%s\"", S);
205       OS << "\n";
206     }
207   }
208   // Report a gap at the end of the table.
209   if (Offset < SectionSize) {
210     OS << format("0x%8.8" PRIx64 ": Gap, length = ", Offset);
211     OS << (SectionSize - Offset) << "\n";
212   }
213 }
214 
215 // Dump the .debug_addr section.
216 static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
217                             DIDumpOptions DumpOpts, uint16_t Version,
218                             uint8_t AddrSize) {
219   uint64_t Offset = 0;
220   while (AddrData.isValidOffset(Offset)) {
221     DWARFDebugAddrTable AddrTable;
222     uint64_t TableOffset = Offset;
223     if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
224                                       DumpOpts.WarningHandler)) {
225       DumpOpts.RecoverableErrorHandler(std::move(Err));
226       // Keep going after an error, if we can, assuming that the length field
227       // could be read. If it couldn't, stop reading the section.
228       if (auto TableLength = AddrTable.getFullLength()) {
229         Offset = TableOffset + *TableLength;
230         continue;
231       }
232       break;
233     }
234     AddrTable.dump(OS, DumpOpts);
235   }
236 }
237 
238 // Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
239 static void dumpRnglistsSection(
240     raw_ostream &OS, DWARFDataExtractor &rnglistData,
241     llvm::function_ref<Optional<object::SectionedAddress>(uint32_t)>
242         LookupPooledAddress,
243     DIDumpOptions DumpOpts) {
244   uint64_t Offset = 0;
245   while (rnglistData.isValidOffset(Offset)) {
246     llvm::DWARFDebugRnglistTable Rnglists;
247     uint64_t TableOffset = Offset;
248     if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
249       DumpOpts.RecoverableErrorHandler(std::move(Err));
250       uint64_t Length = Rnglists.length();
251       // Keep going after an error, if we can, assuming that the length field
252       // could be read. If it couldn't, stop reading the section.
253       if (Length == 0)
254         break;
255       Offset = TableOffset + Length;
256     } else {
257       Rnglists.dump(OS, LookupPooledAddress, DumpOpts);
258     }
259   }
260 }
261 
262 std::unique_ptr<DWARFDebugMacro>
263 DWARFContext::parseMacroOrMacinfo(MacroSecType SectionType) {
264   auto Macro = std::make_unique<DWARFDebugMacro>();
265   auto ParseAndDump = [&](DWARFDataExtractor &Data, bool IsMacro) {
266     // FIXME: Add support for debug_macro.dwo section.
267     if (Error Err = IsMacro ? Macro->parseMacro(compile_units(),
268                                                 getStringExtractor(), Data)
269                             : Macro->parseMacinfo(Data)) {
270       RecoverableErrorHandler(std::move(Err));
271       Macro = nullptr;
272     }
273   };
274   switch (SectionType) {
275   case MacinfoSection: {
276     DWARFDataExtractor Data(DObj->getMacinfoSection(), isLittleEndian(), 0);
277     ParseAndDump(Data, /*IsMacro=*/false);
278     break;
279   }
280   case MacinfoDwoSection: {
281     DWARFDataExtractor Data(DObj->getMacinfoDWOSection(), isLittleEndian(), 0);
282     ParseAndDump(Data, /*IsMacro=*/false);
283     break;
284   }
285   case MacroSection: {
286     DWARFDataExtractor Data(*DObj, DObj->getMacroSection(), isLittleEndian(),
287                             0);
288     ParseAndDump(Data, /*IsMacro=*/true);
289     break;
290   }
291   }
292   return Macro;
293 }
294 
295 static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
296                                 DWARFDataExtractor Data,
297                                 const MCRegisterInfo *MRI,
298                                 const DWARFObject &Obj,
299                                 Optional<uint64_t> DumpOffset) {
300   uint64_t Offset = 0;
301 
302   while (Data.isValidOffset(Offset)) {
303     DWARFListTableHeader Header(".debug_loclists", "locations");
304     if (Error E = Header.extract(Data, &Offset)) {
305       DumpOpts.RecoverableErrorHandler(std::move(E));
306       return;
307     }
308 
309     Header.dump(OS, DumpOpts);
310 
311     uint64_t EndOffset = Header.length() + Header.getHeaderOffset();
312     Data.setAddressSize(Header.getAddrSize());
313     DWARFDebugLoclists Loc(Data, Header.getVersion());
314     if (DumpOffset) {
315       if (DumpOffset >= Offset && DumpOffset < EndOffset) {
316         Offset = *DumpOffset;
317         Loc.dumpLocationList(&Offset, OS, /*BaseAddr=*/None, MRI, Obj, nullptr,
318                              DumpOpts, /*Indent=*/0);
319         OS << "\n";
320         return;
321       }
322     } else {
323       Loc.dumpRange(Offset, EndOffset - Offset, OS, MRI, Obj, DumpOpts);
324     }
325     Offset = EndOffset;
326   }
327 }
328 
329 void DWARFContext::dump(
330     raw_ostream &OS, DIDumpOptions DumpOpts,
331     std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
332   uint64_t DumpType = DumpOpts.DumpType;
333 
334   StringRef Extension = sys::path::extension(DObj->getFileName());
335   bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
336 
337   // Print UUID header.
338   const auto *ObjFile = DObj->getFile();
339   if (DumpType & DIDT_UUID)
340     dumpUUID(OS, *ObjFile);
341 
342   // Print a header for each explicitly-requested section.
343   // Otherwise just print one for non-empty sections.
344   // Only print empty .dwo section headers when dumping a .dwo file.
345   bool Explicit = DumpType != DIDT_All && !IsDWO;
346   bool ExplicitDWO = Explicit && IsDWO;
347   auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
348                         StringRef Section) -> Optional<uint64_t> * {
349     unsigned Mask = 1U << ID;
350     bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
351     if (!Should)
352       return nullptr;
353     OS << "\n" << Name << " contents:\n";
354     return &DumpOffsets[ID];
355   };
356 
357   // Dump individual sections.
358   if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
359                  DObj->getAbbrevSection()))
360     getDebugAbbrev()->dump(OS);
361   if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
362                  DObj->getAbbrevDWOSection()))
363     getDebugAbbrevDWO()->dump(OS);
364 
365   auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
366     OS << '\n' << Name << " contents:\n";
367     if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
368       for (const auto &U : Units)
369         U->getDIEForOffset(DumpOffset.getValue())
370             .dump(OS, 0, DumpOpts.noImplicitRecursion());
371     else
372       for (const auto &U : Units)
373         U->dump(OS, DumpOpts);
374   };
375   if ((DumpType & DIDT_DebugInfo)) {
376     if (Explicit || getNumCompileUnits())
377       dumpDebugInfo(".debug_info", info_section_units());
378     if (ExplicitDWO || getNumDWOCompileUnits())
379       dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
380   }
381 
382   auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
383     OS << '\n' << Name << " contents:\n";
384     for (const auto &U : Units)
385       if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
386         U->getDIEForOffset(*DumpOffset)
387             .dump(OS, 0, DumpOpts.noImplicitRecursion());
388       else
389         U->dump(OS, DumpOpts);
390   };
391   if ((DumpType & DIDT_DebugTypes)) {
392     if (Explicit || getNumTypeUnits())
393       dumpDebugType(".debug_types", types_section_units());
394     if (ExplicitDWO || getNumDWOTypeUnits())
395       dumpDebugType(".debug_types.dwo", dwo_types_section_units());
396   }
397 
398   DIDumpOptions LLDumpOpts = DumpOpts;
399   if (LLDumpOpts.Verbose)
400     LLDumpOpts.DisplayRawContents = true;
401 
402   if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
403                                    DObj->getLocSection().Data)) {
404     getDebugLoc()->dump(OS, getRegisterInfo(), *DObj, LLDumpOpts, *Off);
405   }
406   if (const auto *Off =
407           shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
408                      DObj->getLoclistsSection().Data)) {
409     DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
410                             0);
411     dumpLoclistsSection(OS, LLDumpOpts, Data, getRegisterInfo(), *DObj, *Off);
412   }
413   if (const auto *Off =
414           shouldDump(ExplicitDWO, ".debug_loclists.dwo", DIDT_ID_DebugLoclists,
415                      DObj->getLoclistsDWOSection().Data)) {
416     DWARFDataExtractor Data(*DObj, DObj->getLoclistsDWOSection(),
417                             isLittleEndian(), 0);
418     dumpLoclistsSection(OS, LLDumpOpts, Data, getRegisterInfo(), *DObj, *Off);
419   }
420 
421   if (const auto *Off =
422           shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
423                      DObj->getLocDWOSection().Data)) {
424     DWARFDataExtractor Data(*DObj, DObj->getLocDWOSection(), isLittleEndian(),
425                             4);
426     DWARFDebugLoclists Loc(Data, /*Version=*/4);
427     if (*Off) {
428       uint64_t Offset = **Off;
429       Loc.dumpLocationList(&Offset, OS,
430                            /*BaseAddr=*/None, getRegisterInfo(), *DObj, nullptr,
431                            LLDumpOpts, /*Indent=*/0);
432       OS << "\n";
433     } else {
434       Loc.dumpRange(0, Data.getData().size(), OS, getRegisterInfo(), *DObj,
435                     LLDumpOpts);
436     }
437   }
438 
439   if (const Optional<uint64_t> *Off =
440           shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
441                      DObj->getFrameSection().Data)) {
442     if (Expected<const DWARFDebugFrame *> DF = getDebugFrame())
443       (*DF)->dump(OS, getRegisterInfo(), *Off);
444     else
445       RecoverableErrorHandler(DF.takeError());
446   }
447 
448   if (const Optional<uint64_t> *Off =
449           shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
450                      DObj->getEHFrameSection().Data)) {
451     if (Expected<const DWARFDebugFrame *> DF = getEHFrame())
452       (*DF)->dump(OS, getRegisterInfo(), *Off);
453     else
454       RecoverableErrorHandler(DF.takeError());
455   }
456 
457   if (shouldDump(Explicit, ".debug_macro", DIDT_ID_DebugMacro,
458                  DObj->getMacroSection().Data)) {
459     if (auto Macro = getDebugMacro())
460       Macro->dump(OS);
461   }
462 
463   if (shouldDump(Explicit, ".debug_macinfo", DIDT_ID_DebugMacro,
464                  DObj->getMacinfoSection())) {
465     if (auto Macinfo = getDebugMacinfo())
466       Macinfo->dump(OS);
467   }
468 
469   if (shouldDump(Explicit, ".debug_macinfo.dwo", DIDT_ID_DebugMacro,
470                  DObj->getMacinfoDWOSection())) {
471     if (auto MacinfoDWO = getDebugMacinfoDWO())
472       MacinfoDWO->dump(OS);
473   }
474 
475   if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
476                  DObj->getArangesSection())) {
477     uint64_t offset = 0;
478     DWARFDataExtractor arangesData(DObj->getArangesSection(), isLittleEndian(),
479                                    0);
480     DWARFDebugArangeSet set;
481     while (arangesData.isValidOffset(offset)) {
482       if (Error E = set.extract(arangesData, &offset)) {
483         RecoverableErrorHandler(std::move(E));
484         break;
485       }
486       set.dump(OS);
487     }
488   }
489 
490   auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
491                              DIDumpOptions DumpOpts,
492                              Optional<uint64_t> DumpOffset) {
493     while (!Parser.done()) {
494       if (DumpOffset && Parser.getOffset() != *DumpOffset) {
495         Parser.skip(DumpOpts.WarningHandler, DumpOpts.WarningHandler);
496         continue;
497       }
498       OS << "debug_line[" << format("0x%8.8" PRIx64, Parser.getOffset())
499          << "]\n";
500       OS.flush();
501       if (DumpOpts.Verbose) {
502         Parser.parseNext(DumpOpts.WarningHandler, DumpOpts.WarningHandler, &OS);
503       } else {
504         DWARFDebugLine::LineTable LineTable =
505             Parser.parseNext(DumpOpts.WarningHandler, DumpOpts.WarningHandler);
506         LineTable.dump(OS, DumpOpts);
507       }
508       OS.flush();
509     }
510   };
511 
512   if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
513                                    DObj->getLineSection().Data)) {
514     DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
515                                 0);
516     DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
517                                          type_units());
518     DumpLineSection(Parser, DumpOpts, *Off);
519   }
520 
521   if (const auto *Off =
522           shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
523                      DObj->getLineDWOSection().Data)) {
524     DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
525                                 isLittleEndian(), 0);
526     DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
527                                          dwo_type_units());
528     DumpLineSection(Parser, DumpOpts, *Off);
529   }
530 
531   if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
532                  DObj->getCUIndexSection())) {
533     getCUIndex().dump(OS);
534   }
535 
536   if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
537                  DObj->getTUIndexSection())) {
538     getTUIndex().dump(OS);
539   }
540 
541   if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
542                  DObj->getStrSection())) {
543     DataExtractor strData(DObj->getStrSection(), isLittleEndian(), 0);
544     uint64_t offset = 0;
545     uint64_t strOffset = 0;
546     while (const char *s = strData.getCStr(&offset)) {
547       OS << format("0x%8.8" PRIx64 ": \"%s\"\n", strOffset, s);
548       strOffset = offset;
549     }
550   }
551   if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
552                  DObj->getStrDWOSection())) {
553     DataExtractor strDWOData(DObj->getStrDWOSection(), isLittleEndian(), 0);
554     uint64_t offset = 0;
555     uint64_t strDWOOffset = 0;
556     while (const char *s = strDWOData.getCStr(&offset)) {
557       OS << format("0x%8.8" PRIx64 ": \"%s\"\n", strDWOOffset, s);
558       strDWOOffset = offset;
559     }
560   }
561   if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
562                  DObj->getLineStrSection())) {
563     DataExtractor strData(DObj->getLineStrSection(), isLittleEndian(), 0);
564     uint64_t offset = 0;
565     uint64_t strOffset = 0;
566     while (const char *s = strData.getCStr(&offset)) {
567       OS << format("0x%8.8" PRIx64 ": \"", strOffset);
568       OS.write_escaped(s);
569       OS << "\"\n";
570       strOffset = offset;
571     }
572   }
573 
574   if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
575                  DObj->getAddrSection().Data)) {
576     DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
577                                    isLittleEndian(), 0);
578     dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
579   }
580 
581   if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
582                  DObj->getRangesSection().Data)) {
583     uint8_t savedAddressByteSize = getCUAddrSize();
584     DWARFDataExtractor rangesData(*DObj, DObj->getRangesSection(),
585                                   isLittleEndian(), savedAddressByteSize);
586     uint64_t offset = 0;
587     DWARFDebugRangeList rangeList;
588     while (rangesData.isValidOffset(offset)) {
589       if (Error E = rangeList.extract(rangesData, &offset)) {
590         DumpOpts.RecoverableErrorHandler(std::move(E));
591         break;
592       }
593       rangeList.dump(OS);
594     }
595   }
596 
597   auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
598     const auto &CUs = compile_units();
599     auto I = CUs.begin();
600     if (I == CUs.end())
601       return None;
602     return (*I)->getAddrOffsetSectionItem(Index);
603   };
604 
605   if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
606                  DObj->getRnglistsSection().Data)) {
607     DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
608                                    isLittleEndian(), 0);
609     dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
610   }
611 
612   if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
613                  DObj->getRnglistsDWOSection().Data)) {
614     DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
615                                    isLittleEndian(), 0);
616     dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
617   }
618 
619   if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
620                  DObj->getPubnamesSection().Data))
621     DWARFDebugPubTable(*DObj, DObj->getPubnamesSection(), isLittleEndian(), false)
622         .dump(OS);
623 
624   if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
625                  DObj->getPubtypesSection().Data))
626     DWARFDebugPubTable(*DObj, DObj->getPubtypesSection(), isLittleEndian(), false)
627         .dump(OS);
628 
629   if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
630                  DObj->getGnuPubnamesSection().Data))
631     DWARFDebugPubTable(*DObj, DObj->getGnuPubnamesSection(), isLittleEndian(),
632                        true /* GnuStyle */)
633         .dump(OS);
634 
635   if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
636                  DObj->getGnuPubtypesSection().Data))
637     DWARFDebugPubTable(*DObj, DObj->getGnuPubtypesSection(), isLittleEndian(),
638                        true /* GnuStyle */)
639         .dump(OS);
640 
641   if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
642                  DObj->getStrOffsetsSection().Data))
643     dumpStringOffsetsSection(
644         OS, DumpOpts, "debug_str_offsets", *DObj, DObj->getStrOffsetsSection(),
645         DObj->getStrSection(), normal_units(), isLittleEndian());
646   if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
647                  DObj->getStrOffsetsDWOSection().Data))
648     dumpStringOffsetsSection(OS, DumpOpts, "debug_str_offsets.dwo", *DObj,
649                              DObj->getStrOffsetsDWOSection(),
650                              DObj->getStrDWOSection(), dwo_units(),
651                              isLittleEndian());
652 
653   if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
654                  DObj->getGdbIndexSection())) {
655     getGdbIndex().dump(OS);
656   }
657 
658   if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
659                  DObj->getAppleNamesSection().Data))
660     getAppleNames().dump(OS);
661 
662   if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
663                  DObj->getAppleTypesSection().Data))
664     getAppleTypes().dump(OS);
665 
666   if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
667                  DObj->getAppleNamespacesSection().Data))
668     getAppleNamespaces().dump(OS);
669 
670   if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
671                  DObj->getAppleObjCSection().Data))
672     getAppleObjC().dump(OS);
673   if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
674                  DObj->getNamesSection().Data))
675     getDebugNames().dump(OS);
676 }
677 
678 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
679   parseDWOUnits(LazyParse);
680 
681   if (const auto &CUI = getCUIndex()) {
682     if (const auto *R = CUI.getFromHash(Hash))
683       return dyn_cast_or_null<DWARFCompileUnit>(
684           DWOUnits.getUnitForIndexEntry(*R));
685     return nullptr;
686   }
687 
688   // If there's no index, just search through the CUs in the DWO - there's
689   // probably only one unless this is something like LTO - though an in-process
690   // built/cached lookup table could be used in that case to improve repeated
691   // lookups of different CUs in the DWO.
692   for (const auto &DWOCU : dwo_compile_units()) {
693     // Might not have parsed DWO ID yet.
694     if (!DWOCU->getDWOId()) {
695       if (Optional<uint64_t> DWOId =
696           toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
697         DWOCU->setDWOId(*DWOId);
698       else
699         // No DWO ID?
700         continue;
701     }
702     if (DWOCU->getDWOId() == Hash)
703       return dyn_cast<DWARFCompileUnit>(DWOCU.get());
704   }
705   return nullptr;
706 }
707 
708 DWARFDie DWARFContext::getDIEForOffset(uint64_t Offset) {
709   parseNormalUnits();
710   if (auto *CU = NormalUnits.getUnitForOffset(Offset))
711     return CU->getDIEForOffset(Offset);
712   return DWARFDie();
713 }
714 
715 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
716   bool Success = true;
717   DWARFVerifier verifier(OS, *this, DumpOpts);
718 
719   Success &= verifier.handleDebugAbbrev();
720   if (DumpOpts.DumpType & DIDT_DebugInfo)
721     Success &= verifier.handleDebugInfo();
722   if (DumpOpts.DumpType & DIDT_DebugLine)
723     Success &= verifier.handleDebugLine();
724   Success &= verifier.handleAccelTables();
725   return Success;
726 }
727 
728 const DWARFUnitIndex &DWARFContext::getCUIndex() {
729   if (CUIndex)
730     return *CUIndex;
731 
732   DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
733 
734   CUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
735   CUIndex->parse(CUIndexData);
736   return *CUIndex;
737 }
738 
739 const DWARFUnitIndex &DWARFContext::getTUIndex() {
740   if (TUIndex)
741     return *TUIndex;
742 
743   DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
744 
745   TUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_EXT_TYPES);
746   TUIndex->parse(TUIndexData);
747   return *TUIndex;
748 }
749 
750 DWARFGdbIndex &DWARFContext::getGdbIndex() {
751   if (GdbIndex)
752     return *GdbIndex;
753 
754   DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
755   GdbIndex = std::make_unique<DWARFGdbIndex>();
756   GdbIndex->parse(GdbIndexData);
757   return *GdbIndex;
758 }
759 
760 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
761   if (Abbrev)
762     return Abbrev.get();
763 
764   DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
765 
766   Abbrev.reset(new DWARFDebugAbbrev());
767   Abbrev->extract(abbrData);
768   return Abbrev.get();
769 }
770 
771 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
772   if (AbbrevDWO)
773     return AbbrevDWO.get();
774 
775   DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
776   AbbrevDWO.reset(new DWARFDebugAbbrev());
777   AbbrevDWO->extract(abbrData);
778   return AbbrevDWO.get();
779 }
780 
781 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
782   if (Loc)
783     return Loc.get();
784 
785   // Assume all units have the same address byte size.
786   auto LocData =
787       getNumCompileUnits()
788           ? DWARFDataExtractor(*DObj, DObj->getLocSection(), isLittleEndian(),
789                                getUnitAtIndex(0)->getAddressByteSize())
790           : DWARFDataExtractor("", isLittleEndian(), 0);
791   Loc.reset(new DWARFDebugLoc(std::move(LocData)));
792   return Loc.get();
793 }
794 
795 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
796   if (Aranges)
797     return Aranges.get();
798 
799   Aranges.reset(new DWARFDebugAranges());
800   Aranges->generate(this);
801   return Aranges.get();
802 }
803 
804 Expected<const DWARFDebugFrame *> DWARFContext::getDebugFrame() {
805   if (DebugFrame)
806     return DebugFrame.get();
807 
808   // There's a "bug" in the DWARFv3 standard with respect to the target address
809   // size within debug frame sections. While DWARF is supposed to be independent
810   // of its container, FDEs have fields with size being "target address size",
811   // which isn't specified in DWARF in general. It's only specified for CUs, but
812   // .eh_frame can appear without a .debug_info section. Follow the example of
813   // other tools (libdwarf) and extract this from the container (ObjectFile
814   // provides this information). This problem is fixed in DWARFv4
815   // See this dwarf-discuss discussion for more details:
816   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
817   DWARFDataExtractor debugFrameData(*DObj, DObj->getFrameSection(),
818                                     isLittleEndian(), DObj->getAddressSize());
819   auto DF = std::make_unique<DWARFDebugFrame>(getArch(), /*IsEH=*/false);
820   if (Error E = DF->parse(debugFrameData))
821     return std::move(E);
822 
823   DebugFrame.swap(DF);
824   return DebugFrame.get();
825 }
826 
827 Expected<const DWARFDebugFrame *> DWARFContext::getEHFrame() {
828   if (EHFrame)
829     return EHFrame.get();
830 
831   DWARFDataExtractor debugFrameData(*DObj, DObj->getEHFrameSection(),
832                                     isLittleEndian(), DObj->getAddressSize());
833 
834   auto DF = std::make_unique<DWARFDebugFrame>(getArch(), /*IsEH=*/true);
835   if (Error E = DF->parse(debugFrameData))
836     return std::move(E);
837   DebugFrame.swap(DF);
838   return DebugFrame.get();
839 }
840 
841 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
842   if (!Macro)
843     Macro = parseMacroOrMacinfo(MacroSection);
844   return Macro.get();
845 }
846 
847 const DWARFDebugMacro *DWARFContext::getDebugMacinfo() {
848   if (!Macinfo)
849     Macinfo = parseMacroOrMacinfo(MacinfoSection);
850   return Macinfo.get();
851 }
852 
853 const DWARFDebugMacro *DWARFContext::getDebugMacinfoDWO() {
854   if (!MacinfoDWO)
855     MacinfoDWO = parseMacroOrMacinfo(MacinfoDwoSection);
856   return MacinfoDWO.get();
857 }
858 
859 template <typename T>
860 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
861                         const DWARFSection &Section, StringRef StringSection,
862                         bool IsLittleEndian) {
863   if (Cache)
864     return *Cache;
865   DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
866   DataExtractor StrData(StringSection, IsLittleEndian, 0);
867   Cache.reset(new T(AccelSection, StrData));
868   if (Error E = Cache->extract())
869     llvm::consumeError(std::move(E));
870   return *Cache;
871 }
872 
873 const DWARFDebugNames &DWARFContext::getDebugNames() {
874   return getAccelTable(Names, *DObj, DObj->getNamesSection(),
875                        DObj->getStrSection(), isLittleEndian());
876 }
877 
878 const AppleAcceleratorTable &DWARFContext::getAppleNames() {
879   return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
880                        DObj->getStrSection(), isLittleEndian());
881 }
882 
883 const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
884   return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
885                        DObj->getStrSection(), isLittleEndian());
886 }
887 
888 const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
889   return getAccelTable(AppleNamespaces, *DObj,
890                        DObj->getAppleNamespacesSection(),
891                        DObj->getStrSection(), isLittleEndian());
892 }
893 
894 const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
895   return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
896                        DObj->getStrSection(), isLittleEndian());
897 }
898 
899 const DWARFDebugLine::LineTable *
900 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
901   Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
902       getLineTableForUnit(U, WarningHandler);
903   if (!ExpectedLineTable) {
904     WarningHandler(ExpectedLineTable.takeError());
905     return nullptr;
906   }
907   return *ExpectedLineTable;
908 }
909 
910 Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
911     DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
912   if (!Line)
913     Line.reset(new DWARFDebugLine);
914 
915   auto UnitDIE = U->getUnitDIE();
916   if (!UnitDIE)
917     return nullptr;
918 
919   auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
920   if (!Offset)
921     return nullptr; // No line table for this compile unit.
922 
923   uint64_t stmtOffset = *Offset + U->getLineTableOffset();
924   // See if the line table is cached.
925   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
926     return lt;
927 
928   // Make sure the offset is good before we try to parse.
929   if (stmtOffset >= U->getLineSection().Data.size())
930     return nullptr;
931 
932   // We have to parse it first.
933   DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
934                               U->getAddressByteSize());
935   return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
936                                    RecoverableErrorHandler);
937 }
938 
939 void DWARFContext::parseNormalUnits() {
940   if (!NormalUnits.empty())
941     return;
942   DObj->forEachInfoSections([&](const DWARFSection &S) {
943     NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
944   });
945   NormalUnits.finishedInfoUnits();
946   DObj->forEachTypesSections([&](const DWARFSection &S) {
947     NormalUnits.addUnitsForSection(*this, S, DW_SECT_EXT_TYPES);
948   });
949 }
950 
951 void DWARFContext::parseDWOUnits(bool Lazy) {
952   if (!DWOUnits.empty())
953     return;
954   DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
955     DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
956   });
957   DWOUnits.finishedInfoUnits();
958   DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
959     DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_EXT_TYPES, Lazy);
960   });
961 }
962 
963 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) {
964   parseNormalUnits();
965   return dyn_cast_or_null<DWARFCompileUnit>(
966       NormalUnits.getUnitForOffset(Offset));
967 }
968 
969 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
970   // First, get the offset of the compile unit.
971   uint64_t CUOffset = getDebugAranges()->findAddress(Address);
972   // Retrieve the compile unit.
973   return getCompileUnitForOffset(CUOffset);
974 }
975 
976 DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
977   DIEsForAddress Result;
978 
979   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
980   if (!CU)
981     return Result;
982 
983   Result.CompileUnit = CU;
984   Result.FunctionDIE = CU->getSubroutineForAddress(Address);
985 
986   std::vector<DWARFDie> Worklist;
987   Worklist.push_back(Result.FunctionDIE);
988   while (!Worklist.empty()) {
989     DWARFDie DIE = Worklist.back();
990     Worklist.pop_back();
991 
992     if (!DIE.isValid())
993       continue;
994 
995     if (DIE.getTag() == DW_TAG_lexical_block &&
996         DIE.addressRangeContainsAddress(Address)) {
997       Result.BlockDIE = DIE;
998       break;
999     }
1000 
1001     for (auto Child : DIE)
1002       Worklist.push_back(Child);
1003   }
1004 
1005   return Result;
1006 }
1007 
1008 /// TODO: change input parameter from "uint64_t Address"
1009 ///       into "SectionedAddress Address"
1010 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
1011                                                   uint64_t Address,
1012                                                   FunctionNameKind Kind,
1013                                                   std::string &FunctionName,
1014                                                   uint32_t &StartLine) {
1015   // The address may correspond to instruction in some inlined function,
1016   // so we have to build the chain of inlined functions and take the
1017   // name of the topmost function in it.
1018   SmallVector<DWARFDie, 4> InlinedChain;
1019   CU->getInlinedChainForAddress(Address, InlinedChain);
1020   if (InlinedChain.empty())
1021     return false;
1022 
1023   const DWARFDie &DIE = InlinedChain[0];
1024   bool FoundResult = false;
1025   const char *Name = nullptr;
1026   if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
1027     FunctionName = Name;
1028     FoundResult = true;
1029   }
1030   if (auto DeclLineResult = DIE.getDeclLine()) {
1031     StartLine = DeclLineResult;
1032     FoundResult = true;
1033   }
1034 
1035   return FoundResult;
1036 }
1037 
1038 static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
1039   if (auto SizeAttr = Type.find(DW_AT_byte_size))
1040     if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
1041       return Size;
1042 
1043   switch (Type.getTag()) {
1044   case DW_TAG_pointer_type:
1045   case DW_TAG_reference_type:
1046   case DW_TAG_rvalue_reference_type:
1047     return PointerSize;
1048   case DW_TAG_ptr_to_member_type: {
1049     if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
1050       if (BaseType.getTag() == DW_TAG_subroutine_type)
1051         return 2 * PointerSize;
1052     return PointerSize;
1053   }
1054   case DW_TAG_const_type:
1055   case DW_TAG_volatile_type:
1056   case DW_TAG_restrict_type:
1057   case DW_TAG_typedef: {
1058     if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
1059       return getTypeSize(BaseType, PointerSize);
1060     break;
1061   }
1062   case DW_TAG_array_type: {
1063     DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type);
1064     if (!BaseType)
1065       return Optional<uint64_t>();
1066     Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
1067     if (!BaseSize)
1068       return Optional<uint64_t>();
1069     uint64_t Size = *BaseSize;
1070     for (DWARFDie Child : Type) {
1071       if (Child.getTag() != DW_TAG_subrange_type)
1072         continue;
1073 
1074       if (auto ElemCountAttr = Child.find(DW_AT_count))
1075         if (Optional<uint64_t> ElemCount =
1076                 ElemCountAttr->getAsUnsignedConstant())
1077           Size *= *ElemCount;
1078       if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
1079         if (Optional<int64_t> UpperBound =
1080                 UpperBoundAttr->getAsSignedConstant()) {
1081           int64_t LowerBound = 0;
1082           if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
1083             LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
1084           Size *= *UpperBound - LowerBound + 1;
1085         }
1086     }
1087     return Size;
1088   }
1089   default:
1090     break;
1091   }
1092   return Optional<uint64_t>();
1093 }
1094 
1095 static Optional<int64_t>
1096 getExpressionFrameOffset(ArrayRef<uint8_t> Expr,
1097                          Optional<unsigned> FrameBaseReg) {
1098   if (!Expr.empty() &&
1099       (Expr[0] == DW_OP_fbreg ||
1100        (FrameBaseReg && Expr[0] == DW_OP_breg0 + *FrameBaseReg))) {
1101     unsigned Count;
1102     int64_t Offset = decodeSLEB128(Expr.data() + 1, &Count, Expr.end());
1103     // A single DW_OP_fbreg or DW_OP_breg.
1104     if (Expr.size() == Count + 1)
1105       return Offset;
1106     // Same + DW_OP_deref (Fortran arrays look like this).
1107     if (Expr.size() == Count + 2 && Expr[Count + 1] == DW_OP_deref)
1108       return Offset;
1109     // Fallthrough. Do not accept ex. (DW_OP_breg W29, DW_OP_stack_value)
1110   }
1111   return None;
1112 }
1113 
1114 void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1115                                    DWARFDie Die, std::vector<DILocal> &Result) {
1116   if (Die.getTag() == DW_TAG_variable ||
1117       Die.getTag() == DW_TAG_formal_parameter) {
1118     DILocal Local;
1119     if (const char *Name = Subprogram.getSubroutineName(DINameKind::ShortName))
1120       Local.FunctionName = Name;
1121 
1122     Optional<unsigned> FrameBaseReg;
1123     if (auto FrameBase = Subprogram.find(DW_AT_frame_base))
1124       if (Optional<ArrayRef<uint8_t>> Expr = FrameBase->getAsBlock())
1125         if (!Expr->empty() && (*Expr)[0] >= DW_OP_reg0 &&
1126             (*Expr)[0] <= DW_OP_reg31) {
1127           FrameBaseReg = (*Expr)[0] - DW_OP_reg0;
1128         }
1129 
1130     if (Expected<std::vector<DWARFLocationExpression>> Loc =
1131             Die.getLocations(DW_AT_location)) {
1132       for (const auto &Entry : *Loc) {
1133         if (Optional<int64_t> FrameOffset =
1134                 getExpressionFrameOffset(Entry.Expr, FrameBaseReg)) {
1135           Local.FrameOffset = *FrameOffset;
1136           break;
1137         }
1138       }
1139     } else {
1140       // FIXME: missing DW_AT_location is OK here, but other errors should be
1141       // reported to the user.
1142       consumeError(Loc.takeError());
1143     }
1144 
1145     if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
1146       Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1147 
1148     if (auto Origin =
1149             Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1150       Die = Origin;
1151     if (auto NameAttr = Die.find(DW_AT_name))
1152       if (Optional<const char *> Name = NameAttr->getAsCString())
1153         Local.Name = *Name;
1154     if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
1155       Local.Size = getTypeSize(Type, getCUAddrSize());
1156     if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
1157       if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
1158         LT->getFileNameByIndex(
1159             DeclFileAttr->getAsUnsignedConstant().getValue(),
1160             CU->getCompilationDir(),
1161             DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1162             Local.DeclFile);
1163     }
1164     if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
1165       Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
1166 
1167     Result.push_back(Local);
1168     return;
1169   }
1170 
1171   if (Die.getTag() == DW_TAG_inlined_subroutine)
1172     if (auto Origin =
1173             Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1174       Subprogram = Origin;
1175 
1176   for (auto Child : Die)
1177     addLocalsForDie(CU, Subprogram, Child, Result);
1178 }
1179 
1180 std::vector<DILocal>
1181 DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
1182   std::vector<DILocal> Result;
1183   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1184   if (!CU)
1185     return Result;
1186 
1187   DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
1188   if (Subprogram.isValid())
1189     addLocalsForDie(CU, Subprogram, Subprogram, Result);
1190   return Result;
1191 }
1192 
1193 DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
1194                                                DILineInfoSpecifier Spec) {
1195   DILineInfo Result;
1196 
1197   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1198   if (!CU)
1199     return Result;
1200 
1201   getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1202                                         Result.FunctionName, Result.StartLine);
1203   if (Spec.FLIKind != FileLineInfoKind::None) {
1204     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
1205       LineTable->getFileLineInfoForAddress(
1206           {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1207           Spec.FLIKind, Result);
1208     }
1209   }
1210   return Result;
1211 }
1212 
1213 DILineInfoTable DWARFContext::getLineInfoForAddressRange(
1214     object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
1215   DILineInfoTable  Lines;
1216   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1217   if (!CU)
1218     return Lines;
1219 
1220   uint32_t StartLine = 0;
1221   std::string FunctionName(DILineInfo::BadString);
1222   getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1223                                         FunctionName, StartLine);
1224 
1225   // If the Specifier says we don't need FileLineInfo, just
1226   // return the top-most function at the starting address.
1227   if (Spec.FLIKind == FileLineInfoKind::None) {
1228     DILineInfo Result;
1229     Result.FunctionName = FunctionName;
1230     Result.StartLine = StartLine;
1231     Lines.push_back(std::make_pair(Address.Address, Result));
1232     return Lines;
1233   }
1234 
1235   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
1236 
1237   // Get the index of row we're looking for in the line table.
1238   std::vector<uint32_t> RowVector;
1239   if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
1240                                      Size, RowVector)) {
1241     return Lines;
1242   }
1243 
1244   for (uint32_t RowIndex : RowVector) {
1245     // Take file number and line/column from the row.
1246     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
1247     DILineInfo Result;
1248     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1249                                   Spec.FLIKind, Result.FileName);
1250     Result.FunctionName = FunctionName;
1251     Result.Line = Row.Line;
1252     Result.Column = Row.Column;
1253     Result.StartLine = StartLine;
1254     Lines.push_back(std::make_pair(Row.Address.Address, Result));
1255   }
1256 
1257   return Lines;
1258 }
1259 
1260 DIInliningInfo
1261 DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
1262                                         DILineInfoSpecifier Spec) {
1263   DIInliningInfo InliningInfo;
1264 
1265   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1266   if (!CU)
1267     return InliningInfo;
1268 
1269   const DWARFLineTable *LineTable = nullptr;
1270   SmallVector<DWARFDie, 4> InlinedChain;
1271   CU->getInlinedChainForAddress(Address.Address, InlinedChain);
1272   if (InlinedChain.size() == 0) {
1273     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1274     // try to at least get file/line info from symbol table.
1275     if (Spec.FLIKind != FileLineInfoKind::None) {
1276       DILineInfo Frame;
1277       LineTable = getLineTableForUnit(CU);
1278       if (LineTable && LineTable->getFileLineInfoForAddress(
1279                            {Address.Address, Address.SectionIndex},
1280                            CU->getCompilationDir(), Spec.FLIKind, Frame))
1281         InliningInfo.addFrame(Frame);
1282     }
1283     return InliningInfo;
1284   }
1285 
1286   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
1287   for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1288     DWARFDie &FunctionDIE = InlinedChain[i];
1289     DILineInfo Frame;
1290     // Get function name if necessary.
1291     if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
1292       Frame.FunctionName = Name;
1293     if (auto DeclLineResult = FunctionDIE.getDeclLine())
1294       Frame.StartLine = DeclLineResult;
1295     if (Spec.FLIKind != FileLineInfoKind::None) {
1296       if (i == 0) {
1297         // For the topmost frame, initialize the line table of this
1298         // compile unit and fetch file/line info from it.
1299         LineTable = getLineTableForUnit(CU);
1300         // For the topmost routine, get file/line info from line table.
1301         if (LineTable)
1302           LineTable->getFileLineInfoForAddress(
1303               {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1304               Spec.FLIKind, Frame);
1305       } else {
1306         // Otherwise, use call file, call line and call column from
1307         // previous DIE in inlined chain.
1308         if (LineTable)
1309           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1310                                         Spec.FLIKind, Frame.FileName);
1311         Frame.Line = CallLine;
1312         Frame.Column = CallColumn;
1313         Frame.Discriminator = CallDiscriminator;
1314       }
1315       // Get call file/line/column of a current DIE.
1316       if (i + 1 < n) {
1317         FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1318                                    CallDiscriminator);
1319       }
1320     }
1321     InliningInfo.addFrame(Frame);
1322   }
1323   return InliningInfo;
1324 }
1325 
1326 std::shared_ptr<DWARFContext>
1327 DWARFContext::getDWOContext(StringRef AbsolutePath) {
1328   if (auto S = DWP.lock()) {
1329     DWARFContext *Ctxt = S->Context.get();
1330     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1331   }
1332 
1333   std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1334 
1335   if (auto S = Entry->lock()) {
1336     DWARFContext *Ctxt = S->Context.get();
1337     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1338   }
1339 
1340   Expected<OwningBinary<ObjectFile>> Obj = [&] {
1341     if (!CheckedForDWP) {
1342       SmallString<128> DWPName;
1343       auto Obj = object::ObjectFile::createObjectFile(
1344           this->DWPName.empty()
1345               ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1346               : StringRef(this->DWPName));
1347       if (Obj) {
1348         Entry = &DWP;
1349         return Obj;
1350       } else {
1351         CheckedForDWP = true;
1352         // TODO: Should this error be handled (maybe in a high verbosity mode)
1353         // before falling back to .dwo files?
1354         consumeError(Obj.takeError());
1355       }
1356     }
1357 
1358     return object::ObjectFile::createObjectFile(AbsolutePath);
1359   }();
1360 
1361   if (!Obj) {
1362     // TODO: Actually report errors helpfully.
1363     consumeError(Obj.takeError());
1364     return nullptr;
1365   }
1366 
1367   auto S = std::make_shared<DWOFile>();
1368   S->File = std::move(Obj.get());
1369   S->Context = DWARFContext::create(*S->File.getBinary());
1370   *Entry = S;
1371   auto *Ctxt = S->Context.get();
1372   return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1373 }
1374 
1375 static Error createError(const Twine &Reason, llvm::Error E) {
1376   return make_error<StringError>(Reason + toString(std::move(E)),
1377                                  inconvertibleErrorCode());
1378 }
1379 
1380 /// SymInfo contains information about symbol: it's address
1381 /// and section index which is -1LL for absolute symbols.
1382 struct SymInfo {
1383   uint64_t Address;
1384   uint64_t SectionIndex;
1385 };
1386 
1387 /// Returns the address of symbol relocation used against and a section index.
1388 /// Used for futher relocations computation. Symbol's section load address is
1389 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1390                                        const RelocationRef &Reloc,
1391                                        const LoadedObjectInfo *L,
1392                                        std::map<SymbolRef, SymInfo> &Cache) {
1393   SymInfo Ret = {0, (uint64_t)-1LL};
1394   object::section_iterator RSec = Obj.section_end();
1395   object::symbol_iterator Sym = Reloc.getSymbol();
1396 
1397   std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1398   // First calculate the address of the symbol or section as it appears
1399   // in the object file
1400   if (Sym != Obj.symbol_end()) {
1401     bool New;
1402     std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
1403     if (!New)
1404       return CacheIt->second;
1405 
1406     Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1407     if (!SymAddrOrErr)
1408       return createError("failed to compute symbol address: ",
1409                          SymAddrOrErr.takeError());
1410 
1411     // Also remember what section this symbol is in for later
1412     auto SectOrErr = Sym->getSection();
1413     if (!SectOrErr)
1414       return createError("failed to get symbol section: ",
1415                          SectOrErr.takeError());
1416 
1417     RSec = *SectOrErr;
1418     Ret.Address = *SymAddrOrErr;
1419   } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1420     RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
1421     Ret.Address = RSec->getAddress();
1422   }
1423 
1424   if (RSec != Obj.section_end())
1425     Ret.SectionIndex = RSec->getIndex();
1426 
1427   // If we are given load addresses for the sections, we need to adjust:
1428   // SymAddr = (Address of Symbol Or Section in File) -
1429   //           (Address of Section in File) +
1430   //           (Load Address of Section)
1431   // RSec is now either the section being targeted or the section
1432   // containing the symbol being targeted. In either case,
1433   // we need to perform the same computation.
1434   if (L && RSec != Obj.section_end())
1435     if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
1436       Ret.Address += SectionLoadAddress - RSec->getAddress();
1437 
1438   if (CacheIt != Cache.end())
1439     CacheIt->second = Ret;
1440 
1441   return Ret;
1442 }
1443 
1444 static bool isRelocScattered(const object::ObjectFile &Obj,
1445                              const RelocationRef &Reloc) {
1446   const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1447   if (!MachObj)
1448     return false;
1449   // MachO also has relocations that point to sections and
1450   // scattered relocations.
1451   auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1452   return MachObj->isRelocationScattered(RelocInfo);
1453 }
1454 
1455 namespace {
1456 struct DWARFSectionMap final : public DWARFSection {
1457   RelocAddrMap Relocs;
1458 };
1459 
1460 class DWARFObjInMemory final : public DWARFObject {
1461   bool IsLittleEndian;
1462   uint8_t AddressSize;
1463   StringRef FileName;
1464   const object::ObjectFile *Obj = nullptr;
1465   std::vector<SectionName> SectionNames;
1466 
1467   using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1468                                    std::map<object::SectionRef, unsigned>>;
1469 
1470   InfoSectionMap InfoSections;
1471   InfoSectionMap TypesSections;
1472   InfoSectionMap InfoDWOSections;
1473   InfoSectionMap TypesDWOSections;
1474 
1475   DWARFSectionMap LocSection;
1476   DWARFSectionMap LoclistsSection;
1477   DWARFSectionMap LoclistsDWOSection;
1478   DWARFSectionMap LineSection;
1479   DWARFSectionMap RangesSection;
1480   DWARFSectionMap RnglistsSection;
1481   DWARFSectionMap StrOffsetsSection;
1482   DWARFSectionMap LineDWOSection;
1483   DWARFSectionMap FrameSection;
1484   DWARFSectionMap EHFrameSection;
1485   DWARFSectionMap LocDWOSection;
1486   DWARFSectionMap StrOffsetsDWOSection;
1487   DWARFSectionMap RangesDWOSection;
1488   DWARFSectionMap RnglistsDWOSection;
1489   DWARFSectionMap AddrSection;
1490   DWARFSectionMap AppleNamesSection;
1491   DWARFSectionMap AppleTypesSection;
1492   DWARFSectionMap AppleNamespacesSection;
1493   DWARFSectionMap AppleObjCSection;
1494   DWARFSectionMap NamesSection;
1495   DWARFSectionMap PubnamesSection;
1496   DWARFSectionMap PubtypesSection;
1497   DWARFSectionMap GnuPubnamesSection;
1498   DWARFSectionMap GnuPubtypesSection;
1499   DWARFSectionMap MacroSection;
1500 
1501   DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1502     return StringSwitch<DWARFSectionMap *>(Name)
1503         .Case("debug_loc", &LocSection)
1504         .Case("debug_loclists", &LoclistsSection)
1505         .Case("debug_loclists.dwo", &LoclistsDWOSection)
1506         .Case("debug_line", &LineSection)
1507         .Case("debug_frame", &FrameSection)
1508         .Case("eh_frame", &EHFrameSection)
1509         .Case("debug_str_offsets", &StrOffsetsSection)
1510         .Case("debug_ranges", &RangesSection)
1511         .Case("debug_rnglists", &RnglistsSection)
1512         .Case("debug_loc.dwo", &LocDWOSection)
1513         .Case("debug_line.dwo", &LineDWOSection)
1514         .Case("debug_names", &NamesSection)
1515         .Case("debug_rnglists.dwo", &RnglistsDWOSection)
1516         .Case("debug_str_offsets.dwo", &StrOffsetsDWOSection)
1517         .Case("debug_addr", &AddrSection)
1518         .Case("apple_names", &AppleNamesSection)
1519         .Case("debug_pubnames", &PubnamesSection)
1520         .Case("debug_pubtypes", &PubtypesSection)
1521         .Case("debug_gnu_pubnames", &GnuPubnamesSection)
1522         .Case("debug_gnu_pubtypes", &GnuPubtypesSection)
1523         .Case("apple_types", &AppleTypesSection)
1524         .Case("apple_namespaces", &AppleNamespacesSection)
1525         .Case("apple_namespac", &AppleNamespacesSection)
1526         .Case("apple_objc", &AppleObjCSection)
1527         .Case("debug_macro", &MacroSection)
1528         .Default(nullptr);
1529   }
1530 
1531   StringRef AbbrevSection;
1532   StringRef ArangesSection;
1533   StringRef StrSection;
1534   StringRef MacinfoSection;
1535   StringRef MacinfoDWOSection;
1536   StringRef AbbrevDWOSection;
1537   StringRef StrDWOSection;
1538   StringRef CUIndexSection;
1539   StringRef GdbIndexSection;
1540   StringRef TUIndexSection;
1541   StringRef LineStrSection;
1542 
1543   // A deque holding section data whose iterators are not invalidated when
1544   // new decompressed sections are inserted at the end.
1545   std::deque<SmallString<0>> UncompressedSections;
1546 
1547   StringRef *mapSectionToMember(StringRef Name) {
1548     if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1549       return &Sec->Data;
1550     return StringSwitch<StringRef *>(Name)
1551         .Case("debug_abbrev", &AbbrevSection)
1552         .Case("debug_aranges", &ArangesSection)
1553         .Case("debug_str", &StrSection)
1554         .Case("debug_macinfo", &MacinfoSection)
1555         .Case("debug_macinfo.dwo", &MacinfoDWOSection)
1556         .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1557         .Case("debug_str.dwo", &StrDWOSection)
1558         .Case("debug_cu_index", &CUIndexSection)
1559         .Case("debug_tu_index", &TUIndexSection)
1560         .Case("gdb_index", &GdbIndexSection)
1561         .Case("debug_line_str", &LineStrSection)
1562         // Any more debug info sections go here.
1563         .Default(nullptr);
1564   }
1565 
1566   /// If Sec is compressed section, decompresses and updates its contents
1567   /// provided by Data. Otherwise leaves it unchanged.
1568   Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1569                         StringRef &Data) {
1570     if (!Decompressor::isCompressed(Sec))
1571       return Error::success();
1572 
1573     Expected<Decompressor> Decompressor =
1574         Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1575     if (!Decompressor)
1576       return Decompressor.takeError();
1577 
1578     SmallString<0> Out;
1579     if (auto Err = Decompressor->resizeAndDecompress(Out))
1580       return Err;
1581 
1582     UncompressedSections.push_back(std::move(Out));
1583     Data = UncompressedSections.back();
1584 
1585     return Error::success();
1586   }
1587 
1588 public:
1589   DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1590                    uint8_t AddrSize, bool IsLittleEndian)
1591       : IsLittleEndian(IsLittleEndian) {
1592     for (const auto &SecIt : Sections) {
1593       if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1594         *SectionData = SecIt.second->getBuffer();
1595       else if (SecIt.first() == "debug_info")
1596         // Find debug_info and debug_types data by section rather than name as
1597         // there are multiple, comdat grouped, of these sections.
1598         InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1599       else if (SecIt.first() == "debug_info.dwo")
1600         InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1601       else if (SecIt.first() == "debug_types")
1602         TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1603       else if (SecIt.first() == "debug_types.dwo")
1604         TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1605     }
1606   }
1607   DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1608                    function_ref<void(Error)> HandleError, function_ref<void(Error)> HandleWarning )
1609       : IsLittleEndian(Obj.isLittleEndian()),
1610         AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1611         Obj(&Obj) {
1612 
1613     StringMap<unsigned> SectionAmountMap;
1614     for (const SectionRef &Section : Obj.sections()) {
1615       StringRef Name;
1616       if (auto NameOrErr = Section.getName())
1617         Name = *NameOrErr;
1618       else
1619         consumeError(NameOrErr.takeError());
1620 
1621       ++SectionAmountMap[Name];
1622       SectionNames.push_back({ Name, true });
1623 
1624       // Skip BSS and Virtual sections, they aren't interesting.
1625       if (Section.isBSS() || Section.isVirtual())
1626         continue;
1627 
1628       // Skip sections stripped by dsymutil.
1629       if (Section.isStripped())
1630         continue;
1631 
1632       StringRef Data;
1633       Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1634       if (!SecOrErr) {
1635         HandleError(createError("failed to get relocated section: ",
1636                                 SecOrErr.takeError()));
1637         continue;
1638       }
1639 
1640       // Try to obtain an already relocated version of this section.
1641       // Else use the unrelocated section from the object file. We'll have to
1642       // apply relocations ourselves later.
1643       section_iterator RelocatedSection = *SecOrErr;
1644       if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) {
1645         Expected<StringRef> E = Section.getContents();
1646         if (E)
1647           Data = *E;
1648         else
1649           // maybeDecompress below will error.
1650           consumeError(E.takeError());
1651       }
1652 
1653       if (auto Err = maybeDecompress(Section, Name, Data)) {
1654         HandleError(createError("failed to decompress '" + Name + "', ",
1655                                 std::move(Err)));
1656         continue;
1657       }
1658 
1659       // Compressed sections names in GNU style starts from ".z",
1660       // at this point section is decompressed and we drop compression prefix.
1661       Name = Name.substr(
1662           Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1663 
1664       // Map platform specific debug section names to DWARF standard section
1665       // names.
1666       Name = Obj.mapDebugSectionName(Name);
1667 
1668       if (StringRef *SectionData = mapSectionToMember(Name)) {
1669         *SectionData = Data;
1670         if (Name == "debug_ranges") {
1671           // FIXME: Use the other dwo range section when we emit it.
1672           RangesDWOSection.Data = Data;
1673         }
1674       } else if (Name == "debug_info") {
1675         // Find debug_info and debug_types data by section rather than name as
1676         // there are multiple, comdat grouped, of these sections.
1677         InfoSections[Section].Data = Data;
1678       } else if (Name == "debug_info.dwo") {
1679         InfoDWOSections[Section].Data = Data;
1680       } else if (Name == "debug_types") {
1681         TypesSections[Section].Data = Data;
1682       } else if (Name == "debug_types.dwo") {
1683         TypesDWOSections[Section].Data = Data;
1684       }
1685 
1686       if (RelocatedSection == Obj.section_end())
1687         continue;
1688 
1689       StringRef RelSecName;
1690       if (auto NameOrErr = RelocatedSection->getName())
1691         RelSecName = *NameOrErr;
1692       else
1693         consumeError(NameOrErr.takeError());
1694 
1695       // If the section we're relocating was relocated already by the JIT,
1696       // then we used the relocated version above, so we do not need to process
1697       // relocations for it now.
1698       StringRef RelSecData;
1699       if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1700         continue;
1701 
1702       // In Mach-o files, the relocations do not need to be applied if
1703       // there is no load offset to apply. The value read at the
1704       // relocation point already factors in the section address
1705       // (actually applying the relocations will produce wrong results
1706       // as the section address will be added twice).
1707       if (!L && isa<MachOObjectFile>(&Obj))
1708         continue;
1709 
1710       RelSecName = RelSecName.substr(
1711           RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1712 
1713       // TODO: Add support for relocations in other sections as needed.
1714       // Record relocations for the debug_info and debug_line sections.
1715       DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1716       RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1717       if (!Map) {
1718         // Find debug_info and debug_types relocs by section rather than name
1719         // as there are multiple, comdat grouped, of these sections.
1720         if (RelSecName == "debug_info")
1721           Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1722                      .Relocs;
1723         else if (RelSecName == "debug_info.dwo")
1724           Map = &static_cast<DWARFSectionMap &>(
1725                      InfoDWOSections[*RelocatedSection])
1726                      .Relocs;
1727         else if (RelSecName == "debug_types")
1728           Map =
1729               &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1730                    .Relocs;
1731         else if (RelSecName == "debug_types.dwo")
1732           Map = &static_cast<DWARFSectionMap &>(
1733                      TypesDWOSections[*RelocatedSection])
1734                      .Relocs;
1735         else
1736           continue;
1737       }
1738 
1739       if (Section.relocation_begin() == Section.relocation_end())
1740         continue;
1741 
1742       // Symbol to [address, section index] cache mapping.
1743       std::map<SymbolRef, SymInfo> AddrCache;
1744       bool (*Supports)(uint64_t);
1745       RelocationResolver Resolver;
1746       std::tie(Supports, Resolver) = getRelocationResolver(Obj);
1747       for (const RelocationRef &Reloc : Section.relocations()) {
1748         // FIXME: it's not clear how to correctly handle scattered
1749         // relocations.
1750         if (isRelocScattered(Obj, Reloc))
1751           continue;
1752 
1753         Expected<SymInfo> SymInfoOrErr =
1754             getSymbolInfo(Obj, Reloc, L, AddrCache);
1755         if (!SymInfoOrErr) {
1756           HandleError(SymInfoOrErr.takeError());
1757           continue;
1758         }
1759 
1760         // Check if Resolver can handle this relocation type early so as not to
1761         // handle invalid cases in DWARFDataExtractor.
1762         //
1763         // TODO Don't store Resolver in every RelocAddrEntry.
1764         if (Supports && Supports(Reloc.getType())) {
1765           auto I = Map->try_emplace(
1766               Reloc.getOffset(),
1767               RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
1768                              SymInfoOrErr->Address,
1769                              Optional<object::RelocationRef>(), 0, Resolver});
1770           // If we didn't successfully insert that's because we already had a
1771           // relocation for that offset. Store it as a second relocation in the
1772           // same RelocAddrEntry instead.
1773           if (!I.second) {
1774             RelocAddrEntry &entry = I.first->getSecond();
1775             if (entry.Reloc2) {
1776               HandleError(createError(
1777                   "At most two relocations per offset are supported"));
1778             }
1779             entry.Reloc2 = Reloc;
1780             entry.SymbolValue2 = SymInfoOrErr->Address;
1781           }
1782         } else {
1783           SmallString<32> Type;
1784           Reloc.getTypeName(Type);
1785           // FIXME: Support more relocations & change this to an error
1786           HandleWarning(
1787               createError("failed to compute relocation: " + Type + ", ",
1788                           errorCodeToError(object_error::parse_failed)));
1789         }
1790       }
1791     }
1792 
1793     for (SectionName &S : SectionNames)
1794       if (SectionAmountMap[S.Name] > 1)
1795         S.IsNameUnique = false;
1796   }
1797 
1798   Optional<RelocAddrEntry> find(const DWARFSection &S,
1799                                 uint64_t Pos) const override {
1800     auto &Sec = static_cast<const DWARFSectionMap &>(S);
1801     RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1802     if (AI == Sec.Relocs.end())
1803       return None;
1804     return AI->second;
1805   }
1806 
1807   const object::ObjectFile *getFile() const override { return Obj; }
1808 
1809   ArrayRef<SectionName> getSectionNames() const override {
1810     return SectionNames;
1811   }
1812 
1813   bool isLittleEndian() const override { return IsLittleEndian; }
1814   StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1815   const DWARFSection &getLineDWOSection() const override {
1816     return LineDWOSection;
1817   }
1818   const DWARFSection &getLocDWOSection() const override {
1819     return LocDWOSection;
1820   }
1821   StringRef getStrDWOSection() const override { return StrDWOSection; }
1822   const DWARFSection &getStrOffsetsDWOSection() const override {
1823     return StrOffsetsDWOSection;
1824   }
1825   const DWARFSection &getRangesDWOSection() const override {
1826     return RangesDWOSection;
1827   }
1828   const DWARFSection &getRnglistsDWOSection() const override {
1829     return RnglistsDWOSection;
1830   }
1831   const DWARFSection &getLoclistsDWOSection() const override {
1832     return LoclistsDWOSection;
1833   }
1834   const DWARFSection &getAddrSection() const override { return AddrSection; }
1835   StringRef getCUIndexSection() const override { return CUIndexSection; }
1836   StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1837   StringRef getTUIndexSection() const override { return TUIndexSection; }
1838 
1839   // DWARF v5
1840   const DWARFSection &getStrOffsetsSection() const override {
1841     return StrOffsetsSection;
1842   }
1843   StringRef getLineStrSection() const override { return LineStrSection; }
1844 
1845   // Sections for DWARF5 split dwarf proposal.
1846   void forEachInfoDWOSections(
1847       function_ref<void(const DWARFSection &)> F) const override {
1848     for (auto &P : InfoDWOSections)
1849       F(P.second);
1850   }
1851   void forEachTypesDWOSections(
1852       function_ref<void(const DWARFSection &)> F) const override {
1853     for (auto &P : TypesDWOSections)
1854       F(P.second);
1855   }
1856 
1857   StringRef getAbbrevSection() const override { return AbbrevSection; }
1858   const DWARFSection &getLocSection() const override { return LocSection; }
1859   const DWARFSection &getLoclistsSection() const override { return LoclistsSection; }
1860   StringRef getArangesSection() const override { return ArangesSection; }
1861   const DWARFSection &getFrameSection() const override {
1862     return FrameSection;
1863   }
1864   const DWARFSection &getEHFrameSection() const override {
1865     return EHFrameSection;
1866   }
1867   const DWARFSection &getLineSection() const override { return LineSection; }
1868   StringRef getStrSection() const override { return StrSection; }
1869   const DWARFSection &getRangesSection() const override { return RangesSection; }
1870   const DWARFSection &getRnglistsSection() const override {
1871     return RnglistsSection;
1872   }
1873   const DWARFSection &getMacroSection() const override { return MacroSection; }
1874   StringRef getMacinfoSection() const override { return MacinfoSection; }
1875   StringRef getMacinfoDWOSection() const override { return MacinfoDWOSection; }
1876   const DWARFSection &getPubnamesSection() const override { return PubnamesSection; }
1877   const DWARFSection &getPubtypesSection() const override { return PubtypesSection; }
1878   const DWARFSection &getGnuPubnamesSection() const override {
1879     return GnuPubnamesSection;
1880   }
1881   const DWARFSection &getGnuPubtypesSection() const override {
1882     return GnuPubtypesSection;
1883   }
1884   const DWARFSection &getAppleNamesSection() const override {
1885     return AppleNamesSection;
1886   }
1887   const DWARFSection &getAppleTypesSection() const override {
1888     return AppleTypesSection;
1889   }
1890   const DWARFSection &getAppleNamespacesSection() const override {
1891     return AppleNamespacesSection;
1892   }
1893   const DWARFSection &getAppleObjCSection() const override {
1894     return AppleObjCSection;
1895   }
1896   const DWARFSection &getNamesSection() const override {
1897     return NamesSection;
1898   }
1899 
1900   StringRef getFileName() const override { return FileName; }
1901   uint8_t getAddressSize() const override { return AddressSize; }
1902   void forEachInfoSections(
1903       function_ref<void(const DWARFSection &)> F) const override {
1904     for (auto &P : InfoSections)
1905       F(P.second);
1906   }
1907   void forEachTypesSections(
1908       function_ref<void(const DWARFSection &)> F) const override {
1909     for (auto &P : TypesSections)
1910       F(P.second);
1911   }
1912 };
1913 } // namespace
1914 
1915 std::unique_ptr<DWARFContext>
1916 DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1917                      std::string DWPName,
1918                      std::function<void(Error)> RecoverableErrorHandler,
1919                      std::function<void(Error)> WarningHandler) {
1920   auto DObj =
1921       std::make_unique<DWARFObjInMemory>(Obj, L, RecoverableErrorHandler, WarningHandler);
1922   return std::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName),
1923                                         RecoverableErrorHandler,
1924                                         WarningHandler);
1925 }
1926 
1927 std::unique_ptr<DWARFContext>
1928 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1929                      uint8_t AddrSize, bool isLittleEndian,
1930                      std::function<void(Error)> RecoverableErrorHandler,
1931                      std::function<void(Error)> WarningHandler) {
1932   auto DObj =
1933       std::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1934   return std::make_unique<DWARFContext>(
1935       std::move(DObj), "", RecoverableErrorHandler, WarningHandler);
1936 }
1937 
1938 Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1939   // Detect the architecture from the object file. We usually don't need OS
1940   // info to lookup a target and create register info.
1941   Triple TT;
1942   TT.setArch(Triple::ArchType(Obj.getArch()));
1943   TT.setVendor(Triple::UnknownVendor);
1944   TT.setOS(Triple::UnknownOS);
1945   std::string TargetLookupError;
1946   const Target *TheTarget =
1947       TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1948   if (!TargetLookupError.empty())
1949     return createStringError(errc::invalid_argument,
1950                              TargetLookupError.c_str());
1951   RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1952   return Error::success();
1953 }
1954 
1955 uint8_t DWARFContext::getCUAddrSize() {
1956   // In theory, different compile units may have different address byte
1957   // sizes, but for simplicity we just use the address byte size of the
1958   // first compile unit. In practice the address size field is repeated across
1959   // various DWARF headers (at least in version 5) to make it easier to dump
1960   // them independently, not to enable varying the address size.
1961   unit_iterator_range CUs = compile_units();
1962   return CUs.empty() ? 0 : (*CUs.begin())->getAddressByteSize();
1963 }
1964