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