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/SmallString.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
14 #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
15 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
16 #include "llvm/Object/MachO.h"
17 #include "llvm/Object/RelocVisitor.h"
18 #include "llvm/Support/Compression.h"
19 #include "llvm/Support/Dwarf.h"
20 #include "llvm/Support/ELF.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 using namespace llvm;
26 using namespace dwarf;
27 using namespace object;
28 
29 #define DEBUG_TYPE "dwarf"
30 
31 typedef DWARFDebugLine::LineTable DWARFLineTable;
32 typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
33 typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
34 
35 static void dumpPubSection(raw_ostream &OS, StringRef Name, StringRef Data,
36                            bool LittleEndian, bool GnuStyle) {
37   OS << "\n." << Name << " contents:\n";
38   DataExtractor pubNames(Data, LittleEndian, 0);
39   uint32_t offset = 0;
40   while (pubNames.isValidOffset(offset)) {
41     OS << "length = " << format("0x%08x", pubNames.getU32(&offset));
42     OS << " version = " << format("0x%04x", pubNames.getU16(&offset));
43     OS << " unit_offset = " << format("0x%08x", pubNames.getU32(&offset));
44     OS << " unit_size = " << format("0x%08x", pubNames.getU32(&offset)) << '\n';
45     if (GnuStyle)
46       OS << "Offset     Linkage  Kind     Name\n";
47     else
48       OS << "Offset     Name\n";
49 
50     while (offset < Data.size()) {
51       uint32_t dieRef = pubNames.getU32(&offset);
52       if (dieRef == 0)
53         break;
54       OS << format("0x%8.8x ", dieRef);
55       if (GnuStyle) {
56         PubIndexEntryDescriptor desc(pubNames.getU8(&offset));
57         OS << format("%-8s",
58                      dwarf::GDBIndexEntryLinkageString(desc.Linkage).data())
59            << ' '
60            << format("%-8s", dwarf::GDBIndexEntryKindString(desc.Kind).data())
61            << ' ';
62       }
63       OS << '\"' << pubNames.getCStr(&offset) << "\"\n";
64     }
65   }
66 }
67 
68 static void dumpAccelSection(raw_ostream &OS, StringRef Name,
69                              const DWARFSection& Section, StringRef StringSection,
70                              bool LittleEndian) {
71   DataExtractor AccelSection(Section.Data, LittleEndian, 0);
72   DataExtractor StrData(StringSection, LittleEndian, 0);
73   OS << "\n." << Name << " contents:\n";
74   DWARFAcceleratorTable Accel(AccelSection, StrData, Section.Relocs);
75   if (!Accel.extract())
76     return;
77   Accel.dump(OS);
78 }
79 
80 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType, bool DumpEH,
81                         bool SummarizeTypes) {
82   if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
83     OS << ".debug_abbrev contents:\n";
84     getDebugAbbrev()->dump(OS);
85   }
86 
87   if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
88     if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
89       OS << "\n.debug_abbrev.dwo contents:\n";
90       D->dump(OS);
91     }
92 
93   if (DumpType == DIDT_All || DumpType == DIDT_Info) {
94     OS << "\n.debug_info contents:\n";
95     for (const auto &CU : compile_units())
96       CU->dump(OS);
97   }
98 
99   if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
100       getNumDWOCompileUnits()) {
101     OS << "\n.debug_info.dwo contents:\n";
102     for (const auto &DWOCU : dwo_compile_units())
103       DWOCU->dump(OS);
104   }
105 
106   if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
107     OS << "\n.debug_types contents:\n";
108     for (const auto &TUS : type_unit_sections())
109       for (const auto &TU : TUS)
110         TU->dump(OS, SummarizeTypes);
111   }
112 
113   if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
114       getNumDWOTypeUnits()) {
115     OS << "\n.debug_types.dwo contents:\n";
116     for (const auto &DWOTUS : dwo_type_unit_sections())
117       for (const auto &DWOTU : DWOTUS)
118         DWOTU->dump(OS, SummarizeTypes);
119   }
120 
121   if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
122     OS << "\n.debug_loc contents:\n";
123     getDebugLoc()->dump(OS);
124   }
125 
126   if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
127     OS << "\n.debug_loc.dwo contents:\n";
128     getDebugLocDWO()->dump(OS);
129   }
130 
131   if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
132     OS << "\n.debug_frame contents:\n";
133     getDebugFrame()->dump(OS);
134     if (DumpEH) {
135       OS << "\n.eh_frame contents:\n";
136       getEHFrame()->dump(OS);
137     }
138   }
139 
140   if (DumpType == DIDT_All || DumpType == DIDT_Macro) {
141     OS << "\n.debug_macinfo contents:\n";
142     getDebugMacro()->dump(OS);
143   }
144 
145   uint32_t offset = 0;
146   if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
147     OS << "\n.debug_aranges contents:\n";
148     DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
149     DWARFDebugArangeSet set;
150     while (set.extract(arangesData, &offset))
151       set.dump(OS);
152   }
153 
154   uint8_t savedAddressByteSize = 0;
155   if (DumpType == DIDT_All || DumpType == DIDT_Line) {
156     OS << "\n.debug_line contents:\n";
157     for (const auto &CU : compile_units()) {
158       savedAddressByteSize = CU->getAddressByteSize();
159       const auto *CUDIE = CU->getUnitDIE();
160       if (CUDIE == nullptr)
161         continue;
162       unsigned stmtOffset = CUDIE->getAttributeValueAsSectionOffset(
163           CU.get(), DW_AT_stmt_list, -1U);
164       if (stmtOffset != -1U) {
165         DataExtractor lineData(getLineSection().Data, isLittleEndian(),
166                                savedAddressByteSize);
167         DWARFDebugLine::LineTable LineTable;
168         LineTable.parse(lineData, &getLineSection().Relocs, &stmtOffset);
169         LineTable.dump(OS);
170       }
171     }
172   }
173 
174   if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
175     OS << "\n.debug_cu_index contents:\n";
176     getCUIndex().dump(OS);
177   }
178 
179   if (DumpType == DIDT_All || DumpType == DIDT_TUIndex) {
180     OS << "\n.debug_tu_index contents:\n";
181     getTUIndex().dump(OS);
182   }
183 
184   if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
185     OS << "\n.debug_line.dwo contents:\n";
186     unsigned stmtOffset = 0;
187     DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
188                            savedAddressByteSize);
189     DWARFDebugLine::LineTable LineTable;
190     while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
191       LineTable.dump(OS);
192       LineTable.clear();
193     }
194   }
195 
196   if (DumpType == DIDT_All || DumpType == DIDT_Str) {
197     OS << "\n.debug_str contents:\n";
198     DataExtractor strData(getStringSection(), isLittleEndian(), 0);
199     offset = 0;
200     uint32_t strOffset = 0;
201     while (const char *s = strData.getCStr(&offset)) {
202       OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
203       strOffset = offset;
204     }
205   }
206 
207   if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
208       !getStringDWOSection().empty()) {
209     OS << "\n.debug_str.dwo contents:\n";
210     DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
211     offset = 0;
212     uint32_t strDWOOffset = 0;
213     while (const char *s = strDWOData.getCStr(&offset)) {
214       OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
215       strDWOOffset = offset;
216     }
217   }
218 
219   if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
220     OS << "\n.debug_ranges contents:\n";
221     // In fact, different compile units may have different address byte
222     // sizes, but for simplicity we just use the address byte size of the last
223     // compile unit (there is no easy and fast way to associate address range
224     // list and the compile unit it describes).
225     DataExtractor rangesData(getRangeSection(), isLittleEndian(),
226                              savedAddressByteSize);
227     offset = 0;
228     DWARFDebugRangeList rangeList;
229     while (rangeList.extract(rangesData, &offset))
230       rangeList.dump(OS);
231   }
232 
233   if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
234     dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
235                    isLittleEndian(), false);
236 
237   if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
238     dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
239                    isLittleEndian(), false);
240 
241   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
242     dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
243                    isLittleEndian(), true /* GnuStyle */);
244 
245   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
246     dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
247                    isLittleEndian(), true /* GnuStyle */);
248 
249   if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
250       !getStringOffsetDWOSection().empty()) {
251     OS << "\n.debug_str_offsets.dwo contents:\n";
252     DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
253                                0);
254     offset = 0;
255     uint64_t size = getStringOffsetDWOSection().size();
256     while (offset < size) {
257       OS << format("0x%8.8x: ", offset);
258       OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
259     }
260   }
261 
262   if ((DumpType == DIDT_All || DumpType == DIDT_GdbIndex) &&
263       !getGdbIndexSection().empty()) {
264     OS << "\n.gnu_index contents:\n";
265     getGdbIndex().dump(OS);
266   }
267 
268   if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
269     dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
270                      getStringSection(), isLittleEndian());
271 
272   if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
273     dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
274                      getStringSection(), isLittleEndian());
275 
276   if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
277     dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
278                      getStringSection(), isLittleEndian());
279 
280   if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
281     dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
282                      getStringSection(), isLittleEndian());
283 }
284 
285 const DWARFUnitIndex &DWARFContext::getCUIndex() {
286   if (CUIndex)
287     return *CUIndex;
288 
289   DataExtractor CUIndexData(getCUIndexSection(), isLittleEndian(), 0);
290 
291   CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
292   CUIndex->parse(CUIndexData);
293   return *CUIndex;
294 }
295 
296 const DWARFUnitIndex &DWARFContext::getTUIndex() {
297   if (TUIndex)
298     return *TUIndex;
299 
300   DataExtractor TUIndexData(getTUIndexSection(), isLittleEndian(), 0);
301 
302   TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
303   TUIndex->parse(TUIndexData);
304   return *TUIndex;
305 }
306 
307 DWARFGdbIndex &DWARFContext::getGdbIndex() {
308   if (GdbIndex)
309     return *GdbIndex;
310 
311   DataExtractor GdbIndexData(getGdbIndexSection(), true /*LE*/, 0);
312   GdbIndex = llvm::make_unique<DWARFGdbIndex>();
313   GdbIndex->parse(GdbIndexData);
314   return *GdbIndex;
315 }
316 
317 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
318   if (Abbrev)
319     return Abbrev.get();
320 
321   DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
322 
323   Abbrev.reset(new DWARFDebugAbbrev());
324   Abbrev->extract(abbrData);
325   return Abbrev.get();
326 }
327 
328 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
329   if (AbbrevDWO)
330     return AbbrevDWO.get();
331 
332   DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
333   AbbrevDWO.reset(new DWARFDebugAbbrev());
334   AbbrevDWO->extract(abbrData);
335   return AbbrevDWO.get();
336 }
337 
338 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
339   if (Loc)
340     return Loc.get();
341 
342   DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
343   Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
344   // assume all compile units have the same address byte size
345   if (getNumCompileUnits())
346     Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
347   return Loc.get();
348 }
349 
350 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
351   if (LocDWO)
352     return LocDWO.get();
353 
354   DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
355   LocDWO.reset(new DWARFDebugLocDWO());
356   LocDWO->parse(LocData);
357   return LocDWO.get();
358 }
359 
360 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
361   if (Aranges)
362     return Aranges.get();
363 
364   Aranges.reset(new DWARFDebugAranges());
365   Aranges->generate(this);
366   return Aranges.get();
367 }
368 
369 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
370   if (DebugFrame)
371     return DebugFrame.get();
372 
373   // There's a "bug" in the DWARFv3 standard with respect to the target address
374   // size within debug frame sections. While DWARF is supposed to be independent
375   // of its container, FDEs have fields with size being "target address size",
376   // which isn't specified in DWARF in general. It's only specified for CUs, but
377   // .eh_frame can appear without a .debug_info section. Follow the example of
378   // other tools (libdwarf) and extract this from the container (ObjectFile
379   // provides this information). This problem is fixed in DWARFv4
380   // See this dwarf-discuss discussion for more details:
381   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
382   DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
383                                getAddressSize());
384   DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
385   DebugFrame->parse(debugFrameData);
386   return DebugFrame.get();
387 }
388 
389 const DWARFDebugFrame *DWARFContext::getEHFrame() {
390   if (EHFrame)
391     return EHFrame.get();
392 
393   DataExtractor debugFrameData(getEHFrameSection(), isLittleEndian(),
394                                getAddressSize());
395   DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
396   DebugFrame->parse(debugFrameData);
397   return DebugFrame.get();
398 }
399 
400 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
401   if (Macro)
402     return Macro.get();
403 
404   DataExtractor MacinfoData(getMacinfoSection(), isLittleEndian(), 0);
405   Macro.reset(new DWARFDebugMacro());
406   Macro->parse(MacinfoData);
407   return Macro.get();
408 }
409 
410 const DWARFLineTable *
411 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
412   if (!Line)
413     Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
414 
415   const auto *UnitDIE = U->getUnitDIE();
416   if (UnitDIE == nullptr)
417     return nullptr;
418 
419   unsigned stmtOffset =
420       UnitDIE->getAttributeValueAsSectionOffset(U, DW_AT_stmt_list, -1U);
421   if (stmtOffset == -1U)
422     return nullptr; // No line table for this compile unit.
423 
424   stmtOffset += U->getLineTableOffset();
425   // See if the line table is cached.
426   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
427     return lt;
428 
429   // We have to parse it first.
430   DataExtractor lineData(U->getLineSection(), isLittleEndian(),
431                          U->getAddressByteSize());
432   return Line->getOrParseLineTable(lineData, stmtOffset);
433 }
434 
435 void DWARFContext::parseCompileUnits() {
436   CUs.parse(*this, getInfoSection());
437 }
438 
439 void DWARFContext::parseTypeUnits() {
440   if (!TUs.empty())
441     return;
442   for (const auto &I : getTypesSections()) {
443     TUs.emplace_back();
444     TUs.back().parse(*this, I.second);
445   }
446 }
447 
448 void DWARFContext::parseDWOCompileUnits() {
449   DWOCUs.parseDWO(*this, getInfoDWOSection());
450 }
451 
452 void DWARFContext::parseDWOTypeUnits() {
453   if (!DWOTUs.empty())
454     return;
455   for (const auto &I : getTypesDWOSections()) {
456     DWOTUs.emplace_back();
457     DWOTUs.back().parseDWO(*this, I.second);
458   }
459 }
460 
461 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
462   parseCompileUnits();
463   return CUs.getUnitForOffset(Offset);
464 }
465 
466 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
467   // First, get the offset of the compile unit.
468   uint32_t CUOffset = getDebugAranges()->findAddress(Address);
469   // Retrieve the compile unit.
470   return getCompileUnitForOffset(CUOffset);
471 }
472 
473 static bool getFunctionNameForAddress(DWARFCompileUnit *CU, uint64_t Address,
474                                       FunctionNameKind Kind,
475                                       std::string &FunctionName) {
476   if (Kind == FunctionNameKind::None)
477     return false;
478   // The address may correspond to instruction in some inlined function,
479   // so we have to build the chain of inlined functions and take the
480   // name of the topmost function in it.
481   const DWARFDebugInfoEntryInlinedChain &InlinedChain =
482       CU->getInlinedChainForAddress(Address);
483   if (InlinedChain.DIEs.size() == 0)
484     return false;
485   const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
486   if (const char *Name =
487           TopFunctionDIE.getSubroutineName(InlinedChain.U, Kind)) {
488     FunctionName = Name;
489     return true;
490   }
491   return false;
492 }
493 
494 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
495                                                DILineInfoSpecifier Spec) {
496   DILineInfo Result;
497 
498   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
499   if (!CU)
500     return Result;
501   getFunctionNameForAddress(CU, Address, Spec.FNKind, Result.FunctionName);
502   if (Spec.FLIKind != FileLineInfoKind::None) {
503     if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
504       LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
505                                            Spec.FLIKind, Result);
506   }
507   return Result;
508 }
509 
510 DILineInfoTable
511 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
512                                          DILineInfoSpecifier Spec) {
513   DILineInfoTable  Lines;
514   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
515   if (!CU)
516     return Lines;
517 
518   std::string FunctionName = "<invalid>";
519   getFunctionNameForAddress(CU, Address, Spec.FNKind, FunctionName);
520 
521   // If the Specifier says we don't need FileLineInfo, just
522   // return the top-most function at the starting address.
523   if (Spec.FLIKind == FileLineInfoKind::None) {
524     DILineInfo Result;
525     Result.FunctionName = FunctionName;
526     Lines.push_back(std::make_pair(Address, Result));
527     return Lines;
528   }
529 
530   const DWARFLineTable *LineTable = getLineTableForUnit(CU);
531 
532   // Get the index of row we're looking for in the line table.
533   std::vector<uint32_t> RowVector;
534   if (!LineTable->lookupAddressRange(Address, Size, RowVector))
535     return Lines;
536 
537   for (uint32_t RowIndex : RowVector) {
538     // Take file number and line/column from the row.
539     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
540     DILineInfo Result;
541     LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
542                                   Spec.FLIKind, Result.FileName);
543     Result.FunctionName = FunctionName;
544     Result.Line = Row.Line;
545     Result.Column = Row.Column;
546     Lines.push_back(std::make_pair(Row.Address, Result));
547   }
548 
549   return Lines;
550 }
551 
552 DIInliningInfo
553 DWARFContext::getInliningInfoForAddress(uint64_t Address,
554                                         DILineInfoSpecifier Spec) {
555   DIInliningInfo InliningInfo;
556 
557   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
558   if (!CU)
559     return InliningInfo;
560 
561   const DWARFLineTable *LineTable = nullptr;
562   const DWARFDebugInfoEntryInlinedChain &InlinedChain =
563       CU->getInlinedChainForAddress(Address);
564   if (InlinedChain.DIEs.size() == 0) {
565     // If there is no DIE for address (e.g. it is in unavailable .dwo file),
566     // try to at least get file/line info from symbol table.
567     if (Spec.FLIKind != FileLineInfoKind::None) {
568       DILineInfo Frame;
569       LineTable = getLineTableForUnit(CU);
570       if (LineTable &&
571           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
572                                                Spec.FLIKind, Frame))
573         InliningInfo.addFrame(Frame);
574     }
575     return InliningInfo;
576   }
577 
578   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
579   for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
580     const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
581     DILineInfo Frame;
582     // Get function name if necessary.
583     if (const char *Name =
584             FunctionDIE.getSubroutineName(InlinedChain.U, Spec.FNKind))
585       Frame.FunctionName = Name;
586     if (Spec.FLIKind != FileLineInfoKind::None) {
587       if (i == 0) {
588         // For the topmost frame, initialize the line table of this
589         // compile unit and fetch file/line info from it.
590         LineTable = getLineTableForUnit(CU);
591         // For the topmost routine, get file/line info from line table.
592         if (LineTable)
593           LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
594                                                Spec.FLIKind, Frame);
595       } else {
596         // Otherwise, use call file, call line and call column from
597         // previous DIE in inlined chain.
598         if (LineTable)
599           LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
600                                         Spec.FLIKind, Frame.FileName);
601         Frame.Line = CallLine;
602         Frame.Column = CallColumn;
603       }
604       // Get call file/line/column of a current DIE.
605       if (i + 1 < n) {
606         FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
607                                    CallColumn);
608       }
609     }
610     InliningInfo.addFrame(Frame);
611   }
612   return InliningInfo;
613 }
614 
615 static bool consumeCompressedGnuHeader(StringRef &data,
616                                        uint64_t &OriginalSize) {
617   // Consume "ZLIB" prefix.
618   if (!data.startswith("ZLIB"))
619     return false;
620   data = data.substr(4);
621   // Consume uncompressed section size (big-endian 8 bytes).
622   DataExtractor extractor(data, false, 8);
623   uint32_t Offset = 0;
624   OriginalSize = extractor.getU64(&Offset);
625   if (Offset == 0)
626     return false;
627   data = data.substr(Offset);
628   return true;
629 }
630 
631 static bool consumeCompressedZLibHeader(StringRef &Data, uint64_t &OriginalSize,
632                                         bool IsLE, bool Is64Bit) {
633   using namespace ELF;
634   uint64_t HdrSize = Is64Bit ? sizeof(Elf64_Chdr) : sizeof(Elf32_Chdr);
635   if (Data.size() < HdrSize)
636     return false;
637 
638   DataExtractor Extractor(Data, IsLE, 0);
639   uint32_t Offset = 0;
640   if (Extractor.getUnsigned(&Offset, Is64Bit ? sizeof(Elf64_Word)
641                                              : sizeof(Elf32_Word)) !=
642       ELFCOMPRESS_ZLIB)
643     return false;
644 
645   // Skip Elf64_Chdr::ch_reserved field.
646   if (Is64Bit)
647     Offset += sizeof(Elf64_Word);
648 
649   OriginalSize = Extractor.getUnsigned(&Offset, Is64Bit ? sizeof(Elf64_Xword)
650                                                         : sizeof(Elf32_Word));
651   Data = Data.substr(HdrSize);
652   return true;
653 }
654 
655 static bool tryDecompress(StringRef &Name, StringRef &Data,
656                           SmallString<32> &Out, bool ZLibStyle, bool IsLE,
657                           bool Is64Bit) {
658   if (!zlib::isAvailable())
659     return false;
660 
661   uint64_t OriginalSize;
662   bool Result =
663       ZLibStyle ? consumeCompressedZLibHeader(Data, OriginalSize, IsLE, Is64Bit)
664                 : consumeCompressedGnuHeader(Data, OriginalSize);
665 
666   if (!Result || zlib::uncompress(Data, Out, OriginalSize) != zlib::StatusOK)
667     return false;
668 
669   // gnu-style names are started from "z", consume that.
670   if (!ZLibStyle)
671     Name = Name.substr(1);
672   return true;
673 }
674 
675 DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
676     const LoadedObjectInfo *L)
677     : IsLittleEndian(Obj.isLittleEndian()),
678       AddressSize(Obj.getBytesInAddress()) {
679   for (const SectionRef &Section : Obj.sections()) {
680     StringRef name;
681     Section.getName(name);
682     // Skip BSS and Virtual sections, they aren't interesting.
683     bool IsBSS = Section.isBSS();
684     if (IsBSS)
685       continue;
686     bool IsVirtual = Section.isVirtual();
687     if (IsVirtual)
688       continue;
689     StringRef data;
690 
691     section_iterator RelocatedSection = Section.getRelocatedSection();
692     // Try to obtain an already relocated version of this section.
693     // Else use the unrelocated section from the object file. We'll have to
694     // apply relocations ourselves later.
695     if (!L || !L->getLoadedSectionContents(*RelocatedSection,data))
696       Section.getContents(data);
697 
698     name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
699 
700     bool ZLibStyleCompressed = Section.isCompressed();
701     if (ZLibStyleCompressed || name.startswith("zdebug_")) {
702       SmallString<32> Out;
703       if (!tryDecompress(name, data, Out, ZLibStyleCompressed, IsLittleEndian,
704                          AddressSize == 8))
705         continue;
706       UncompressedSections.emplace_back(std::move(Out));
707       data = UncompressedSections.back();
708     }
709 
710     StringRef *SectionData =
711         StringSwitch<StringRef *>(name)
712             .Case("debug_info", &InfoSection.Data)
713             .Case("debug_abbrev", &AbbrevSection)
714             .Case("debug_loc", &LocSection.Data)
715             .Case("debug_line", &LineSection.Data)
716             .Case("debug_aranges", &ARangeSection)
717             .Case("debug_frame", &DebugFrameSection)
718             .Case("eh_frame", &EHFrameSection)
719             .Case("debug_str", &StringSection)
720             .Case("debug_ranges", &RangeSection)
721             .Case("debug_macinfo", &MacinfoSection)
722             .Case("debug_pubnames", &PubNamesSection)
723             .Case("debug_pubtypes", &PubTypesSection)
724             .Case("debug_gnu_pubnames", &GnuPubNamesSection)
725             .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
726             .Case("debug_info.dwo", &InfoDWOSection.Data)
727             .Case("debug_abbrev.dwo", &AbbrevDWOSection)
728             .Case("debug_loc.dwo", &LocDWOSection.Data)
729             .Case("debug_line.dwo", &LineDWOSection.Data)
730             .Case("debug_str.dwo", &StringDWOSection)
731             .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
732             .Case("debug_addr", &AddrSection)
733             .Case("apple_names", &AppleNamesSection.Data)
734             .Case("apple_types", &AppleTypesSection.Data)
735             .Case("apple_namespaces", &AppleNamespacesSection.Data)
736             .Case("apple_namespac", &AppleNamespacesSection.Data)
737             .Case("apple_objc", &AppleObjCSection.Data)
738             .Case("debug_cu_index", &CUIndexSection)
739             .Case("debug_tu_index", &TUIndexSection)
740             .Case("gdb_index", &GdbIndexSection)
741             // Any more debug info sections go here.
742             .Default(nullptr);
743     if (SectionData) {
744       *SectionData = data;
745       if (name == "debug_ranges") {
746         // FIXME: Use the other dwo range section when we emit it.
747         RangeDWOSection = data;
748       }
749     } else if (name == "debug_types") {
750       // Find debug_types data by section rather than name as there are
751       // multiple, comdat grouped, debug_types sections.
752       TypesSections[Section].Data = data;
753     } else if (name == "debug_types.dwo") {
754       TypesDWOSections[Section].Data = data;
755     }
756 
757     if (RelocatedSection == Obj.section_end())
758       continue;
759 
760     StringRef RelSecName;
761     StringRef RelSecData;
762     RelocatedSection->getName(RelSecName);
763 
764     // If the section we're relocating was relocated already by the JIT,
765     // then we used the relocated version above, so we do not need to process
766     // relocations for it now.
767     if (L && L->getLoadedSectionContents(*RelocatedSection,RelSecData))
768       continue;
769 
770     // In Mach-o files, the relocations do not need to be applied if
771     // there is no load offset to apply. The value read at the
772     // relocation point already factors in the section address
773     // (actually applying the relocations will produce wrong results
774     // as the section address will be added twice).
775     if (!L && isa<MachOObjectFile>(&Obj))
776       continue;
777 
778     RelSecName = RelSecName.substr(
779         RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
780 
781     // TODO: Add support for relocations in other sections as needed.
782     // Record relocations for the debug_info and debug_line sections.
783     RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
784         .Case("debug_info", &InfoSection.Relocs)
785         .Case("debug_loc", &LocSection.Relocs)
786         .Case("debug_info.dwo", &InfoDWOSection.Relocs)
787         .Case("debug_line", &LineSection.Relocs)
788         .Case("apple_names", &AppleNamesSection.Relocs)
789         .Case("apple_types", &AppleTypesSection.Relocs)
790         .Case("apple_namespaces", &AppleNamespacesSection.Relocs)
791         .Case("apple_namespac", &AppleNamespacesSection.Relocs)
792         .Case("apple_objc", &AppleObjCSection.Relocs)
793         .Default(nullptr);
794     if (!Map) {
795       // Find debug_types relocs by section rather than name as there are
796       // multiple, comdat grouped, debug_types sections.
797       if (RelSecName == "debug_types")
798         Map = &TypesSections[*RelocatedSection].Relocs;
799       else if (RelSecName == "debug_types.dwo")
800         Map = &TypesDWOSections[*RelocatedSection].Relocs;
801       else
802         continue;
803     }
804 
805     if (Section.relocation_begin() != Section.relocation_end()) {
806       uint64_t SectionSize = RelocatedSection->getSize();
807       for (const RelocationRef &Reloc : Section.relocations()) {
808         uint64_t Address = Reloc.getOffset();
809         uint64_t Type = Reloc.getType();
810         uint64_t SymAddr = 0;
811         uint64_t SectionLoadAddress = 0;
812         object::symbol_iterator Sym = Reloc.getSymbol();
813         object::section_iterator RSec = Obj.section_end();
814 
815         // First calculate the address of the symbol or section as it appears
816         // in the objct file
817         if (Sym != Obj.symbol_end()) {
818           Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
819           if (!SymAddrOrErr) {
820             std::string Buf;
821             raw_string_ostream OS(Buf);
822             logAllUnhandledErrors(SymAddrOrErr.takeError(), OS, "");
823             OS.flush();
824             errs() << "error: failed to compute symbol address: "
825                    << Buf << '\n';
826             continue;
827           }
828           SymAddr = *SymAddrOrErr;
829           // Also remember what section this symbol is in for later
830           auto SectOrErr = Sym->getSection();
831           if (!SectOrErr) {
832             std::string Buf;
833             raw_string_ostream OS(Buf);
834             logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
835             OS.flush();
836             errs() << "error: failed to get symbol section: "
837                    << Buf << '\n';
838             continue;
839           }
840           RSec = *SectOrErr;
841         } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
842           // MachO also has relocations that point to sections and
843           // scattered relocations.
844           auto RelocInfo = MObj->getRelocation(Reloc.getRawDataRefImpl());
845           if (MObj->isRelocationScattered(RelocInfo)) {
846             // FIXME: it's not clear how to correctly handle scattered
847             // relocations.
848             continue;
849           } else {
850             RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
851             SymAddr = RSec->getAddress();
852           }
853         }
854 
855         // If we are given load addresses for the sections, we need to adjust:
856         // SymAddr = (Address of Symbol Or Section in File) -
857         //           (Address of Section in File) +
858         //           (Load Address of Section)
859         if (L != nullptr && RSec != Obj.section_end()) {
860           // RSec is now either the section being targeted or the section
861           // containing the symbol being targeted. In either case,
862           // we need to perform the same computation.
863           StringRef SecName;
864           RSec->getName(SecName);
865 //           llvm::dbgs() << "Name: '" << SecName
866 //                        << "', RSec: " << RSec->getRawDataRefImpl()
867 //                        << ", Section: " << Section.getRawDataRefImpl() << "\n";
868           SectionLoadAddress = L->getSectionLoadAddress(*RSec);
869           if (SectionLoadAddress != 0)
870             SymAddr += SectionLoadAddress - RSec->getAddress();
871         }
872 
873         object::RelocVisitor V(Obj);
874         object::RelocToApply R(V.visit(Type, Reloc, SymAddr));
875         if (V.error()) {
876           SmallString<32> Name;
877           Reloc.getTypeName(Name);
878           errs() << "error: failed to compute relocation: "
879                  << Name << "\n";
880           continue;
881         }
882 
883         if (Address + R.Width > SectionSize) {
884           errs() << "error: " << R.Width << "-byte relocation starting "
885                  << Address << " bytes into section " << name << " which is "
886                  << SectionSize << " bytes long.\n";
887           continue;
888         }
889         if (R.Width > 8) {
890           errs() << "error: can't handle a relocation of more than 8 bytes at "
891                     "a time.\n";
892           continue;
893         }
894         DEBUG(dbgs() << "Writing " << format("%p", R.Value)
895                      << " at " << format("%p", Address)
896                      << " with width " << format("%d", R.Width)
897                      << "\n");
898         Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
899       }
900     }
901   }
902 }
903 
904 void DWARFContextInMemory::anchor() { }
905