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 const DWARFDebugAbbrev *D = getDebugAbbrevDWO();
115 OS << "\n.debug_abbrev.dwo contents:\n";
116 getDebugAbbrevDWO()->dump(OS);
120 if (DumpType == DIDT_All || DumpType == DIDT_InfoDwo)
121 if (getNumDWOCompileUnits()) {
122 OS << "\n.debug_info.dwo contents:\n";
123 for (unsigned i = 0, e = getNumDWOCompileUnits(); i != e; ++i)
124 getDWOCompileUnitAtIndex(i)->dump(OS);
127 if (DumpType == DIDT_All || DumpType == DIDT_StrDwo)
128 if (!getStringDWOSection().empty()) {
129 OS << "\n.debug_str.dwo contents:\n";
130 DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
132 uint32_t strDWOOffset = 0;
133 while (const char *s = strDWOData.getCStr(&offset)) {
134 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
135 strDWOOffset = offset;
139 if (DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo)
140 if (!getStringOffsetDWOSection().empty()) {
141 OS << "\n.debug_str_offsets.dwo contents:\n";
142 DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(), 0);
144 uint64_t size = getStringOffsetDWOSection().size();
145 while (offset < size) {
146 OS << format("0x%8.8x: ", offset);
147 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
152 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
156 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
158 Abbrev.reset(new DWARFDebugAbbrev());
159 Abbrev->parse(abbrData);
163 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
165 return AbbrevDWO.get();
167 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
168 AbbrevDWO.reset(new DWARFDebugAbbrev());
169 AbbrevDWO->parse(abbrData);
170 return AbbrevDWO.get();
173 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
175 return Aranges.get();
177 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
179 Aranges.reset(new DWARFDebugAranges());
180 Aranges->extract(arangesData);
181 // Generate aranges from DIEs: even if .debug_aranges section is present,
182 // it may describe only a small subset of compilation units, so we need to
183 // manually build aranges for the rest of them.
184 Aranges->generate(this);
185 return Aranges.get();
188 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
190 return DebugFrame.get();
192 // There's a "bug" in the DWARFv3 standard with respect to the target address
193 // size within debug frame sections. While DWARF is supposed to be independent
194 // of its container, FDEs have fields with size being "target address size",
195 // which isn't specified in DWARF in general. It's only specified for CUs, but
196 // .eh_frame can appear without a .debug_info section. Follow the example of
197 // other tools (libdwarf) and extract this from the container (ObjectFile
198 // provides this information). This problem is fixed in DWARFv4
199 // See this dwarf-discuss discussion for more details:
200 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
201 DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
203 DebugFrame.reset(new DWARFDebugFrame());
204 DebugFrame->parse(debugFrameData);
205 return DebugFrame.get();
208 const DWARFLineTable *
209 DWARFContext::getLineTableForCompileUnit(DWARFCompileUnit *cu) {
211 Line.reset(new DWARFDebugLine(&lineRelocMap()));
213 unsigned stmtOffset =
214 cu->getCompileUnitDIE()->getAttributeValueAsUnsigned(cu, DW_AT_stmt_list,
216 if (stmtOffset == -1U)
217 return 0; // No line table for this compile unit.
219 // See if the line table is cached.
220 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
223 // We have to parse it first.
224 DataExtractor lineData(getLineSection(), isLittleEndian(),
225 cu->getAddressByteSize());
226 return Line->getOrParseLineTable(lineData, stmtOffset);
229 void DWARFContext::parseCompileUnits() {
231 const DataExtractor &DIData = DataExtractor(getInfoSection(),
232 isLittleEndian(), 0);
233 while (DIData.isValidOffset(offset)) {
234 CUs.push_back(DWARFCompileUnit(getDebugAbbrev(), getInfoSection(),
235 getAbbrevSection(), getRangeSection(),
236 getStringSection(), StringRef(),
240 if (!CUs.back().extract(DIData, &offset)) {
245 offset = CUs.back().getNextCompileUnitOffset();
249 void DWARFContext::parseDWOCompileUnits() {
251 const DataExtractor &DIData = DataExtractor(getInfoDWOSection(),
252 isLittleEndian(), 0);
253 while (DIData.isValidOffset(offset)) {
254 DWOCUs.push_back(DWARFCompileUnit(getDebugAbbrevDWO(), getInfoDWOSection(),
255 getAbbrevDWOSection(),
256 getRangeDWOSection(),
257 getStringDWOSection(),
258 getStringOffsetDWOSection(),
262 if (!DWOCUs.back().extract(DIData, &offset)) {
267 offset = DWOCUs.back().getNextCompileUnitOffset();
272 struct OffsetComparator {
273 bool operator()(const DWARFCompileUnit &LHS,
274 const DWARFCompileUnit &RHS) const {
275 return LHS.getOffset() < RHS.getOffset();
277 bool operator()(const DWARFCompileUnit &LHS, uint32_t RHS) const {
278 return LHS.getOffset() < RHS;
280 bool operator()(uint32_t LHS, const DWARFCompileUnit &RHS) const {
281 return LHS < RHS.getOffset();
286 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
290 DWARFCompileUnit *CU = std::lower_bound(CUs.begin(), CUs.end(), Offset,
297 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
298 // First, get the offset of the compile unit.
299 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
300 // Retrieve the compile unit.
301 return getCompileUnitForOffset(CUOffset);
304 static bool getFileNameForCompileUnit(DWARFCompileUnit *CU,
305 const DWARFLineTable *LineTable,
307 bool NeedsAbsoluteFilePath,
308 std::string &FileName) {
311 !LineTable->getFileNameByIndex(FileIndex, NeedsAbsoluteFilePath,
314 if (NeedsAbsoluteFilePath && sys::path::is_relative(FileName)) {
315 // We may still need to append compilation directory of compile unit.
316 SmallString<16> AbsolutePath;
317 if (const char *CompilationDir = CU->getCompilationDir()) {
318 sys::path::append(AbsolutePath, CompilationDir);
320 sys::path::append(AbsolutePath, FileName);
321 FileName = AbsolutePath.str();
326 static bool getFileLineInfoForCompileUnit(DWARFCompileUnit *CU,
327 const DWARFLineTable *LineTable,
329 bool NeedsAbsoluteFilePath,
330 std::string &FileName,
331 uint32_t &Line, uint32_t &Column) {
332 if (CU == 0 || LineTable == 0)
334 // Get the index of row we're looking for in the line table.
335 uint32_t RowIndex = LineTable->lookupAddress(Address);
338 // Take file number and line/column from the row.
339 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
340 if (!getFileNameForCompileUnit(CU, LineTable, Row.File,
341 NeedsAbsoluteFilePath, FileName))
348 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
349 DILineInfoSpecifier Specifier) {
350 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
353 std::string FileName = "<invalid>";
354 std::string FunctionName = "<invalid>";
357 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
358 // The address may correspond to instruction in some inlined function,
359 // so we have to build the chain of inlined functions and take the
360 // name of the topmost function in it.
361 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
362 CU->getInlinedChainForAddress(Address);
363 if (InlinedChain.size() > 0) {
364 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
365 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
369 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
370 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
371 const bool NeedsAbsoluteFilePath =
372 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
373 getFileLineInfoForCompileUnit(CU, LineTable, Address,
374 NeedsAbsoluteFilePath,
375 FileName, Line, Column);
377 return DILineInfo(StringRef(FileName), StringRef(FunctionName),
381 DILineInfoTable DWARFContext::getLineInfoForAddressRange(uint64_t Address,
383 DILineInfoSpecifier Specifier) {
384 DILineInfoTable Lines;
385 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
389 std::string FunctionName = "<invalid>";
390 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
391 // The address may correspond to instruction in some inlined function,
392 // so we have to build the chain of inlined functions and take the
393 // name of the topmost function in it.
394 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
395 CU->getInlinedChainForAddress(Address);
396 if (InlinedChain.size() > 0) {
397 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
398 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
403 StringRef FuncNameRef = StringRef(FunctionName);
405 // If the Specifier says we don't need FileLineInfo, just
406 // return the top-most function at the starting address.
407 if (!Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
408 Lines.push_back(std::make_pair(Address,
409 DILineInfo(StringRef("<invalid>"),
410 FuncNameRef, 0, 0)));
414 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
415 const bool NeedsAbsoluteFilePath =
416 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
418 // Get the index of row we're looking for in the line table.
419 std::vector<uint32_t> RowVector;
420 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
423 uint32_t NumRows = RowVector.size();
424 for (uint32_t i = 0; i < NumRows; ++i) {
425 uint32_t RowIndex = RowVector[i];
426 // Take file number and line/column from the row.
427 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
428 std::string FileName = "<invalid>";
429 getFileNameForCompileUnit(CU, LineTable, Row.File,
430 NeedsAbsoluteFilePath, FileName);
431 Lines.push_back(std::make_pair(Row.Address,
432 DILineInfo(StringRef(FileName),
433 FuncNameRef, Row.Line, Row.Column)));
439 DIInliningInfo DWARFContext::getInliningInfoForAddress(uint64_t Address,
440 DILineInfoSpecifier Specifier) {
441 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
443 return DIInliningInfo();
445 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
446 CU->getInlinedChainForAddress(Address);
447 if (InlinedChain.size() == 0)
448 return DIInliningInfo();
450 DIInliningInfo InliningInfo;
451 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
452 const DWARFLineTable *LineTable = 0;
453 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
454 const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain[i];
455 std::string FileName = "<invalid>";
456 std::string FunctionName = "<invalid>";
459 // Get function name if necessary.
460 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
461 if (const char *Name = FunctionDIE.getSubroutineName(CU))
464 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
465 const bool NeedsAbsoluteFilePath =
466 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
468 // For the topmost frame, initialize the line table of this
469 // compile unit and fetch file/line info from it.
470 LineTable = getLineTableForCompileUnit(CU);
471 // For the topmost routine, get file/line info from line table.
472 getFileLineInfoForCompileUnit(CU, LineTable, Address,
473 NeedsAbsoluteFilePath,
474 FileName, Line, Column);
476 // Otherwise, use call file, call line and call column from
477 // previous DIE in inlined chain.
478 getFileNameForCompileUnit(CU, LineTable, CallFile,
479 NeedsAbsoluteFilePath, FileName);
483 // Get call file/line/column of a current DIE.
485 FunctionDIE.getCallerFrame(CU, CallFile, CallLine, CallColumn);
488 DILineInfo Frame(StringRef(FileName), StringRef(FunctionName),
490 InliningInfo.addFrame(Frame);
495 static bool consumeCompressedDebugSectionHeader(StringRef &data,
496 uint64_t &OriginalSize) {
497 // Consume "ZLIB" prefix.
498 if (!data.startswith("ZLIB"))
500 data = data.substr(4);
501 // Consume uncompressed section size (big-endian 8 bytes).
502 DataExtractor extractor(data, false, 8);
504 OriginalSize = extractor.getU64(&Offset);
507 data = data.substr(Offset);
511 DWARFContextInMemory::DWARFContextInMemory(object::ObjectFile *Obj) :
512 IsLittleEndian(Obj->isLittleEndian()),
513 AddressSize(Obj->getBytesInAddress()) {
515 for (object::section_iterator i = Obj->begin_sections(),
516 e = Obj->end_sections();
517 i != e; i.increment(ec)) {
521 i->getContents(data);
523 name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
525 // Check if debug info section is compressed with zlib.
526 if (name.startswith("zdebug_")) {
527 uint64_t OriginalSize;
528 if (!zlib::isAvailable() ||
529 !consumeCompressedDebugSectionHeader(data, OriginalSize))
531 OwningPtr<MemoryBuffer> UncompressedSection;
532 if (zlib::uncompress(data, UncompressedSection, OriginalSize) !=
535 // Make data point to uncompressed section contents and save its contents.
536 name = name.substr(1);
537 data = UncompressedSection->getBuffer();
538 UncompressedSections.push_back(UncompressedSection.take());
541 StringRef *Section = StringSwitch<StringRef*>(name)
542 .Case("debug_info", &InfoSection)
543 .Case("debug_abbrev", &AbbrevSection)
544 .Case("debug_line", &LineSection)
545 .Case("debug_aranges", &ARangeSection)
546 .Case("debug_frame", &DebugFrameSection)
547 .Case("debug_str", &StringSection)
548 .Case("debug_ranges", &RangeSection)
549 .Case("debug_pubnames", &PubNamesSection)
550 .Case("debug_info.dwo", &InfoDWOSection)
551 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
552 .Case("debug_str.dwo", &StringDWOSection)
553 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
554 .Case("debug_addr", &AddrSection)
555 // Any more debug info sections go here.
560 if (name == "debug_ranges") {
561 // FIXME: Use the other dwo range section when we emit it.
562 RangeDWOSection = data;
565 // TODO: Add support for relocations in other sections as needed.
566 // Record relocations for the debug_info and debug_line sections.
567 RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(name)
568 .Case("debug_info", &InfoRelocMap)
569 .Case("debug_info.dwo", &InfoDWORelocMap)
570 .Case("debug_line", &LineRelocMap)
575 if (i->begin_relocations() != i->end_relocations()) {
576 uint64_t SectionSize;
577 i->getSize(SectionSize);
578 for (object::relocation_iterator reloc_i = i->begin_relocations(),
579 reloc_e = i->end_relocations();
580 reloc_i != reloc_e; reloc_i.increment(ec)) {
582 reloc_i->getOffset(Address);
584 reloc_i->getType(Type);
585 uint64_t SymAddr = 0;
586 // ELF relocations may need the symbol address
588 object::SymbolRef Sym;
589 reloc_i->getSymbol(Sym);
590 Sym.getAddress(SymAddr);
593 object::RelocVisitor V(Obj->getFileFormatName());
594 // The section address is always 0 for debug sections.
595 object::RelocToApply R(V.visit(Type, *reloc_i, 0, SymAddr));
597 SmallString<32> Name;
598 error_code ec(reloc_i->getTypeName(Name));
600 errs() << "Aaaaaa! Nameless relocation! Aaaaaa!\n";
602 errs() << "error: failed to compute relocation: "
607 if (Address + R.Width > SectionSize) {
608 errs() << "error: " << R.Width << "-byte relocation starting "
609 << Address << " bytes into section " << name << " which is "
610 << SectionSize << " bytes long.\n";
614 errs() << "error: can't handle a relocation of more than 8 bytes at "
618 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
619 << " at " << format("%p", Address)
620 << " with width " << format("%d", R.Width)
622 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
628 DWARFContextInMemory::~DWARFContextInMemory() {
629 DeleteContainerPointers(UncompressedSections);
632 void DWARFContextInMemory::anchor() { }