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/Support/Dwarf.h"
13 #include "llvm/Support/Format.h"
14 #include "llvm/Support/Path.h"
15 #include "llvm/Support/raw_ostream.h"
18 using namespace dwarf;
20 typedef DWARFDebugLine::LineTable DWARFLineTable;
22 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
23 if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
24 OS << ".debug_abbrev contents:\n";
25 getDebugAbbrev()->dump(OS);
28 if (DumpType == DIDT_All || DumpType == DIDT_Info) {
29 OS << "\n.debug_info contents:\n";
30 for (unsigned i = 0, e = getNumCompileUnits(); i != e; ++i)
31 getCompileUnitAtIndex(i)->dump(OS);
35 if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
36 OS << "\n.debug_aranges contents:\n";
37 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
38 DWARFDebugArangeSet set;
39 while (set.extract(arangesData, &offset))
43 uint8_t savedAddressByteSize = 0;
44 if (DumpType == DIDT_All || DumpType == DIDT_Line) {
45 OS << "\n.debug_line contents:\n";
46 for (unsigned i = 0, e = getNumCompileUnits(); i != e; ++i) {
47 DWARFCompileUnit *cu = getCompileUnitAtIndex(i);
48 savedAddressByteSize = cu->getAddressByteSize();
50 cu->getCompileUnitDIE()->getAttributeValueAsUnsigned(cu, DW_AT_stmt_list,
52 if (stmtOffset != -1U) {
53 DataExtractor lineData(getLineSection(), isLittleEndian(),
54 savedAddressByteSize);
55 DWARFDebugLine::DumpingState state(OS);
56 DWARFDebugLine::parseStatementTable(lineData, &lineRelocMap(), &stmtOffset, state);
61 if (DumpType == DIDT_All || DumpType == DIDT_Str) {
62 OS << "\n.debug_str contents:\n";
63 DataExtractor strData(getStringSection(), isLittleEndian(), 0);
65 uint32_t strOffset = 0;
66 while (const char *s = strData.getCStr(&offset)) {
67 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
72 if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
73 OS << "\n.debug_ranges contents:\n";
74 // In fact, different compile units may have different address byte
75 // sizes, but for simplicity we just use the address byte size of the last
76 // compile unit (there is no easy and fast way to associate address range
77 // list and the compile unit it describes).
78 DataExtractor rangesData(getRangeSection(), isLittleEndian(),
79 savedAddressByteSize);
81 DWARFDebugRangeList rangeList;
82 while (rangeList.extract(rangesData, &offset))
86 if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo) {
87 OS << "\n.debug_abbrev.dwo contents:\n";
88 getDebugAbbrevDWO()->dump(OS);
91 if (DumpType == DIDT_All || DumpType == DIDT_InfoDwo) {
92 OS << "\n.debug_info.dwo contents:\n";
93 for (unsigned i = 0, e = getNumDWOCompileUnits(); i != e; ++i)
94 getDWOCompileUnitAtIndex(i)->dump(OS);
97 if (DumpType == DIDT_All || DumpType == DIDT_StrDwo) {
98 OS << "\n.debug_str.dwo contents:\n";
99 DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
101 uint32_t strDWOOffset = 0;
102 while (const char *s = strDWOData.getCStr(&offset)) {
103 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
104 strDWOOffset = offset;
108 if (DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) {
109 OS << "\n.debug_str_offsets.dwo contents:\n";
110 DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(), 0);
112 while (offset < getStringOffsetDWOSection().size()) {
113 OS << format("0x%8.8x: ", offset);
114 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
119 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
123 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
125 Abbrev.reset(new DWARFDebugAbbrev());
126 Abbrev->parse(abbrData);
130 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
132 return AbbrevDWO.get();
134 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
135 AbbrevDWO.reset(new DWARFDebugAbbrev());
136 AbbrevDWO->parse(abbrData);
137 return AbbrevDWO.get();
140 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
142 return Aranges.get();
144 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
146 Aranges.reset(new DWARFDebugAranges());
147 Aranges->extract(arangesData);
148 // Generate aranges from DIEs: even if .debug_aranges section is present,
149 // it may describe only a small subset of compilation units, so we need to
150 // manually build aranges for the rest of them.
151 Aranges->generate(this);
152 return Aranges.get();
155 const DWARFLineTable *
156 DWARFContext::getLineTableForCompileUnit(DWARFCompileUnit *cu) {
158 Line.reset(new DWARFDebugLine(&lineRelocMap()));
160 unsigned stmtOffset =
161 cu->getCompileUnitDIE()->getAttributeValueAsUnsigned(cu, DW_AT_stmt_list,
163 if (stmtOffset == -1U)
164 return 0; // No line table for this compile unit.
166 // See if the line table is cached.
167 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
170 // We have to parse it first.
171 DataExtractor lineData(getLineSection(), isLittleEndian(),
172 cu->getAddressByteSize());
173 return Line->getOrParseLineTable(lineData, stmtOffset);
176 void DWARFContext::parseCompileUnits() {
178 const DataExtractor &DIData = DataExtractor(getInfoSection(),
179 isLittleEndian(), 0);
180 while (DIData.isValidOffset(offset)) {
181 CUs.push_back(DWARFCompileUnit(getDebugAbbrev(), getInfoSection(),
182 getAbbrevSection(), getRangeSection(),
183 getStringSection(), StringRef(),
187 if (!CUs.back().extract(DIData, &offset)) {
192 offset = CUs.back().getNextCompileUnitOffset();
196 void DWARFContext::parseDWOCompileUnits() {
198 const DataExtractor &DIData = DataExtractor(getInfoDWOSection(),
199 isLittleEndian(), 0);
200 while (DIData.isValidOffset(offset)) {
201 DWOCUs.push_back(DWARFCompileUnit(getDebugAbbrevDWO(), getInfoDWOSection(),
202 getAbbrevDWOSection(),
203 getRangeDWOSection(),
204 getStringDWOSection(),
205 getStringOffsetDWOSection(),
209 if (!DWOCUs.back().extract(DIData, &offset)) {
214 offset = DWOCUs.back().getNextCompileUnitOffset();
219 struct OffsetComparator {
220 bool operator()(const DWARFCompileUnit &LHS,
221 const DWARFCompileUnit &RHS) const {
222 return LHS.getOffset() < RHS.getOffset();
224 bool operator()(const DWARFCompileUnit &LHS, uint32_t RHS) const {
225 return LHS.getOffset() < RHS;
227 bool operator()(uint32_t LHS, const DWARFCompileUnit &RHS) const {
228 return LHS < RHS.getOffset();
233 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
237 DWARFCompileUnit *CU = std::lower_bound(CUs.begin(), CUs.end(), Offset,
244 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
245 // First, get the offset of the compile unit.
246 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
247 // Retrieve the compile unit.
248 return getCompileUnitForOffset(CUOffset);
251 static bool getFileNameForCompileUnit(DWARFCompileUnit *CU,
252 const DWARFLineTable *LineTable,
254 bool NeedsAbsoluteFilePath,
255 std::string &FileName) {
258 !LineTable->getFileNameByIndex(FileIndex, NeedsAbsoluteFilePath,
261 if (NeedsAbsoluteFilePath && sys::path::is_relative(FileName)) {
262 // We may still need to append compilation directory of compile unit.
263 SmallString<16> AbsolutePath;
264 if (const char *CompilationDir = CU->getCompilationDir()) {
265 sys::path::append(AbsolutePath, CompilationDir);
267 sys::path::append(AbsolutePath, FileName);
268 FileName = AbsolutePath.str();
273 static bool getFileLineInfoForCompileUnit(DWARFCompileUnit *CU,
274 const DWARFLineTable *LineTable,
276 bool NeedsAbsoluteFilePath,
277 std::string &FileName,
278 uint32_t &Line, uint32_t &Column) {
279 if (CU == 0 || LineTable == 0)
281 // Get the index of row we're looking for in the line table.
282 uint32_t RowIndex = LineTable->lookupAddress(Address);
285 // Take file number and line/column from the row.
286 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
287 if (!getFileNameForCompileUnit(CU, LineTable, Row.File,
288 NeedsAbsoluteFilePath, FileName))
295 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
296 DILineInfoSpecifier Specifier) {
297 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
300 std::string FileName = "<invalid>";
301 std::string FunctionName = "<invalid>";
304 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
305 // The address may correspond to instruction in some inlined function,
306 // so we have to build the chain of inlined functions and take the
307 // name of the topmost function in it.
308 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
309 CU->getInlinedChainForAddress(Address);
310 if (InlinedChain.size() > 0) {
311 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
312 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
316 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
317 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
318 const bool NeedsAbsoluteFilePath =
319 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
320 getFileLineInfoForCompileUnit(CU, LineTable, Address,
321 NeedsAbsoluteFilePath,
322 FileName, Line, Column);
324 return DILineInfo(StringRef(FileName), StringRef(FunctionName),
328 DILineInfoTable DWARFContext::getLineInfoForAddressRange(uint64_t Address,
330 DILineInfoSpecifier Specifier) {
331 DILineInfoTable Lines;
332 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
336 std::string FunctionName = "<invalid>";
337 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
338 // The address may correspond to instruction in some inlined function,
339 // so we have to build the chain of inlined functions and take the
340 // name of the topmost function in it.
341 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
342 CU->getInlinedChainForAddress(Address);
343 if (InlinedChain.size() > 0) {
344 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain[0];
345 if (const char *Name = TopFunctionDIE.getSubroutineName(CU))
350 StringRef FuncNameRef = StringRef(FunctionName);
352 // If the Specifier says we don't need FileLineInfo, just
353 // return the top-most function at the starting address.
354 if (!Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
355 Lines.push_back(std::make_pair(Address,
356 DILineInfo(StringRef("<invalid>"),
357 FuncNameRef, 0, 0)));
361 const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
362 const bool NeedsAbsoluteFilePath =
363 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
365 // Get the index of row we're looking for in the line table.
366 std::vector<uint32_t> RowVector;
367 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
370 uint32_t NumRows = RowVector.size();
371 for (uint32_t i = 0; i < NumRows; ++i) {
372 uint32_t RowIndex = RowVector[i];
373 // Take file number and line/column from the row.
374 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
375 std::string FileName = "<invalid>";
376 getFileNameForCompileUnit(CU, LineTable, Row.File,
377 NeedsAbsoluteFilePath, FileName);
378 Lines.push_back(std::make_pair(Row.Address,
379 DILineInfo(StringRef(FileName),
380 FuncNameRef, Row.Line, Row.Column)));
386 DIInliningInfo DWARFContext::getInliningInfoForAddress(uint64_t Address,
387 DILineInfoSpecifier Specifier) {
388 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
390 return DIInliningInfo();
392 const DWARFDebugInfoEntryMinimal::InlinedChain &InlinedChain =
393 CU->getInlinedChainForAddress(Address);
394 if (InlinedChain.size() == 0)
395 return DIInliningInfo();
397 DIInliningInfo InliningInfo;
398 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
399 const DWARFLineTable *LineTable = 0;
400 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
401 const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain[i];
402 std::string FileName = "<invalid>";
403 std::string FunctionName = "<invalid>";
406 // Get function name if necessary.
407 if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
408 if (const char *Name = FunctionDIE.getSubroutineName(CU))
411 if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
412 const bool NeedsAbsoluteFilePath =
413 Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
415 // For the topmost frame, initialize the line table of this
416 // compile unit and fetch file/line info from it.
417 LineTable = getLineTableForCompileUnit(CU);
418 // For the topmost routine, get file/line info from line table.
419 getFileLineInfoForCompileUnit(CU, LineTable, Address,
420 NeedsAbsoluteFilePath,
421 FileName, Line, Column);
423 // Otherwise, use call file, call line and call column from
424 // previous DIE in inlined chain.
425 getFileNameForCompileUnit(CU, LineTable, CallFile,
426 NeedsAbsoluteFilePath, FileName);
430 // Get call file/line/column of a current DIE.
432 FunctionDIE.getCallerFrame(CU, CallFile, CallLine, CallColumn);
435 DILineInfo Frame(StringRef(FileName), StringRef(FunctionName),
437 InliningInfo.addFrame(Frame);
442 DWARFContextInMemory::DWARFContextInMemory(object::ObjectFile *Obj) :
443 IsLittleEndian(Obj->isLittleEndian()) {
445 for (object::section_iterator i = Obj->begin_sections(),
446 e = Obj->end_sections();
447 i != e; i.increment(ec)) {
451 i->getContents(data);
453 name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
454 if (name == "debug_info")
456 else if (name == "debug_abbrev")
457 AbbrevSection = data;
458 else if (name == "debug_line")
460 else if (name == "debug_aranges")
461 ARangeSection = data;
462 else if (name == "debug_str")
463 StringSection = data;
464 else if (name == "debug_ranges") {
465 // FIXME: Use the other dwo range section when we emit it.
466 RangeDWOSection = data;
469 else if (name == "debug_info.dwo")
470 InfoDWOSection = data;
471 else if (name == "debug_abbrev.dwo")
472 AbbrevDWOSection = data;
473 else if (name == "debug_str.dwo")
474 StringDWOSection = data;
475 else if (name == "debug_str_offsets.dwo")
476 StringOffsetDWOSection = data;
477 else if (name == "debug_addr")
479 // Any more debug info sections go here.
483 // TODO: Add support for relocations in other sections as needed.
484 // Record relocations for the debug_info and debug_line sections.
486 if (name == "debug_info")
488 else if (name == "debug_info.dwo")
489 Map = &InfoDWORelocMap;
490 else if (name == "debug_line")
495 if (i->begin_relocations() != i->end_relocations()) {
496 uint64_t SectionSize;
497 i->getSize(SectionSize);
498 for (object::relocation_iterator reloc_i = i->begin_relocations(),
499 reloc_e = i->end_relocations();
500 reloc_i != reloc_e; reloc_i.increment(ec)) {
502 reloc_i->getAddress(Address);
504 reloc_i->getType(Type);
505 uint64_t SymAddr = 0;
506 // ELF relocations may need the symbol address
508 object::SymbolRef Sym;
509 reloc_i->getSymbol(Sym);
510 Sym.getAddress(SymAddr);
513 object::RelocVisitor V(Obj->getFileFormatName());
514 // The section address is always 0 for debug sections.
515 object::RelocToApply R(V.visit(Type, *reloc_i, 0, SymAddr));
517 SmallString<32> Name;
518 error_code ec(reloc_i->getTypeName(Name));
520 errs() << "Aaaaaa! Nameless relocation! Aaaaaa!\n";
522 errs() << "error: failed to compute relocation: "
527 if (Address + R.Width > SectionSize) {
528 errs() << "error: " << R.Width << "-byte relocation starting "
529 << Address << " bytes into section " << name << " which is "
530 << SectionSize << " bytes long.\n";
534 errs() << "error: can't handle a relocation of more than 8 bytes at "
538 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
539 << " at " << format("%p", Address)
540 << " with width " << format("%d", R.Width)
542 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
548 void DWARFContextInMemory::anchor() { }