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