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/DWARFUnitIndex.h"
16 #include "llvm/Support/Compression.h"
17 #include "llvm/Support/Dwarf.h"
18 #include "llvm/Support/Format.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/raw_ostream.h"
23 using namespace dwarf;
24 using namespace object;
26 #define DEBUG_TYPE "dwarf"
28 typedef DWARFDebugLine::LineTable DWARFLineTable;
29 typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
30 typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
32 static void dumpPubSection(raw_ostream &OS, StringRef Name, StringRef Data,
33 bool LittleEndian, bool GnuStyle) {
34 OS << "\n." << Name << " contents:\n";
35 DataExtractor pubNames(Data, LittleEndian, 0);
37 while (pubNames.isValidOffset(offset)) {
38 OS << "length = " << format("0x%08x", pubNames.getU32(&offset));
39 OS << " version = " << format("0x%04x", pubNames.getU16(&offset));
40 OS << " unit_offset = " << format("0x%08x", pubNames.getU32(&offset));
41 OS << " unit_size = " << format("0x%08x", pubNames.getU32(&offset)) << '\n';
43 OS << "Offset Linkage Kind Name\n";
45 OS << "Offset Name\n";
47 while (offset < Data.size()) {
48 uint32_t dieRef = pubNames.getU32(&offset);
51 OS << format("0x%8.8x ", dieRef);
53 PubIndexEntryDescriptor desc(pubNames.getU8(&offset));
54 OS << format("%-8s", dwarf::GDBIndexEntryLinkageString(desc.Linkage))
55 << ' ' << format("%-8s", dwarf::GDBIndexEntryKindString(desc.Kind))
58 OS << '\"' << pubNames.getCStr(&offset) << "\"\n";
63 static void dumpAccelSection(raw_ostream &OS, StringRef Name,
64 const DWARFSection& Section, StringRef StringSection,
66 DataExtractor AccelSection(Section.Data, LittleEndian, 0);
67 DataExtractor StrData(StringSection, LittleEndian, 0);
68 OS << "\n." << Name << " contents:\n";
69 DWARFAcceleratorTable Accel(AccelSection, StrData, Section.Relocs);
75 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
76 if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
77 OS << ".debug_abbrev contents:\n";
78 getDebugAbbrev()->dump(OS);
81 if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
82 if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
83 OS << "\n.debug_abbrev.dwo contents:\n";
87 if (DumpType == DIDT_All || DumpType == DIDT_Info) {
88 OS << "\n.debug_info contents:\n";
89 for (const auto &CU : compile_units())
93 if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
94 getNumDWOCompileUnits()) {
95 OS << "\n.debug_info.dwo contents:\n";
96 for (const auto &DWOCU : dwo_compile_units())
100 if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
101 OS << "\n.debug_types contents:\n";
102 for (const auto &TUS : type_unit_sections())
103 for (const auto &TU : TUS)
107 if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
108 getNumDWOTypeUnits()) {
109 OS << "\n.debug_types.dwo contents:\n";
110 for (const auto &DWOTUS : dwo_type_unit_sections())
111 for (const auto &DWOTU : DWOTUS)
115 if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
116 OS << "\n.debug_loc contents:\n";
117 getDebugLoc()->dump(OS);
120 if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
121 OS << "\n.debug_loc.dwo contents:\n";
122 getDebugLocDWO()->dump(OS);
125 if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
126 OS << "\n.debug_frame contents:\n";
127 getDebugFrame()->dump(OS);
131 if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
132 OS << "\n.debug_aranges contents:\n";
133 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
134 DWARFDebugArangeSet set;
135 while (set.extract(arangesData, &offset))
139 uint8_t savedAddressByteSize = 0;
140 if (DumpType == DIDT_All || DumpType == DIDT_Line) {
141 OS << "\n.debug_line contents:\n";
142 for (const auto &CU : compile_units()) {
143 savedAddressByteSize = CU->getAddressByteSize();
144 const auto *CUDIE = CU->getUnitDIE();
145 if (CUDIE == nullptr)
147 unsigned stmtOffset = CUDIE->getAttributeValueAsSectionOffset(
148 CU.get(), DW_AT_stmt_list, -1U);
149 if (stmtOffset != -1U) {
150 DataExtractor lineData(getLineSection().Data, isLittleEndian(),
151 savedAddressByteSize);
152 DWARFDebugLine::LineTable LineTable;
153 LineTable.parse(lineData, &getLineSection().Relocs, &stmtOffset);
159 if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
160 OS << "\n.debug_cu_index contents:\n";
161 DataExtractor CUIndexData(getCUIndexSection(), isLittleEndian(), savedAddressByteSize);
162 DWARFUnitIndex CUIndex;
163 CUIndex.parse(CUIndexData);
167 if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
168 OS << "\n.debug_line.dwo contents:\n";
169 unsigned stmtOffset = 0;
170 DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
171 savedAddressByteSize);
172 DWARFDebugLine::LineTable LineTable;
173 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
179 if (DumpType == DIDT_All || DumpType == DIDT_Str) {
180 OS << "\n.debug_str contents:\n";
181 DataExtractor strData(getStringSection(), isLittleEndian(), 0);
183 uint32_t strOffset = 0;
184 while (const char *s = strData.getCStr(&offset)) {
185 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
190 if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
191 !getStringDWOSection().empty()) {
192 OS << "\n.debug_str.dwo contents:\n";
193 DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
195 uint32_t strDWOOffset = 0;
196 while (const char *s = strDWOData.getCStr(&offset)) {
197 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
198 strDWOOffset = offset;
202 if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
203 OS << "\n.debug_ranges contents:\n";
204 // In fact, different compile units may have different address byte
205 // sizes, but for simplicity we just use the address byte size of the last
206 // compile unit (there is no easy and fast way to associate address range
207 // list and the compile unit it describes).
208 DataExtractor rangesData(getRangeSection(), isLittleEndian(),
209 savedAddressByteSize);
211 DWARFDebugRangeList rangeList;
212 while (rangeList.extract(rangesData, &offset))
216 if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
217 dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
218 isLittleEndian(), false);
220 if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
221 dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
222 isLittleEndian(), false);
224 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
225 dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
226 isLittleEndian(), true /* GnuStyle */);
228 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
229 dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
230 isLittleEndian(), true /* GnuStyle */);
232 if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
233 !getStringOffsetDWOSection().empty()) {
234 OS << "\n.debug_str_offsets.dwo contents:\n";
235 DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
238 uint64_t size = getStringOffsetDWOSection().size();
239 while (offset < size) {
240 OS << format("0x%8.8x: ", offset);
241 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
245 if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
246 dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
247 getStringSection(), isLittleEndian());
249 if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
250 dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
251 getStringSection(), isLittleEndian());
253 if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
254 dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
255 getStringSection(), isLittleEndian());
257 if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
258 dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
259 getStringSection(), isLittleEndian());
262 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
266 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
268 Abbrev.reset(new DWARFDebugAbbrev());
269 Abbrev->extract(abbrData);
273 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
275 return AbbrevDWO.get();
277 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
278 AbbrevDWO.reset(new DWARFDebugAbbrev());
279 AbbrevDWO->extract(abbrData);
280 return AbbrevDWO.get();
283 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
287 DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
288 Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
289 // assume all compile units have the same address byte size
290 if (getNumCompileUnits())
291 Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
295 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
299 DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
300 LocDWO.reset(new DWARFDebugLocDWO());
301 LocDWO->parse(LocData);
305 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
307 return Aranges.get();
309 Aranges.reset(new DWARFDebugAranges());
310 Aranges->generate(this);
311 return Aranges.get();
314 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
316 return DebugFrame.get();
318 // There's a "bug" in the DWARFv3 standard with respect to the target address
319 // size within debug frame sections. While DWARF is supposed to be independent
320 // of its container, FDEs have fields with size being "target address size",
321 // which isn't specified in DWARF in general. It's only specified for CUs, but
322 // .eh_frame can appear without a .debug_info section. Follow the example of
323 // other tools (libdwarf) and extract this from the container (ObjectFile
324 // provides this information). This problem is fixed in DWARFv4
325 // See this dwarf-discuss discussion for more details:
326 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
327 DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
329 DebugFrame.reset(new DWARFDebugFrame());
330 DebugFrame->parse(debugFrameData);
331 return DebugFrame.get();
334 const DWARFLineTable *
335 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
337 Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
338 const auto *UnitDIE = U->getUnitDIE();
339 if (UnitDIE == nullptr)
341 unsigned stmtOffset =
342 UnitDIE->getAttributeValueAsSectionOffset(U, DW_AT_stmt_list, -1U);
343 if (stmtOffset == -1U)
344 return nullptr; // No line table for this compile unit.
346 // See if the line table is cached.
347 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
350 // We have to parse it first.
351 DataExtractor lineData(getLineSection().Data, isLittleEndian(),
352 U->getAddressByteSize());
353 return Line->getOrParseLineTable(lineData, stmtOffset);
356 void DWARFContext::parseCompileUnits() {
357 CUs.parse(*this, getInfoSection());
360 void DWARFContext::parseTypeUnits() {
363 for (const auto &I : getTypesSections()) {
365 TUs.back().parse(*this, I.second);
369 void DWARFContext::parseDWOCompileUnits() {
370 DWOCUs.parseDWO(*this, getInfoDWOSection());
373 void DWARFContext::parseDWOTypeUnits() {
376 for (const auto &I : getTypesDWOSections()) {
377 DWOTUs.emplace_back();
378 DWOTUs.back().parseDWO(*this, I.second);
382 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
384 return CUs.getUnitForOffset(Offset);
387 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
388 // First, get the offset of the compile unit.
389 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
390 // Retrieve the compile unit.
391 return getCompileUnitForOffset(CUOffset);
394 static bool getFunctionNameForAddress(DWARFCompileUnit *CU, uint64_t Address,
395 FunctionNameKind Kind,
396 std::string &FunctionName) {
397 if (Kind == FunctionNameKind::None)
399 // The address may correspond to instruction in some inlined function,
400 // so we have to build the chain of inlined functions and take the
401 // name of the topmost function in it.
402 const DWARFDebugInfoEntryInlinedChain &InlinedChain =
403 CU->getInlinedChainForAddress(Address);
404 if (InlinedChain.DIEs.size() == 0)
406 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
407 if (const char *Name =
408 TopFunctionDIE.getSubroutineName(InlinedChain.U, Kind)) {
415 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
416 DILineInfoSpecifier Spec) {
419 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
422 getFunctionNameForAddress(CU, Address, Spec.FNKind, Result.FunctionName);
423 if (Spec.FLIKind != FileLineInfoKind::None) {
424 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
425 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
426 Spec.FLIKind, Result);
432 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
433 DILineInfoSpecifier Spec) {
434 DILineInfoTable Lines;
435 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
439 std::string FunctionName = "<invalid>";
440 getFunctionNameForAddress(CU, Address, Spec.FNKind, FunctionName);
442 // If the Specifier says we don't need FileLineInfo, just
443 // return the top-most function at the starting address.
444 if (Spec.FLIKind == FileLineInfoKind::None) {
446 Result.FunctionName = FunctionName;
447 Lines.push_back(std::make_pair(Address, Result));
451 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
453 // Get the index of row we're looking for in the line table.
454 std::vector<uint32_t> RowVector;
455 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
458 for (uint32_t RowIndex : RowVector) {
459 // Take file number and line/column from the row.
460 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
462 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
463 Spec.FLIKind, Result.FileName);
464 Result.FunctionName = FunctionName;
465 Result.Line = Row.Line;
466 Result.Column = Row.Column;
467 Lines.push_back(std::make_pair(Row.Address, Result));
474 DWARFContext::getInliningInfoForAddress(uint64_t Address,
475 DILineInfoSpecifier Spec) {
476 DIInliningInfo InliningInfo;
478 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
482 const DWARFLineTable *LineTable = nullptr;
483 const DWARFDebugInfoEntryInlinedChain &InlinedChain =
484 CU->getInlinedChainForAddress(Address);
485 if (InlinedChain.DIEs.size() == 0) {
486 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
487 // try to at least get file/line info from symbol table.
488 if (Spec.FLIKind != FileLineInfoKind::None) {
490 LineTable = getLineTableForUnit(CU);
492 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
493 Spec.FLIKind, Frame))
494 InliningInfo.addFrame(Frame);
499 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
500 for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
501 const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
503 // Get function name if necessary.
504 if (const char *Name =
505 FunctionDIE.getSubroutineName(InlinedChain.U, Spec.FNKind))
506 Frame.FunctionName = Name;
507 if (Spec.FLIKind != FileLineInfoKind::None) {
509 // For the topmost frame, initialize the line table of this
510 // compile unit and fetch file/line info from it.
511 LineTable = getLineTableForUnit(CU);
512 // For the topmost routine, get file/line info from line table.
514 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
515 Spec.FLIKind, Frame);
517 // Otherwise, use call file, call line and call column from
518 // previous DIE in inlined chain.
520 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
521 Spec.FLIKind, Frame.FileName);
522 Frame.Line = CallLine;
523 Frame.Column = CallColumn;
525 // Get call file/line/column of a current DIE.
527 FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
531 InliningInfo.addFrame(Frame);
536 static bool consumeCompressedDebugSectionHeader(StringRef &data,
537 uint64_t &OriginalSize) {
538 // Consume "ZLIB" prefix.
539 if (!data.startswith("ZLIB"))
541 data = data.substr(4);
542 // Consume uncompressed section size (big-endian 8 bytes).
543 DataExtractor extractor(data, false, 8);
545 OriginalSize = extractor.getU64(&Offset);
548 data = data.substr(Offset);
552 DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
553 const LoadedObjectInfo *L)
554 : IsLittleEndian(Obj.isLittleEndian()),
555 AddressSize(Obj.getBytesInAddress()) {
556 for (const SectionRef &Section : Obj.sections()) {
558 Section.getName(name);
559 // Skip BSS and Virtual sections, they aren't interesting.
560 bool IsBSS = Section.isBSS();
563 bool IsVirtual = Section.isVirtual();
568 section_iterator RelocatedSection = Section.getRelocatedSection();
569 // Try to obtain an already relocated version of this section.
570 // Else use the unrelocated section from the object file. We'll have to
571 // apply relocations ourselves later.
572 if (!L || !L->getLoadedSectionContents(*RelocatedSection,data))
573 Section.getContents(data);
575 name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
577 // Check if debug info section is compressed with zlib.
578 if (name.startswith("zdebug_")) {
579 uint64_t OriginalSize;
580 if (!zlib::isAvailable() ||
581 !consumeCompressedDebugSectionHeader(data, OriginalSize))
583 UncompressedSections.resize(UncompressedSections.size() + 1);
584 if (zlib::uncompress(data, UncompressedSections.back(), OriginalSize) !=
586 UncompressedSections.pop_back();
589 // Make data point to uncompressed section contents and save its contents.
590 name = name.substr(1);
591 data = UncompressedSections.back();
594 StringRef *SectionData =
595 StringSwitch<StringRef *>(name)
596 .Case("debug_info", &InfoSection.Data)
597 .Case("debug_abbrev", &AbbrevSection)
598 .Case("debug_loc", &LocSection.Data)
599 .Case("debug_line", &LineSection.Data)
600 .Case("debug_aranges", &ARangeSection)
601 .Case("debug_frame", &DebugFrameSection)
602 .Case("debug_str", &StringSection)
603 .Case("debug_ranges", &RangeSection)
604 .Case("debug_pubnames", &PubNamesSection)
605 .Case("debug_pubtypes", &PubTypesSection)
606 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
607 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
608 .Case("debug_info.dwo", &InfoDWOSection.Data)
609 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
610 .Case("debug_loc.dwo", &LocDWOSection.Data)
611 .Case("debug_line.dwo", &LineDWOSection.Data)
612 .Case("debug_str.dwo", &StringDWOSection)
613 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
614 .Case("debug_addr", &AddrSection)
615 .Case("apple_names", &AppleNamesSection.Data)
616 .Case("apple_types", &AppleTypesSection.Data)
617 .Case("apple_namespaces", &AppleNamespacesSection.Data)
618 .Case("apple_namespac", &AppleNamespacesSection.Data)
619 .Case("apple_objc", &AppleObjCSection.Data)
620 .Case("debug_cu_index", &CUIndexSection)
621 // Any more debug info sections go here.
625 if (name == "debug_ranges") {
626 // FIXME: Use the other dwo range section when we emit it.
627 RangeDWOSection = data;
629 } else if (name == "debug_types") {
630 // Find debug_types data by section rather than name as there are
631 // multiple, comdat grouped, debug_types sections.
632 TypesSections[Section].Data = data;
633 } else if (name == "debug_types.dwo") {
634 TypesDWOSections[Section].Data = data;
637 if (RelocatedSection == Obj.section_end())
640 StringRef RelSecName;
641 StringRef RelSecData;
642 RelocatedSection->getName(RelSecName);
644 // If the section we're relocating was relocated already by the JIT,
645 // then we used the relocated version above, so we do not need to process
646 // relocations for it now.
647 if (L && L->getLoadedSectionContents(*RelocatedSection,RelSecData))
650 // In Mach-o files, the relocations do not need to be applied if
651 // there is no load offset to apply. The value read at the
652 // relocation point already factors in the section address
653 // (actually applying the relocations will produce wrong results
654 // as the section address will be added twice).
655 if (!L && dyn_cast<MachOObjectFile>(&Obj))
658 RelSecName = RelSecName.substr(
659 RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
661 // TODO: Add support for relocations in other sections as needed.
662 // Record relocations for the debug_info and debug_line sections.
663 RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
664 .Case("debug_info", &InfoSection.Relocs)
665 .Case("debug_loc", &LocSection.Relocs)
666 .Case("debug_info.dwo", &InfoDWOSection.Relocs)
667 .Case("debug_line", &LineSection.Relocs)
668 .Case("apple_names", &AppleNamesSection.Relocs)
669 .Case("apple_types", &AppleTypesSection.Relocs)
670 .Case("apple_namespaces", &AppleNamespacesSection.Relocs)
671 .Case("apple_namespac", &AppleNamespacesSection.Relocs)
672 .Case("apple_objc", &AppleObjCSection.Relocs)
675 // Find debug_types relocs by section rather than name as there are
676 // multiple, comdat grouped, debug_types sections.
677 if (RelSecName == "debug_types")
678 Map = &TypesSections[*RelocatedSection].Relocs;
679 else if (RelSecName == "debug_types.dwo")
680 Map = &TypesDWOSections[*RelocatedSection].Relocs;
685 if (Section.relocation_begin() != Section.relocation_end()) {
686 uint64_t SectionSize = RelocatedSection->getSize();
687 for (const RelocationRef &Reloc : Section.relocations()) {
688 uint64_t Address = Reloc.getOffset();
689 uint64_t Type = Reloc.getType();
690 uint64_t SymAddr = 0;
691 uint64_t SectionLoadAddress = 0;
692 object::symbol_iterator Sym = Reloc.getSymbol();
693 object::section_iterator RSec = Obj.section_end();
695 // First calculate the address of the symbol or section as it appears
697 if (Sym != Obj.symbol_end()) {
698 ErrorOr<uint64_t> SymAddrOrErr = Sym->getAddress();
699 if (std::error_code EC = SymAddrOrErr.getError()) {
700 errs() << "error: failed to compute symbol address: "
701 << EC.message() << '\n';
704 SymAddr = *SymAddrOrErr;
705 // Also remember what section this symbol is in for later
706 RSec = *Sym->getSection();
707 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
708 // MachO also has relocations that point to sections and
709 // scattered relocations.
710 auto RelocInfo = MObj->getRelocation(Reloc.getRawDataRefImpl());
711 if (MObj->isRelocationScattered(RelocInfo)) {
712 // FIXME: it's not clear how to correctly handle scattered
716 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
717 SymAddr = RSec->getAddress();
721 // If we are given load addresses for the sections, we need to adjust:
722 // SymAddr = (Address of Symbol Or Section in File) -
723 // (Address of Section in File) +
724 // (Load Address of Section)
725 if (L != nullptr && RSec != Obj.section_end()) {
726 // RSec is now either the section being targeted or the section
727 // containing the symbol being targeted. In either case,
728 // we need to perform the same computation.
730 RSec->getName(SecName);
731 // llvm::dbgs() << "Name: '" << SecName
732 // << "', RSec: " << RSec->getRawDataRefImpl()
733 // << ", Section: " << Section.getRawDataRefImpl() << "\n";
734 SectionLoadAddress = L->getSectionLoadAddress(*RSec);
735 if (SectionLoadAddress != 0)
736 SymAddr += SectionLoadAddress - RSec->getAddress();
739 object::RelocVisitor V(Obj);
740 object::RelocToApply R(V.visit(Type, Reloc, SymAddr));
742 SmallString<32> Name;
743 Reloc.getTypeName(Name);
744 errs() << "error: failed to compute relocation: "
749 if (Address + R.Width > SectionSize) {
750 errs() << "error: " << R.Width << "-byte relocation starting "
751 << Address << " bytes into section " << name << " which is "
752 << SectionSize << " bytes long.\n";
756 errs() << "error: can't handle a relocation of more than 8 bytes at "
760 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
761 << " at " << format("%p", Address)
762 << " with width " << format("%d", R.Width)
764 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
770 void DWARFContextInMemory::anchor() { }