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