1 //===-- DWARFContext.cpp --------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
21 using namespace dwarf;
23 typedef DWARFDebugLine::LineTable DWARFLineTable;
25 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
26 if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
27 OS << ".debug_abbrev contents:\n";
28 getDebugAbbrev()->dump(OS);
31 if (DumpType == DIDT_All || DumpType == DIDT_Info) {
32 OS << "\n.debug_info contents:\n";
33 for (unsigned i = 0, e = getNumCompileUnits(); i != e; ++i)
34 getCompileUnitAtIndex(i)->dump(OS);
37 if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
38 OS << "\n.debug_frame contents:\n";
39 getDebugFrame()->dump(OS);
43 if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
44 OS << "\n.debug_aranges contents:\n";
45 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
46 DWARFDebugArangeSet set;
47 while (set.extract(arangesData, &offset))
51 uint8_t savedAddressByteSize = 0;
52 if (DumpType == DIDT_All || DumpType == DIDT_Line) {
53 OS << "\n.debug_line contents:\n";
54 for (unsigned i = 0, e = getNumCompileUnits(); i != e; ++i) {
55 DWARFCompileUnit *cu = getCompileUnitAtIndex(i);
56 savedAddressByteSize = cu->getAddressByteSize();
58 cu->getCompileUnitDIE()->getAttributeValueAsUnsigned(cu, DW_AT_stmt_list,
60 if (stmtOffset != -1U) {
61 DataExtractor lineData(getLineSection(), isLittleEndian(),
62 savedAddressByteSize);
63 DWARFDebugLine::DumpingState state(OS);
64 DWARFDebugLine::parseStatementTable(lineData, &lineRelocMap(), &stmtOffset, state);
69 if (DumpType == DIDT_All || DumpType == DIDT_Str) {
70 OS << "\n.debug_str contents:\n";
71 DataExtractor strData(getStringSection(), isLittleEndian(), 0);
73 uint32_t strOffset = 0;
74 while (const char *s = strData.getCStr(&offset)) {
75 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
80 if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
81 OS << "\n.debug_ranges contents:\n";
82 // In fact, different compile units may have different address byte
83 // sizes, but for simplicity we just use the address byte size of the last
84 // compile unit (there is no easy and fast way to associate address range
85 // list and the compile unit it describes).
86 DataExtractor rangesData(getRangeSection(), isLittleEndian(),
87 savedAddressByteSize);
89 DWARFDebugRangeList rangeList;
90 while (rangeList.extract(rangesData, &offset))
94 if (DumpType == DIDT_All || DumpType == DIDT_Pubnames) {
95 OS << "\n.debug_pubnames contents:\n";
96 DataExtractor pubNames(getPubNamesSection(), isLittleEndian(), 0);
98 OS << "Length: " << pubNames.getU32(&offset) << "\n";
99 OS << "Version: " << pubNames.getU16(&offset) << "\n";
100 OS << "Offset in .debug_info: " << pubNames.getU32(&offset) << "\n";
101 OS << "Size: " << pubNames.getU32(&offset) << "\n";
102 OS << "\n Offset Name\n";
103 while (offset < getPubNamesSection().size()) {
104 uint32_t n = pubNames.getU32(&offset);
107 OS << format("%8x ", n);
108 OS << pubNames.getCStr(&offset) << "\n";
112 if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo) {
113 OS << "\n.debug_abbrev.dwo contents:\n";
114 getDebugAbbrevDWO()->dump(OS);
117 if (DumpType == DIDT_All || DumpType == DIDT_InfoDwo) {
118 OS << "\n.debug_info.dwo contents:\n";
119 for (unsigned i = 0, e = getNumDWOCompileUnits(); i != e; ++i)
120 getDWOCompileUnitAtIndex(i)->dump(OS);
123 if (DumpType == DIDT_All || DumpType == DIDT_StrDwo) {
124 OS << "\n.debug_str.dwo contents:\n";
125 DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
127 uint32_t strDWOOffset = 0;
128 while (const char *s = strDWOData.getCStr(&offset)) {
129 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
130 strDWOOffset = offset;
134 if (DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) {
135 OS << "\n.debug_str_offsets.dwo contents:\n";
136 DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(), 0);
138 while (offset < getStringOffsetDWOSection().size()) {
139 OS << format("0x%8.8x: ", offset);
140 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
145 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
149 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
151 Abbrev.reset(new DWARFDebugAbbrev());
152 Abbrev->parse(abbrData);
156 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
158 return AbbrevDWO.get();
160 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
161 AbbrevDWO.reset(new DWARFDebugAbbrev());
162 AbbrevDWO->parse(abbrData);
163 return AbbrevDWO.get();
166 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
168 return Aranges.get();
170 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
172 Aranges.reset(new DWARFDebugAranges());
173 Aranges->extract(arangesData);
174 // Generate aranges from DIEs: even if .debug_aranges section is present,
175 // it may describe only a small subset of compilation units, so we need to
176 // manually build aranges for the rest of them.
177 Aranges->generate(this);
178 return Aranges.get();
181 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
183 return DebugFrame.get();
185 // There's a "bug" in the DWARFv3 standard with respect to the target address
186 // size within debug frame sections. While DWARF is supposed to be independent
187 // of its container, FDEs have fields with size being "target address size",
188 // which isn't specified in DWARF in general. It's only specified for CUs, but
189 // .eh_frame can appear without a .debug_info section. Follow the example of
190 // other tools (libdwarf) and extract this from the container (ObjectFile
191 // provides this information). This problem is fixed in DWARFv4
192 // See this dwarf-discuss discussion for more details:
193 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
194 DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
196 DebugFrame.reset(new DWARFDebugFrame());
197 DebugFrame->parse(debugFrameData);
198 return DebugFrame.get();
201 const DWARFLineTable *
202 DWARFContext::getLineTableForCompileUnit(DWARFCompileUnit *cu) {
204 Line.reset(new DWARFDebugLine(&lineRelocMap()));
206 unsigned stmtOffset =
207 cu->getCompileUnitDIE()->getAttributeValueAsUnsigned(cu, DW_AT_stmt_list,
209 if (stmtOffset == -1U)
210 return 0; // No line table for this compile unit.
212 // See if the line table is cached.
213 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
216 // We have to parse it first.
217 DataExtractor lineData(getLineSection(), isLittleEndian(),
218 cu->getAddressByteSize());
219 return Line->getOrParseLineTable(lineData, stmtOffset);
222 void DWARFContext::parseCompileUnits() {
224 const DataExtractor &DIData = DataExtractor(getInfoSection(),
225 isLittleEndian(), 0);
226 while (DIData.isValidOffset(offset)) {
227 CUs.push_back(DWARFCompileUnit(getDebugAbbrev(), getInfoSection(),
228 getAbbrevSection(), getRangeSection(),
229 getStringSection(), StringRef(),
233 if (!CUs.back().extract(DIData, &offset)) {
238 offset = CUs.back().getNextCompileUnitOffset();
242 void DWARFContext::parseDWOCompileUnits() {
244 const DataExtractor &DIData = DataExtractor(getInfoDWOSection(),
245 isLittleEndian(), 0);
246 while (DIData.isValidOffset(offset)) {
247 DWOCUs.push_back(DWARFCompileUnit(getDebugAbbrevDWO(), getInfoDWOSection(),
248 getAbbrevDWOSection(),
249 getRangeDWOSection(),
250 getStringDWOSection(),
251 getStringOffsetDWOSection(),
255 if (!DWOCUs.back().extract(DIData, &offset)) {
260 offset = DWOCUs.back().getNextCompileUnitOffset();
265 struct OffsetComparator {
266 bool operator()(const DWARFCompileUnit &LHS,
267 const DWARFCompileUnit &RHS) const {
268 return LHS.getOffset() < RHS.getOffset();
270 bool operator()(const DWARFCompileUnit &LHS, uint32_t RHS) const {
271 return LHS.getOffset() < RHS;
273 bool operator()(uint32_t LHS, const DWARFCompileUnit &RHS) const {
274 return LHS < RHS.getOffset();
279 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
283 DWARFCompileUnit *CU = std::lower_bound(CUs.begin(), CUs.end(), Offset,
290 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
291 // First, get the offset of the compile unit.
292 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
293 // Retrieve the compile unit.
294 return getCompileUnitForOffset(CUOffset);
297 static bool getFileNameForCompileUnit(DWARFCompileUnit *CU,
298 const DWARFLineTable *LineTable,
300 bool NeedsAbsoluteFilePath,
301 std::string &FileName) {
304 !LineTable->getFileNameByIndex(FileIndex, NeedsAbsoluteFilePath,
307 if (NeedsAbsoluteFilePath && sys::path::is_relative(FileName)) {
308 // We may still need to append compilation directory of compile unit.
309 SmallString<16> AbsolutePath;
310 if (const char *CompilationDir = CU->getCompilationDir()) {
311 sys::path::append(AbsolutePath, CompilationDir);
313 sys::path::append(AbsolutePath, FileName);
314 FileName = AbsolutePath.str();
319 static bool getFileLineInfoForCompileUnit(DWARFCompileUnit *CU,
320 const DWARFLineTable *LineTable,
322 bool NeedsAbsoluteFilePath,
323 std::string &FileName,
324 uint32_t &Line, uint32_t &Column) {
325 if (CU == 0 || LineTable == 0)
327 // Get the index of row we're looking for in the line table.
328 uint32_t RowIndex = LineTable->lookupAddress(Address);
331 // Take file number and line/column from the row.
332 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
333 if (!getFileNameForCompileUnit(CU, LineTable, Row.File,
334 NeedsAbsoluteFilePath, FileName))
341 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
342 DILineInfoSpecifier Specifier) {
343 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
346 std::string FileName = "<invalid>";
347 std::string FunctionName = "<invalid>";
350 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
351 // The address may correspond to instruction in some inlined function,
352 // so we have to build the chain of inlined functions and take the
353 // name of the topmost function in it.
354 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
355 CU->getInlinedChainForAddress(Address);
356 if (InlinedChain.size() > 0) {
357 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
358 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
362 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
363 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
364 const bool NeedsAbsoluteFilePath =
365 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
366 getFileLineInfoForCompileUnit(CU, LineTable, Address,
367 NeedsAbsoluteFilePath,
368 FileName, Line, Column);
370 return DILineInfo(StringRef(FileName), StringRef(FunctionName),
374 DILineInfoTable DWARFContext::getLineInfoForAddressRange(uint64_t Address,
376 DILineInfoSpecifier Specifier) {
377 DILineInfoTable Lines;
378 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
382 std::string FunctionName = "<invalid>";
383 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
384 // The address may correspond to instruction in some inlined function,
385 // so we have to build the chain of inlined functions and take the
386 // name of the topmost function in it.
387 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
388 CU->getInlinedChainForAddress(Address);
389 if (InlinedChain.size() > 0) {
390 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
391 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
396 StringRef FuncNameRef = StringRef(FunctionName);
398 // If the Specifier says we don't need FileLineInfo, just
399 // return the top-most function at the starting address.
400 if (!Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
401 Lines.push_back(std::make_pair(Address,
402 DILineInfo(StringRef("<invalid>"),
403 FuncNameRef, 0, 0)));
407 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
408 const bool NeedsAbsoluteFilePath =
409 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
411 // Get the index of row we're looking for in the line table.
412 std::vector<uint32_t> RowVector;
413 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
416 uint32_t NumRows = RowVector.size();
417 for (uint32_t i = 0; i < NumRows; ++i) {
418 uint32_t RowIndex = RowVector[i];
419 // Take file number and line/column from the row.
420 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
421 std::string FileName = "<invalid>";
422 getFileNameForCompileUnit(CU, LineTable, Row.File,
423 NeedsAbsoluteFilePath, FileName);
424 Lines.push_back(std::make_pair(Row.Address,
425 DILineInfo(StringRef(FileName),
426 FuncNameRef, Row.Line, Row.Column)));
432 DIInliningInfo DWARFContext::getInliningInfoForAddress(uint64_t Address,
433 DILineInfoSpecifier Specifier) {
434 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
436 return DIInliningInfo();
438 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
439 CU->getInlinedChainForAddress(Address);
440 if (InlinedChain.size() == 0)
441 return DIInliningInfo();
443 DIInliningInfo InliningInfo;
444 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
445 const DWARFLineTable *LineTable = 0;
446 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
447 const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain[i];
448 std::string FileName = "<invalid>";
449 std::string FunctionName = "<invalid>";
452 // Get function name if necessary.
453 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
454 if (const char *Name = FunctionDIE.getSubroutineName(CU))
457 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
458 const bool NeedsAbsoluteFilePath =
459 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
461 // For the topmost frame, initialize the line table of this
462 // compile unit and fetch file/line info from it.
463 LineTable = getLineTableForCompileUnit(CU);
464 // For the topmost routine, get file/line info from line table.
465 getFileLineInfoForCompileUnit(CU, LineTable, Address,
466 NeedsAbsoluteFilePath,
467 FileName, Line, Column);
469 // Otherwise, use call file, call line and call column from
470 // previous DIE in inlined chain.
471 getFileNameForCompileUnit(CU, LineTable, CallFile,
472 NeedsAbsoluteFilePath, FileName);
476 // Get call file/line/column of a current DIE.
478 FunctionDIE.getCallerFrame(CU, CallFile, CallLine, CallColumn);
481 DILineInfo Frame(StringRef(FileName), StringRef(FunctionName),
483 InliningInfo.addFrame(Frame);
488 static bool consumeCompressedDebugSectionHeader(StringRef &data,
489 uint64_t &OriginalSize) {
490 // Consume "ZLIB" prefix.
491 if (!data.startswith("ZLIB"))
493 data = data.substr(4);
494 // Consume uncompressed section size (big-endian 8 bytes).
495 DataExtractor extractor(data, false, 8);
497 OriginalSize = extractor.getU64(&Offset);
500 data = data.substr(Offset);
504 DWARFContextInMemory::DWARFContextInMemory(object::ObjectFile *Obj) :
505 IsLittleEndian(Obj->isLittleEndian()),
506 AddressSize(Obj->getBytesInAddress()) {
508 for (object::section_iterator i = Obj->begin_sections(),
509 e = Obj->end_sections();
510 i != e; i.increment(ec)) {
514 i->getContents(data);
516 name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
518 // Check if debug info section is compressed with zlib.
519 if (name.startswith("zdebug_")) {
520 uint64_t OriginalSize;
521 if (!zlib::isAvailable() ||
522 !consumeCompressedDebugSectionHeader(data, OriginalSize))
524 OwningPtr<MemoryBuffer> UncompressedSection;
525 if (zlib::uncompress(data, UncompressedSection, OriginalSize) !=
528 // Make data point to uncompressed section contents and save its contents.
529 name = name.substr(1);
530 data = UncompressedSection->getBuffer();
531 UncompressedSections.push_back(UncompressedSection.take());
534 StringRef *Section = StringSwitch<StringRef*>(name)
535 .Case("debug_info", &InfoSection)
536 .Case("debug_abbrev", &AbbrevSection)
537 .Case("debug_line", &LineSection)
538 .Case("debug_aranges", &ARangeSection)
539 .Case("debug_frame", &DebugFrameSection)
540 .Case("debug_str", &StringSection)
541 .Case("debug_ranges", &RangeSection)
542 .Case("debug_pubnames", &PubNamesSection)
543 .Case("debug_info.dwo", &InfoDWOSection)
544 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
545 .Case("debug_str.dwo", &StringDWOSection)
546 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
547 .Case("debug_addr", &AddrSection)
548 // Any more debug info sections go here.
553 if (name == "debug_ranges") {
554 // FIXME: Use the other dwo range section when we emit it.
555 RangeDWOSection = data;
558 // TODO: Add support for relocations in other sections as needed.
559 // Record relocations for the debug_info and debug_line sections.
560 RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(name)
561 .Case("debug_info", &InfoRelocMap)
562 .Case("debug_info.dwo", &InfoDWORelocMap)
563 .Case("debug_line", &LineRelocMap)
568 if (i->begin_relocations() != i->end_relocations()) {
569 uint64_t SectionSize;
570 i->getSize(SectionSize);
571 for (object::relocation_iterator reloc_i = i->begin_relocations(),
572 reloc_e = i->end_relocations();
573 reloc_i != reloc_e; reloc_i.increment(ec)) {
575 reloc_i->getOffset(Address);
577 reloc_i->getType(Type);
578 uint64_t SymAddr = 0;
579 // ELF relocations may need the symbol address
581 object::SymbolRef Sym;
582 reloc_i->getSymbol(Sym);
583 Sym.getAddress(SymAddr);
586 object::RelocVisitor V(Obj->getFileFormatName());
587 // The section address is always 0 for debug sections.
588 object::RelocToApply R(V.visit(Type, *reloc_i, 0, SymAddr));
590 SmallString<32> Name;
591 error_code ec(reloc_i->getTypeName(Name));
593 errs() << "Aaaaaa! Nameless relocation! Aaaaaa!\n";
595 errs() << "error: failed to compute relocation: "
600 if (Address + R.Width > SectionSize) {
601 errs() << "error: " << R.Width << "-byte relocation starting "
602 << Address << " bytes into section " << name << " which is "
603 << SectionSize << " bytes long.\n";
607 errs() << "error: can't handle a relocation of more than 8 bytes at "
611 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
612 << " at " << format("%p", Address)
613 << " with width " << format("%d", R.Width)
615 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
621 DWARFContextInMemory::~DWARFContextInMemory() {
622 DeleteContainerPointers(UncompressedSections);
625 void DWARFContextInMemory::anchor() { }