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