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 while (offset < getStringOffsetDWOSection().size()) {
145 OS << format("0x%8.8x: ", offset);
146 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
151 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
155 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
157 Abbrev.reset(new DWARFDebugAbbrev());
158 Abbrev->parse(abbrData);
162 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
164 return AbbrevDWO.get();
166 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
167 AbbrevDWO.reset(new DWARFDebugAbbrev());
168 AbbrevDWO->parse(abbrData);
169 return AbbrevDWO.get();
172 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
174 return Aranges.get();
176 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
178 Aranges.reset(new DWARFDebugAranges());
179 Aranges->extract(arangesData);
180 // Generate aranges from DIEs: even if .debug_aranges section is present,
181 // it may describe only a small subset of compilation units, so we need to
182 // manually build aranges for the rest of them.
183 Aranges->generate(this);
184 return Aranges.get();
187 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
189 return DebugFrame.get();
191 // There's a "bug" in the DWARFv3 standard with respect to the target address
192 // size within debug frame sections. While DWARF is supposed to be independent
193 // of its container, FDEs have fields with size being "target address size",
194 // which isn't specified in DWARF in general. It's only specified for CUs, but
195 // .eh_frame can appear without a .debug_info section. Follow the example of
196 // other tools (libdwarf) and extract this from the container (ObjectFile
197 // provides this information). This problem is fixed in DWARFv4
198 // See this dwarf-discuss discussion for more details:
199 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
200 DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
202 DebugFrame.reset(new DWARFDebugFrame());
203 DebugFrame->parse(debugFrameData);
204 return DebugFrame.get();
207 const DWARFLineTable *
208 DWARFContext::getLineTableForCompileUnit(DWARFCompileUnit *cu) {
210 Line.reset(new DWARFDebugLine(&lineRelocMap()));
212 unsigned stmtOffset =
213 cu->getCompileUnitDIE()->getAttributeValueAsUnsigned(cu, DW_AT_stmt_list,
215 if (stmtOffset == -1U)
216 return 0; // No line table for this compile unit.
218 // See if the line table is cached.
219 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
222 // We have to parse it first.
223 DataExtractor lineData(getLineSection(), isLittleEndian(),
224 cu->getAddressByteSize());
225 return Line->getOrParseLineTable(lineData, stmtOffset);
228 void DWARFContext::parseCompileUnits() {
230 const DataExtractor &DIData = DataExtractor(getInfoSection(),
231 isLittleEndian(), 0);
232 while (DIData.isValidOffset(offset)) {
233 CUs.push_back(DWARFCompileUnit(getDebugAbbrev(), getInfoSection(),
234 getAbbrevSection(), getRangeSection(),
235 getStringSection(), StringRef(),
239 if (!CUs.back().extract(DIData, &offset)) {
244 offset = CUs.back().getNextCompileUnitOffset();
248 void DWARFContext::parseDWOCompileUnits() {
250 const DataExtractor &DIData = DataExtractor(getInfoDWOSection(),
251 isLittleEndian(), 0);
252 while (DIData.isValidOffset(offset)) {
253 DWOCUs.push_back(DWARFCompileUnit(getDebugAbbrevDWO(), getInfoDWOSection(),
254 getAbbrevDWOSection(),
255 getRangeDWOSection(),
256 getStringDWOSection(),
257 getStringOffsetDWOSection(),
261 if (!DWOCUs.back().extract(DIData, &offset)) {
266 offset = DWOCUs.back().getNextCompileUnitOffset();
271 struct OffsetComparator {
272 bool operator()(const DWARFCompileUnit &LHS,
273 const DWARFCompileUnit &RHS) const {
274 return LHS.getOffset() < RHS.getOffset();
276 bool operator()(const DWARFCompileUnit &LHS, uint32_t RHS) const {
277 return LHS.getOffset() < RHS;
279 bool operator()(uint32_t LHS, const DWARFCompileUnit &RHS) const {
280 return LHS < RHS.getOffset();
285 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
289 DWARFCompileUnit *CU = std::lower_bound(CUs.begin(), CUs.end(), Offset,
296 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
297 // First, get the offset of the compile unit.
298 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
299 // Retrieve the compile unit.
300 return getCompileUnitForOffset(CUOffset);
303 static bool getFileNameForCompileUnit(DWARFCompileUnit *CU,
304 const DWARFLineTable *LineTable,
306 bool NeedsAbsoluteFilePath,
307 std::string &FileName) {
310 !LineTable->getFileNameByIndex(FileIndex, NeedsAbsoluteFilePath,
313 if (NeedsAbsoluteFilePath && sys::path::is_relative(FileName)) {
314 // We may still need to append compilation directory of compile unit.
315 SmallString<16> AbsolutePath;
316 if (const char *CompilationDir = CU->getCompilationDir()) {
317 sys::path::append(AbsolutePath, CompilationDir);
319 sys::path::append(AbsolutePath, FileName);
320 FileName = AbsolutePath.str();
325 static bool getFileLineInfoForCompileUnit(DWARFCompileUnit *CU,
326 const DWARFLineTable *LineTable,
328 bool NeedsAbsoluteFilePath,
329 std::string &FileName,
330 uint32_t &Line, uint32_t &Column) {
331 if (CU == 0 || LineTable == 0)
333 // Get the index of row we're looking for in the line table.
334 uint32_t RowIndex = LineTable->lookupAddress(Address);
337 // Take file number and line/column from the row.
338 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
339 if (!getFileNameForCompileUnit(CU, LineTable, Row.File,
340 NeedsAbsoluteFilePath, FileName))
347 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
348 DILineInfoSpecifier Specifier) {
349 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
352 std::string FileName = "<invalid>";
353 std::string FunctionName = "<invalid>";
356 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
357 // The address may correspond to instruction in some inlined function,
358 // so we have to build the chain of inlined functions and take the
359 // name of the topmost function in it.
360 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
361 CU->getInlinedChainForAddress(Address);
362 if (InlinedChain.size() > 0) {
363 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
364 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
368 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
369 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
370 const bool NeedsAbsoluteFilePath =
371 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
372 getFileLineInfoForCompileUnit(CU, LineTable, Address,
373 NeedsAbsoluteFilePath,
374 FileName, Line, Column);
376 return DILineInfo(StringRef(FileName), StringRef(FunctionName),
380 DILineInfoTable DWARFContext::getLineInfoForAddressRange(uint64_t Address,
382 DILineInfoSpecifier Specifier) {
383 DILineInfoTable Lines;
384 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
388 std::string FunctionName = "<invalid>";
389 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
390 // The address may correspond to instruction in some inlined function,
391 // so we have to build the chain of inlined functions and take the
392 // name of the topmost function in it.
393 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
394 CU->getInlinedChainForAddress(Address);
395 if (InlinedChain.size() > 0) {
396 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
397 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
402 StringRef FuncNameRef = StringRef(FunctionName);
404 // If the Specifier says we don't need FileLineInfo, just
405 // return the top-most function at the starting address.
406 if (!Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
407 Lines.push_back(std::make_pair(Address,
408 DILineInfo(StringRef("<invalid>"),
409 FuncNameRef, 0, 0)));
413 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
414 const bool NeedsAbsoluteFilePath =
415 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
417 // Get the index of row we're looking for in the line table.
418 std::vector<uint32_t> RowVector;
419 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
422 uint32_t NumRows = RowVector.size();
423 for (uint32_t i = 0; i < NumRows; ++i) {
424 uint32_t RowIndex = RowVector[i];
425 // Take file number and line/column from the row.
426 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
427 std::string FileName = "<invalid>";
428 getFileNameForCompileUnit(CU, LineTable, Row.File,
429 NeedsAbsoluteFilePath, FileName);
430 Lines.push_back(std::make_pair(Row.Address,
431 DILineInfo(StringRef(FileName),
432 FuncNameRef, Row.Line, Row.Column)));
438 DIInliningInfo DWARFContext::getInliningInfoForAddress(uint64_t Address,
439 DILineInfoSpecifier Specifier) {
440 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
442 return DIInliningInfo();
444 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
445 CU->getInlinedChainForAddress(Address);
446 if (InlinedChain.size() == 0)
447 return DIInliningInfo();
449 DIInliningInfo InliningInfo;
450 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
451 const DWARFLineTable *LineTable = 0;
452 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
453 const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain[i];
454 std::string FileName = "<invalid>";
455 std::string FunctionName = "<invalid>";
458 // Get function name if necessary.
459 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
460 if (const char *Name = FunctionDIE.getSubroutineName(CU))
463 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
464 const bool NeedsAbsoluteFilePath =
465 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
467 // For the topmost frame, initialize the line table of this
468 // compile unit and fetch file/line info from it.
469 LineTable = getLineTableForCompileUnit(CU);
470 // For the topmost routine, get file/line info from line table.
471 getFileLineInfoForCompileUnit(CU, LineTable, Address,
472 NeedsAbsoluteFilePath,
473 FileName, Line, Column);
475 // Otherwise, use call file, call line and call column from
476 // previous DIE in inlined chain.
477 getFileNameForCompileUnit(CU, LineTable, CallFile,
478 NeedsAbsoluteFilePath, FileName);
482 // Get call file/line/column of a current DIE.
484 FunctionDIE.getCallerFrame(CU, CallFile, CallLine, CallColumn);
487 DILineInfo Frame(StringRef(FileName), StringRef(FunctionName),
489 InliningInfo.addFrame(Frame);
494 static bool consumeCompressedDebugSectionHeader(StringRef &data,
495 uint64_t &OriginalSize) {
496 // Consume "ZLIB" prefix.
497 if (!data.startswith("ZLIB"))
499 data = data.substr(4);
500 // Consume uncompressed section size (big-endian 8 bytes).
501 DataExtractor extractor(data, false, 8);
503 OriginalSize = extractor.getU64(&Offset);
506 data = data.substr(Offset);
510 DWARFContextInMemory::DWARFContextInMemory(object::ObjectFile *Obj) :
511 IsLittleEndian(Obj->isLittleEndian()),
512 AddressSize(Obj->getBytesInAddress()) {
514 for (object::section_iterator i = Obj->begin_sections(),
515 e = Obj->end_sections();
516 i != e; i.increment(ec)) {
520 i->getContents(data);
522 name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
524 // Check if debug info section is compressed with zlib.
525 if (name.startswith("zdebug_")) {
526 uint64_t OriginalSize;
527 if (!zlib::isAvailable() ||
528 !consumeCompressedDebugSectionHeader(data, OriginalSize))
530 OwningPtr<MemoryBuffer> UncompressedSection;
531 if (zlib::uncompress(data, UncompressedSection, OriginalSize) !=
534 // Make data point to uncompressed section contents and save its contents.
535 name = name.substr(1);
536 data = UncompressedSection->getBuffer();
537 UncompressedSections.push_back(UncompressedSection.take());
540 StringRef *Section = StringSwitch<StringRef*>(name)
541 .Case("debug_info", &InfoSection)
542 .Case("debug_abbrev", &AbbrevSection)
543 .Case("debug_line", &LineSection)
544 .Case("debug_aranges", &ARangeSection)
545 .Case("debug_frame", &DebugFrameSection)
546 .Case("debug_str", &StringSection)
547 .Case("debug_ranges", &RangeSection)
548 .Case("debug_pubnames", &PubNamesSection)
549 .Case("debug_info.dwo", &InfoDWOSection)
550 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
551 .Case("debug_str.dwo", &StringDWOSection)
552 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
553 .Case("debug_addr", &AddrSection)
554 // Any more debug info sections go here.
559 if (name == "debug_ranges") {
560 // FIXME: Use the other dwo range section when we emit it.
561 RangeDWOSection = data;
564 // TODO: Add support for relocations in other sections as needed.
565 // Record relocations for the debug_info and debug_line sections.
566 RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(name)
567 .Case("debug_info", &InfoRelocMap)
568 .Case("debug_info.dwo", &InfoDWORelocMap)
569 .Case("debug_line", &LineRelocMap)
574 if (i->begin_relocations() != i->end_relocations()) {
575 uint64_t SectionSize;
576 i->getSize(SectionSize);
577 for (object::relocation_iterator reloc_i = i->begin_relocations(),
578 reloc_e = i->end_relocations();
579 reloc_i != reloc_e; reloc_i.increment(ec)) {
581 reloc_i->getOffset(Address);
583 reloc_i->getType(Type);
584 uint64_t SymAddr = 0;
585 // ELF relocations may need the symbol address
587 object::SymbolRef Sym;
588 reloc_i->getSymbol(Sym);
589 Sym.getAddress(SymAddr);
592 object::RelocVisitor V(Obj->getFileFormatName());
593 // The section address is always 0 for debug sections.
594 object::RelocToApply R(V.visit(Type, *reloc_i, 0, SymAddr));
596 SmallString<32> Name;
597 error_code ec(reloc_i->getTypeName(Name));
599 errs() << "Aaaaaa! Nameless relocation! Aaaaaa!\n";
601 errs() << "error: failed to compute relocation: "
606 if (Address + R.Width > SectionSize) {
607 errs() << "error: " << R.Width << "-byte relocation starting "
608 << Address << " bytes into section " << name << " which is "
609 << SectionSize << " bytes long.\n";
613 errs() << "error: can't handle a relocation of more than 8 bytes at "
617 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
618 << " at " << format("%p", Address)
619 << " with width " << format("%d", R.Width)
621 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
627 DWARFContextInMemory::~DWARFContextInMemory() {
628 DeleteContainerPointers(UncompressedSections);
631 void DWARFContextInMemory::anchor() { }