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