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