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