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 auto *Off = shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
440                                    DObj->getFrameSection().Data))
441     getDebugFrame()->dump(OS, getRegisterInfo(), *Off);
442 
443   if (const auto *Off = shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
444                                    DObj->getEHFrameSection().Data))
445     getEHFrame()->dump(OS, getRegisterInfo(), *Off);
446 
447   if (shouldDump(Explicit, ".debug_macro", DIDT_ID_DebugMacro,
448                  DObj->getMacroSection().Data)) {
449     if (auto Macro = getDebugMacro())
450       Macro->dump(OS);
451   }
452 
453   if (shouldDump(Explicit, ".debug_macinfo", DIDT_ID_DebugMacro,
454                  DObj->getMacinfoSection())) {
455     if (auto Macinfo = getDebugMacinfo())
456       Macinfo->dump(OS);
457   }
458 
459   if (shouldDump(Explicit, ".debug_macinfo.dwo", DIDT_ID_DebugMacro,
460                  DObj->getMacinfoDWOSection())) {
461     if (auto MacinfoDWO = getDebugMacinfoDWO())
462       MacinfoDWO->dump(OS);
463   }
464 
465   if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
466                  DObj->getArangesSection())) {
467     uint64_t offset = 0;
468     DWARFDataExtractor arangesData(DObj->getArangesSection(), isLittleEndian(),
469                                    0);
470     DWARFDebugArangeSet set;
471     while (arangesData.isValidOffset(offset)) {
472       if (Error E = set.extract(arangesData, &offset)) {
473         RecoverableErrorHandler(std::move(E));
474         break;
475       }
476       set.dump(OS);
477     }
478   }
479 
480   auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
481                              DIDumpOptions DumpOpts,
482                              Optional<uint64_t> DumpOffset) {
483     while (!Parser.done()) {
484       if (DumpOffset && Parser.getOffset() != *DumpOffset) {
485         Parser.skip(DumpOpts.WarningHandler, DumpOpts.WarningHandler);
486         continue;
487       }
488       OS << "debug_line[" << format("0x%8.8" PRIx64, Parser.getOffset())
489          << "]\n";
490       OS.flush();
491       if (DumpOpts.Verbose) {
492         Parser.parseNext(DumpOpts.WarningHandler, DumpOpts.WarningHandler, &OS);
493       } else {
494         DWARFDebugLine::LineTable LineTable =
495             Parser.parseNext(DumpOpts.WarningHandler, DumpOpts.WarningHandler);
496         LineTable.dump(OS, DumpOpts);
497       }
498       OS.flush();
499     }
500   };
501 
502   if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
503                                    DObj->getLineSection().Data)) {
504     DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
505                                 0);
506     DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
507                                          type_units());
508     DumpLineSection(Parser, DumpOpts, *Off);
509   }
510 
511   if (const auto *Off =
512           shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
513                      DObj->getLineDWOSection().Data)) {
514     DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
515                                 isLittleEndian(), 0);
516     DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
517                                          dwo_type_units());
518     DumpLineSection(Parser, DumpOpts, *Off);
519   }
520 
521   if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
522                  DObj->getCUIndexSection())) {
523     getCUIndex().dump(OS);
524   }
525 
526   if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
527                  DObj->getTUIndexSection())) {
528     getTUIndex().dump(OS);
529   }
530 
531   if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
532                  DObj->getStrSection())) {
533     DataExtractor strData(DObj->getStrSection(), isLittleEndian(), 0);
534     uint64_t offset = 0;
535     uint64_t strOffset = 0;
536     while (const char *s = strData.getCStr(&offset)) {
537       OS << format("0x%8.8" PRIx64 ": \"%s\"\n", strOffset, s);
538       strOffset = offset;
539     }
540   }
541   if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
542                  DObj->getStrDWOSection())) {
543     DataExtractor strDWOData(DObj->getStrDWOSection(), isLittleEndian(), 0);
544     uint64_t offset = 0;
545     uint64_t strDWOOffset = 0;
546     while (const char *s = strDWOData.getCStr(&offset)) {
547       OS << format("0x%8.8" PRIx64 ": \"%s\"\n", strDWOOffset, s);
548       strDWOOffset = offset;
549     }
550   }
551   if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
552                  DObj->getLineStrSection())) {
553     DataExtractor strData(DObj->getLineStrSection(), isLittleEndian(), 0);
554     uint64_t offset = 0;
555     uint64_t strOffset = 0;
556     while (const char *s = strData.getCStr(&offset)) {
557       OS << format("0x%8.8" PRIx64 ": \"", strOffset);
558       OS.write_escaped(s);
559       OS << "\"\n";
560       strOffset = offset;
561     }
562   }
563 
564   if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
565                  DObj->getAddrSection().Data)) {
566     DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
567                                    isLittleEndian(), 0);
568     dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
569   }
570 
571   if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
572                  DObj->getRangesSection().Data)) {
573     uint8_t savedAddressByteSize = getCUAddrSize();
574     DWARFDataExtractor rangesData(*DObj, DObj->getRangesSection(),
575                                   isLittleEndian(), savedAddressByteSize);
576     uint64_t offset = 0;
577     DWARFDebugRangeList rangeList;
578     while (rangesData.isValidOffset(offset)) {
579       if (Error E = rangeList.extract(rangesData, &offset)) {
580         DumpOpts.RecoverableErrorHandler(std::move(E));
581         break;
582       }
583       rangeList.dump(OS);
584     }
585   }
586 
587   auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
588     const auto &CUs = compile_units();
589     auto I = CUs.begin();
590     if (I == CUs.end())
591       return None;
592     return (*I)->getAddrOffsetSectionItem(Index);
593   };
594 
595   if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
596                  DObj->getRnglistsSection().Data)) {
597     DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
598                                    isLittleEndian(), 0);
599     dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
600   }
601 
602   if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
603                  DObj->getRnglistsDWOSection().Data)) {
604     DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
605                                    isLittleEndian(), 0);
606     dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
607   }
608 
609   if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
610                  DObj->getPubnamesSection().Data))
611     DWARFDebugPubTable(*DObj, DObj->getPubnamesSection(), isLittleEndian(), false)
612         .dump(OS);
613 
614   if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
615                  DObj->getPubtypesSection().Data))
616     DWARFDebugPubTable(*DObj, DObj->getPubtypesSection(), isLittleEndian(), false)
617         .dump(OS);
618 
619   if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
620                  DObj->getGnuPubnamesSection().Data))
621     DWARFDebugPubTable(*DObj, DObj->getGnuPubnamesSection(), isLittleEndian(),
622                        true /* GnuStyle */)
623         .dump(OS);
624 
625   if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
626                  DObj->getGnuPubtypesSection().Data))
627     DWARFDebugPubTable(*DObj, DObj->getGnuPubtypesSection(), isLittleEndian(),
628                        true /* GnuStyle */)
629         .dump(OS);
630 
631   if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
632                  DObj->getStrOffsetsSection().Data))
633     dumpStringOffsetsSection(
634         OS, DumpOpts, "debug_str_offsets", *DObj, DObj->getStrOffsetsSection(),
635         DObj->getStrSection(), normal_units(), isLittleEndian());
636   if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
637                  DObj->getStrOffsetsDWOSection().Data))
638     dumpStringOffsetsSection(OS, DumpOpts, "debug_str_offsets.dwo", *DObj,
639                              DObj->getStrOffsetsDWOSection(),
640                              DObj->getStrDWOSection(), dwo_units(),
641                              isLittleEndian());
642 
643   if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
644                  DObj->getGdbIndexSection())) {
645     getGdbIndex().dump(OS);
646   }
647 
648   if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
649                  DObj->getAppleNamesSection().Data))
650     getAppleNames().dump(OS);
651 
652   if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
653                  DObj->getAppleTypesSection().Data))
654     getAppleTypes().dump(OS);
655 
656   if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
657                  DObj->getAppleNamespacesSection().Data))
658     getAppleNamespaces().dump(OS);
659 
660   if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
661                  DObj->getAppleObjCSection().Data))
662     getAppleObjC().dump(OS);
663   if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
664                  DObj->getNamesSection().Data))
665     getDebugNames().dump(OS);
666 }
667 
668 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
669   parseDWOUnits(LazyParse);
670 
671   if (const auto &CUI = getCUIndex()) {
672     if (const auto *R = CUI.getFromHash(Hash))
673       return dyn_cast_or_null<DWARFCompileUnit>(
674           DWOUnits.getUnitForIndexEntry(*R));
675     return nullptr;
676   }
677 
678   // If there's no index, just search through the CUs in the DWO - there's
679   // probably only one unless this is something like LTO - though an in-process
680   // built/cached lookup table could be used in that case to improve repeated
681   // lookups of different CUs in the DWO.
682   for (const auto &DWOCU : dwo_compile_units()) {
683     // Might not have parsed DWO ID yet.
684     if (!DWOCU->getDWOId()) {
685       if (Optional<uint64_t> DWOId =
686           toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
687         DWOCU->setDWOId(*DWOId);
688       else
689         // No DWO ID?
690         continue;
691     }
692     if (DWOCU->getDWOId() == Hash)
693       return dyn_cast<DWARFCompileUnit>(DWOCU.get());
694   }
695   return nullptr;
696 }
697 
698 DWARFDie DWARFContext::getDIEForOffset(uint64_t Offset) {
699   parseNormalUnits();
700   if (auto *CU = NormalUnits.getUnitForOffset(Offset))
701     return CU->getDIEForOffset(Offset);
702   return DWARFDie();
703 }
704 
705 bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
706   bool Success = true;
707   DWARFVerifier verifier(OS, *this, DumpOpts);
708 
709   Success &= verifier.handleDebugAbbrev();
710   if (DumpOpts.DumpType & DIDT_DebugInfo)
711     Success &= verifier.handleDebugInfo();
712   if (DumpOpts.DumpType & DIDT_DebugLine)
713     Success &= verifier.handleDebugLine();
714   Success &= verifier.handleAccelTables();
715   return Success;
716 }
717 
718 const DWARFUnitIndex &DWARFContext::getCUIndex() {
719   if (CUIndex)
720     return *CUIndex;
721 
722   DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
723 
724   CUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
725   CUIndex->parse(CUIndexData);
726   return *CUIndex;
727 }
728 
729 const DWARFUnitIndex &DWARFContext::getTUIndex() {
730   if (TUIndex)
731     return *TUIndex;
732 
733   DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
734 
735   TUIndex = std::make_unique<DWARFUnitIndex>(DW_SECT_EXT_TYPES);
736   TUIndex->parse(TUIndexData);
737   return *TUIndex;
738 }
739 
740 DWARFGdbIndex &DWARFContext::getGdbIndex() {
741   if (GdbIndex)
742     return *GdbIndex;
743 
744   DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
745   GdbIndex = std::make_unique<DWARFGdbIndex>();
746   GdbIndex->parse(GdbIndexData);
747   return *GdbIndex;
748 }
749 
750 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
751   if (Abbrev)
752     return Abbrev.get();
753 
754   DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
755 
756   Abbrev.reset(new DWARFDebugAbbrev());
757   Abbrev->extract(abbrData);
758   return Abbrev.get();
759 }
760 
761 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
762   if (AbbrevDWO)
763     return AbbrevDWO.get();
764 
765   DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
766   AbbrevDWO.reset(new DWARFDebugAbbrev());
767   AbbrevDWO->extract(abbrData);
768   return AbbrevDWO.get();
769 }
770 
771 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
772   if (Loc)
773     return Loc.get();
774 
775   // Assume all units have the same address byte size.
776   auto LocData =
777       getNumCompileUnits()
778           ? DWARFDataExtractor(*DObj, DObj->getLocSection(), isLittleEndian(),
779                                getUnitAtIndex(0)->getAddressByteSize())
780           : DWARFDataExtractor("", isLittleEndian(), 0);
781   Loc.reset(new DWARFDebugLoc(std::move(LocData)));
782   return Loc.get();
783 }
784 
785 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
786   if (Aranges)
787     return Aranges.get();
788 
789   Aranges.reset(new DWARFDebugAranges());
790   Aranges->generate(this);
791   return Aranges.get();
792 }
793 
794 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
795   if (DebugFrame)
796     return DebugFrame.get();
797 
798   // There's a "bug" in the DWARFv3 standard with respect to the target address
799   // size within debug frame sections. While DWARF is supposed to be independent
800   // of its container, FDEs have fields with size being "target address size",
801   // which isn't specified in DWARF in general. It's only specified for CUs, but
802   // .eh_frame can appear without a .debug_info section. Follow the example of
803   // other tools (libdwarf) and extract this from the container (ObjectFile
804   // provides this information). This problem is fixed in DWARFv4
805   // See this dwarf-discuss discussion for more details:
806   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
807   DWARFDataExtractor debugFrameData(*DObj, DObj->getFrameSection(),
808                                     isLittleEndian(), DObj->getAddressSize());
809   DebugFrame.reset(new DWARFDebugFrame(getArch(), false /* IsEH */));
810   DebugFrame->parse(debugFrameData);
811   return DebugFrame.get();
812 }
813 
814 const DWARFDebugFrame *DWARFContext::getEHFrame() {
815   if (EHFrame)
816     return EHFrame.get();
817 
818   DWARFDataExtractor debugFrameData(*DObj, DObj->getEHFrameSection(),
819                                     isLittleEndian(), DObj->getAddressSize());
820   DebugFrame.reset(new DWARFDebugFrame(getArch(), true /* IsEH */));
821   DebugFrame->parse(debugFrameData);
822   return DebugFrame.get();
823 }
824 
825 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
826   if (!Macro)
827     Macro = parseMacroOrMacinfo(MacroSection);
828   return Macro.get();
829 }
830 
831 const DWARFDebugMacro *DWARFContext::getDebugMacinfo() {
832   if (!Macinfo)
833     Macinfo = parseMacroOrMacinfo(MacinfoSection);
834   return Macinfo.get();
835 }
836 
837 const DWARFDebugMacro *DWARFContext::getDebugMacinfoDWO() {
838   if (!MacinfoDWO)
839     MacinfoDWO = parseMacroOrMacinfo(MacinfoDwoSection);
840   return MacinfoDWO.get();
841 }
842 
843 template <typename T>
844 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
845                         const DWARFSection &Section, StringRef StringSection,
846                         bool IsLittleEndian) {
847   if (Cache)
848     return *Cache;
849   DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
850   DataExtractor StrData(StringSection, IsLittleEndian, 0);
851   Cache.reset(new T(AccelSection, StrData));
852   if (Error E = Cache->extract())
853     llvm::consumeError(std::move(E));
854   return *Cache;
855 }
856 
857 const DWARFDebugNames &DWARFContext::getDebugNames() {
858   return getAccelTable(Names, *DObj, DObj->getNamesSection(),
859                        DObj->getStrSection(), isLittleEndian());
860 }
861 
862 const AppleAcceleratorTable &DWARFContext::getAppleNames() {
863   return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
864                        DObj->getStrSection(), isLittleEndian());
865 }
866 
867 const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
868   return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
869                        DObj->getStrSection(), isLittleEndian());
870 }
871 
872 const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
873   return getAccelTable(AppleNamespaces, *DObj,
874                        DObj->getAppleNamespacesSection(),
875                        DObj->getStrSection(), isLittleEndian());
876 }
877 
878 const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
879   return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
880                        DObj->getStrSection(), isLittleEndian());
881 }
882 
883 const DWARFDebugLine::LineTable *
884 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
885   Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
886       getLineTableForUnit(U, WarningHandler);
887   if (!ExpectedLineTable) {
888     WarningHandler(ExpectedLineTable.takeError());
889     return nullptr;
890   }
891   return *ExpectedLineTable;
892 }
893 
894 Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
895     DWARFUnit *U, function_ref<void(Error)> RecoverableErrorHandler) {
896   if (!Line)
897     Line.reset(new DWARFDebugLine);
898 
899   auto UnitDIE = U->getUnitDIE();
900   if (!UnitDIE)
901     return nullptr;
902 
903   auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
904   if (!Offset)
905     return nullptr; // No line table for this compile unit.
906 
907   uint64_t stmtOffset = *Offset + U->getLineTableOffset();
908   // See if the line table is cached.
909   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
910     return lt;
911 
912   // Make sure the offset is good before we try to parse.
913   if (stmtOffset >= U->getLineSection().Data.size())
914     return nullptr;
915 
916   // We have to parse it first.
917   DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
918                               U->getAddressByteSize());
919   return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
920                                    RecoverableErrorHandler);
921 }
922 
923 void DWARFContext::parseNormalUnits() {
924   if (!NormalUnits.empty())
925     return;
926   DObj->forEachInfoSections([&](const DWARFSection &S) {
927     NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
928   });
929   NormalUnits.finishedInfoUnits();
930   DObj->forEachTypesSections([&](const DWARFSection &S) {
931     NormalUnits.addUnitsForSection(*this, S, DW_SECT_EXT_TYPES);
932   });
933 }
934 
935 void DWARFContext::parseDWOUnits(bool Lazy) {
936   if (!DWOUnits.empty())
937     return;
938   DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
939     DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
940   });
941   DWOUnits.finishedInfoUnits();
942   DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
943     DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_EXT_TYPES, Lazy);
944   });
945 }
946 
947 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint64_t Offset) {
948   parseNormalUnits();
949   return dyn_cast_or_null<DWARFCompileUnit>(
950       NormalUnits.getUnitForOffset(Offset));
951 }
952 
953 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
954   // First, get the offset of the compile unit.
955   uint64_t CUOffset = getDebugAranges()->findAddress(Address);
956   // Retrieve the compile unit.
957   return getCompileUnitForOffset(CUOffset);
958 }
959 
960 DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
961   DIEsForAddress Result;
962 
963   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
964   if (!CU)
965     return Result;
966 
967   Result.CompileUnit = CU;
968   Result.FunctionDIE = CU->getSubroutineForAddress(Address);
969 
970   std::vector<DWARFDie> Worklist;
971   Worklist.push_back(Result.FunctionDIE);
972   while (!Worklist.empty()) {
973     DWARFDie DIE = Worklist.back();
974     Worklist.pop_back();
975 
976     if (!DIE.isValid())
977       continue;
978 
979     if (DIE.getTag() == DW_TAG_lexical_block &&
980         DIE.addressRangeContainsAddress(Address)) {
981       Result.BlockDIE = DIE;
982       break;
983     }
984 
985     for (auto Child : DIE)
986       Worklist.push_back(Child);
987   }
988 
989   return Result;
990 }
991 
992 /// TODO: change input parameter from "uint64_t Address"
993 ///       into "SectionedAddress Address"
994 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
995                                                   uint64_t Address,
996                                                   FunctionNameKind Kind,
997                                                   std::string &FunctionName,
998                                                   uint32_t &StartLine) {
999   // The address may correspond to instruction in some inlined function,
1000   // so we have to build the chain of inlined functions and take the
1001   // name of the topmost function in it.
1002   SmallVector<DWARFDie, 4> InlinedChain;
1003   CU->getInlinedChainForAddress(Address, InlinedChain);
1004   if (InlinedChain.empty())
1005     return false;
1006 
1007   const DWARFDie &DIE = InlinedChain[0];
1008   bool FoundResult = false;
1009   const char *Name = nullptr;
1010   if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
1011     FunctionName = Name;
1012     FoundResult = true;
1013   }
1014   if (auto DeclLineResult = DIE.getDeclLine()) {
1015     StartLine = DeclLineResult;
1016     FoundResult = true;
1017   }
1018 
1019   return FoundResult;
1020 }
1021 
1022 static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
1023   if (auto SizeAttr = Type.find(DW_AT_byte_size))
1024     if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
1025       return Size;
1026 
1027   switch (Type.getTag()) {
1028   case DW_TAG_pointer_type:
1029   case DW_TAG_reference_type:
1030   case DW_TAG_rvalue_reference_type:
1031     return PointerSize;
1032   case DW_TAG_ptr_to_member_type: {
1033     if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
1034       if (BaseType.getTag() == DW_TAG_subroutine_type)
1035         return 2 * PointerSize;
1036     return PointerSize;
1037   }
1038   case DW_TAG_const_type:
1039   case DW_TAG_volatile_type:
1040   case DW_TAG_restrict_type:
1041   case DW_TAG_typedef: {
1042     if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
1043       return getTypeSize(BaseType, PointerSize);
1044     break;
1045   }
1046   case DW_TAG_array_type: {
1047     DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type);
1048     if (!BaseType)
1049       return Optional<uint64_t>();
1050     Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
1051     if (!BaseSize)
1052       return Optional<uint64_t>();
1053     uint64_t Size = *BaseSize;
1054     for (DWARFDie Child : Type) {
1055       if (Child.getTag() != DW_TAG_subrange_type)
1056         continue;
1057 
1058       if (auto ElemCountAttr = Child.find(DW_AT_count))
1059         if (Optional<uint64_t> ElemCount =
1060                 ElemCountAttr->getAsUnsignedConstant())
1061           Size *= *ElemCount;
1062       if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
1063         if (Optional<int64_t> UpperBound =
1064                 UpperBoundAttr->getAsSignedConstant()) {
1065           int64_t LowerBound = 0;
1066           if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
1067             LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
1068           Size *= *UpperBound - LowerBound + 1;
1069         }
1070     }
1071     return Size;
1072   }
1073   default:
1074     break;
1075   }
1076   return Optional<uint64_t>();
1077 }
1078 
1079 static Optional<int64_t>
1080 getExpressionFrameOffset(ArrayRef<uint8_t> Expr,
1081                          Optional<unsigned> FrameBaseReg) {
1082   if (!Expr.empty() &&
1083       (Expr[0] == DW_OP_fbreg ||
1084        (FrameBaseReg && Expr[0] == DW_OP_breg0 + *FrameBaseReg))) {
1085     unsigned Count;
1086     int64_t Offset = decodeSLEB128(Expr.data() + 1, &Count, Expr.end());
1087     // A single DW_OP_fbreg or DW_OP_breg.
1088     if (Expr.size() == Count + 1)
1089       return Offset;
1090     // Same + DW_OP_deref (Fortran arrays look like this).
1091     if (Expr.size() == Count + 2 && Expr[Count + 1] == DW_OP_deref)
1092       return Offset;
1093     // Fallthrough. Do not accept ex. (DW_OP_breg W29, DW_OP_stack_value)
1094   }
1095   return None;
1096 }
1097 
1098 void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1099                                    DWARFDie Die, std::vector<DILocal> &Result) {
1100   if (Die.getTag() == DW_TAG_variable ||
1101       Die.getTag() == DW_TAG_formal_parameter) {
1102     DILocal Local;
1103     if (const char *Name = Subprogram.getSubroutineName(DINameKind::ShortName))
1104       Local.FunctionName = Name;
1105 
1106     Optional<unsigned> FrameBaseReg;
1107     if (auto FrameBase = Subprogram.find(DW_AT_frame_base))
1108       if (Optional<ArrayRef<uint8_t>> Expr = FrameBase->getAsBlock())
1109         if (!Expr->empty() && (*Expr)[0] >= DW_OP_reg0 &&
1110             (*Expr)[0] <= DW_OP_reg31) {
1111           FrameBaseReg = (*Expr)[0] - DW_OP_reg0;
1112         }
1113 
1114     if (Expected<std::vector<DWARFLocationExpression>> Loc =
1115             Die.getLocations(DW_AT_location)) {
1116       for (const auto &Entry : *Loc) {
1117         if (Optional<int64_t> FrameOffset =
1118                 getExpressionFrameOffset(Entry.Expr, FrameBaseReg)) {
1119           Local.FrameOffset = *FrameOffset;
1120           break;
1121         }
1122       }
1123     } else {
1124       // FIXME: missing DW_AT_location is OK here, but other errors should be
1125       // reported to the user.
1126       consumeError(Loc.takeError());
1127     }
1128 
1129     if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
1130       Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1131 
1132     if (auto Origin =
1133             Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1134       Die = Origin;
1135     if (auto NameAttr = Die.find(DW_AT_name))
1136       if (Optional<const char *> Name = NameAttr->getAsCString())
1137         Local.Name = *Name;
1138     if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
1139       Local.Size = getTypeSize(Type, getCUAddrSize());
1140     if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
1141       if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
1142         LT->getFileNameByIndex(
1143             DeclFileAttr->getAsUnsignedConstant().getValue(),
1144             CU->getCompilationDir(),
1145             DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1146             Local.DeclFile);
1147     }
1148     if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
1149       Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
1150 
1151     Result.push_back(Local);
1152     return;
1153   }
1154 
1155   if (Die.getTag() == DW_TAG_inlined_subroutine)
1156     if (auto Origin =
1157             Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1158       Subprogram = Origin;
1159 
1160   for (auto Child : Die)
1161     addLocalsForDie(CU, Subprogram, Child, Result);
1162 }
1163 
1164 std::vector<DILocal>
1165 DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
1166   std::vector<DILocal> Result;
1167   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1168   if (!CU)
1169     return Result;
1170 
1171   DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
1172   if (Subprogram.isValid())
1173     addLocalsForDie(CU, Subprogram, Subprogram, Result);
1174   return Result;
1175 }
1176 
1177 DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
1178                                                DILineInfoSpecifier Spec) {
1179   DILineInfo Result;
1180 
1181   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1182   if (!CU)
1183     return Result;
1184 
1185   getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1186                                         Result.FunctionName, Result.StartLine);
1187   if (Spec.FLIKind != FileLineInfoKind::None) {
1188     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
1189       LineTable->getFileLineInfoForAddress(
1190           {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1191           Spec.FLIKind, Result);
1192     }
1193   }
1194   return Result;
1195 }
1196 
1197 DILineInfoTable DWARFContext::getLineInfoForAddressRange(
1198     object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
1199   DILineInfoTable  Lines;
1200   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1201   if (!CU)
1202     return Lines;
1203 
1204   uint32_t StartLine = 0;
1205   std::string FunctionName(DILineInfo::BadString);
1206   getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1207                                         FunctionName, StartLine);
1208 
1209   // If the Specifier says we don't need FileLineInfo, just
1210   // return the top-most function at the starting address.
1211   if (Spec.FLIKind == FileLineInfoKind::None) {
1212     DILineInfo Result;
1213     Result.FunctionName = FunctionName;
1214     Result.StartLine = StartLine;
1215     Lines.push_back(std::make_pair(Address.Address, Result));
1216     return Lines;
1217   }
1218 
1219   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
1220 
1221   // Get the index of row we're looking for in the line table.
1222   std::vector<uint32_t> RowVector;
1223   if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
1224                                      Size, RowVector)) {
1225     return Lines;
1226   }
1227 
1228   for (uint32_t RowIndex : RowVector) {
1229     // Take file number and line/column from the row.
1230     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
1231     DILineInfo Result;
1232     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1233                                   Spec.FLIKind, Result.FileName);
1234     Result.FunctionName = FunctionName;
1235     Result.Line = Row.Line;
1236     Result.Column = Row.Column;
1237     Result.StartLine = StartLine;
1238     Lines.push_back(std::make_pair(Row.Address.Address, Result));
1239   }
1240 
1241   return Lines;
1242 }
1243 
1244 DIInliningInfo
1245 DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
1246                                         DILineInfoSpecifier Spec) {
1247   DIInliningInfo InliningInfo;
1248 
1249   DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1250   if (!CU)
1251     return InliningInfo;
1252 
1253   const DWARFLineTable *LineTable = nullptr;
1254   SmallVector<DWARFDie, 4> InlinedChain;
1255   CU->getInlinedChainForAddress(Address.Address, InlinedChain);
1256   if (InlinedChain.size() == 0) {
1257     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1258     // try to at least get file/line info from symbol table.
1259     if (Spec.FLIKind != FileLineInfoKind::None) {
1260       DILineInfo Frame;
1261       LineTable = getLineTableForUnit(CU);
1262       if (LineTable && LineTable->getFileLineInfoForAddress(
1263                            {Address.Address, Address.SectionIndex},
1264                            CU->getCompilationDir(), Spec.FLIKind, Frame))
1265         InliningInfo.addFrame(Frame);
1266     }
1267     return InliningInfo;
1268   }
1269 
1270   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
1271   for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1272     DWARFDie &FunctionDIE = InlinedChain[i];
1273     DILineInfo Frame;
1274     // Get function name if necessary.
1275     if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
1276       Frame.FunctionName = Name;
1277     if (auto DeclLineResult = FunctionDIE.getDeclLine())
1278       Frame.StartLine = DeclLineResult;
1279     if (Spec.FLIKind != FileLineInfoKind::None) {
1280       if (i == 0) {
1281         // For the topmost frame, initialize the line table of this
1282         // compile unit and fetch file/line info from it.
1283         LineTable = getLineTableForUnit(CU);
1284         // For the topmost routine, get file/line info from line table.
1285         if (LineTable)
1286           LineTable->getFileLineInfoForAddress(
1287               {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1288               Spec.FLIKind, Frame);
1289       } else {
1290         // Otherwise, use call file, call line and call column from
1291         // previous DIE in inlined chain.
1292         if (LineTable)
1293           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1294                                         Spec.FLIKind, Frame.FileName);
1295         Frame.Line = CallLine;
1296         Frame.Column = CallColumn;
1297         Frame.Discriminator = CallDiscriminator;
1298       }
1299       // Get call file/line/column of a current DIE.
1300       if (i + 1 < n) {
1301         FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1302                                    CallDiscriminator);
1303       }
1304     }
1305     InliningInfo.addFrame(Frame);
1306   }
1307   return InliningInfo;
1308 }
1309 
1310 std::shared_ptr<DWARFContext>
1311 DWARFContext::getDWOContext(StringRef AbsolutePath) {
1312   if (auto S = DWP.lock()) {
1313     DWARFContext *Ctxt = S->Context.get();
1314     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1315   }
1316 
1317   std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1318 
1319   if (auto S = Entry->lock()) {
1320     DWARFContext *Ctxt = S->Context.get();
1321     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1322   }
1323 
1324   Expected<OwningBinary<ObjectFile>> Obj = [&] {
1325     if (!CheckedForDWP) {
1326       SmallString<128> DWPName;
1327       auto Obj = object::ObjectFile::createObjectFile(
1328           this->DWPName.empty()
1329               ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1330               : StringRef(this->DWPName));
1331       if (Obj) {
1332         Entry = &DWP;
1333         return Obj;
1334       } else {
1335         CheckedForDWP = true;
1336         // TODO: Should this error be handled (maybe in a high verbosity mode)
1337         // before falling back to .dwo files?
1338         consumeError(Obj.takeError());
1339       }
1340     }
1341 
1342     return object::ObjectFile::createObjectFile(AbsolutePath);
1343   }();
1344 
1345   if (!Obj) {
1346     // TODO: Actually report errors helpfully.
1347     consumeError(Obj.takeError());
1348     return nullptr;
1349   }
1350 
1351   auto S = std::make_shared<DWOFile>();
1352   S->File = std::move(Obj.get());
1353   S->Context = DWARFContext::create(*S->File.getBinary());
1354   *Entry = S;
1355   auto *Ctxt = S->Context.get();
1356   return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1357 }
1358 
1359 static Error createError(const Twine &Reason, llvm::Error E) {
1360   return make_error<StringError>(Reason + toString(std::move(E)),
1361                                  inconvertibleErrorCode());
1362 }
1363 
1364 /// SymInfo contains information about symbol: it's address
1365 /// and section index which is -1LL for absolute symbols.
1366 struct SymInfo {
1367   uint64_t Address;
1368   uint64_t SectionIndex;
1369 };
1370 
1371 /// Returns the address of symbol relocation used against and a section index.
1372 /// Used for futher relocations computation. Symbol's section load address is
1373 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1374                                        const RelocationRef &Reloc,
1375                                        const LoadedObjectInfo *L,
1376                                        std::map<SymbolRef, SymInfo> &Cache) {
1377   SymInfo Ret = {0, (uint64_t)-1LL};
1378   object::section_iterator RSec = Obj.section_end();
1379   object::symbol_iterator Sym = Reloc.getSymbol();
1380 
1381   std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1382   // First calculate the address of the symbol or section as it appears
1383   // in the object file
1384   if (Sym != Obj.symbol_end()) {
1385     bool New;
1386     std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
1387     if (!New)
1388       return CacheIt->second;
1389 
1390     Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1391     if (!SymAddrOrErr)
1392       return createError("failed to compute symbol address: ",
1393                          SymAddrOrErr.takeError());
1394 
1395     // Also remember what section this symbol is in for later
1396     auto SectOrErr = Sym->getSection();
1397     if (!SectOrErr)
1398       return createError("failed to get symbol section: ",
1399                          SectOrErr.takeError());
1400 
1401     RSec = *SectOrErr;
1402     Ret.Address = *SymAddrOrErr;
1403   } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1404     RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
1405     Ret.Address = RSec->getAddress();
1406   }
1407 
1408   if (RSec != Obj.section_end())
1409     Ret.SectionIndex = RSec->getIndex();
1410 
1411   // If we are given load addresses for the sections, we need to adjust:
1412   // SymAddr = (Address of Symbol Or Section in File) -
1413   //           (Address of Section in File) +
1414   //           (Load Address of Section)
1415   // RSec is now either the section being targeted or the section
1416   // containing the symbol being targeted. In either case,
1417   // we need to perform the same computation.
1418   if (L && RSec != Obj.section_end())
1419     if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
1420       Ret.Address += SectionLoadAddress - RSec->getAddress();
1421 
1422   if (CacheIt != Cache.end())
1423     CacheIt->second = Ret;
1424 
1425   return Ret;
1426 }
1427 
1428 static bool isRelocScattered(const object::ObjectFile &Obj,
1429                              const RelocationRef &Reloc) {
1430   const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1431   if (!MachObj)
1432     return false;
1433   // MachO also has relocations that point to sections and
1434   // scattered relocations.
1435   auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1436   return MachObj->isRelocationScattered(RelocInfo);
1437 }
1438 
1439 namespace {
1440 struct DWARFSectionMap final : public DWARFSection {
1441   RelocAddrMap Relocs;
1442 };
1443 
1444 class DWARFObjInMemory final : public DWARFObject {
1445   bool IsLittleEndian;
1446   uint8_t AddressSize;
1447   StringRef FileName;
1448   const object::ObjectFile *Obj = nullptr;
1449   std::vector<SectionName> SectionNames;
1450 
1451   using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1452                                    std::map<object::SectionRef, unsigned>>;
1453 
1454   InfoSectionMap InfoSections;
1455   InfoSectionMap TypesSections;
1456   InfoSectionMap InfoDWOSections;
1457   InfoSectionMap TypesDWOSections;
1458 
1459   DWARFSectionMap LocSection;
1460   DWARFSectionMap LoclistsSection;
1461   DWARFSectionMap LoclistsDWOSection;
1462   DWARFSectionMap LineSection;
1463   DWARFSectionMap RangesSection;
1464   DWARFSectionMap RnglistsSection;
1465   DWARFSectionMap StrOffsetsSection;
1466   DWARFSectionMap LineDWOSection;
1467   DWARFSectionMap FrameSection;
1468   DWARFSectionMap EHFrameSection;
1469   DWARFSectionMap LocDWOSection;
1470   DWARFSectionMap StrOffsetsDWOSection;
1471   DWARFSectionMap RangesDWOSection;
1472   DWARFSectionMap RnglistsDWOSection;
1473   DWARFSectionMap AddrSection;
1474   DWARFSectionMap AppleNamesSection;
1475   DWARFSectionMap AppleTypesSection;
1476   DWARFSectionMap AppleNamespacesSection;
1477   DWARFSectionMap AppleObjCSection;
1478   DWARFSectionMap NamesSection;
1479   DWARFSectionMap PubnamesSection;
1480   DWARFSectionMap PubtypesSection;
1481   DWARFSectionMap GnuPubnamesSection;
1482   DWARFSectionMap GnuPubtypesSection;
1483   DWARFSectionMap MacroSection;
1484 
1485   DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1486     return StringSwitch<DWARFSectionMap *>(Name)
1487         .Case("debug_loc", &LocSection)
1488         .Case("debug_loclists", &LoclistsSection)
1489         .Case("debug_loclists.dwo", &LoclistsDWOSection)
1490         .Case("debug_line", &LineSection)
1491         .Case("debug_frame", &FrameSection)
1492         .Case("eh_frame", &EHFrameSection)
1493         .Case("debug_str_offsets", &StrOffsetsSection)
1494         .Case("debug_ranges", &RangesSection)
1495         .Case("debug_rnglists", &RnglistsSection)
1496         .Case("debug_loc.dwo", &LocDWOSection)
1497         .Case("debug_line.dwo", &LineDWOSection)
1498         .Case("debug_names", &NamesSection)
1499         .Case("debug_rnglists.dwo", &RnglistsDWOSection)
1500         .Case("debug_str_offsets.dwo", &StrOffsetsDWOSection)
1501         .Case("debug_addr", &AddrSection)
1502         .Case("apple_names", &AppleNamesSection)
1503         .Case("debug_pubnames", &PubnamesSection)
1504         .Case("debug_pubtypes", &PubtypesSection)
1505         .Case("debug_gnu_pubnames", &GnuPubnamesSection)
1506         .Case("debug_gnu_pubtypes", &GnuPubtypesSection)
1507         .Case("apple_types", &AppleTypesSection)
1508         .Case("apple_namespaces", &AppleNamespacesSection)
1509         .Case("apple_namespac", &AppleNamespacesSection)
1510         .Case("apple_objc", &AppleObjCSection)
1511         .Case("debug_macro", &MacroSection)
1512         .Default(nullptr);
1513   }
1514 
1515   StringRef AbbrevSection;
1516   StringRef ArangesSection;
1517   StringRef StrSection;
1518   StringRef MacinfoSection;
1519   StringRef MacinfoDWOSection;
1520   StringRef AbbrevDWOSection;
1521   StringRef StrDWOSection;
1522   StringRef CUIndexSection;
1523   StringRef GdbIndexSection;
1524   StringRef TUIndexSection;
1525   StringRef LineStrSection;
1526 
1527   // A deque holding section data whose iterators are not invalidated when
1528   // new decompressed sections are inserted at the end.
1529   std::deque<SmallString<0>> UncompressedSections;
1530 
1531   StringRef *mapSectionToMember(StringRef Name) {
1532     if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1533       return &Sec->Data;
1534     return StringSwitch<StringRef *>(Name)
1535         .Case("debug_abbrev", &AbbrevSection)
1536         .Case("debug_aranges", &ArangesSection)
1537         .Case("debug_str", &StrSection)
1538         .Case("debug_macinfo", &MacinfoSection)
1539         .Case("debug_macinfo.dwo", &MacinfoDWOSection)
1540         .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1541         .Case("debug_str.dwo", &StrDWOSection)
1542         .Case("debug_cu_index", &CUIndexSection)
1543         .Case("debug_tu_index", &TUIndexSection)
1544         .Case("gdb_index", &GdbIndexSection)
1545         .Case("debug_line_str", &LineStrSection)
1546         // Any more debug info sections go here.
1547         .Default(nullptr);
1548   }
1549 
1550   /// If Sec is compressed section, decompresses and updates its contents
1551   /// provided by Data. Otherwise leaves it unchanged.
1552   Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1553                         StringRef &Data) {
1554     if (!Decompressor::isCompressed(Sec))
1555       return Error::success();
1556 
1557     Expected<Decompressor> Decompressor =
1558         Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1559     if (!Decompressor)
1560       return Decompressor.takeError();
1561 
1562     SmallString<0> Out;
1563     if (auto Err = Decompressor->resizeAndDecompress(Out))
1564       return Err;
1565 
1566     UncompressedSections.push_back(std::move(Out));
1567     Data = UncompressedSections.back();
1568 
1569     return Error::success();
1570   }
1571 
1572 public:
1573   DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1574                    uint8_t AddrSize, bool IsLittleEndian)
1575       : IsLittleEndian(IsLittleEndian) {
1576     for (const auto &SecIt : Sections) {
1577       if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1578         *SectionData = SecIt.second->getBuffer();
1579       else if (SecIt.first() == "debug_info")
1580         // Find debug_info and debug_types data by section rather than name as
1581         // there are multiple, comdat grouped, of these sections.
1582         InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1583       else if (SecIt.first() == "debug_info.dwo")
1584         InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1585       else if (SecIt.first() == "debug_types")
1586         TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1587       else if (SecIt.first() == "debug_types.dwo")
1588         TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1589     }
1590   }
1591   DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1592                    function_ref<void(Error)> HandleError, function_ref<void(Error)> HandleWarning )
1593       : IsLittleEndian(Obj.isLittleEndian()),
1594         AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1595         Obj(&Obj) {
1596 
1597     StringMap<unsigned> SectionAmountMap;
1598     for (const SectionRef &Section : Obj.sections()) {
1599       StringRef Name;
1600       if (auto NameOrErr = Section.getName())
1601         Name = *NameOrErr;
1602       else
1603         consumeError(NameOrErr.takeError());
1604 
1605       ++SectionAmountMap[Name];
1606       SectionNames.push_back({ Name, true });
1607 
1608       // Skip BSS and Virtual sections, they aren't interesting.
1609       if (Section.isBSS() || Section.isVirtual())
1610         continue;
1611 
1612       // Skip sections stripped by dsymutil.
1613       if (Section.isStripped())
1614         continue;
1615 
1616       StringRef Data;
1617       Expected<section_iterator> SecOrErr = Section.getRelocatedSection();
1618       if (!SecOrErr) {
1619         HandleError(createError("failed to get relocated section: ",
1620                                 SecOrErr.takeError()));
1621         continue;
1622       }
1623 
1624       // Try to obtain an already relocated version of this section.
1625       // Else use the unrelocated section from the object file. We'll have to
1626       // apply relocations ourselves later.
1627       section_iterator RelocatedSection = *SecOrErr;
1628       if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) {
1629         Expected<StringRef> E = Section.getContents();
1630         if (E)
1631           Data = *E;
1632         else
1633           // maybeDecompress below will error.
1634           consumeError(E.takeError());
1635       }
1636 
1637       if (auto Err = maybeDecompress(Section, Name, Data)) {
1638         HandleError(createError("failed to decompress '" + Name + "', ",
1639                                 std::move(Err)));
1640         continue;
1641       }
1642 
1643       // Compressed sections names in GNU style starts from ".z",
1644       // at this point section is decompressed and we drop compression prefix.
1645       Name = Name.substr(
1646           Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1647 
1648       // Map platform specific debug section names to DWARF standard section
1649       // names.
1650       Name = Obj.mapDebugSectionName(Name);
1651 
1652       if (StringRef *SectionData = mapSectionToMember(Name)) {
1653         *SectionData = Data;
1654         if (Name == "debug_ranges") {
1655           // FIXME: Use the other dwo range section when we emit it.
1656           RangesDWOSection.Data = Data;
1657         }
1658       } else if (Name == "debug_info") {
1659         // Find debug_info and debug_types data by section rather than name as
1660         // there are multiple, comdat grouped, of these sections.
1661         InfoSections[Section].Data = Data;
1662       } else if (Name == "debug_info.dwo") {
1663         InfoDWOSections[Section].Data = Data;
1664       } else if (Name == "debug_types") {
1665         TypesSections[Section].Data = Data;
1666       } else if (Name == "debug_types.dwo") {
1667         TypesDWOSections[Section].Data = Data;
1668       }
1669 
1670       if (RelocatedSection == Obj.section_end())
1671         continue;
1672 
1673       StringRef RelSecName;
1674       if (auto NameOrErr = RelocatedSection->getName())
1675         RelSecName = *NameOrErr;
1676       else
1677         consumeError(NameOrErr.takeError());
1678 
1679       // If the section we're relocating was relocated already by the JIT,
1680       // then we used the relocated version above, so we do not need to process
1681       // relocations for it now.
1682       StringRef RelSecData;
1683       if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1684         continue;
1685 
1686       // In Mach-o files, the relocations do not need to be applied if
1687       // there is no load offset to apply. The value read at the
1688       // relocation point already factors in the section address
1689       // (actually applying the relocations will produce wrong results
1690       // as the section address will be added twice).
1691       if (!L && isa<MachOObjectFile>(&Obj))
1692         continue;
1693 
1694       RelSecName = RelSecName.substr(
1695           RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1696 
1697       // TODO: Add support for relocations in other sections as needed.
1698       // Record relocations for the debug_info and debug_line sections.
1699       DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1700       RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1701       if (!Map) {
1702         // Find debug_info and debug_types relocs by section rather than name
1703         // as there are multiple, comdat grouped, of these sections.
1704         if (RelSecName == "debug_info")
1705           Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1706                      .Relocs;
1707         else if (RelSecName == "debug_info.dwo")
1708           Map = &static_cast<DWARFSectionMap &>(
1709                      InfoDWOSections[*RelocatedSection])
1710                      .Relocs;
1711         else if (RelSecName == "debug_types")
1712           Map =
1713               &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1714                    .Relocs;
1715         else if (RelSecName == "debug_types.dwo")
1716           Map = &static_cast<DWARFSectionMap &>(
1717                      TypesDWOSections[*RelocatedSection])
1718                      .Relocs;
1719         else
1720           continue;
1721       }
1722 
1723       if (Section.relocation_begin() == Section.relocation_end())
1724         continue;
1725 
1726       // Symbol to [address, section index] cache mapping.
1727       std::map<SymbolRef, SymInfo> AddrCache;
1728       bool (*Supports)(uint64_t);
1729       RelocationResolver Resolver;
1730       std::tie(Supports, Resolver) = getRelocationResolver(Obj);
1731       for (const RelocationRef &Reloc : Section.relocations()) {
1732         // FIXME: it's not clear how to correctly handle scattered
1733         // relocations.
1734         if (isRelocScattered(Obj, Reloc))
1735           continue;
1736 
1737         Expected<SymInfo> SymInfoOrErr =
1738             getSymbolInfo(Obj, Reloc, L, AddrCache);
1739         if (!SymInfoOrErr) {
1740           HandleError(SymInfoOrErr.takeError());
1741           continue;
1742         }
1743 
1744         // Check if Resolver can handle this relocation type early so as not to
1745         // handle invalid cases in DWARFDataExtractor.
1746         //
1747         // TODO Don't store Resolver in every RelocAddrEntry.
1748         if (Supports && Supports(Reloc.getType())) {
1749           auto I = Map->try_emplace(
1750               Reloc.getOffset(),
1751               RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
1752                              SymInfoOrErr->Address,
1753                              Optional<object::RelocationRef>(), 0, Resolver});
1754           // If we didn't successfully insert that's because we already had a
1755           // relocation for that offset. Store it as a second relocation in the
1756           // same RelocAddrEntry instead.
1757           if (!I.second) {
1758             RelocAddrEntry &entry = I.first->getSecond();
1759             if (entry.Reloc2) {
1760               HandleError(createError(
1761                   "At most two relocations per offset are supported"));
1762             }
1763             entry.Reloc2 = Reloc;
1764             entry.SymbolValue2 = SymInfoOrErr->Address;
1765           }
1766         } else {
1767           SmallString<32> Type;
1768           Reloc.getTypeName(Type);
1769           // FIXME: Support more relocations & change this to an error
1770           HandleWarning(
1771               createError("failed to compute relocation: " + Type + ", ",
1772                           errorCodeToError(object_error::parse_failed)));
1773         }
1774       }
1775     }
1776 
1777     for (SectionName &S : SectionNames)
1778       if (SectionAmountMap[S.Name] > 1)
1779         S.IsNameUnique = false;
1780   }
1781 
1782   Optional<RelocAddrEntry> find(const DWARFSection &S,
1783                                 uint64_t Pos) const override {
1784     auto &Sec = static_cast<const DWARFSectionMap &>(S);
1785     RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1786     if (AI == Sec.Relocs.end())
1787       return None;
1788     return AI->second;
1789   }
1790 
1791   const object::ObjectFile *getFile() const override { return Obj; }
1792 
1793   ArrayRef<SectionName> getSectionNames() const override {
1794     return SectionNames;
1795   }
1796 
1797   bool isLittleEndian() const override { return IsLittleEndian; }
1798   StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1799   const DWARFSection &getLineDWOSection() const override {
1800     return LineDWOSection;
1801   }
1802   const DWARFSection &getLocDWOSection() const override {
1803     return LocDWOSection;
1804   }
1805   StringRef getStrDWOSection() const override { return StrDWOSection; }
1806   const DWARFSection &getStrOffsetsDWOSection() const override {
1807     return StrOffsetsDWOSection;
1808   }
1809   const DWARFSection &getRangesDWOSection() const override {
1810     return RangesDWOSection;
1811   }
1812   const DWARFSection &getRnglistsDWOSection() const override {
1813     return RnglistsDWOSection;
1814   }
1815   const DWARFSection &getLoclistsDWOSection() const override {
1816     return LoclistsDWOSection;
1817   }
1818   const DWARFSection &getAddrSection() const override { return AddrSection; }
1819   StringRef getCUIndexSection() const override { return CUIndexSection; }
1820   StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1821   StringRef getTUIndexSection() const override { return TUIndexSection; }
1822 
1823   // DWARF v5
1824   const DWARFSection &getStrOffsetsSection() const override {
1825     return StrOffsetsSection;
1826   }
1827   StringRef getLineStrSection() const override { return LineStrSection; }
1828 
1829   // Sections for DWARF5 split dwarf proposal.
1830   void forEachInfoDWOSections(
1831       function_ref<void(const DWARFSection &)> F) const override {
1832     for (auto &P : InfoDWOSections)
1833       F(P.second);
1834   }
1835   void forEachTypesDWOSections(
1836       function_ref<void(const DWARFSection &)> F) const override {
1837     for (auto &P : TypesDWOSections)
1838       F(P.second);
1839   }
1840 
1841   StringRef getAbbrevSection() const override { return AbbrevSection; }
1842   const DWARFSection &getLocSection() const override { return LocSection; }
1843   const DWARFSection &getLoclistsSection() const override { return LoclistsSection; }
1844   StringRef getArangesSection() const override { return ArangesSection; }
1845   const DWARFSection &getFrameSection() const override {
1846     return FrameSection;
1847   }
1848   const DWARFSection &getEHFrameSection() const override {
1849     return EHFrameSection;
1850   }
1851   const DWARFSection &getLineSection() const override { return LineSection; }
1852   StringRef getStrSection() const override { return StrSection; }
1853   const DWARFSection &getRangesSection() const override { return RangesSection; }
1854   const DWARFSection &getRnglistsSection() const override {
1855     return RnglistsSection;
1856   }
1857   const DWARFSection &getMacroSection() const override { return MacroSection; }
1858   StringRef getMacinfoSection() const override { return MacinfoSection; }
1859   StringRef getMacinfoDWOSection() const override { return MacinfoDWOSection; }
1860   const DWARFSection &getPubnamesSection() const override { return PubnamesSection; }
1861   const DWARFSection &getPubtypesSection() const override { return PubtypesSection; }
1862   const DWARFSection &getGnuPubnamesSection() const override {
1863     return GnuPubnamesSection;
1864   }
1865   const DWARFSection &getGnuPubtypesSection() const override {
1866     return GnuPubtypesSection;
1867   }
1868   const DWARFSection &getAppleNamesSection() const override {
1869     return AppleNamesSection;
1870   }
1871   const DWARFSection &getAppleTypesSection() const override {
1872     return AppleTypesSection;
1873   }
1874   const DWARFSection &getAppleNamespacesSection() const override {
1875     return AppleNamespacesSection;
1876   }
1877   const DWARFSection &getAppleObjCSection() const override {
1878     return AppleObjCSection;
1879   }
1880   const DWARFSection &getNamesSection() const override {
1881     return NamesSection;
1882   }
1883 
1884   StringRef getFileName() const override { return FileName; }
1885   uint8_t getAddressSize() const override { return AddressSize; }
1886   void forEachInfoSections(
1887       function_ref<void(const DWARFSection &)> F) const override {
1888     for (auto &P : InfoSections)
1889       F(P.second);
1890   }
1891   void forEachTypesSections(
1892       function_ref<void(const DWARFSection &)> F) const override {
1893     for (auto &P : TypesSections)
1894       F(P.second);
1895   }
1896 };
1897 } // namespace
1898 
1899 std::unique_ptr<DWARFContext>
1900 DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1901                      std::string DWPName,
1902                      std::function<void(Error)> RecoverableErrorHandler,
1903                      std::function<void(Error)> WarningHandler) {
1904   auto DObj =
1905       std::make_unique<DWARFObjInMemory>(Obj, L, RecoverableErrorHandler, WarningHandler);
1906   return std::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName),
1907                                         RecoverableErrorHandler,
1908                                         WarningHandler);
1909 }
1910 
1911 std::unique_ptr<DWARFContext>
1912 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1913                      uint8_t AddrSize, bool isLittleEndian,
1914                      std::function<void(Error)> RecoverableErrorHandler,
1915                      std::function<void(Error)> WarningHandler) {
1916   auto DObj =
1917       std::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1918   return std::make_unique<DWARFContext>(
1919       std::move(DObj), "", RecoverableErrorHandler, WarningHandler);
1920 }
1921 
1922 Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1923   // Detect the architecture from the object file. We usually don't need OS
1924   // info to lookup a target and create register info.
1925   Triple TT;
1926   TT.setArch(Triple::ArchType(Obj.getArch()));
1927   TT.setVendor(Triple::UnknownVendor);
1928   TT.setOS(Triple::UnknownOS);
1929   std::string TargetLookupError;
1930   const Target *TheTarget =
1931       TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1932   if (!TargetLookupError.empty())
1933     return createStringError(errc::invalid_argument,
1934                              TargetLookupError.c_str());
1935   RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1936   return Error::success();
1937 }
1938 
1939 uint8_t DWARFContext::getCUAddrSize() {
1940   // In theory, different compile units may have different address byte
1941   // sizes, but for simplicity we just use the address byte size of the
1942   // first compile unit. In practice the address size field is repeated across
1943   // various DWARF headers (at least in version 5) to make it easier to dump
1944   // them independently, not to enable varying the address size.
1945   unit_iterator_range CUs = compile_units();
1946   return CUs.empty() ? 0 : (*CUs.begin())->getAddressByteSize();
1947 }
1948