1 //===- DWARFContext.cpp ---------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
17 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
22 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
23 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
24 #include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
25 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
26 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
27 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
28 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
29 #include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
30 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
31 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
32 #include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
33 #include "llvm/Object/Decompressor.h"
34 #include "llvm/Object/MachO.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Object/RelocVisitor.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/DataExtractor.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include <algorithm>
45 #include <cstdint>
46 #include <map>
47 #include <set>
48 #include <string>
49 #include <utility>
50 #include <vector>
51 
52 using namespace llvm;
53 using namespace dwarf;
54 using namespace object;
55 
56 #define DEBUG_TYPE "dwarf"
57 
58 typedef DWARFDebugLine::LineTable DWARFLineTable;
59 typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
60 typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
61 
62 uint64_t llvm::getRelocatedValue(const DataExtractor &Data, uint32_t Size,
63                                  uint32_t *Off, const RelocAddrMap *Relocs,
64                                  uint64_t *SectionIndex) {
65   if (!Relocs)
66     return Data.getUnsigned(Off, Size);
67   RelocAddrMap::const_iterator AI = Relocs->find(*Off);
68   if (AI == Relocs->end())
69     return Data.getUnsigned(Off, Size);
70   if (SectionIndex)
71     *SectionIndex = AI->second.SectionIndex;
72   return Data.getUnsigned(Off, Size) + AI->second.Value;
73 }
74 
75 static void dumpAccelSection(raw_ostream &OS, StringRef Name,
76                              const DWARFSection& Section, StringRef StringSection,
77                              bool LittleEndian) {
78   DataExtractor AccelSection(Section.Data, LittleEndian, 0);
79   DataExtractor StrData(StringSection, LittleEndian, 0);
80   OS << "\n." << Name << " contents:\n";
81   DWARFAcceleratorTable Accel(AccelSection, StrData, Section.Relocs);
82   if (!Accel.extract())
83     return;
84   Accel.dump(OS);
85 }
86 
87 static void
88 dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
89                                 const DWARFSection &StringOffsetsSection,
90                                 StringRef StringSection, bool LittleEndian) {
91   DataExtractor StrOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
92   uint32_t Offset = 0;
93   uint64_t SectionSize = StringOffsetsSection.Data.size();
94 
95   while (Offset < SectionSize) {
96     unsigned Version = 0;
97     DwarfFormat Format = DWARF32;
98     unsigned EntrySize = 4;
99     // Perform validation and extract the segment size from the header.
100     if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
101       OS << "error: invalid contribution to string offsets table in section ."
102          << SectionName << ".\n";
103       return;
104     }
105     uint32_t ContributionStart = Offset;
106     uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
107     // A contribution size of 0xffffffff indicates DWARF64, with the actual size
108     // in the following 8 bytes. Otherwise, the DWARF standard mandates that
109     // the contribution size must be at most 0xfffffff0.
110     if (ContributionSize == 0xffffffff) {
111       if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
112         OS << "error: invalid contribution to string offsets table in section ."
113            << SectionName << ".\n";
114         return;
115       }
116       Format = DWARF64;
117       EntrySize = 8;
118       ContributionSize = StrOffsetExt.getU64(&Offset);
119     } else if (ContributionSize > 0xfffffff0) {
120       OS << "error: invalid contribution to string offsets table in section ."
121          << SectionName << ".\n";
122       return;
123     }
124 
125     // We must ensure that we don't read a partial record at the end, so we
126     // validate for a multiple of EntrySize. Also, we're expecting a version
127     // number and padding, which adds an additional 4 bytes.
128     uint64_t ValidationSize =
129         4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
130     if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
131       OS << "error: contribution to string offsets table in section ."
132          << SectionName << " has invalid length.\n";
133       return;
134     }
135 
136     Version = StrOffsetExt.getU16(&Offset);
137     Offset += 2;
138     OS << format("0x%8.8x: ", ContributionStart);
139     OS << "Contribution size = " << ContributionSize
140        << ", Version = " << Version << "\n";
141 
142     uint32_t ContributionBase = Offset;
143     DataExtractor StrData(StringSection, LittleEndian, 0);
144     while (Offset - ContributionBase < ContributionSize) {
145       OS << format("0x%8.8x: ", Offset);
146       // FIXME: We can only extract strings in DWARF32 format at the moment.
147       uint64_t StringOffset = getRelocatedValue(
148           StrOffsetExt, EntrySize, &Offset, &StringOffsetsSection.Relocs);
149       if (Format == DWARF32) {
150         OS << format("%8.8x ", StringOffset);
151         uint32_t StringOffset32 = (uint32_t)StringOffset;
152         const char *S = StrData.getCStr(&StringOffset32);
153         if (S)
154           OS << format("\"%s\"", S);
155       } else
156         OS << format("%16.16x ", StringOffset);
157       OS << "\n";
158     }
159   }
160 }
161 
162 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted
163 // string offsets section, where each compile or type unit contributes a
164 // number of entries (string offsets), with each contribution preceded by
165 // a header containing size and version number. Alternatively, it may be a
166 // monolithic series of string offsets, as generated by the pre-DWARF v5
167 // implementation of split DWARF.
168 static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
169                                      const DWARFSection &StringOffsetsSection,
170                                      StringRef StringSection, bool LittleEndian,
171                                      unsigned MaxVersion) {
172   if (StringOffsetsSection.Data.empty())
173     return;
174   OS << "\n." << SectionName << " contents:\n";
175   // If we have at least one (compile or type) unit with DWARF v5 or greater,
176   // we assume that the section is formatted like a DWARF v5 string offsets
177   // section.
178   if (MaxVersion >= 5)
179     dumpDWARFv5StringOffsetsSection(OS, SectionName, StringOffsetsSection,
180                                     StringSection, LittleEndian);
181   else {
182     DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
183     uint32_t offset = 0;
184     uint64_t size = StringOffsetsSection.Data.size();
185     // Ensure that size is a multiple of the size of an entry.
186     if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
187       OS << "error: size of ." << SectionName << " is not a multiple of "
188          << sizeof(uint32_t) << ".\n";
189       size &= -(uint64_t)sizeof(uint32_t);
190     }
191     DataExtractor StrData(StringSection, LittleEndian, 0);
192     while (offset < size) {
193       OS << format("0x%8.8x: ", offset);
194       uint32_t StringOffset = strOffsetExt.getU32(&offset);
195       OS << format("%8.8x  ", StringOffset);
196       const char *S = StrData.getCStr(&StringOffset);
197       if (S)
198         OS << format("\"%s\"", S);
199       OS << "\n";
200     }
201   }
202 }
203 
204 void DWARFContext::dump(raw_ostream &OS, DIDumpOptions DumpOpts){
205 
206   DIDumpType DumpType = DumpOpts.DumpType;
207   bool DumpEH = DumpOpts.DumpEH;
208   bool SummarizeTypes = DumpOpts.SummarizeTypes;
209 
210   if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
211     OS << ".debug_abbrev contents:\n";
212     getDebugAbbrev()->dump(OS);
213   }
214 
215   if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
216     if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
217       OS << "\n.debug_abbrev.dwo contents:\n";
218       D->dump(OS);
219     }
220 
221   if (DumpType == DIDT_All || DumpType == DIDT_Info) {
222     OS << "\n.debug_info contents:\n";
223     for (const auto &CU : compile_units())
224       CU->dump(OS, DumpOpts);
225   }
226 
227   if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
228       getNumDWOCompileUnits()) {
229     OS << "\n.debug_info.dwo contents:\n";
230     for (const auto &DWOCU : dwo_compile_units())
231       DWOCU->dump(OS, DumpOpts);
232   }
233 
234   if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
235     OS << "\n.debug_types contents:\n";
236     for (const auto &TUS : type_unit_sections())
237       for (const auto &TU : TUS)
238         TU->dump(OS, SummarizeTypes);
239   }
240 
241   if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
242       getNumDWOTypeUnits()) {
243     OS << "\n.debug_types.dwo contents:\n";
244     for (const auto &DWOTUS : dwo_type_unit_sections())
245       for (const auto &DWOTU : DWOTUS)
246         DWOTU->dump(OS, SummarizeTypes);
247   }
248 
249   if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
250     OS << "\n.debug_loc contents:\n";
251     getDebugLoc()->dump(OS);
252   }
253 
254   if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
255     OS << "\n.debug_loc.dwo contents:\n";
256     getDebugLocDWO()->dump(OS);
257   }
258 
259   if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
260     OS << "\n.debug_frame contents:\n";
261     getDebugFrame()->dump(OS);
262     if (DumpEH) {
263       OS << "\n.eh_frame contents:\n";
264       getEHFrame()->dump(OS);
265     }
266   }
267 
268   if (DumpType == DIDT_All || DumpType == DIDT_Macro) {
269     OS << "\n.debug_macinfo contents:\n";
270     getDebugMacro()->dump(OS);
271   }
272 
273   uint32_t offset = 0;
274   if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
275     OS << "\n.debug_aranges contents:\n";
276     DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
277     DWARFDebugArangeSet set;
278     while (set.extract(arangesData, &offset))
279       set.dump(OS);
280   }
281 
282   uint8_t savedAddressByteSize = 0;
283   if (DumpType == DIDT_All || DumpType == DIDT_Line) {
284     OS << "\n.debug_line contents:\n";
285     for (const auto &CU : compile_units()) {
286       savedAddressByteSize = CU->getAddressByteSize();
287       auto CUDIE = CU->getUnitDIE();
288       if (!CUDIE)
289         continue;
290       if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
291         DataExtractor lineData(getLineSection().Data, isLittleEndian(),
292                                savedAddressByteSize);
293         DWARFDebugLine::LineTable LineTable;
294         uint32_t Offset = *StmtOffset;
295         LineTable.parse(lineData, &getLineSection().Relocs, &Offset);
296         LineTable.dump(OS);
297       }
298     }
299   }
300 
301   if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
302     OS << "\n.debug_cu_index contents:\n";
303     getCUIndex().dump(OS);
304   }
305 
306   if (DumpType == DIDT_All || DumpType == DIDT_TUIndex) {
307     OS << "\n.debug_tu_index contents:\n";
308     getTUIndex().dump(OS);
309   }
310 
311   if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
312     OS << "\n.debug_line.dwo contents:\n";
313     unsigned stmtOffset = 0;
314     DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
315                            savedAddressByteSize);
316     DWARFDebugLine::LineTable LineTable;
317     while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
318       LineTable.dump(OS);
319       LineTable.clear();
320     }
321   }
322 
323   if (DumpType == DIDT_All || DumpType == DIDT_Str) {
324     OS << "\n.debug_str contents:\n";
325     DataExtractor strData(getStringSection(), isLittleEndian(), 0);
326     offset = 0;
327     uint32_t strOffset = 0;
328     while (const char *s = strData.getCStr(&offset)) {
329       OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
330       strOffset = offset;
331     }
332   }
333 
334   if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
335       !getStringDWOSection().empty()) {
336     OS << "\n.debug_str.dwo contents:\n";
337     DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
338     offset = 0;
339     uint32_t strDWOOffset = 0;
340     while (const char *s = strDWOData.getCStr(&offset)) {
341       OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
342       strDWOOffset = offset;
343     }
344   }
345 
346   if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
347     OS << "\n.debug_ranges contents:\n";
348     // In fact, different compile units may have different address byte
349     // sizes, but for simplicity we just use the address byte size of the last
350     // compile unit (there is no easy and fast way to associate address range
351     // list and the compile unit it describes).
352     DataExtractor rangesData(getRangeSection().Data, isLittleEndian(),
353                              savedAddressByteSize);
354     offset = 0;
355     DWARFDebugRangeList rangeList;
356     while (rangeList.extract(rangesData, &offset, getRangeSection().Relocs))
357       rangeList.dump(OS);
358   }
359 
360   if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
361     DWARFDebugPubTable(getPubNamesSection(), isLittleEndian(), false)
362         .dump("debug_pubnames", OS);
363 
364   if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
365     DWARFDebugPubTable(getPubTypesSection(), isLittleEndian(), false)
366         .dump("debug_pubtypes", OS);
367 
368   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
369     DWARFDebugPubTable(getGnuPubNamesSection(), isLittleEndian(),
370                        true /* GnuStyle */)
371         .dump("debug_gnu_pubnames", OS);
372 
373   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
374     DWARFDebugPubTable(getGnuPubTypesSection(), isLittleEndian(),
375                        true /* GnuStyle */)
376         .dump("debug_gnu_pubtypes", OS);
377 
378   if (DumpType == DIDT_All || DumpType == DIDT_StrOffsets)
379     dumpStringOffsetsSection(OS, "debug_str_offsets", getStringOffsetSection(),
380                              getStringSection(), isLittleEndian(),
381                              getMaxVersion());
382 
383   if (DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) {
384     dumpStringOffsetsSection(OS, "debug_str_offsets.dwo",
385                              getStringOffsetDWOSection(), getStringDWOSection(),
386                              isLittleEndian(), getMaxVersion());
387   }
388 
389   if ((DumpType == DIDT_All || DumpType == DIDT_GdbIndex) &&
390       !getGdbIndexSection().empty()) {
391     OS << "\n.gnu_index contents:\n";
392     getGdbIndex().dump(OS);
393   }
394 
395   if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
396     dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
397                      getStringSection(), isLittleEndian());
398 
399   if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
400     dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
401                      getStringSection(), isLittleEndian());
402 
403   if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
404     dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
405                      getStringSection(), isLittleEndian());
406 
407   if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
408     dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
409                      getStringSection(), isLittleEndian());
410 }
411 
412 DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
413   // FIXME: Improve this for the case where this DWO file is really a DWP file
414   // with an index - use the index for lookup instead of a linear search.
415   for (const auto &DWOCU : dwo_compile_units())
416     if (DWOCU->getDWOId() == Hash)
417       return DWOCU.get();
418   return nullptr;
419 }
420 
421 DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
422   parseCompileUnits();
423   if (auto *CU = CUs.getUnitForOffset(Offset))
424     return CU->getDIEForOffset(Offset);
425   return DWARFDie();
426 }
427 
428 bool DWARFContext::verify(raw_ostream &OS, DIDumpType DumpType) {
429   bool Success = true;
430   DWARFVerifier verifier(OS, *this);
431   if (DumpType == DIDT_All || DumpType == DIDT_Info) {
432     if (!verifier.handleDebugInfo())
433       Success = false;
434   }
435   if (DumpType == DIDT_All || DumpType == DIDT_Line) {
436     if (!verifier.handleDebugLine())
437       Success = false;
438   }
439   if (DumpType == DIDT_All || DumpType == DIDT_AppleNames) {
440     if (!verifier.handleAppleNames())
441       Success = false;
442   }
443   return Success;
444 }
445 
446 const DWARFUnitIndex &DWARFContext::getCUIndex() {
447   if (CUIndex)
448     return *CUIndex;
449 
450   DataExtractor CUIndexData(getCUIndexSection(), isLittleEndian(), 0);
451 
452   CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
453   CUIndex->parse(CUIndexData);
454   return *CUIndex;
455 }
456 
457 const DWARFUnitIndex &DWARFContext::getTUIndex() {
458   if (TUIndex)
459     return *TUIndex;
460 
461   DataExtractor TUIndexData(getTUIndexSection(), isLittleEndian(), 0);
462 
463   TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
464   TUIndex->parse(TUIndexData);
465   return *TUIndex;
466 }
467 
468 DWARFGdbIndex &DWARFContext::getGdbIndex() {
469   if (GdbIndex)
470     return *GdbIndex;
471 
472   DataExtractor GdbIndexData(getGdbIndexSection(), true /*LE*/, 0);
473   GdbIndex = llvm::make_unique<DWARFGdbIndex>();
474   GdbIndex->parse(GdbIndexData);
475   return *GdbIndex;
476 }
477 
478 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
479   if (Abbrev)
480     return Abbrev.get();
481 
482   DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
483 
484   Abbrev.reset(new DWARFDebugAbbrev());
485   Abbrev->extract(abbrData);
486   return Abbrev.get();
487 }
488 
489 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
490   if (AbbrevDWO)
491     return AbbrevDWO.get();
492 
493   DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
494   AbbrevDWO.reset(new DWARFDebugAbbrev());
495   AbbrevDWO->extract(abbrData);
496   return AbbrevDWO.get();
497 }
498 
499 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
500   if (Loc)
501     return Loc.get();
502 
503   DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
504   Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
505   // assume all compile units have the same address byte size
506   if (getNumCompileUnits())
507     Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
508   return Loc.get();
509 }
510 
511 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
512   if (LocDWO)
513     return LocDWO.get();
514 
515   DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
516   LocDWO.reset(new DWARFDebugLocDWO());
517   LocDWO->parse(LocData);
518   return LocDWO.get();
519 }
520 
521 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
522   if (Aranges)
523     return Aranges.get();
524 
525   Aranges.reset(new DWARFDebugAranges());
526   Aranges->generate(this);
527   return Aranges.get();
528 }
529 
530 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
531   if (DebugFrame)
532     return DebugFrame.get();
533 
534   // There's a "bug" in the DWARFv3 standard with respect to the target address
535   // size within debug frame sections. While DWARF is supposed to be independent
536   // of its container, FDEs have fields with size being "target address size",
537   // which isn't specified in DWARF in general. It's only specified for CUs, but
538   // .eh_frame can appear without a .debug_info section. Follow the example of
539   // other tools (libdwarf) and extract this from the container (ObjectFile
540   // provides this information). This problem is fixed in DWARFv4
541   // See this dwarf-discuss discussion for more details:
542   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
543   DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
544                                getAddressSize());
545   DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
546   DebugFrame->parse(debugFrameData);
547   return DebugFrame.get();
548 }
549 
550 const DWARFDebugFrame *DWARFContext::getEHFrame() {
551   if (EHFrame)
552     return EHFrame.get();
553 
554   DataExtractor debugFrameData(getEHFrameSection(), isLittleEndian(),
555                                getAddressSize());
556   DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
557   DebugFrame->parse(debugFrameData);
558   return DebugFrame.get();
559 }
560 
561 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
562   if (Macro)
563     return Macro.get();
564 
565   DataExtractor MacinfoData(getMacinfoSection(), isLittleEndian(), 0);
566   Macro.reset(new DWARFDebugMacro());
567   Macro->parse(MacinfoData);
568   return Macro.get();
569 }
570 
571 const DWARFLineTable *
572 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
573   if (!Line)
574     Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
575 
576   auto UnitDIE = U->getUnitDIE();
577   if (!UnitDIE)
578     return nullptr;
579 
580   auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
581   if (!Offset)
582     return nullptr; // No line table for this compile unit.
583 
584   uint32_t stmtOffset = *Offset + U->getLineTableOffset();
585   // See if the line table is cached.
586   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
587     return lt;
588 
589   // Make sure the offset is good before we try to parse.
590   if (stmtOffset >= U->getLineSection().size())
591     return nullptr;
592 
593   // We have to parse it first.
594   DataExtractor lineData(U->getLineSection(), isLittleEndian(),
595                          U->getAddressByteSize());
596   return Line->getOrParseLineTable(lineData, stmtOffset);
597 }
598 
599 void DWARFContext::parseCompileUnits() {
600   CUs.parse(*this, getInfoSection());
601 }
602 
603 void DWARFContext::parseTypeUnits() {
604   if (!TUs.empty())
605     return;
606   for (const auto &I : getTypesSections()) {
607     TUs.emplace_back();
608     TUs.back().parse(*this, I.second);
609   }
610 }
611 
612 void DWARFContext::parseDWOCompileUnits() {
613   DWOCUs.parseDWO(*this, getInfoDWOSection());
614 }
615 
616 void DWARFContext::parseDWOTypeUnits() {
617   if (!DWOTUs.empty())
618     return;
619   for (const auto &I : getTypesDWOSections()) {
620     DWOTUs.emplace_back();
621     DWOTUs.back().parseDWO(*this, I.second);
622   }
623 }
624 
625 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
626   parseCompileUnits();
627   return CUs.getUnitForOffset(Offset);
628 }
629 
630 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
631   // First, get the offset of the compile unit.
632   uint32_t CUOffset = getDebugAranges()->findAddress(Address);
633   // Retrieve the compile unit.
634   return getCompileUnitForOffset(CUOffset);
635 }
636 
637 static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
638                                                   uint64_t Address,
639                                                   FunctionNameKind Kind,
640                                                   std::string &FunctionName,
641                                                   uint32_t &StartLine) {
642   // The address may correspond to instruction in some inlined function,
643   // so we have to build the chain of inlined functions and take the
644   // name of the topmost function in it.
645   SmallVector<DWARFDie, 4> InlinedChain;
646   CU->getInlinedChainForAddress(Address, InlinedChain);
647   if (InlinedChain.empty())
648     return false;
649 
650   const DWARFDie &DIE = InlinedChain[0];
651   bool FoundResult = false;
652   const char *Name = nullptr;
653   if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
654     FunctionName = Name;
655     FoundResult = true;
656   }
657   if (auto DeclLineResult = DIE.getDeclLine()) {
658     StartLine = DeclLineResult;
659     FoundResult = true;
660   }
661 
662   return FoundResult;
663 }
664 
665 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
666                                                DILineInfoSpecifier Spec) {
667   DILineInfo Result;
668 
669   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
670   if (!CU)
671     return Result;
672   getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
673                                         Result.FunctionName,
674                                         Result.StartLine);
675   if (Spec.FLIKind != FileLineInfoKind::None) {
676     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
677       LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
678                                            Spec.FLIKind, Result);
679   }
680   return Result;
681 }
682 
683 DILineInfoTable
684 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
685                                          DILineInfoSpecifier Spec) {
686   DILineInfoTable  Lines;
687   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
688   if (!CU)
689     return Lines;
690 
691   std::string FunctionName = "<invalid>";
692   uint32_t StartLine = 0;
693   getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
694                                         StartLine);
695 
696   // If the Specifier says we don't need FileLineInfo, just
697   // return the top-most function at the starting address.
698   if (Spec.FLIKind == FileLineInfoKind::None) {
699     DILineInfo Result;
700     Result.FunctionName = FunctionName;
701     Result.StartLine = StartLine;
702     Lines.push_back(std::make_pair(Address, Result));
703     return Lines;
704   }
705 
706   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
707 
708   // Get the index of row we're looking for in the line table.
709   std::vector<uint32_t> RowVector;
710   if (!LineTable->lookupAddressRange(Address, Size, RowVector))
711     return Lines;
712 
713   for (uint32_t RowIndex : RowVector) {
714     // Take file number and line/column from the row.
715     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
716     DILineInfo Result;
717     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
718                                   Spec.FLIKind, Result.FileName);
719     Result.FunctionName = FunctionName;
720     Result.Line = Row.Line;
721     Result.Column = Row.Column;
722     Result.StartLine = StartLine;
723     Lines.push_back(std::make_pair(Row.Address, Result));
724   }
725 
726   return Lines;
727 }
728 
729 DIInliningInfo
730 DWARFContext::getInliningInfoForAddress(uint64_t Address,
731                                         DILineInfoSpecifier Spec) {
732   DIInliningInfo InliningInfo;
733 
734   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
735   if (!CU)
736     return InliningInfo;
737 
738   const DWARFLineTable *LineTable = nullptr;
739   SmallVector<DWARFDie, 4> InlinedChain;
740   CU->getInlinedChainForAddress(Address, InlinedChain);
741   if (InlinedChain.size() == 0) {
742     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
743     // try to at least get file/line info from symbol table.
744     if (Spec.FLIKind != FileLineInfoKind::None) {
745       DILineInfo Frame;
746       LineTable = getLineTableForUnit(CU);
747       if (LineTable &&
748           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
749                                                Spec.FLIKind, Frame))
750         InliningInfo.addFrame(Frame);
751     }
752     return InliningInfo;
753   }
754 
755   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
756   for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
757     DWARFDie &FunctionDIE = InlinedChain[i];
758     DILineInfo Frame;
759     // Get function name if necessary.
760     if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
761       Frame.FunctionName = Name;
762     if (auto DeclLineResult = FunctionDIE.getDeclLine())
763       Frame.StartLine = DeclLineResult;
764     if (Spec.FLIKind != FileLineInfoKind::None) {
765       if (i == 0) {
766         // For the topmost frame, initialize the line table of this
767         // compile unit and fetch file/line info from it.
768         LineTable = getLineTableForUnit(CU);
769         // For the topmost routine, get file/line info from line table.
770         if (LineTable)
771           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
772                                                Spec.FLIKind, Frame);
773       } else {
774         // Otherwise, use call file, call line and call column from
775         // previous DIE in inlined chain.
776         if (LineTable)
777           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
778                                         Spec.FLIKind, Frame.FileName);
779         Frame.Line = CallLine;
780         Frame.Column = CallColumn;
781         Frame.Discriminator = CallDiscriminator;
782       }
783       // Get call file/line/column of a current DIE.
784       if (i + 1 < n) {
785         FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
786                                    CallDiscriminator);
787       }
788     }
789     InliningInfo.addFrame(Frame);
790   }
791   return InliningInfo;
792 }
793 
794 std::shared_ptr<DWARFContext>
795 DWARFContext::getDWOContext(StringRef AbsolutePath) {
796   if (auto S = DWP.lock()) {
797     DWARFContext *Ctxt = S->Context.get();
798     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
799   }
800 
801   std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
802 
803   if (auto S = Entry->lock()) {
804     DWARFContext *Ctxt = S->Context.get();
805     return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
806   }
807 
808   SmallString<128> DWPName;
809   Expected<OwningBinary<ObjectFile>> Obj = [&] {
810     if (!CheckedForDWP) {
811       (getFileName() + ".dwp").toVector(DWPName);
812       auto Obj = object::ObjectFile::createObjectFile(DWPName);
813       if (Obj) {
814         Entry = &DWP;
815         return Obj;
816       } else {
817         CheckedForDWP = true;
818         // TODO: Should this error be handled (maybe in a high verbosity mode)
819         // before falling back to .dwo files?
820         consumeError(Obj.takeError());
821       }
822     }
823 
824     return object::ObjectFile::createObjectFile(AbsolutePath);
825   }();
826 
827   if (!Obj) {
828     // TODO: Actually report errors helpfully.
829     consumeError(Obj.takeError());
830     return nullptr;
831   }
832 
833   auto S = std::make_shared<DWOFile>();
834   S->File = std::move(Obj.get());
835   S->Context = llvm::make_unique<DWARFContextInMemory>(*S->File.getBinary());
836   *Entry = S;
837   auto *Ctxt = S->Context.get();
838   return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
839 }
840 
841 static Error createError(const Twine &Reason, llvm::Error E) {
842   return make_error<StringError>(Reason + toString(std::move(E)),
843                                  inconvertibleErrorCode());
844 }
845 
846 /// SymInfo contains information about symbol: it's address
847 /// and section index which is -1LL for absolute symbols.
848 struct SymInfo {
849   uint64_t Address;
850   uint64_t SectionIndex;
851 };
852 
853 /// Returns the address of symbol relocation used against and a section index.
854 /// Used for futher relocations computation. Symbol's section load address is
855 static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
856                                        const RelocationRef &Reloc,
857                                        const LoadedObjectInfo *L,
858                                        std::map<SymbolRef, SymInfo> &Cache) {
859   SymInfo Ret = {0, (uint64_t)-1LL};
860   object::section_iterator RSec = Obj.section_end();
861   object::symbol_iterator Sym = Reloc.getSymbol();
862 
863   std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
864   // First calculate the address of the symbol or section as it appears
865   // in the object file
866   if (Sym != Obj.symbol_end()) {
867     bool New;
868     std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
869     if (!New)
870       return CacheIt->second;
871 
872     Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
873     if (!SymAddrOrErr)
874       return createError("error: failed to compute symbol address: ",
875                          SymAddrOrErr.takeError());
876 
877     // Also remember what section this symbol is in for later
878     auto SectOrErr = Sym->getSection();
879     if (!SectOrErr)
880       return createError("error: failed to get symbol section: ",
881                          SectOrErr.takeError());
882 
883     RSec = *SectOrErr;
884     Ret.Address = *SymAddrOrErr;
885   } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
886     RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
887     Ret.Address = RSec->getAddress();
888   }
889 
890   if (RSec != Obj.section_end())
891     Ret.SectionIndex = RSec->getIndex();
892 
893   // If we are given load addresses for the sections, we need to adjust:
894   // SymAddr = (Address of Symbol Or Section in File) -
895   //           (Address of Section in File) +
896   //           (Load Address of Section)
897   // RSec is now either the section being targeted or the section
898   // containing the symbol being targeted. In either case,
899   // we need to perform the same computation.
900   if (L && RSec != Obj.section_end())
901     if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
902       Ret.Address += SectionLoadAddress - RSec->getAddress();
903 
904   if (CacheIt != Cache.end())
905     CacheIt->second = Ret;
906 
907   return Ret;
908 }
909 
910 static bool isRelocScattered(const object::ObjectFile &Obj,
911                              const RelocationRef &Reloc) {
912   const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
913   if (!MachObj)
914     return false;
915   // MachO also has relocations that point to sections and
916   // scattered relocations.
917   auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
918   return MachObj->isRelocationScattered(RelocInfo);
919 }
920 
921 Error DWARFContextInMemory::maybeDecompress(const SectionRef &Sec,
922                                             StringRef Name, StringRef &Data) {
923   if (!Decompressor::isCompressed(Sec))
924     return Error::success();
925 
926   Expected<Decompressor> Decompressor =
927       Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
928   if (!Decompressor)
929     return Decompressor.takeError();
930 
931   SmallString<32> Out;
932   if (auto Err = Decompressor->resizeAndDecompress(Out))
933     return Err;
934 
935   UncompressedSections.emplace_back(std::move(Out));
936   Data = UncompressedSections.back();
937 
938   return Error::success();
939 }
940 
941 DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
942                                            const LoadedObjectInfo *L)
943     : FileName(Obj.getFileName()), IsLittleEndian(Obj.isLittleEndian()),
944       AddressSize(Obj.getBytesInAddress()) {
945   for (const SectionRef &Section : Obj.sections()) {
946     StringRef name;
947     Section.getName(name);
948     // Skip BSS and Virtual sections, they aren't interesting.
949     bool IsBSS = Section.isBSS();
950     if (IsBSS)
951       continue;
952     bool IsVirtual = Section.isVirtual();
953     if (IsVirtual)
954       continue;
955     StringRef data;
956 
957     section_iterator RelocatedSection = Section.getRelocatedSection();
958     // Try to obtain an already relocated version of this section.
959     // Else use the unrelocated section from the object file. We'll have to
960     // apply relocations ourselves later.
961     if (!L || !L->getLoadedSectionContents(*RelocatedSection, data))
962       Section.getContents(data);
963 
964     if (auto Err = maybeDecompress(Section, name, data)) {
965       errs() << "error: failed to decompress '" + name + "', " +
966                     toString(std::move(Err))
967              << '\n';
968       continue;
969     }
970 
971     // Compressed sections names in GNU style starts from ".z",
972     // at this point section is decompressed and we drop compression prefix.
973     name = name.substr(
974         name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
975 
976     if (StringRef *SectionData = MapSectionToMember(name)) {
977       *SectionData = data;
978       if (name == "debug_ranges") {
979         // FIXME: Use the other dwo range section when we emit it.
980         RangeDWOSection.Data = data;
981       }
982     } else if (name == "debug_types") {
983       // Find debug_types data by section rather than name as there are
984       // multiple, comdat grouped, debug_types sections.
985       TypesSections[Section].Data = data;
986     } else if (name == "debug_types.dwo") {
987       TypesDWOSections[Section].Data = data;
988     }
989 
990     // Map platform specific debug section names to DWARF standard section
991     // names.
992     name = Obj.mapDebugSectionName(name);
993 
994     if (RelocatedSection == Obj.section_end())
995       continue;
996 
997     StringRef RelSecName;
998     StringRef RelSecData;
999     RelocatedSection->getName(RelSecName);
1000 
1001     // If the section we're relocating was relocated already by the JIT,
1002     // then we used the relocated version above, so we do not need to process
1003     // relocations for it now.
1004     if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1005       continue;
1006 
1007     // In Mach-o files, the relocations do not need to be applied if
1008     // there is no load offset to apply. The value read at the
1009     // relocation point already factors in the section address
1010     // (actually applying the relocations will produce wrong results
1011     // as the section address will be added twice).
1012     if (!L && isa<MachOObjectFile>(&Obj))
1013       continue;
1014 
1015     RelSecName = RelSecName.substr(
1016         RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1017 
1018     // TODO: Add support for relocations in other sections as needed.
1019     // Record relocations for the debug_info and debug_line sections.
1020     RelocAddrMap *Map =
1021         StringSwitch<RelocAddrMap *>(RelSecName)
1022             .Case("debug_info", &InfoSection.Relocs)
1023             .Case("debug_loc", &LocSection.Relocs)
1024             .Case("debug_info.dwo", &InfoDWOSection.Relocs)
1025             .Case("debug_line", &LineSection.Relocs)
1026             .Case("debug_str_offsets", &StringOffsetSection.Relocs)
1027             .Case("debug_ranges", &RangeSection.Relocs)
1028             .Case("debug_addr", &AddrSection.Relocs)
1029             .Case("apple_names", &AppleNamesSection.Relocs)
1030             .Case("apple_types", &AppleTypesSection.Relocs)
1031             .Case("apple_namespaces", &AppleNamespacesSection.Relocs)
1032             .Case("apple_namespac", &AppleNamespacesSection.Relocs)
1033             .Case("apple_objc", &AppleObjCSection.Relocs)
1034             .Default(nullptr);
1035     if (!Map) {
1036       // Find debug_types relocs by section rather than name as there are
1037       // multiple, comdat grouped, debug_types sections.
1038       if (RelSecName == "debug_types")
1039         Map = &TypesSections[*RelocatedSection].Relocs;
1040       else if (RelSecName == "debug_types.dwo")
1041         Map = &TypesDWOSections[*RelocatedSection].Relocs;
1042       else
1043         continue;
1044     }
1045 
1046     if (Section.relocation_begin() == Section.relocation_end())
1047       continue;
1048 
1049     // Symbol to [address, section index] cache mapping.
1050     std::map<SymbolRef, SymInfo> AddrCache;
1051     for (const RelocationRef &Reloc : Section.relocations()) {
1052       // FIXME: it's not clear how to correctly handle scattered
1053       // relocations.
1054       if (isRelocScattered(Obj, Reloc))
1055         continue;
1056 
1057       Expected<SymInfo> SymInfoOrErr = getSymbolInfo(Obj, Reloc, L, AddrCache);
1058       if (!SymInfoOrErr) {
1059         errs() << toString(SymInfoOrErr.takeError()) << '\n';
1060         continue;
1061       }
1062 
1063       object::RelocVisitor V(Obj);
1064       uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1065       if (V.error()) {
1066         SmallString<32> Name;
1067         Reloc.getTypeName(Name);
1068         errs() << "error: failed to compute relocation: " << Name << "\n";
1069         continue;
1070       }
1071       llvm::RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1072       Map->insert({Reloc.getOffset(), Rel});
1073     }
1074   }
1075 }
1076 
1077 DWARFContextInMemory::DWARFContextInMemory(
1078     const StringMap<std::unique_ptr<MemoryBuffer>> &Sections, uint8_t AddrSize,
1079     bool isLittleEndian)
1080     : IsLittleEndian(isLittleEndian), AddressSize(AddrSize) {
1081   for (const auto &SecIt : Sections) {
1082     if (StringRef *SectionData = MapSectionToMember(SecIt.first()))
1083       *SectionData = SecIt.second->getBuffer();
1084   }
1085 }
1086 
1087 StringRef *DWARFContextInMemory::MapSectionToMember(StringRef Name) {
1088   return StringSwitch<StringRef *>(Name)
1089       .Case("debug_info", &InfoSection.Data)
1090       .Case("debug_abbrev", &AbbrevSection)
1091       .Case("debug_loc", &LocSection.Data)
1092       .Case("debug_line", &LineSection.Data)
1093       .Case("debug_aranges", &ARangeSection)
1094       .Case("debug_frame", &DebugFrameSection)
1095       .Case("eh_frame", &EHFrameSection)
1096       .Case("debug_str", &StringSection)
1097       .Case("debug_str_offsets", &StringOffsetSection.Data)
1098       .Case("debug_ranges", &RangeSection.Data)
1099       .Case("debug_macinfo", &MacinfoSection)
1100       .Case("debug_pubnames", &PubNamesSection)
1101       .Case("debug_pubtypes", &PubTypesSection)
1102       .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1103       .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1104       .Case("debug_info.dwo", &InfoDWOSection.Data)
1105       .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1106       .Case("debug_loc.dwo", &LocDWOSection.Data)
1107       .Case("debug_line.dwo", &LineDWOSection.Data)
1108       .Case("debug_str.dwo", &StringDWOSection)
1109       .Case("debug_str_offsets.dwo", &StringOffsetDWOSection.Data)
1110       .Case("debug_addr", &AddrSection.Data)
1111       .Case("apple_names", &AppleNamesSection.Data)
1112       .Case("apple_types", &AppleTypesSection.Data)
1113       .Case("apple_namespaces", &AppleNamespacesSection.Data)
1114       .Case("apple_namespac", &AppleNamespacesSection.Data)
1115       .Case("apple_objc", &AppleObjCSection.Data)
1116       .Case("debug_cu_index", &CUIndexSection)
1117       .Case("debug_tu_index", &TUIndexSection)
1118       .Case("gdb_index", &GdbIndexSection)
1119       // Any more debug info sections go here.
1120       .Default(nullptr);
1121 }
1122 
1123 void DWARFContextInMemory::anchor() {}
1124