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, bool DumpEH) {
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);
129 OS << "\n.eh_frame contents:\n";
130 getEHFrame()->dump(OS);
134 if (DumpType == DIDT_All || DumpType == DIDT_Macro) {
135 OS << "\n.debug_macinfo contents:\n";
136 getDebugMacro()->dump(OS);
140 if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
141 OS << "\n.debug_aranges contents:\n";
142 DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
143 DWARFDebugArangeSet set;
144 while (set.extract(arangesData, &offset))
148 uint8_t savedAddressByteSize = 0;
149 if (DumpType == DIDT_All || DumpType == DIDT_Line) {
150 OS << "\n.debug_line contents:\n";
151 for (const auto &CU : compile_units()) {
152 savedAddressByteSize = CU->getAddressByteSize();
153 const auto *CUDIE = CU->getUnitDIE();
154 if (CUDIE == nullptr)
156 unsigned stmtOffset = CUDIE->getAttributeValueAsSectionOffset(
157 CU.get(), DW_AT_stmt_list, -1U);
158 if (stmtOffset != -1U) {
159 DataExtractor lineData(getLineSection().Data, isLittleEndian(),
160 savedAddressByteSize);
161 DWARFDebugLine::LineTable LineTable;
162 LineTable.parse(lineData, &getLineSection().Relocs, &stmtOffset);
168 if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
169 OS << "\n.debug_cu_index contents:\n";
170 getCUIndex().dump(OS);
173 if (DumpType == DIDT_All || DumpType == DIDT_TUIndex) {
174 OS << "\n.debug_tu_index contents:\n";
175 getTUIndex().dump(OS);
178 if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
179 OS << "\n.debug_line.dwo contents:\n";
180 unsigned stmtOffset = 0;
181 DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
182 savedAddressByteSize);
183 DWARFDebugLine::LineTable LineTable;
184 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
190 if (DumpType == DIDT_All || DumpType == DIDT_Str) {
191 OS << "\n.debug_str contents:\n";
192 DataExtractor strData(getStringSection(), isLittleEndian(), 0);
194 uint32_t strOffset = 0;
195 while (const char *s = strData.getCStr(&offset)) {
196 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
201 if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
202 !getStringDWOSection().empty()) {
203 OS << "\n.debug_str.dwo contents:\n";
204 DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
206 uint32_t strDWOOffset = 0;
207 while (const char *s = strDWOData.getCStr(&offset)) {
208 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
209 strDWOOffset = offset;
213 if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
214 OS << "\n.debug_ranges contents:\n";
215 // In fact, different compile units may have different address byte
216 // sizes, but for simplicity we just use the address byte size of the last
217 // compile unit (there is no easy and fast way to associate address range
218 // list and the compile unit it describes).
219 DataExtractor rangesData(getRangeSection(), isLittleEndian(),
220 savedAddressByteSize);
222 DWARFDebugRangeList rangeList;
223 while (rangeList.extract(rangesData, &offset))
227 if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
228 dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
229 isLittleEndian(), false);
231 if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
232 dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
233 isLittleEndian(), false);
235 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
236 dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
237 isLittleEndian(), true /* GnuStyle */);
239 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
240 dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
241 isLittleEndian(), true /* GnuStyle */);
243 if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
244 !getStringOffsetDWOSection().empty()) {
245 OS << "\n.debug_str_offsets.dwo contents:\n";
246 DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
249 uint64_t size = getStringOffsetDWOSection().size();
250 while (offset < size) {
251 OS << format("0x%8.8x: ", offset);
252 OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
256 if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
257 dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
258 getStringSection(), isLittleEndian());
260 if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
261 dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
262 getStringSection(), isLittleEndian());
264 if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
265 dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
266 getStringSection(), isLittleEndian());
268 if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
269 dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
270 getStringSection(), isLittleEndian());
273 const DWARFUnitIndex &DWARFContext::getCUIndex() {
277 DataExtractor CUIndexData(getCUIndexSection(), isLittleEndian(), 0);
279 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
280 CUIndex->parse(CUIndexData);
284 const DWARFUnitIndex &DWARFContext::getTUIndex() {
288 DataExtractor TUIndexData(getTUIndexSection(), isLittleEndian(), 0);
290 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
291 TUIndex->parse(TUIndexData);
295 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
299 DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
301 Abbrev.reset(new DWARFDebugAbbrev());
302 Abbrev->extract(abbrData);
306 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
308 return AbbrevDWO.get();
310 DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
311 AbbrevDWO.reset(new DWARFDebugAbbrev());
312 AbbrevDWO->extract(abbrData);
313 return AbbrevDWO.get();
316 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
320 DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
321 Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
322 // assume all compile units have the same address byte size
323 if (getNumCompileUnits())
324 Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
328 const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
332 DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
333 LocDWO.reset(new DWARFDebugLocDWO());
334 LocDWO->parse(LocData);
338 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
340 return Aranges.get();
342 Aranges.reset(new DWARFDebugAranges());
343 Aranges->generate(this);
344 return Aranges.get();
347 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
349 return DebugFrame.get();
351 // There's a "bug" in the DWARFv3 standard with respect to the target address
352 // size within debug frame sections. While DWARF is supposed to be independent
353 // of its container, FDEs have fields with size being "target address size",
354 // which isn't specified in DWARF in general. It's only specified for CUs, but
355 // .eh_frame can appear without a .debug_info section. Follow the example of
356 // other tools (libdwarf) and extract this from the container (ObjectFile
357 // provides this information). This problem is fixed in DWARFv4
358 // See this dwarf-discuss discussion for more details:
359 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
360 DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
362 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
363 DebugFrame->parse(debugFrameData);
364 return DebugFrame.get();
367 const DWARFDebugFrame *DWARFContext::getEHFrame() {
369 return EHFrame.get();
371 DataExtractor debugFrameData(getEHFrameSection(), isLittleEndian(),
373 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
374 DebugFrame->parse(debugFrameData);
375 return DebugFrame.get();
378 const DWARFDebugMacro *DWARFContext::getDebugMacro() {
382 DataExtractor MacinfoData(getMacinfoSection(), isLittleEndian(), 0);
383 Macro.reset(new DWARFDebugMacro());
384 Macro->parse(MacinfoData);
388 const DWARFLineTable *
389 DWARFContext::getLineTableForUnit(DWARFUnit *U) {
391 Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
393 const auto *UnitDIE = U->getUnitDIE();
394 if (UnitDIE == nullptr)
397 unsigned stmtOffset =
398 UnitDIE->getAttributeValueAsSectionOffset(U, DW_AT_stmt_list, -1U);
399 if (stmtOffset == -1U)
400 return nullptr; // No line table for this compile unit.
402 stmtOffset += U->getLineTableOffset();
403 // See if the line table is cached.
404 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
407 // We have to parse it first.
408 DataExtractor lineData(U->getLineSection(), isLittleEndian(),
409 U->getAddressByteSize());
410 return Line->getOrParseLineTable(lineData, stmtOffset);
413 void DWARFContext::parseCompileUnits() {
414 CUs.parse(*this, getInfoSection());
417 void DWARFContext::parseTypeUnits() {
420 for (const auto &I : getTypesSections()) {
422 TUs.back().parse(*this, I.second);
426 void DWARFContext::parseDWOCompileUnits() {
427 DWOCUs.parseDWO(*this, getInfoDWOSection());
430 void DWARFContext::parseDWOTypeUnits() {
433 for (const auto &I : getTypesDWOSections()) {
434 DWOTUs.emplace_back();
435 DWOTUs.back().parseDWO(*this, I.second);
439 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
441 return CUs.getUnitForOffset(Offset);
444 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
445 // First, get the offset of the compile unit.
446 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
447 // Retrieve the compile unit.
448 return getCompileUnitForOffset(CUOffset);
451 static bool getFunctionNameForAddress(DWARFCompileUnit *CU, uint64_t Address,
452 FunctionNameKind Kind,
453 std::string &FunctionName) {
454 if (Kind == FunctionNameKind::None)
456 // The address may correspond to instruction in some inlined function,
457 // so we have to build the chain of inlined functions and take the
458 // name of the topmost function in it.
459 const DWARFDebugInfoEntryInlinedChain &InlinedChain =
460 CU->getInlinedChainForAddress(Address);
461 if (InlinedChain.DIEs.size() == 0)
463 const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
464 if (const char *Name =
465 TopFunctionDIE.getSubroutineName(InlinedChain.U, Kind)) {
472 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
473 DILineInfoSpecifier Spec) {
476 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
479 getFunctionNameForAddress(CU, Address, Spec.FNKind, Result.FunctionName);
480 if (Spec.FLIKind != FileLineInfoKind::None) {
481 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
482 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
483 Spec.FLIKind, Result);
489 DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
490 DILineInfoSpecifier Spec) {
491 DILineInfoTable Lines;
492 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
496 std::string FunctionName = "<invalid>";
497 getFunctionNameForAddress(CU, Address, Spec.FNKind, FunctionName);
499 // If the Specifier says we don't need FileLineInfo, just
500 // return the top-most function at the starting address.
501 if (Spec.FLIKind == FileLineInfoKind::None) {
503 Result.FunctionName = FunctionName;
504 Lines.push_back(std::make_pair(Address, Result));
508 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
510 // Get the index of row we're looking for in the line table.
511 std::vector<uint32_t> RowVector;
512 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
515 for (uint32_t RowIndex : RowVector) {
516 // Take file number and line/column from the row.
517 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
519 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
520 Spec.FLIKind, Result.FileName);
521 Result.FunctionName = FunctionName;
522 Result.Line = Row.Line;
523 Result.Column = Row.Column;
524 Lines.push_back(std::make_pair(Row.Address, Result));
531 DWARFContext::getInliningInfoForAddress(uint64_t Address,
532 DILineInfoSpecifier Spec) {
533 DIInliningInfo InliningInfo;
535 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
539 const DWARFLineTable *LineTable = nullptr;
540 const DWARFDebugInfoEntryInlinedChain &InlinedChain =
541 CU->getInlinedChainForAddress(Address);
542 if (InlinedChain.DIEs.size() == 0) {
543 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
544 // try to at least get file/line info from symbol table.
545 if (Spec.FLIKind != FileLineInfoKind::None) {
547 LineTable = getLineTableForUnit(CU);
549 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
550 Spec.FLIKind, Frame))
551 InliningInfo.addFrame(Frame);
556 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
557 for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
558 const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
560 // Get function name if necessary.
561 if (const char *Name =
562 FunctionDIE.getSubroutineName(InlinedChain.U, Spec.FNKind))
563 Frame.FunctionName = Name;
564 if (Spec.FLIKind != FileLineInfoKind::None) {
566 // For the topmost frame, initialize the line table of this
567 // compile unit and fetch file/line info from it.
568 LineTable = getLineTableForUnit(CU);
569 // For the topmost routine, get file/line info from line table.
571 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
572 Spec.FLIKind, Frame);
574 // Otherwise, use call file, call line and call column from
575 // previous DIE in inlined chain.
577 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
578 Spec.FLIKind, Frame.FileName);
579 Frame.Line = CallLine;
580 Frame.Column = CallColumn;
582 // Get call file/line/column of a current DIE.
584 FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
588 InliningInfo.addFrame(Frame);
593 static bool consumeCompressedDebugSectionHeader(StringRef &data,
594 uint64_t &OriginalSize) {
595 // Consume "ZLIB" prefix.
596 if (!data.startswith("ZLIB"))
598 data = data.substr(4);
599 // Consume uncompressed section size (big-endian 8 bytes).
600 DataExtractor extractor(data, false, 8);
602 OriginalSize = extractor.getU64(&Offset);
605 data = data.substr(Offset);
609 DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
610 const LoadedObjectInfo *L)
611 : IsLittleEndian(Obj.isLittleEndian()),
612 AddressSize(Obj.getBytesInAddress()) {
613 for (const SectionRef &Section : Obj.sections()) {
615 Section.getName(name);
616 // Skip BSS and Virtual sections, they aren't interesting.
617 bool IsBSS = Section.isBSS();
620 bool IsVirtual = Section.isVirtual();
625 section_iterator RelocatedSection = Section.getRelocatedSection();
626 // Try to obtain an already relocated version of this section.
627 // Else use the unrelocated section from the object file. We'll have to
628 // apply relocations ourselves later.
629 if (!L || !L->getLoadedSectionContents(*RelocatedSection,data))
630 Section.getContents(data);
632 name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
634 // Check if debug info section is compressed with zlib.
635 if (name.startswith("zdebug_")) {
636 uint64_t OriginalSize;
637 if (!zlib::isAvailable() ||
638 !consumeCompressedDebugSectionHeader(data, OriginalSize))
640 UncompressedSections.resize(UncompressedSections.size() + 1);
641 if (zlib::uncompress(data, UncompressedSections.back(), OriginalSize) !=
643 UncompressedSections.pop_back();
646 // Make data point to uncompressed section contents and save its contents.
647 name = name.substr(1);
648 data = UncompressedSections.back();
651 StringRef *SectionData =
652 StringSwitch<StringRef *>(name)
653 .Case("debug_info", &InfoSection.Data)
654 .Case("debug_abbrev", &AbbrevSection)
655 .Case("debug_loc", &LocSection.Data)
656 .Case("debug_line", &LineSection.Data)
657 .Case("debug_aranges", &ARangeSection)
658 .Case("debug_frame", &DebugFrameSection)
659 .Case("eh_frame", &EHFrameSection)
660 .Case("debug_str", &StringSection)
661 .Case("debug_ranges", &RangeSection)
662 .Case("debug_macinfo", &MacinfoSection)
663 .Case("debug_pubnames", &PubNamesSection)
664 .Case("debug_pubtypes", &PubTypesSection)
665 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
666 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
667 .Case("debug_info.dwo", &InfoDWOSection.Data)
668 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
669 .Case("debug_loc.dwo", &LocDWOSection.Data)
670 .Case("debug_line.dwo", &LineDWOSection.Data)
671 .Case("debug_str.dwo", &StringDWOSection)
672 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
673 .Case("debug_addr", &AddrSection)
674 .Case("apple_names", &AppleNamesSection.Data)
675 .Case("apple_types", &AppleTypesSection.Data)
676 .Case("apple_namespaces", &AppleNamespacesSection.Data)
677 .Case("apple_namespac", &AppleNamespacesSection.Data)
678 .Case("apple_objc", &AppleObjCSection.Data)
679 .Case("debug_cu_index", &CUIndexSection)
680 .Case("debug_tu_index", &TUIndexSection)
681 // Any more debug info sections go here.
685 if (name == "debug_ranges") {
686 // FIXME: Use the other dwo range section when we emit it.
687 RangeDWOSection = data;
689 } else if (name == "debug_types") {
690 // Find debug_types data by section rather than name as there are
691 // multiple, comdat grouped, debug_types sections.
692 TypesSections[Section].Data = data;
693 } else if (name == "debug_types.dwo") {
694 TypesDWOSections[Section].Data = data;
697 if (RelocatedSection == Obj.section_end())
700 StringRef RelSecName;
701 StringRef RelSecData;
702 RelocatedSection->getName(RelSecName);
704 // If the section we're relocating was relocated already by the JIT,
705 // then we used the relocated version above, so we do not need to process
706 // relocations for it now.
707 if (L && L->getLoadedSectionContents(*RelocatedSection,RelSecData))
710 // In Mach-o files, the relocations do not need to be applied if
711 // there is no load offset to apply. The value read at the
712 // relocation point already factors in the section address
713 // (actually applying the relocations will produce wrong results
714 // as the section address will be added twice).
715 if (!L && isa<MachOObjectFile>(&Obj))
718 RelSecName = RelSecName.substr(
719 RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
721 // TODO: Add support for relocations in other sections as needed.
722 // Record relocations for the debug_info and debug_line sections.
723 RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
724 .Case("debug_info", &InfoSection.Relocs)
725 .Case("debug_loc", &LocSection.Relocs)
726 .Case("debug_info.dwo", &InfoDWOSection.Relocs)
727 .Case("debug_line", &LineSection.Relocs)
728 .Case("apple_names", &AppleNamesSection.Relocs)
729 .Case("apple_types", &AppleTypesSection.Relocs)
730 .Case("apple_namespaces", &AppleNamespacesSection.Relocs)
731 .Case("apple_namespac", &AppleNamespacesSection.Relocs)
732 .Case("apple_objc", &AppleObjCSection.Relocs)
735 // Find debug_types relocs by section rather than name as there are
736 // multiple, comdat grouped, debug_types sections.
737 if (RelSecName == "debug_types")
738 Map = &TypesSections[*RelocatedSection].Relocs;
739 else if (RelSecName == "debug_types.dwo")
740 Map = &TypesDWOSections[*RelocatedSection].Relocs;
745 if (Section.relocation_begin() != Section.relocation_end()) {
746 uint64_t SectionSize = RelocatedSection->getSize();
747 for (const RelocationRef &Reloc : Section.relocations()) {
748 uint64_t Address = Reloc.getOffset();
749 uint64_t Type = Reloc.getType();
750 uint64_t SymAddr = 0;
751 uint64_t SectionLoadAddress = 0;
752 object::symbol_iterator Sym = Reloc.getSymbol();
753 object::section_iterator RSec = Obj.section_end();
755 // First calculate the address of the symbol or section as it appears
757 if (Sym != Obj.symbol_end()) {
758 ErrorOr<uint64_t> SymAddrOrErr = Sym->getAddress();
759 if (std::error_code EC = SymAddrOrErr.getError()) {
760 errs() << "error: failed to compute symbol address: "
761 << EC.message() << '\n';
764 SymAddr = *SymAddrOrErr;
765 // Also remember what section this symbol is in for later
766 RSec = *Sym->getSection();
767 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
768 // MachO also has relocations that point to sections and
769 // scattered relocations.
770 auto RelocInfo = MObj->getRelocation(Reloc.getRawDataRefImpl());
771 if (MObj->isRelocationScattered(RelocInfo)) {
772 // FIXME: it's not clear how to correctly handle scattered
776 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
777 SymAddr = RSec->getAddress();
781 // If we are given load addresses for the sections, we need to adjust:
782 // SymAddr = (Address of Symbol Or Section in File) -
783 // (Address of Section in File) +
784 // (Load Address of Section)
785 if (L != nullptr && RSec != Obj.section_end()) {
786 // RSec is now either the section being targeted or the section
787 // containing the symbol being targeted. In either case,
788 // we need to perform the same computation.
790 RSec->getName(SecName);
791 // llvm::dbgs() << "Name: '" << SecName
792 // << "', RSec: " << RSec->getRawDataRefImpl()
793 // << ", Section: " << Section.getRawDataRefImpl() << "\n";
794 SectionLoadAddress = L->getSectionLoadAddress(*RSec);
795 if (SectionLoadAddress != 0)
796 SymAddr += SectionLoadAddress - RSec->getAddress();
799 object::RelocVisitor V(Obj);
800 object::RelocToApply R(V.visit(Type, Reloc, SymAddr));
802 SmallString<32> Name;
803 Reloc.getTypeName(Name);
804 errs() << "error: failed to compute relocation: "
809 if (Address + R.Width > SectionSize) {
810 errs() << "error: " << R.Width << "-byte relocation starting "
811 << Address << " bytes into section " << name << " which is "
812 << SectionSize << " bytes long.\n";
816 errs() << "error: can't handle a relocation of more than 8 bytes at "
820 DEBUG(dbgs() << "Writing " << format("%p", R.Value)
821 << " at " << format("%p", Address)
822 << " with width " << format("%d", R.Width)
824 Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
830 void DWARFContextInMemory::anchor() { }