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