[C++11] DWARF parser: use SmallVector<std::unique_ptr> for parsed units in DWARFConte...
[oota-llvm.git] / lib / DebugInfo / 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 "DWARFContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/Support/Compression.h"
14 #include "llvm/Support/Dwarf.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/Path.h"
17 #include "llvm/Support/raw_ostream.h"
18 #include <algorithm>
19 using namespace llvm;
20 using namespace dwarf;
21 using namespace object;
22
23 typedef DWARFDebugLine::LineTable DWARFLineTable;
24
25 static void dumpPubSection(raw_ostream &OS, StringRef Name, StringRef Data,
26                            bool LittleEndian, bool GnuStyle) {
27   OS << "\n." << Name << " contents:\n";
28   DataExtractor pubNames(Data, LittleEndian, 0);
29   uint32_t offset = 0;
30   while (pubNames.isValidOffset(offset)) {
31     OS << "length = " << format("0x%08x", pubNames.getU32(&offset));
32     OS << " version = " << format("0x%04x", pubNames.getU16(&offset));
33     OS << " unit_offset = " << format("0x%08x", pubNames.getU32(&offset));
34     OS << " unit_size = " << format("0x%08x", pubNames.getU32(&offset)) << '\n';
35     if (GnuStyle)
36       OS << "Offset     Linkage  Kind     Name\n";
37     else
38       OS << "Offset     Name\n";
39
40     while (offset < Data.size()) {
41       uint32_t dieRef = pubNames.getU32(&offset);
42       if (dieRef == 0)
43         break;
44       OS << format("0x%8.8x ", dieRef);
45       if (GnuStyle) {
46         PubIndexEntryDescriptor desc(pubNames.getU8(&offset));
47         OS << format("%-8s", dwarf::GDBIndexEntryLinkageString(desc.Linkage))
48            << ' ' << format("%-8s", dwarf::GDBIndexEntryKindString(desc.Kind))
49            << ' ';
50       }
51       OS << '\"' << pubNames.getCStr(&offset) << "\"\n";
52     }
53   }
54 }
55
56 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
57   if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
58     OS << ".debug_abbrev contents:\n";
59     getDebugAbbrev()->dump(OS);
60   }
61
62   if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
63     if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
64       OS << "\n.debug_abbrev.dwo contents:\n";
65       D->dump(OS);
66     }
67
68   if (DumpType == DIDT_All || DumpType == DIDT_Info) {
69     OS << "\n.debug_info contents:\n";
70     for (const auto &CU : compile_units())
71       CU->dump(OS);
72   }
73
74   if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
75       getNumDWOCompileUnits()) {
76     OS << "\n.debug_info.dwo contents:\n";
77     for (const auto &DWOCU : dwo_compile_units())
78       DWOCU->dump(OS);
79   }
80
81   if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
82     OS << "\n.debug_types contents:\n";
83     for (const auto &TU : type_units())
84       TU->dump(OS);
85   }
86
87   if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
88       getNumDWOTypeUnits()) {
89     OS << "\n.debug_types.dwo contents:\n";
90     for (const auto &DWOTU : dwo_type_units())
91       DWOTU->dump(OS);
92   }
93
94   if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
95     OS << "\n.debug_loc contents:\n";
96     getDebugLoc()->dump(OS);
97   }
98
99   if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
100     OS << "\n.debug_frame contents:\n";
101     getDebugFrame()->dump(OS);
102   }
103
104   uint32_t offset = 0;
105   if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
106     OS << "\n.debug_aranges contents:\n";
107     DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
108     DWARFDebugArangeSet set;
109     while (set.extract(arangesData, &offset))
110       set.dump(OS);
111   }
112
113   uint8_t savedAddressByteSize = 0;
114   if (DumpType == DIDT_All || DumpType == DIDT_Line) {
115     OS << "\n.debug_line contents:\n";
116     for (const auto &CU : compile_units()) {
117       savedAddressByteSize = CU->getAddressByteSize();
118       unsigned stmtOffset =
119           CU->getCompileUnitDIE()->getAttributeValueAsSectionOffset(
120               CU.get(), DW_AT_stmt_list, -1U);
121       if (stmtOffset != -1U) {
122         DataExtractor lineData(getLineSection().Data, isLittleEndian(),
123                                savedAddressByteSize);
124         DWARFDebugLine::DumpingState state(OS);
125         DWARFDebugLine::parseStatementTable(lineData, &getLineSection().Relocs, &stmtOffset, state);
126       }
127     }
128   }
129
130   if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
131     OS << "\n.debug_line.dwo contents:\n";
132     unsigned stmtOffset = 0;
133     DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
134                            savedAddressByteSize);
135     DWARFDebugLine::DumpingState state(OS);
136     while (DWARFDebugLine::parsePrologue(lineData, &stmtOffset, &state.Prologue))
137       state.finalize();
138   }
139
140   if (DumpType == DIDT_All || DumpType == DIDT_Str) {
141     OS << "\n.debug_str contents:\n";
142     DataExtractor strData(getStringSection(), isLittleEndian(), 0);
143     offset = 0;
144     uint32_t strOffset = 0;
145     while (const char *s = strData.getCStr(&offset)) {
146       OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
147       strOffset = offset;
148     }
149   }
150
151   if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
152       !getStringDWOSection().empty()) {
153     OS << "\n.debug_str.dwo contents:\n";
154     DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
155     offset = 0;
156     uint32_t strDWOOffset = 0;
157     while (const char *s = strDWOData.getCStr(&offset)) {
158       OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
159       strDWOOffset = offset;
160     }
161   }
162
163   if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
164     OS << "\n.debug_ranges contents:\n";
165     // In fact, different compile units may have different address byte
166     // sizes, but for simplicity we just use the address byte size of the last
167     // compile unit (there is no easy and fast way to associate address range
168     // list and the compile unit it describes).
169     DataExtractor rangesData(getRangeSection(), isLittleEndian(),
170                              savedAddressByteSize);
171     offset = 0;
172     DWARFDebugRangeList rangeList;
173     while (rangeList.extract(rangesData, &offset))
174       rangeList.dump(OS);
175   }
176
177   if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
178     dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
179                    isLittleEndian(), false);
180
181   if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
182     dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
183                    isLittleEndian(), false);
184
185   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
186     dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
187                    isLittleEndian(), true /* GnuStyle */);
188
189   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
190     dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
191                    isLittleEndian(), true /* GnuStyle */);
192
193   if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
194       !getStringOffsetDWOSection().empty()) {
195     OS << "\n.debug_str_offsets.dwo contents:\n";
196     DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
197                                0);
198     offset = 0;
199     uint64_t size = getStringOffsetDWOSection().size();
200     while (offset < size) {
201       OS << format("0x%8.8x: ", offset);
202       OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
203     }
204   }
205 }
206
207 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
208   if (Abbrev)
209     return Abbrev.get();
210
211   DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
212
213   Abbrev.reset(new DWARFDebugAbbrev());
214   Abbrev->parse(abbrData);
215   return Abbrev.get();
216 }
217
218 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
219   if (AbbrevDWO)
220     return AbbrevDWO.get();
221
222   DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
223   AbbrevDWO.reset(new DWARFDebugAbbrev());
224   AbbrevDWO->parse(abbrData);
225   return AbbrevDWO.get();
226 }
227
228 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
229   if (Loc)
230     return Loc.get();
231
232   DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
233   Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
234   // assume all compile units have the same address byte size
235   if (getNumCompileUnits())
236     Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
237   return Loc.get();
238 }
239
240 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
241   if (Aranges)
242     return Aranges.get();
243
244   Aranges.reset(new DWARFDebugAranges());
245   Aranges->generate(this);
246   return Aranges.get();
247 }
248
249 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
250   if (DebugFrame)
251     return DebugFrame.get();
252
253   // There's a "bug" in the DWARFv3 standard with respect to the target address
254   // size within debug frame sections. While DWARF is supposed to be independent
255   // of its container, FDEs have fields with size being "target address size",
256   // which isn't specified in DWARF in general. It's only specified for CUs, but
257   // .eh_frame can appear without a .debug_info section. Follow the example of
258   // other tools (libdwarf) and extract this from the container (ObjectFile
259   // provides this information). This problem is fixed in DWARFv4
260   // See this dwarf-discuss discussion for more details:
261   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
262   DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
263                                getAddressSize());
264   DebugFrame.reset(new DWARFDebugFrame());
265   DebugFrame->parse(debugFrameData);
266   return DebugFrame.get();
267 }
268
269 const DWARFLineTable *
270 DWARFContext::getLineTableForCompileUnit(DWARFCompileUnit *cu) {
271   if (!Line)
272     Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
273
274   unsigned stmtOffset =
275       cu->getCompileUnitDIE()->getAttributeValueAsSectionOffset(
276           cu, DW_AT_stmt_list, -1U);
277   if (stmtOffset == -1U)
278     return 0; // No line table for this compile unit.
279
280   // See if the line table is cached.
281   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
282     return lt;
283
284   // We have to parse it first.
285   DataExtractor lineData(getLineSection().Data, isLittleEndian(),
286                          cu->getAddressByteSize());
287   return Line->getOrParseLineTable(lineData, stmtOffset);
288 }
289
290 void DWARFContext::parseCompileUnits() {
291   if (!CUs.empty())
292     return;
293   uint32_t offset = 0;
294   const DataExtractor &DIData = DataExtractor(getInfoSection().Data,
295                                               isLittleEndian(), 0);
296   while (DIData.isValidOffset(offset)) {
297     std::unique_ptr<DWARFCompileUnit> CU(new DWARFCompileUnit(
298         getDebugAbbrev(), getInfoSection().Data, getAbbrevSection(),
299         getRangeSection(), getStringSection(), StringRef(), getAddrSection(),
300         &getInfoSection().Relocs, isLittleEndian()));
301     if (!CU->extract(DIData, &offset)) {
302       break;
303     }
304     CUs.push_back(std::move(CU));
305     offset = CUs.back()->getNextUnitOffset();
306   }
307 }
308
309 void DWARFContext::parseTypeUnits() {
310   if (!TUs.empty())
311     return;
312   for (const auto &I : getTypesSections()) {
313     uint32_t offset = 0;
314     const DataExtractor &DIData =
315         DataExtractor(I.second.Data, isLittleEndian(), 0);
316     while (DIData.isValidOffset(offset)) {
317       std::unique_ptr<DWARFTypeUnit> TU(new DWARFTypeUnit(
318           getDebugAbbrev(), I.second.Data, getAbbrevSection(),
319           getRangeSection(), getStringSection(), StringRef(), getAddrSection(),
320           &I.second.Relocs, isLittleEndian()));
321       if (!TU->extract(DIData, &offset))
322         break;
323       TUs.push_back(std::move(TU));
324       offset = TUs.back()->getNextUnitOffset();
325     }
326   }
327 }
328
329 void DWARFContext::parseDWOCompileUnits() {
330   if (!DWOCUs.empty())
331     return;
332   uint32_t offset = 0;
333   const DataExtractor &DIData =
334       DataExtractor(getInfoDWOSection().Data, isLittleEndian(), 0);
335   while (DIData.isValidOffset(offset)) {
336     std::unique_ptr<DWARFCompileUnit> DWOCU(new DWARFCompileUnit(
337         getDebugAbbrevDWO(), getInfoDWOSection().Data, getAbbrevDWOSection(),
338         getRangeDWOSection(), getStringDWOSection(),
339         getStringOffsetDWOSection(), getAddrSection(),
340         &getInfoDWOSection().Relocs, isLittleEndian()));
341     if (!DWOCU->extract(DIData, &offset)) {
342       break;
343     }
344     DWOCUs.push_back(std::move(DWOCU));
345     offset = DWOCUs.back()->getNextUnitOffset();
346   }
347 }
348
349 void DWARFContext::parseDWOTypeUnits() {
350   if (!DWOTUs.empty())
351     return;
352   for (const auto &I : getTypesDWOSections()) {
353     uint32_t offset = 0;
354     const DataExtractor &DIData =
355         DataExtractor(I.second.Data, isLittleEndian(), 0);
356     while (DIData.isValidOffset(offset)) {
357       std::unique_ptr<DWARFTypeUnit> TU(new DWARFTypeUnit(
358           getDebugAbbrevDWO(), I.second.Data, getAbbrevDWOSection(),
359           getRangeDWOSection(), getStringDWOSection(),
360           getStringOffsetDWOSection(), getAddrSection(), &I.second.Relocs,
361           isLittleEndian()));
362       if (!TU->extract(DIData, &offset))
363         break;
364       DWOTUs.push_back(std::move(TU));
365       offset = DWOTUs.back()->getNextUnitOffset();
366     }
367   }
368 }
369
370 namespace {
371   struct OffsetComparator {
372
373     bool operator()(const std::unique_ptr<DWARFCompileUnit> &LHS,
374                     const std::unique_ptr<DWARFCompileUnit> &RHS) const {
375       return LHS->getOffset() < RHS->getOffset();
376     }
377     bool operator()(const std::unique_ptr<DWARFCompileUnit> &LHS,
378                     uint32_t RHS) const {
379       return LHS->getOffset() < RHS;
380     }
381     bool operator()(uint32_t LHS,
382                     const std::unique_ptr<DWARFCompileUnit> &RHS) const {
383       return LHS < RHS->getOffset();
384     }
385   };
386 }
387
388 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
389   parseCompileUnits();
390
391   std::unique_ptr<DWARFCompileUnit> *CU =
392       std::lower_bound(CUs.begin(), CUs.end(), Offset, OffsetComparator());
393   if (CU != CUs.end()) {
394     return CU->get();
395   }
396   return 0;
397 }
398
399 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
400   // First, get the offset of the compile unit.
401   uint32_t CUOffset = getDebugAranges()->findAddress(Address);
402   // Retrieve the compile unit.
403   return getCompileUnitForOffset(CUOffset);
404 }
405
406 static bool getFileNameForCompileUnit(DWARFCompileUnit *CU,
407                                       const DWARFLineTable *LineTable,
408                                       uint64_t FileIndex,
409                                       bool NeedsAbsoluteFilePath,
410                                       std::string &FileName) {
411   if (CU == 0 ||
412       LineTable == 0 ||
413       !LineTable->getFileNameByIndex(FileIndex, NeedsAbsoluteFilePath,
414                                      FileName))
415     return false;
416   if (NeedsAbsoluteFilePath && sys::path::is_relative(FileName)) {
417     // We may still need to append compilation directory of compile unit.
418     SmallString<16> AbsolutePath;
419     if (const char *CompilationDir = CU->getCompilationDir()) {
420       sys::path::append(AbsolutePath, CompilationDir);
421     }
422     sys::path::append(AbsolutePath, FileName);
423     FileName = AbsolutePath.str();
424   }
425   return true;
426 }
427
428 static bool getFileLineInfoForCompileUnit(DWARFCompileUnit *CU,
429                                           const DWARFLineTable *LineTable,
430                                           uint64_t Address,
431                                           bool NeedsAbsoluteFilePath,
432                                           std::string &FileName,
433                                           uint32_t &Line, uint32_t &Column) {
434   if (CU == 0 || LineTable == 0)
435     return false;
436   // Get the index of row we're looking for in the line table.
437   uint32_t RowIndex = LineTable->lookupAddress(Address);
438   if (RowIndex == -1U)
439     return false;
440   // Take file number and line/column from the row.
441   const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
442   if (!getFileNameForCompileUnit(CU, LineTable, Row.File,
443                                  NeedsAbsoluteFilePath, FileName))
444     return false;
445   Line = Row.Line;
446   Column = Row.Column;
447   return true;
448 }
449
450 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
451     DILineInfoSpecifier Specifier) {
452   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
453   if (!CU)
454     return DILineInfo();
455   std::string FileName = "<invalid>";
456   std::string FunctionName = "<invalid>";
457   uint32_t Line = 0;
458   uint32_t Column = 0;
459   if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
460     // The address may correspond to instruction in some inlined function,
461     // so we have to build the chain of inlined functions and take the
462     // name of the topmost function in it.
463     const DWARFDebugInfoEntryInlinedChain &InlinedChain =
464         CU->getInlinedChainForAddress(Address);
465     if (InlinedChain.DIEs.size() > 0) {
466       const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
467       if (const char *Name = TopFunctionDIE.getSubroutineName(InlinedChain.U))
468         FunctionName = Name;
469     }
470   }
471   if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
472     const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
473     const bool NeedsAbsoluteFilePath =
474         Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
475     getFileLineInfoForCompileUnit(CU, LineTable, Address,
476                                   NeedsAbsoluteFilePath,
477                                   FileName, Line, Column);
478   }
479   return DILineInfo(StringRef(FileName), StringRef(FunctionName),
480                     Line, Column);
481 }
482
483 DILineInfoTable DWARFContext::getLineInfoForAddressRange(uint64_t Address,
484     uint64_t Size,
485     DILineInfoSpecifier Specifier) {
486   DILineInfoTable  Lines;
487   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
488   if (!CU)
489     return Lines;
490
491   std::string FunctionName = "<invalid>";
492   if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
493     // The address may correspond to instruction in some inlined function,
494     // so we have to build the chain of inlined functions and take the
495     // name of the topmost function in it.
496     const DWARFDebugInfoEntryInlinedChain &InlinedChain =
497         CU->getInlinedChainForAddress(Address);
498     if (InlinedChain.DIEs.size() > 0) {
499       const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
500       if (const char *Name = TopFunctionDIE.getSubroutineName(InlinedChain.U))
501         FunctionName = Name;
502     }
503   }
504
505   // If the Specifier says we don't need FileLineInfo, just
506   // return the top-most function at the starting address.
507   if (!Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
508     Lines.push_back(
509         std::make_pair(Address, DILineInfo("<invalid>", FunctionName, 0, 0)));
510     return Lines;
511   }
512
513   const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
514   const bool NeedsAbsoluteFilePath =
515       Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
516
517   // Get the index of row we're looking for in the line table.
518   std::vector<uint32_t> RowVector;
519   if (!LineTable->lookupAddressRange(Address, Size, RowVector))
520     return Lines;
521
522   for (uint32_t RowIndex : RowVector) {
523     // Take file number and line/column from the row.
524     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
525     std::string FileName = "<invalid>";
526     getFileNameForCompileUnit(CU, LineTable, Row.File,
527                               NeedsAbsoluteFilePath, FileName);
528     Lines.push_back(std::make_pair(
529         Row.Address, DILineInfo(FileName, FunctionName, Row.Line, Row.Column)));
530   }
531
532   return Lines;
533 }
534
535 DIInliningInfo DWARFContext::getInliningInfoForAddress(uint64_t Address,
536     DILineInfoSpecifier Specifier) {
537   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
538   if (!CU)
539     return DIInliningInfo();
540
541   const DWARFDebugInfoEntryInlinedChain &InlinedChain =
542       CU->getInlinedChainForAddress(Address);
543   if (InlinedChain.DIEs.size() == 0)
544     return DIInliningInfo();
545
546   DIInliningInfo InliningInfo;
547   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
548   const DWARFLineTable *LineTable = 0;
549   for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
550     const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
551     std::string FileName = "<invalid>";
552     std::string FunctionName = "<invalid>";
553     uint32_t Line = 0;
554     uint32_t Column = 0;
555     // Get function name if necessary.
556     if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
557       if (const char *Name = FunctionDIE.getSubroutineName(InlinedChain.U))
558         FunctionName = Name;
559     }
560     if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
561       const bool NeedsAbsoluteFilePath =
562           Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
563       if (i == 0) {
564         // For the topmost frame, initialize the line table of this
565         // compile unit and fetch file/line info from it.
566         LineTable = getLineTableForCompileUnit(CU);
567         // For the topmost routine, get file/line info from line table.
568         getFileLineInfoForCompileUnit(CU, LineTable, Address,
569                                       NeedsAbsoluteFilePath,
570                                       FileName, Line, Column);
571       } else {
572         // Otherwise, use call file, call line and call column from
573         // previous DIE in inlined chain.
574         getFileNameForCompileUnit(CU, LineTable, CallFile,
575                                   NeedsAbsoluteFilePath, FileName);
576         Line = CallLine;
577         Column = CallColumn;
578       }
579       // Get call file/line/column of a current DIE.
580       if (i + 1 < n) {
581         FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
582                                    CallColumn);
583       }
584     }
585     DILineInfo Frame(StringRef(FileName), StringRef(FunctionName),
586                      Line, Column);
587     InliningInfo.addFrame(Frame);
588   }
589   return InliningInfo;
590 }
591
592 static bool consumeCompressedDebugSectionHeader(StringRef &data,
593                                                 uint64_t &OriginalSize) {
594   // Consume "ZLIB" prefix.
595   if (!data.startswith("ZLIB"))
596     return false;
597   data = data.substr(4);
598   // Consume uncompressed section size (big-endian 8 bytes).
599   DataExtractor extractor(data, false, 8);
600   uint32_t Offset = 0;
601   OriginalSize = extractor.getU64(&Offset);
602   if (Offset == 0)
603     return false;
604   data = data.substr(Offset);
605   return true;
606 }
607
608 DWARFContextInMemory::DWARFContextInMemory(object::ObjectFile *Obj) :
609   IsLittleEndian(Obj->isLittleEndian()),
610   AddressSize(Obj->getBytesInAddress()) {
611   for (object::section_iterator i = Obj->section_begin(),
612                                 e = Obj->section_end();
613        i != e; ++i) {
614     StringRef name;
615     i->getName(name);
616     StringRef data;
617     i->getContents(data);
618
619     name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
620
621     // Check if debug info section is compressed with zlib.
622     if (name.startswith("zdebug_")) {
623       uint64_t OriginalSize;
624       if (!zlib::isAvailable() ||
625           !consumeCompressedDebugSectionHeader(data, OriginalSize))
626         continue;
627       std::unique_ptr<MemoryBuffer> UncompressedSection;
628       if (zlib::uncompress(data, UncompressedSection, OriginalSize) !=
629           zlib::StatusOK)
630         continue;
631       // Make data point to uncompressed section contents and save its contents.
632       name = name.substr(1);
633       data = UncompressedSection->getBuffer();
634       UncompressedSections.push_back(std::move(UncompressedSection));
635     }
636
637     StringRef *Section =
638         StringSwitch<StringRef *>(name)
639             .Case("debug_info", &InfoSection.Data)
640             .Case("debug_abbrev", &AbbrevSection)
641             .Case("debug_loc", &LocSection.Data)
642             .Case("debug_line", &LineSection.Data)
643             .Case("debug_aranges", &ARangeSection)
644             .Case("debug_frame", &DebugFrameSection)
645             .Case("debug_str", &StringSection)
646             .Case("debug_ranges", &RangeSection)
647             .Case("debug_pubnames", &PubNamesSection)
648             .Case("debug_pubtypes", &PubTypesSection)
649             .Case("debug_gnu_pubnames", &GnuPubNamesSection)
650             .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
651             .Case("debug_info.dwo", &InfoDWOSection.Data)
652             .Case("debug_abbrev.dwo", &AbbrevDWOSection)
653             .Case("debug_line.dwo", &LineDWOSection.Data)
654             .Case("debug_str.dwo", &StringDWOSection)
655             .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
656             .Case("debug_addr", &AddrSection)
657             // Any more debug info sections go here.
658             .Default(0);
659     if (Section) {
660       *Section = 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[*i].Data = data;
669     } else if (name == "debug_types.dwo") {
670       TypesDWOSections[*i].Data = data;
671     }
672
673     section_iterator RelocatedSection = i->getRelocatedSection();
674     if (RelocatedSection == Obj->section_end())
675       continue;
676
677     StringRef RelSecName;
678     RelocatedSection->getName(RelSecName);
679     RelSecName = RelSecName.substr(
680         RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
681
682     // TODO: Add support for relocations in other sections as needed.
683     // Record relocations for the debug_info and debug_line sections.
684     RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
685         .Case("debug_info", &InfoSection.Relocs)
686         .Case("debug_loc", &LocSection.Relocs)
687         .Case("debug_info.dwo", &InfoDWOSection.Relocs)
688         .Case("debug_line", &LineSection.Relocs)
689         .Default(0);
690     if (!Map) {
691       // Find debug_types relocs by section rather than name as there are
692       // multiple, comdat grouped, debug_types sections.
693       if (RelSecName == "debug_types")
694         Map = &TypesSections[*RelocatedSection].Relocs;
695       else if (RelSecName == "debug_types.dwo")
696         Map = &TypesDWOSections[*RelocatedSection].Relocs;
697       else
698         continue;
699     }
700
701     if (i->relocation_begin() != i->relocation_end()) {
702       uint64_t SectionSize;
703       RelocatedSection->getSize(SectionSize);
704       for (object::relocation_iterator reloc_i = i->relocation_begin(),
705                                        reloc_e = i->relocation_end();
706            reloc_i != reloc_e; ++reloc_i) {
707         uint64_t Address;
708         reloc_i->getOffset(Address);
709         uint64_t Type;
710         reloc_i->getType(Type);
711         uint64_t SymAddr = 0;
712         // ELF relocations may need the symbol address
713         if (Obj->isELF()) {
714           object::symbol_iterator Sym = reloc_i->getSymbol();
715           Sym->getAddress(SymAddr);
716         }
717
718         object::RelocVisitor V(Obj->getFileFormatName());
719         // The section address is always 0 for debug sections.
720         object::RelocToApply R(V.visit(Type, *reloc_i, 0, SymAddr));
721         if (V.error()) {
722           SmallString<32> Name;
723           error_code ec(reloc_i->getTypeName(Name));
724           if (ec) {
725             errs() << "Aaaaaa! Nameless relocation! Aaaaaa!\n";
726           }
727           errs() << "error: failed to compute relocation: "
728                  << Name << "\n";
729           continue;
730         }
731
732         if (Address + R.Width > SectionSize) {
733           errs() << "error: " << R.Width << "-byte relocation starting "
734                  << Address << " bytes into section " << name << " which is "
735                  << SectionSize << " bytes long.\n";
736           continue;
737         }
738         if (R.Width > 8) {
739           errs() << "error: can't handle a relocation of more than 8 bytes at "
740                     "a time.\n";
741           continue;
742         }
743         DEBUG(dbgs() << "Writing " << format("%p", R.Value)
744                      << " at " << format("%p", Address)
745                      << " with width " << format("%d", R.Width)
746                      << "\n");
747         Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
748       }
749     }
750   }
751 }
752
753 void DWARFContextInMemory::anchor() { }