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 "llvm/DebugInfo/DWARF/DWARFContext.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
14 #include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
15 #include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
16 #include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
17 #include "llvm/Object/Decompressor.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Object/RelocVisitor.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/Dwarf.h"
22 #include "llvm/Support/ELF.h"
23 #include "llvm/Support/Format.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/raw_ostream.h"
28 using namespace dwarf;
29 using namespace object;
31 #define DEBUG_TYPE "dwarf"
33 typedef DWARFDebugLine::LineTable DWARFLineTable;
34 typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
35 typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
37 static void dumpAccelSection(raw_ostream &OS, StringRef Name,
38 const DWARFSection& Section, StringRef StringSection,
40 DataExtractor AccelSection(Section.Data, LittleEndian, 0);
41 DataExtractor StrData(StringSection, LittleEndian, 0);
42 OS << "\n." << Name << " contents:\n";
43 DWARFAcceleratorTable Accel(AccelSection, StrData, Section.Relocs);
49 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType, bool DumpEH,
50 bool SummarizeTypes) {
51 if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
52 OS << ".debug_abbrev contents:\n";
53 getDebugAbbrev()->dump(OS);
56 if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
57 if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
58 OS << "\n.debug_abbrev.dwo contents:\n";
62 if (DumpType == DIDT_All || DumpType == DIDT_Info) {
63 OS << "\n.debug_info contents:\n";
64 for (const auto &CU : compile_units())
68 if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
69 getNumDWOCompileUnits()) {
70 OS << "\n.debug_info.dwo contents:\n";
71 for (const auto &DWOCU : dwo_compile_units())
75 if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
76 OS << "\n.debug_types contents:\n";
77 for (const auto &TUS : type_unit_sections())
78 for (const auto &TU : TUS)
79 TU->dump(OS, SummarizeTypes);
82 if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
83 getNumDWOTypeUnits()) {
84 OS << "\n.debug_types.dwo contents:\n";
85 for (const auto &DWOTUS : dwo_type_unit_sections())
86 for (const auto &DWOTU : DWOTUS)
87 DWOTU->dump(OS, SummarizeTypes);
90 if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
91 OS << "\n.debug_loc contents:\n";
92 getDebugLoc()->dump(OS);
95 if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
96 OS << "\n.debug_loc.dwo contents:\n";
97 getDebugLocDWO()->dump(OS);
100 if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
101 OS << "\n.debug_frame contents:\n";
102 getDebugFrame()->dump(OS);
104 OS << "\n.eh_frame contents:\n";
105 getEHFrame()->dump(OS);
109 if (DumpType == DIDT_All || DumpType == DIDT_Macro) {
110 OS << "\n.debug_macinfo contents:\n";
111 getDebugMacro()->dump(OS);
115 if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
116 OS << "\n.debug_aranges contents:\n";
117 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
118 DWARFDebugArangeSet set;
119 while (set.extract(arangesData, &offset))
123 uint8_t savedAddressByteSize = 0;
124 if (DumpType == DIDT_All || DumpType == DIDT_Line) {
125 OS << "\n.debug_line contents:\n";
126 for (const auto &CU : compile_units()) {
127 savedAddressByteSize = CU->getAddressByteSize();
128 auto CUDIE = CU->getUnitDIE();
131 if (auto StmtOffset =
132 CUDIE.getAttributeValueAsSectionOffset(DW_AT_stmt_list)) {
133 DataExtractor lineData(getLineSection().Data, isLittleEndian(),
134 savedAddressByteSize);
135 DWARFDebugLine::LineTable LineTable;
136 uint32_t Offset = *StmtOffset;
137 LineTable.parse(lineData, &getLineSection().Relocs, &Offset);
143 if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
144 OS << "\n.debug_cu_index contents:\n";
145 getCUIndex().dump(OS);
148 if (DumpType == DIDT_All || DumpType == DIDT_TUIndex) {
149 OS << "\n.debug_tu_index contents:\n";
150 getTUIndex().dump(OS);
153 if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
154 OS << "\n.debug_line.dwo contents:\n";
155 unsigned stmtOffset = 0;
156 DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
157 savedAddressByteSize);
158 DWARFDebugLine::LineTable LineTable;
159 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
165 if (DumpType == DIDT_All || DumpType == DIDT_Str) {
166 OS << "\n.debug_str contents:\n";
167 DataExtractor strData(getStringSection(), isLittleEndian(), 0);
169 uint32_t strOffset = 0;
170 while (const char *s = strData.getCStr(&offset)) {
171 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
176 if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
177 !getStringDWOSection().empty()) {
178 OS << "\n.debug_str.dwo contents:\n";
179 DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
181 uint32_t strDWOOffset = 0;
182 while (const char *s = strDWOData.getCStr(&offset)) {
183 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
184 strDWOOffset = offset;
188 if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
189 OS << "\n.debug_ranges contents:\n";
190 // In fact, different compile units may have different address byte
191 // sizes, but for simplicity we just use the address byte size of the last
192 // compile unit (there is no easy and fast way to associate address range
193 // list and the compile unit it describes).
194 DataExtractor rangesData(getRangeSection(), isLittleEndian(),
195 savedAddressByteSize);
197 DWARFDebugRangeList rangeList;
198 while (rangeList.extract(rangesData, &offset))
202 if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
203 DWARFDebugPubTable(getPubNamesSection(), isLittleEndian(), false)
204 .dump("debug_pubnames", OS);
206 if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
207 DWARFDebugPubTable(getPubTypesSection(), isLittleEndian(), false)
208 .dump("debug_pubtypes", OS);
210 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
211 DWARFDebugPubTable(getGnuPubNamesSection(), isLittleEndian(),
213 .dump("debug_gnu_pubnames", OS);
215 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
216 DWARFDebugPubTable(getGnuPubTypesSection(), isLittleEndian(),
218 .dump("debug_gnu_pubtypes", OS);
220 if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
221 !getStringOffsetDWOSection().empty()) {
222 OS << "\n.debug_str_offsets.dwo contents:\n";
223 DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
226 uint64_t size = getStringOffsetDWOSection().size();
227 while (offset < size) {
228 OS << format("0x%8.8x: ", offset);
229 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
233 if ((DumpType == DIDT_All || DumpType == DIDT_GdbIndex) &&
234 !getGdbIndexSection().empty()) {
235 OS << "\n.gnu_index contents:\n";
236 getGdbIndex().dump(OS);
239 if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
240 dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
241 getStringSection(), isLittleEndian());
243 if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
244 dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
245 getStringSection(), isLittleEndian());
247 if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
248 dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
249 getStringSection(), isLittleEndian());
251 if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
252 dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
253 getStringSection(), isLittleEndian());
256 const DWARFUnitIndex &DWARFContext::getCUIndex() {
260 DataExtractor CUIndexData(getCUIndexSection(), isLittleEndian(), 0);
262 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
263 CUIndex->parse(CUIndexData);
267 const DWARFUnitIndex &DWARFContext::getTUIndex() {
271 DataExtractor TUIndexData(getTUIndexSection(), isLittleEndian(), 0);
273 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
274 TUIndex->parse(TUIndexData);
278 DWARFGdbIndex &DWARFContext::getGdbIndex() {
282 DataExtractor GdbIndexData(getGdbIndexSection(), true /*LE*/, 0);
283 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
284 GdbIndex->parse(GdbIndexData);
288 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
292 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
294 Abbrev.reset(new DWARFDebugAbbrev());
295 Abbrev->extract(abbrData);
299 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
301 return AbbrevDWO.get();
303 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
304 AbbrevDWO.reset(new DWARFDebugAbbrev());
305 AbbrevDWO->extract(abbrData);
306 return AbbrevDWO.get();
309 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
313 DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
314 Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
315 // assume all compile units have the same address byte size
316 if (getNumCompileUnits())
317 Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
321 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
325 DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
326 LocDWO.reset(new DWARFDebugLocDWO());
327 LocDWO->parse(LocData);
331 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
333 return Aranges.get();
335 Aranges.reset(new DWARFDebugAranges());
336 Aranges->generate(this);
337 return Aranges.get();
340 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
342 return DebugFrame.get();
344 // There's a "bug" in the DWARFv3 standard with respect to the target address
345 // size within debug frame sections. While DWARF is supposed to be independent
346 // of its container, FDEs have fields with size being "target address size",
347 // which isn't specified in DWARF in general. It's only specified for CUs, but
348 // .eh_frame can appear without a .debug_info section. Follow the example of
349 // other tools (libdwarf) and extract this from the container (ObjectFile
350 // provides this information). This problem is fixed in DWARFv4
351 // See this dwarf-discuss discussion for more details:
352 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
353 DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
355 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
356 DebugFrame->parse(debugFrameData);
357 return DebugFrame.get();
360 const DWARFDebugFrame *DWARFContext::getEHFrame() {
362 return EHFrame.get();
364 DataExtractor debugFrameData(getEHFrameSection(), isLittleEndian(),
366 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
367 DebugFrame->parse(debugFrameData);
368 return DebugFrame.get();
371 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
375 DataExtractor MacinfoData(getMacinfoSection(), isLittleEndian(), 0);
376 Macro.reset(new DWARFDebugMacro());
377 Macro->parse(MacinfoData);
381 const DWARFLineTable *
382 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
384 Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
386 auto UnitDIE = U->getUnitDIE();
390 auto Offset = UnitDIE.getAttributeValueAsSectionOffset(DW_AT_stmt_list);
392 return nullptr; // No line table for this compile unit.
394 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
395 // See if the line table is cached.
396 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
399 // We have to parse it first.
400 DataExtractor lineData(U->getLineSection(), isLittleEndian(),
401 U->getAddressByteSize());
402 return Line->getOrParseLineTable(lineData, stmtOffset);
405 void DWARFContext::parseCompileUnits() {
406 CUs.parse(*this, getInfoSection());
409 void DWARFContext::parseTypeUnits() {
412 for (const auto &I : getTypesSections()) {
414 TUs.back().parse(*this, I.second);
418 void DWARFContext::parseDWOCompileUnits() {
419 DWOCUs.parseDWO(*this, getInfoDWOSection());
422 void DWARFContext::parseDWOTypeUnits() {
425 for (const auto &I : getTypesDWOSections()) {
426 DWOTUs.emplace_back();
427 DWOTUs.back().parseDWO(*this, I.second);
431 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
433 return CUs.getUnitForOffset(Offset);
436 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
437 // First, get the offset of the compile unit.
438 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
439 // Retrieve the compile unit.
440 return getCompileUnitForOffset(CUOffset);
443 static bool getFunctionNameForAddress(DWARFCompileUnit *CU, uint64_t Address,
444 FunctionNameKind Kind,
445 std::string &FunctionName) {
446 if (Kind == FunctionNameKind::None)
448 // The address may correspond to instruction in some inlined function,
449 // so we have to build the chain of inlined functions and take the
450 // name of the topmost function in it.SmallVectorImpl<DWARFDie> &InlinedChain
451 SmallVector<DWARFDie, 4> InlinedChain;
452 CU->getInlinedChainForAddress(Address, InlinedChain);
453 if (InlinedChain.size() == 0)
455 if (const char *Name = InlinedChain[0].getSubroutineName(Kind)) {
462 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
463 DILineInfoSpecifier Spec) {
466 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
469 getFunctionNameForAddress(CU, Address, Spec.FNKind, Result.FunctionName);
470 if (Spec.FLIKind != FileLineInfoKind::None) {
471 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
472 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
473 Spec.FLIKind, Result);
479 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
480 DILineInfoSpecifier Spec) {
481 DILineInfoTable Lines;
482 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
486 std::string FunctionName = "<invalid>";
487 getFunctionNameForAddress(CU, Address, Spec.FNKind, FunctionName);
489 // If the Specifier says we don't need FileLineInfo, just
490 // return the top-most function at the starting address.
491 if (Spec.FLIKind == FileLineInfoKind::None) {
493 Result.FunctionName = FunctionName;
494 Lines.push_back(std::make_pair(Address, Result));
498 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
500 // Get the index of row we're looking for in the line table.
501 std::vector<uint32_t> RowVector;
502 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
505 for (uint32_t RowIndex : RowVector) {
506 // Take file number and line/column from the row.
507 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
509 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
510 Spec.FLIKind, Result.FileName);
511 Result.FunctionName = FunctionName;
512 Result.Line = Row.Line;
513 Result.Column = Row.Column;
514 Lines.push_back(std::make_pair(Row.Address, Result));
521 DWARFContext::getInliningInfoForAddress(uint64_t Address,
522 DILineInfoSpecifier Spec) {
523 DIInliningInfo InliningInfo;
525 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
529 const DWARFLineTable *LineTable = nullptr;
530 SmallVector<DWARFDie, 4> InlinedChain;
531 CU->getInlinedChainForAddress(Address, InlinedChain);
532 if (InlinedChain.size() == 0) {
533 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
534 // try to at least get file/line info from symbol table.
535 if (Spec.FLIKind != FileLineInfoKind::None) {
537 LineTable = getLineTableForUnit(CU);
539 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
540 Spec.FLIKind, Frame))
541 InliningInfo.addFrame(Frame);
546 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
547 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
548 DWARFDie &FunctionDIE = InlinedChain[i];
550 // Get function name if necessary.
551 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
552 Frame.FunctionName = Name;
553 if (Spec.FLIKind != FileLineInfoKind::None) {
555 // For the topmost frame, initialize the line table of this
556 // compile unit and fetch file/line info from it.
557 LineTable = getLineTableForUnit(CU);
558 // For the topmost routine, get file/line info from line table.
560 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
561 Spec.FLIKind, Frame);
563 // Otherwise, use call file, call line and call column from
564 // previous DIE in inlined chain.
566 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
567 Spec.FLIKind, Frame.FileName);
568 Frame.Line = CallLine;
569 Frame.Column = CallColumn;
571 // Get call file/line/column of a current DIE.
573 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn);
576 InliningInfo.addFrame(Frame);
581 DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
582 const LoadedObjectInfo *L)
583 : IsLittleEndian(Obj.isLittleEndian()),
584 AddressSize(Obj.getBytesInAddress()) {
585 for (const SectionRef &Section : Obj.sections()) {
587 Section.getName(name);
588 // Skip BSS and Virtual sections, they aren't interesting.
589 bool IsBSS = Section.isBSS();
592 bool IsVirtual = Section.isVirtual();
597 section_iterator RelocatedSection = Section.getRelocatedSection();
598 // Try to obtain an already relocated version of this section.
599 // Else use the unrelocated section from the object file. We'll have to
600 // apply relocations ourselves later.
601 if (!L || !L->getLoadedSectionContents(*RelocatedSection,data))
602 Section.getContents(data);
604 if (Decompressor::isCompressed(Section)) {
605 Expected<Decompressor> Decompressor =
606 Decompressor::create(name, data, IsLittleEndian, AddressSize == 8);
610 if (auto Err = Decompressor->decompress(Out))
612 UncompressedSections.emplace_back(std::move(Out));
613 data = UncompressedSections.back();
616 // Compressed sections names in GNU style starts from ".z",
617 // at this point section is decompressed and we drop compression prefix.
619 name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
621 StringRef *SectionData =
622 StringSwitch<StringRef *>(name)
623 .Case("debug_info", &InfoSection.Data)
624 .Case("debug_abbrev", &AbbrevSection)
625 .Case("debug_loc", &LocSection.Data)
626 .Case("debug_line", &LineSection.Data)
627 .Case("debug_aranges", &ARangeSection)
628 .Case("debug_frame", &DebugFrameSection)
629 .Case("eh_frame", &EHFrameSection)
630 .Case("debug_str", &StringSection)
631 .Case("debug_ranges", &RangeSection)
632 .Case("debug_macinfo", &MacinfoSection)
633 .Case("debug_pubnames", &PubNamesSection)
634 .Case("debug_pubtypes", &PubTypesSection)
635 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
636 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
637 .Case("debug_info.dwo", &InfoDWOSection.Data)
638 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
639 .Case("debug_loc.dwo", &LocDWOSection.Data)
640 .Case("debug_line.dwo", &LineDWOSection.Data)
641 .Case("debug_str.dwo", &StringDWOSection)
642 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
643 .Case("debug_addr", &AddrSection)
644 .Case("apple_names", &AppleNamesSection.Data)
645 .Case("apple_types", &AppleTypesSection.Data)
646 .Case("apple_namespaces", &AppleNamespacesSection.Data)
647 .Case("apple_namespac", &AppleNamespacesSection.Data)
648 .Case("apple_objc", &AppleObjCSection.Data)
649 .Case("debug_cu_index", &CUIndexSection)
650 .Case("debug_tu_index", &TUIndexSection)
651 .Case("gdb_index", &GdbIndexSection)
652 // Any more debug info sections go here.
656 if (name == "debug_ranges") {
657 // FIXME: Use the other dwo range section when we emit it.
658 RangeDWOSection = data;
660 } else if (name == "debug_types") {
661 // Find debug_types data by section rather than name as there are
662 // multiple, comdat grouped, debug_types sections.
663 TypesSections[Section].Data = data;
664 } else if (name == "debug_types.dwo") {
665 TypesDWOSections[Section].Data = data;
668 if (RelocatedSection == Obj.section_end())
671 StringRef RelSecName;
672 StringRef RelSecData;
673 RelocatedSection->getName(RelSecName);
675 // If the section we're relocating was relocated already by the JIT,
676 // then we used the relocated version above, so we do not need to process
677 // relocations for it now.
678 if (L && L->getLoadedSectionContents(*RelocatedSection,RelSecData))
681 // In Mach-o files, the relocations do not need to be applied if
682 // there is no load offset to apply. The value read at the
683 // relocation point already factors in the section address
684 // (actually applying the relocations will produce wrong results
685 // as the section address will be added twice).
686 if (!L && isa<MachOObjectFile>(&Obj))
689 RelSecName = RelSecName.substr(
690 RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
692 // TODO: Add support for relocations in other sections as needed.
693 // Record relocations for the debug_info and debug_line sections.
694 RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
695 .Case("debug_info", &InfoSection.Relocs)
696 .Case("debug_loc", &LocSection.Relocs)
697 .Case("debug_info.dwo", &InfoDWOSection.Relocs)
698 .Case("debug_line", &LineSection.Relocs)
699 .Case("apple_names", &AppleNamesSection.Relocs)
700 .Case("apple_types", &AppleTypesSection.Relocs)
701 .Case("apple_namespaces", &AppleNamespacesSection.Relocs)
702 .Case("apple_namespac", &AppleNamespacesSection.Relocs)
703 .Case("apple_objc", &AppleObjCSection.Relocs)
706 // Find debug_types relocs by section rather than name as there are
707 // multiple, comdat grouped, debug_types sections.
708 if (RelSecName == "debug_types")
709 Map = &TypesSections[*RelocatedSection].Relocs;
710 else if (RelSecName == "debug_types.dwo")
711 Map = &TypesDWOSections[*RelocatedSection].Relocs;
716 if (Section.relocation_begin() != Section.relocation_end()) {
717 uint64_t SectionSize = RelocatedSection->getSize();
718 for (const RelocationRef &Reloc : Section.relocations()) {
719 uint64_t Address = Reloc.getOffset();
720 uint64_t Type = Reloc.getType();
721 uint64_t SymAddr = 0;
722 uint64_t SectionLoadAddress = 0;
723 object::symbol_iterator Sym = Reloc.getSymbol();
724 object::section_iterator RSec = Obj.section_end();
726 // First calculate the address of the symbol or section as it appears
728 if (Sym != Obj.symbol_end()) {
729 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
732 raw_string_ostream OS(Buf);
733 logAllUnhandledErrors(SymAddrOrErr.takeError(), OS, "");
735 errs() << "error: failed to compute symbol address: "
739 SymAddr = *SymAddrOrErr;
740 // Also remember what section this symbol is in for later
741 auto SectOrErr = Sym->getSection();
744 raw_string_ostream OS(Buf);
745 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
747 errs() << "error: failed to get symbol section: "
752 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
753 // MachO also has relocations that point to sections and
754 // scattered relocations.
755 auto RelocInfo = MObj->getRelocation(Reloc.getRawDataRefImpl());
756 if (MObj->isRelocationScattered(RelocInfo)) {
757 // FIXME: it's not clear how to correctly handle scattered
761 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
762 SymAddr = RSec->getAddress();
766 // If we are given load addresses for the sections, we need to adjust:
767 // SymAddr = (Address of Symbol Or Section in File) -
768 // (Address of Section in File) +
769 // (Load Address of Section)
770 if (L != nullptr && RSec != Obj.section_end()) {
771 // RSec is now either the section being targeted or the section
772 // containing the symbol being targeted. In either case,
773 // we need to perform the same computation.
775 RSec->getName(SecName);
776 // llvm::dbgs() << "Name: '" << SecName
777 // << "', RSec: " << RSec->getRawDataRefImpl()
778 // << ", Section: " << Section.getRawDataRefImpl() << "\n";
779 SectionLoadAddress = L->getSectionLoadAddress(*RSec);
780 if (SectionLoadAddress != 0)
781 SymAddr += SectionLoadAddress - RSec->getAddress();
784 object::RelocVisitor V(Obj);
785 object::RelocToApply R(V.visit(Type, Reloc, SymAddr));
787 SmallString<32> Name;
788 Reloc.getTypeName(Name);
789 errs() << "error: failed to compute relocation: "
794 if (Address + R.Width > SectionSize) {
795 errs() << "error: " << R.Width << "-byte relocation starting "
796 << Address << " bytes into section " << name << " which is "
797 << SectionSize << " bytes long.\n";
801 errs() << "error: can't handle a relocation of more than 8 bytes at "
805 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
806 << " at " << format("%p", Address)
807 << " with width " << format("%d", R.Width)
809 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
815 void DWARFContextInMemory::anchor() { }