blob: cd7a81fe892855780df965e2dd97e49ded8ae888 [file] [log] [blame]
Eugene Zelenko28db7e62017-03-01 01:14:23 +00001//===- DWARFContext.cpp ---------------------------------------------------===//
Benjamin Krameraa2f78f2011-09-13 19:42:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Greg Claytonb8c162b2017-05-03 16:02:29 +000010#include "llvm/DebugInfo/DWARF/DWARFContext.h"
11#include "llvm/ADT/STLExtras.h"
Alexey Samsonove16e16a2012-07-19 07:03:58 +000012#include "llvm/ADT/SmallString.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000013#include "llvm/ADT/SmallVector.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000014#include "llvm/ADT/StringRef.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000015#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000016#include "llvm/BinaryFormat/Dwarf.h"
Zachary Turner82af9432015-01-30 18:07:45 +000017#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000018#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000019#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000021#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000022#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
23#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
24#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
25#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
George Rimare71e33f2016-12-17 09:10:32 +000026#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000027#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
28#include "llvm/DebugInfo/DWARF/DWARFDie.h"
29#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
30#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
31#include "llvm/DebugInfo/DWARF/DWARFSection.h"
David Blaikie65a8efe2015-11-11 19:28:21 +000032#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000033#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Reid Klecknera0587362017-08-29 21:41:21 +000034#include "llvm/MC/MCRegisterInfo.h"
George Rimar4bf30832017-01-11 15:26:41 +000035#include "llvm/Object/Decompressor.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000036#include "llvm/Object/MachO.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000037#include "llvm/Object/ObjectFile.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000038#include "llvm/Object/RelocVisitor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000039#include "llvm/Support/Casting.h"
40#include "llvm/Support/DataExtractor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000041#include "llvm/Support/Error.h"
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +000042#include "llvm/Support/Format.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000043#include "llvm/Support/MemoryBuffer.h"
Adrian Prantl3ae35eb2017-09-13 22:09:01 +000044#include "llvm/Support/Path.h"
Reid Klecknera0587362017-08-29 21:41:21 +000045#include "llvm/Support/TargetRegistry.h"
Benjamin Kramera6002fd2011-09-14 01:09:52 +000046#include "llvm/Support/raw_ostream.h"
Benjamin Kramer2602ca62011-09-15 20:43:22 +000047#include <algorithm>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000048#include <cstdint>
Greg Claytonc7695a82017-05-02 20:28:33 +000049#include <map>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000050#include <string>
51#include <utility>
52#include <vector>
53
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000054using namespace llvm;
Benjamin Kramer6dda0322011-09-15 18:02:20 +000055using namespace dwarf;
Rafael Espindola4f60a382013-05-30 03:05:14 +000056using namespace object;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000057
Chandler Carruthe96dd892014-04-21 22:55:11 +000058#define DEBUG_TYPE "dwarf"
59
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000060using DWARFLineTable = DWARFDebugLine::LineTable;
61using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
62using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
Eric Christopher494109b2012-10-16 23:46:25 +000063
Reid Klecknera0587362017-08-29 21:41:21 +000064DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
65 std::string DWPName)
66 : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
67
68DWARFContext::~DWARFContext() = default;
69
Adrian Prantl3dcd1222017-09-13 18:22:59 +000070/// Dump the UUID load command.
71static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
72 auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
73 if (!MachO)
74 return;
75 for (auto LC : MachO->load_commands()) {
76 raw_ostream::uuid_t UUID;
77 if (LC.C.cmd == MachO::LC_UUID) {
78 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
79 OS << "error: UUID load command is too short.\n";
80 return;
81 }
82 OS << "UUID: ";
83 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
84 OS.write_uuid(UUID);
85 OS << ' ' << MachO->getFileFormatName();
86 OS << ' ' << MachO->getFileName() << '\n';
87 }
88 }
89}
90
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000091static void
92dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +000093 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000094 const DWARFSection &StringOffsetsSection,
95 StringRef StringSection, bool LittleEndian) {
Rafael Espindolac398e672017-07-19 22:27:28 +000096 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000097 uint32_t Offset = 0;
98 uint64_t SectionSize = StringOffsetsSection.Data.size();
99
100 while (Offset < SectionSize) {
101 unsigned Version = 0;
102 DwarfFormat Format = DWARF32;
103 unsigned EntrySize = 4;
104 // Perform validation and extract the segment size from the header.
105 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
106 OS << "error: invalid contribution to string offsets table in section ."
107 << SectionName << ".\n";
108 return;
109 }
110 uint32_t ContributionStart = Offset;
111 uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
112 // A contribution size of 0xffffffff indicates DWARF64, with the actual size
113 // in the following 8 bytes. Otherwise, the DWARF standard mandates that
114 // the contribution size must be at most 0xfffffff0.
115 if (ContributionSize == 0xffffffff) {
116 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
117 OS << "error: invalid contribution to string offsets table in section ."
118 << SectionName << ".\n";
119 return;
120 }
121 Format = DWARF64;
122 EntrySize = 8;
123 ContributionSize = StrOffsetExt.getU64(&Offset);
124 } else if (ContributionSize > 0xfffffff0) {
125 OS << "error: invalid contribution to string offsets table in section ."
126 << SectionName << ".\n";
127 return;
128 }
129
130 // We must ensure that we don't read a partial record at the end, so we
131 // validate for a multiple of EntrySize. Also, we're expecting a version
132 // number and padding, which adds an additional 4 bytes.
133 uint64_t ValidationSize =
134 4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
135 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
136 OS << "error: contribution to string offsets table in section ."
137 << SectionName << " has invalid length.\n";
138 return;
139 }
140
141 Version = StrOffsetExt.getU16(&Offset);
142 Offset += 2;
143 OS << format("0x%8.8x: ", ContributionStart);
144 OS << "Contribution size = " << ContributionSize
145 << ", Version = " << Version << "\n";
146
147 uint32_t ContributionBase = Offset;
148 DataExtractor StrData(StringSection, LittleEndian, 0);
149 while (Offset - ContributionBase < ContributionSize) {
150 OS << format("0x%8.8x: ", Offset);
151 // FIXME: We can only extract strings in DWARF32 format at the moment.
Paul Robinson17536b92017-06-29 16:52:08 +0000152 uint64_t StringOffset =
153 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000154 if (Format == DWARF32) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000155 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000156 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000157 const char *S = StrData.getCStr(&StringOffset32);
158 if (S)
159 OS << format("\"%s\"", S);
160 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000161 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000162 OS << "\n";
163 }
164 }
165}
166
167// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
168// string offsets section, where each compile or type unit contributes a
169// number of entries (string offsets), with each contribution preceded by
170// a header containing size and version number. Alternatively, it may be a
171// monolithic series of string offsets, as generated by the pre-DWARF v5
172// implementation of split DWARF.
173static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000174 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000175 const DWARFSection &StringOffsetsSection,
176 StringRef StringSection, bool LittleEndian,
177 unsigned MaxVersion) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000178 // If we have at least one (compile or type) unit with DWARF v5 or greater,
179 // we assume that the section is formatted like a DWARF v5 string offsets
180 // section.
181 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000182 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000183 StringSection, LittleEndian);
184 else {
185 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
186 uint32_t offset = 0;
187 uint64_t size = StringOffsetsSection.Data.size();
188 // Ensure that size is a multiple of the size of an entry.
189 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
190 OS << "error: size of ." << SectionName << " is not a multiple of "
191 << sizeof(uint32_t) << ".\n";
192 size &= -(uint64_t)sizeof(uint32_t);
193 }
194 DataExtractor StrData(StringSection, LittleEndian, 0);
195 while (offset < size) {
196 OS << format("0x%8.8x: ", offset);
197 uint32_t StringOffset = strOffsetExt.getU32(&offset);
198 OS << format("%8.8x ", StringOffset);
199 const char *S = StrData.getCStr(&StringOffset);
200 if (S)
201 OS << format("\"%s\"", S);
202 OS << "\n";
203 }
204 }
205}
206
Paul Robinson63811a42017-11-22 15:33:17 +0000207// We want to supply the Unit associated with a .debug_line[.dwo] table when
208// we dump it, if possible, but still dump the table even if there isn't a Unit.
209// Therefore, collect up handles on all the Units that point into the
210// line-table section.
211typedef std::map<uint64_t, DWARFUnit *> LineToUnitMap;
212
213static LineToUnitMap
214buildLineToUnitMap(DWARFContext::cu_iterator_range CUs,
215 DWARFContext::tu_section_iterator_range TUSections) {
216 LineToUnitMap LineToUnit;
217 for (const auto &CU : CUs)
218 if (auto CUDIE = CU->getUnitDIE())
219 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
220 LineToUnit.insert(std::make_pair(*StmtOffset, &*CU));
221 for (const auto &TUS : TUSections)
222 for (const auto &TU : TUS)
223 if (auto TUDIE = TU->getUnitDIE())
224 if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list)))
225 LineToUnit.insert(std::make_pair(*StmtOffset, &*TU));
226 return LineToUnit;
227}
228
Adrian Prantl057d3362017-09-15 23:04:04 +0000229void DWARFContext::dump(
230 raw_ostream &OS, DIDumpOptions DumpOpts,
231 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
232
233 Optional<uint64_t> DumpOffset;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000234 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000235
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000236 StringRef Extension = sys::path::extension(DObj->getFileName());
237 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
238
239 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000240 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000241 if (DumpType & DIDT_UUID)
242 dumpUUID(OS, *ObjFile);
243
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000244 // Print a header for each explicitly-requested section.
245 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000246 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000247 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000248 bool ExplicitDWO = Explicit && IsDWO;
249 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
250 StringRef Section) {
251 DumpOffset = DumpOffsets[ID];
252 unsigned Mask = 1U << ID;
253 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
Adrian Prantl84168022017-09-15 17:39:50 +0000254 if (Should)
Adrian Prantl057d3362017-09-15 23:04:04 +0000255 OS << "\n" << Name << " contents:\n";
Adrian Prantl84168022017-09-15 17:39:50 +0000256 return Should;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000257 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000258
259 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000260 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
261 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000262 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000263 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
264 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000265 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000266
Adrian Prantl057d3362017-09-15 23:04:04 +0000267 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
268 DWARFSection Section, cu_iterator_range CUs) {
269 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
Adrian Prantlc8d86532017-09-18 21:44:40 +0000270 if (DumpOffset)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000271 getDIEForOffset(DumpOffset.getValue())
272 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantlc8d86532017-09-18 21:44:40 +0000273 else
274 for (const auto &CU : CUs)
Adrian Prantl057d3362017-09-15 23:04:04 +0000275 CU->dump(OS, DumpOpts);
276 }
277 };
278 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
279 compile_units());
280 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
281 dwo_compile_units());
David Blaikie622dce42014-01-08 23:29:59 +0000282
Adrian Prantl099d7e42017-09-16 16:58:18 +0000283 auto dumpDebugType = [&](const char *Name,
284 tu_section_iterator_range TUSections) {
285 OS << '\n' << Name << " contents:\n";
286 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
287 for (const auto &TUS : TUSections)
288 for (const auto &TU : TUS)
289 if (DumpOffset)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000290 TU->getDIEForOffset(*DumpOffset)
291 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantl099d7e42017-09-16 16:58:18 +0000292 else
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000293 TU->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000294 };
295 if ((DumpType & DIDT_DebugTypes)) {
296 if (Explicit || getNumTypeUnits())
297 dumpDebugType(".debug_types", type_unit_sections());
298 if (ExplicitDWO || getNumDWOTypeUnits())
299 dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
David Blaikie03c089c2013-09-23 22:44:47 +0000300 }
301
Adrian Prantl057d3362017-09-15 23:04:04 +0000302 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000303 DObj->getLocSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000304 getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie18e73502013-06-19 21:37:13 +0000305 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000306 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000307 DObj->getLocDWOSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000308 getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie9c550ac2014-03-25 01:44:02 +0000309 }
310
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000311 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000312 DObj->getDebugFrameSection()))
313 getDebugFrame()->dump(OS, DumpOffset);
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000314
315 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000316 DObj->getEHFrameSection()))
317 getEHFrame()->dump(OS, DumpOffset);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000318
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000319 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000320 if (Explicit || !getDebugMacro()->empty()) {
321 OS << "\n.debug_macinfo contents:\n";
322 getDebugMacro()->dump(OS);
323 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000324 }
325
Adrian Prantl057d3362017-09-15 23:04:04 +0000326 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000327 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000328 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000329 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000330 DWARFDebugArangeSet set;
331 while (set.extract(arangesData, &offset))
332 set.dump(OS);
333 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000334
Adrian Prantl057d3362017-09-15 23:04:04 +0000335 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000336 DObj->getLineSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000337 LineToUnitMap LineToUnit =
338 buildLineToUnitMap(compile_units(), type_unit_sections());
339 unsigned Offset = 0;
340 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
341 0);
342 while (Offset < LineData.getData().size()) {
343 DWARFUnit *U = nullptr;
344 auto It = LineToUnit.find(Offset);
Paul Robinson511b54c2017-11-22 15:48:30 +0000345 if (It != LineToUnit.end())
Paul Robinson63811a42017-11-22 15:33:17 +0000346 U = It->second;
Paul Robinson511b54c2017-11-22 15:48:30 +0000347 LineData.setAddressSize(U ? U->getAddressByteSize() : 0);
Paul Robinson63811a42017-11-22 15:33:17 +0000348 DWARFDebugLine::LineTable LineTable;
349 if (DumpOffset && Offset != *DumpOffset) {
350 // Find the size of this part of the line table section and skip it.
351 unsigned OldOffset = Offset;
352 LineTable.Prologue.parse(LineData, &Offset, U);
353 Offset = OldOffset + LineTable.Prologue.TotalLength +
354 LineTable.Prologue.sizeofTotalLength();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000355 continue;
Paul Robinson63811a42017-11-22 15:33:17 +0000356 }
357 // Verbose dumping is done during parsing and not on the intermediate
358 // representation.
359 OS << "debug_line[" << format("0x%8.8x", Offset) << "]\n";
360 if (DumpOpts.Verbose) {
361 LineTable.parse(LineData, &Offset, U, &OS);
362 } else {
363 LineTable.parse(LineData, &Offset, U);
364 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000365 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000366 }
367 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000368
Adrian Prantl057d3362017-09-15 23:04:04 +0000369 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000370 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000371 LineToUnitMap LineToUnit =
372 buildLineToUnitMap(dwo_compile_units(), dwo_type_unit_sections());
373 unsigned Offset = 0;
374 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
375 isLittleEndian(), 0);
376 while (Offset < LineData.getData().size()) {
377 DWARFUnit *U = nullptr;
378 auto It = LineToUnit.find(Offset);
379 if (It != LineToUnit.end())
380 U = It->second;
381 DWARFDebugLine::LineTable LineTable;
382 if (!LineTable.Prologue.parse(LineData, &Offset, U))
383 break;
Alexey Samsonov110d5952014-04-30 00:09:19 +0000384 LineTable.dump(OS);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000385 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000386 }
387
Adrian Prantl057d3362017-09-15 23:04:04 +0000388 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000389 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000390 getCUIndex().dump(OS);
391 }
392
Adrian Prantl057d3362017-09-15 23:04:04 +0000393 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000394 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000395 getTUIndex().dump(OS);
396 }
397
Adrian Prantl057d3362017-09-15 23:04:04 +0000398 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000399 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000400 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000401 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000402 uint32_t strOffset = 0;
403 while (const char *s = strData.getCStr(&offset)) {
404 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
405 strOffset = offset;
406 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000407 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000408 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000409 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000410 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000411 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000412 uint32_t strDWOOffset = 0;
413 while (const char *s = strDWOData.getCStr(&offset)) {
414 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
415 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000416 }
David Blaikie66865d62014-01-09 00:13:35 +0000417 }
David Blaikie622dce42014-01-08 23:29:59 +0000418
Adrian Prantl057d3362017-09-15 23:04:04 +0000419 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000420 DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000421 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000422 // sizes, but for simplicity we just use the address byte size of the
423 // last compile unit (there is no easy and fast way to associate address
424 // range list and the compile unit it describes).
425 // FIXME: savedAddressByteSize seems sketchy.
Paul Robinson63811a42017-11-22 15:33:17 +0000426 uint8_t savedAddressByteSize = 0;
427 for (const auto &CU : compile_units()) {
428 savedAddressByteSize = CU->getAddressByteSize();
429 break;
430 }
Rafael Espindolac398e672017-07-19 22:27:28 +0000431 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
432 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000433 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000434 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000435 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000436 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000437 }
Eric Christopher962c9082013-01-15 23:56:56 +0000438
Adrian Prantl057d3362017-09-15 23:04:04 +0000439 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000440 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000441 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000442 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000443
Adrian Prantl057d3362017-09-15 23:04:04 +0000444 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000445 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000446 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000447 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000448
Adrian Prantl057d3362017-09-15 23:04:04 +0000449 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000450 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000451 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000452 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000453 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000454
Adrian Prantl057d3362017-09-15 23:04:04 +0000455 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000456 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000457 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000458 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000459 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000460
Adrian Prantl057d3362017-09-15 23:04:04 +0000461 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000462 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000463 dumpStringOffsetsSection(
464 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
465 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000466 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000467 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000468 dumpStringOffsetsSection(
469 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
470 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000471
Adrian Prantl057d3362017-09-15 23:04:04 +0000472 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000473 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000474 getGdbIndex().dump(OS);
475 }
476
Adrian Prantl057d3362017-09-15 23:04:04 +0000477 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000478 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000479 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000480
Adrian Prantl057d3362017-09-15 23:04:04 +0000481 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000482 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000483 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000484
Adrian Prantl057d3362017-09-15 23:04:04 +0000485 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000486 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000487 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000488
Adrian Prantl057d3362017-09-15 23:04:04 +0000489 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000490 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000491 getAppleObjC().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000492}
493
David Blaikie15d85fc2017-05-23 06:48:53 +0000494DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiee79dda32017-09-19 18:36:11 +0000495 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000496
David Blaikieebac0b92017-07-30 08:12:07 +0000497 if (const auto &CUI = getCUIndex()) {
498 if (const auto *R = CUI.getFromHash(Hash))
David Blaikiee79dda32017-09-19 18:36:11 +0000499 return DWOCUs.getUnitForIndexEntry(*R);
David Blaikieebac0b92017-07-30 08:12:07 +0000500 return nullptr;
501 }
502
503 // If there's no index, just search through the CUs in the DWO - there's
504 // probably only one unless this is something like LTO - though an in-process
505 // built/cached lookup table could be used in that case to improve repeated
506 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000507 for (const auto &DWOCU : dwo_compile_units())
508 if (DWOCU->getDWOId() == Hash)
509 return DWOCU.get();
510 return nullptr;
511}
512
Greg Claytonc7695a82017-05-02 20:28:33 +0000513DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
514 parseCompileUnits();
515 if (auto *CU = CUs.getUnitForOffset(Offset))
516 return CU->getDIEForOffset(Offset);
517 return DWARFDie();
518}
519
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000520bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000521 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000522 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000523
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000524 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000525 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000526 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000527 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000528 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000529 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000530 return Success;
531}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000532
David Blaikie82641be2015-11-17 00:39:55 +0000533const DWARFUnitIndex &DWARFContext::getCUIndex() {
534 if (CUIndex)
535 return *CUIndex;
536
Rafael Espindolac398e672017-07-19 22:27:28 +0000537 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000538
David Blaikieb073cb92015-12-02 06:21:34 +0000539 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000540 CUIndex->parse(CUIndexData);
541 return *CUIndex;
542}
543
544const DWARFUnitIndex &DWARFContext::getTUIndex() {
545 if (TUIndex)
546 return *TUIndex;
547
Rafael Espindolac398e672017-07-19 22:27:28 +0000548 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000549
David Blaikieb073cb92015-12-02 06:21:34 +0000550 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000551 TUIndex->parse(TUIndexData);
552 return *TUIndex;
553}
554
George Rimar4f82df52016-09-23 11:01:53 +0000555DWARFGdbIndex &DWARFContext::getGdbIndex() {
556 if (GdbIndex)
557 return *GdbIndex;
558
Rafael Espindolac398e672017-07-19 22:27:28 +0000559 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000560 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
561 GdbIndex->parse(GdbIndexData);
562 return *GdbIndex;
563}
564
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000565const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
566 if (Abbrev)
567 return Abbrev.get();
568
Rafael Espindolac398e672017-07-19 22:27:28 +0000569 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000570
571 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000572 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000573 return Abbrev.get();
574}
575
Eric Christopherda4b2192013-01-02 23:52:13 +0000576const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
577 if (AbbrevDWO)
578 return AbbrevDWO.get();
579
Rafael Espindolac398e672017-07-19 22:27:28 +0000580 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000581 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000582 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000583 return AbbrevDWO.get();
584}
585
David Blaikie18e73502013-06-19 21:37:13 +0000586const DWARFDebugLoc *DWARFContext::getDebugLoc() {
587 if (Loc)
588 return Loc.get();
589
Paul Robinson17536b92017-06-29 16:52:08 +0000590 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000591 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000592 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000593 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000594 getCompileUnitAtIndex(0)->getAddressByteSize());
595 Loc->parse(LocData);
596 }
David Blaikie18e73502013-06-19 21:37:13 +0000597 return Loc.get();
598}
599
David Blaikie9c550ac2014-03-25 01:44:02 +0000600const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
601 if (LocDWO)
602 return LocDWO.get();
603
Rafael Espindolac398e672017-07-19 22:27:28 +0000604 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000605 LocDWO.reset(new DWARFDebugLocDWO());
606 LocDWO->parse(LocData);
607 return LocDWO.get();
608}
609
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000610const DWARFDebugAranges *DWARFContext::getDebugAranges() {
611 if (Aranges)
612 return Aranges.get();
613
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000614 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000615 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000616 return Aranges.get();
617}
618
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000619const DWARFDebugFrame *DWARFContext::getDebugFrame() {
620 if (DebugFrame)
621 return DebugFrame.get();
622
623 // There's a "bug" in the DWARFv3 standard with respect to the target address
624 // size within debug frame sections. While DWARF is supposed to be independent
625 // of its container, FDEs have fields with size being "target address size",
626 // which isn't specified in DWARF in general. It's only specified for CUs, but
627 // .eh_frame can appear without a .debug_info section. Follow the example of
628 // other tools (libdwarf) and extract this from the container (ObjectFile
629 // provides this information). This problem is fixed in DWARFv4
630 // See this dwarf-discuss discussion for more details:
631 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000632 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
633 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000634 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
635 DebugFrame->parse(debugFrameData);
636 return DebugFrame.get();
637}
638
639const DWARFDebugFrame *DWARFContext::getEHFrame() {
640 if (EHFrame)
641 return EHFrame.get();
642
Rafael Espindolac398e672017-07-19 22:27:28 +0000643 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
644 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000645 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000646 DebugFrame->parse(debugFrameData);
647 return DebugFrame.get();
648}
649
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000650const DWARFDebugMacro *DWARFContext::getDebugMacro() {
651 if (Macro)
652 return Macro.get();
653
Rafael Espindolac398e672017-07-19 22:27:28 +0000654 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000655 Macro.reset(new DWARFDebugMacro());
656 Macro->parse(MacinfoData);
657 return Macro.get();
658}
659
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000660static DWARFAcceleratorTable &
661getAccelTable(std::unique_ptr<DWARFAcceleratorTable> &Cache,
662 const DWARFObject &Obj, const DWARFSection &Section,
663 StringRef StringSection, bool IsLittleEndian) {
664 if (Cache)
665 return *Cache;
666 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
667 DataExtractor StrData(StringSection, IsLittleEndian, 0);
668 Cache.reset(new DWARFAcceleratorTable(AccelSection, StrData));
669 Cache->extract();
670 return *Cache;
671}
672
673const DWARFAcceleratorTable &DWARFContext::getAppleNames() {
674 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
675 DObj->getStringSection(), isLittleEndian());
676}
677
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000678const DWARFAcceleratorTable &DWARFContext::getAppleTypes() {
679 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
680 DObj->getStringSection(), isLittleEndian());
681}
682
Adrian Prantlf51e7802017-09-29 00:52:33 +0000683const DWARFAcceleratorTable &DWARFContext::getAppleNamespaces() {
684 return getAccelTable(AppleNamespaces, *DObj,
685 DObj->getAppleNamespacesSection(),
686 DObj->getStringSection(), isLittleEndian());
687}
688
689const DWARFAcceleratorTable &DWARFContext::getAppleObjC() {
690 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
691 DObj->getStringSection(), isLittleEndian());
692}
693
Eric Christopher494109b2012-10-16 23:46:25 +0000694const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000695DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000696 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000697 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000698
Greg Claytonc8c10322016-12-13 18:25:19 +0000699 auto UnitDIE = U->getUnitDIE();
700 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000701 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000702
Greg Clayton97d22182017-01-13 21:08:18 +0000703 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000704 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000705 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000706
Greg Clayton52fe1f62016-12-14 22:38:08 +0000707 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000708 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000709 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000710 return lt;
711
Greg Clayton48ff66a2017-05-04 18:29:44 +0000712 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000713 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000714 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000715
Benjamin Kramer679e1752011-09-15 20:43:18 +0000716 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000717 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000718 U->getAddressByteSize());
Paul Robinsone5400f82017-11-07 19:57:12 +0000719 return Line->getOrParseLineTable(lineData, stmtOffset, U);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000720}
721
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000722void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000723 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000724}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000725
David Blaikie03c089c2013-09-23 22:44:47 +0000726void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000727 if (!TUs.empty())
728 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000729 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000730 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000731 TUs.back().parse(*this, S);
732 });
David Blaikie03c089c2013-09-23 22:44:47 +0000733}
734
Eric Christopherda4b2192013-01-02 23:52:13 +0000735void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000736 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000737}
738
David Blaikie92d9d622014-01-09 05:08:24 +0000739void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000740 if (!DWOTUs.empty())
741 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000742 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000743 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000744 DWOTUs.back().parseDWO(*this, S);
745 });
David Blaikie92d9d622014-01-09 05:08:24 +0000746}
747
Alexey Samsonov45be7932012-08-30 07:49:50 +0000748DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000749 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000750 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000751}
752
Alexey Samsonov45be7932012-08-30 07:49:50 +0000753DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000754 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000755 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000756 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000757 return getCompileUnitForOffset(CUOffset);
758}
759
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000760DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
761 DIEsForAddress Result;
762
763 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
764 if (!CU)
765 return Result;
766
767 Result.CompileUnit = CU;
768 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
769
770 std::vector<DWARFDie> Worklist;
771 Worklist.push_back(Result.FunctionDIE);
772 while (!Worklist.empty()) {
773 DWARFDie DIE = Worklist.back();
774 Worklist.pop_back();
775
776 if (DIE.getTag() == DW_TAG_lexical_block &&
777 DIE.addressRangeContainsAddress(Address)) {
778 Result.BlockDIE = DIE;
779 break;
780 }
781
782 for (auto Child : DIE)
783 Worklist.push_back(Child);
784 }
785
786 return Result;
787}
788
David Blaikieefc4eba2017-02-06 20:19:02 +0000789static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
790 uint64_t Address,
791 FunctionNameKind Kind,
792 std::string &FunctionName,
793 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000794 // The address may correspond to instruction in some inlined function,
795 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000796 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000797 SmallVector<DWARFDie, 4> InlinedChain;
798 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000799 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000800 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000801
802 const DWARFDie &DIE = InlinedChain[0];
803 bool FoundResult = false;
804 const char *Name = nullptr;
805 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000806 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000807 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000808 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000809 if (auto DeclLineResult = DIE.getDeclLine()) {
810 StartLine = DeclLineResult;
811 FoundResult = true;
812 }
813
814 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000815}
816
Alexey Samsonov45be7932012-08-30 07:49:50 +0000817DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000818 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000819 DILineInfo Result;
820
Alexey Samsonov45be7932012-08-30 07:49:50 +0000821 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
822 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000823 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000824 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
825 Result.FunctionName,
826 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000827 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000828 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
829 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
830 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000831 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000832 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000833}
David Blaikiea379b1812011-12-20 02:50:00 +0000834
Alexey Samsonovdce67342014-05-15 21:24:32 +0000835DILineInfoTable
836DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
837 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000838 DILineInfoTable Lines;
839 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
840 if (!CU)
841 return Lines;
842
843 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000844 uint32_t StartLine = 0;
845 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
846 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000847
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000848 // If the Specifier says we don't need FileLineInfo, just
849 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000850 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000851 DILineInfo Result;
852 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000853 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000854 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000855 return Lines;
856 }
857
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000858 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000859
860 // Get the index of row we're looking for in the line table.
861 std::vector<uint32_t> RowVector;
862 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
863 return Lines;
864
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000865 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000866 // Take file number and line/column from the row.
867 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000868 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000869 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
870 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000871 Result.FunctionName = FunctionName;
872 Result.Line = Row.Line;
873 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000874 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000875 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000876 }
877
878 return Lines;
879}
880
Alexey Samsonovdce67342014-05-15 21:24:32 +0000881DIInliningInfo
882DWARFContext::getInliningInfoForAddress(uint64_t Address,
883 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000884 DIInliningInfo InliningInfo;
885
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000886 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
887 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000888 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000889
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000890 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000891 SmallVector<DWARFDie, 4> InlinedChain;
892 CU->getInlinedChainForAddress(Address, InlinedChain);
893 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000894 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
895 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000896 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000897 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000898 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000899 if (LineTable &&
900 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
901 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000902 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000903 }
904 return InliningInfo;
905 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000906
Dehao Chenef700d52017-04-17 20:10:39 +0000907 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000908 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
909 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000910 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000911 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000912 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000913 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000914 if (auto DeclLineResult = FunctionDIE.getDeclLine())
915 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000916 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000917 if (i == 0) {
918 // For the topmost frame, initialize the line table of this
919 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000920 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000921 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000922 if (LineTable)
923 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
924 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000925 } else {
926 // Otherwise, use call file, call line and call column from
927 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000928 if (LineTable)
929 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
930 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000931 Frame.Line = CallLine;
932 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000933 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000934 }
935 // Get call file/line/column of a current DIE.
936 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000937 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
938 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000939 }
940 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000941 InliningInfo.addFrame(Frame);
942 }
943 return InliningInfo;
944}
945
David Blaikief9803fb2017-05-23 00:30:42 +0000946std::shared_ptr<DWARFContext>
947DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000948 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000949 DWARFContext *Ctxt = S->Context.get();
950 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
951 }
952
David Blaikie15d85fc2017-05-23 06:48:53 +0000953 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
954
955 if (auto S = Entry->lock()) {
956 DWARFContext *Ctxt = S->Context.get();
957 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
958 }
959
David Blaikie15d85fc2017-05-23 06:48:53 +0000960 Expected<OwningBinary<ObjectFile>> Obj = [&] {
961 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000962 SmallString<128> DWPName;
963 auto Obj = object::ObjectFile::createObjectFile(
964 this->DWPName.empty()
965 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
966 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000967 if (Obj) {
968 Entry = &DWP;
969 return Obj;
970 } else {
971 CheckedForDWP = true;
972 // TODO: Should this error be handled (maybe in a high verbosity mode)
973 // before falling back to .dwo files?
974 consumeError(Obj.takeError());
975 }
976 }
977
978 return object::ObjectFile::createObjectFile(AbsolutePath);
979 }();
980
David Blaikief9803fb2017-05-23 00:30:42 +0000981 if (!Obj) {
982 // TODO: Actually report errors helpfully.
983 consumeError(Obj.takeError());
984 return nullptr;
985 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000986
987 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000988 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000989 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000990 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000991 auto *Ctxt = S->Context.get();
992 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
993}
994
George Rimar702dac62017-04-12 08:59:15 +0000995static Error createError(const Twine &Reason, llvm::Error E) {
996 return make_error<StringError>(Reason + toString(std::move(E)),
997 inconvertibleErrorCode());
998}
999
George Rimara25d3292017-05-27 18:10:23 +00001000/// SymInfo contains information about symbol: it's address
1001/// and section index which is -1LL for absolute symbols.
1002struct SymInfo {
1003 uint64_t Address;
1004 uint64_t SectionIndex;
1005};
1006
1007/// Returns the address of symbol relocation used against and a section index.
1008/// Used for futher relocations computation. Symbol's section load address is
1009static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1010 const RelocationRef &Reloc,
1011 const LoadedObjectInfo *L,
1012 std::map<SymbolRef, SymInfo> &Cache) {
1013 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001014 object::section_iterator RSec = Obj.section_end();
1015 object::symbol_iterator Sym = Reloc.getSymbol();
1016
George Rimara25d3292017-05-27 18:10:23 +00001017 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001018 // First calculate the address of the symbol or section as it appears
1019 // in the object file
1020 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001021 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001022 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001023 if (!New)
1024 return CacheIt->second;
1025
George Rimar702dac62017-04-12 08:59:15 +00001026 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1027 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001028 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001029 SymAddrOrErr.takeError());
1030
1031 // Also remember what section this symbol is in for later
1032 auto SectOrErr = Sym->getSection();
1033 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001034 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001035 SectOrErr.takeError());
1036
1037 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001038 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001039 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1040 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001041 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001042 }
1043
George Rimara25d3292017-05-27 18:10:23 +00001044 if (RSec != Obj.section_end())
1045 Ret.SectionIndex = RSec->getIndex();
1046
George Rimar702dac62017-04-12 08:59:15 +00001047 // If we are given load addresses for the sections, we need to adjust:
1048 // SymAddr = (Address of Symbol Or Section in File) -
1049 // (Address of Section in File) +
1050 // (Load Address of Section)
1051 // RSec is now either the section being targeted or the section
1052 // containing the symbol being targeted. In either case,
1053 // we need to perform the same computation.
1054 if (L && RSec != Obj.section_end())
1055 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001056 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001057
1058 if (CacheIt != Cache.end())
1059 CacheIt->second = Ret;
1060
George Rimar702dac62017-04-12 08:59:15 +00001061 return Ret;
1062}
1063
1064static bool isRelocScattered(const object::ObjectFile &Obj,
1065 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001066 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1067 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001068 return false;
1069 // MachO also has relocations that point to sections and
1070 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001071 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1072 return MachObj->isRelocationScattered(RelocInfo);
1073}
1074
Rafael Espindolac398e672017-07-19 22:27:28 +00001075ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +00001076 errs() << "error: " + toString(std::move(E)) << '\n';
1077 return ErrorPolicy::Continue;
1078}
1079
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001080namespace {
1081struct DWARFSectionMap final : public DWARFSection {
1082 RelocAddrMap Relocs;
1083};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001084
Rafael Espindolac398e672017-07-19 22:27:28 +00001085class DWARFObjInMemory final : public DWARFObject {
1086 bool IsLittleEndian;
1087 uint8_t AddressSize;
1088 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001089 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001090 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001091
Rafael Espindolac398e672017-07-19 22:27:28 +00001092 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1093 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001094
Rafael Espindolac398e672017-07-19 22:27:28 +00001095 TypeSectionMap TypesSections;
1096 TypeSectionMap TypesDWOSections;
1097
1098 DWARFSectionMap InfoSection;
1099 DWARFSectionMap LocSection;
1100 DWARFSectionMap LineSection;
1101 DWARFSectionMap RangeSection;
1102 DWARFSectionMap StringOffsetSection;
1103 DWARFSectionMap InfoDWOSection;
1104 DWARFSectionMap LineDWOSection;
1105 DWARFSectionMap LocDWOSection;
1106 DWARFSectionMap StringOffsetDWOSection;
1107 DWARFSectionMap RangeDWOSection;
1108 DWARFSectionMap AddrSection;
1109 DWARFSectionMap AppleNamesSection;
1110 DWARFSectionMap AppleTypesSection;
1111 DWARFSectionMap AppleNamespacesSection;
1112 DWARFSectionMap AppleObjCSection;
1113
1114 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1115 return StringSwitch<DWARFSectionMap *>(Name)
1116 .Case("debug_info", &InfoSection)
1117 .Case("debug_loc", &LocSection)
1118 .Case("debug_line", &LineSection)
1119 .Case("debug_str_offsets", &StringOffsetSection)
1120 .Case("debug_ranges", &RangeSection)
1121 .Case("debug_info.dwo", &InfoDWOSection)
1122 .Case("debug_loc.dwo", &LocDWOSection)
1123 .Case("debug_line.dwo", &LineDWOSection)
1124 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1125 .Case("debug_addr", &AddrSection)
1126 .Case("apple_names", &AppleNamesSection)
1127 .Case("apple_types", &AppleTypesSection)
1128 .Case("apple_namespaces", &AppleNamespacesSection)
1129 .Case("apple_namespac", &AppleNamespacesSection)
1130 .Case("apple_objc", &AppleObjCSection)
1131 .Default(nullptr);
1132 }
1133
1134 StringRef AbbrevSection;
1135 StringRef ARangeSection;
1136 StringRef DebugFrameSection;
1137 StringRef EHFrameSection;
1138 StringRef StringSection;
1139 StringRef MacinfoSection;
1140 StringRef PubNamesSection;
1141 StringRef PubTypesSection;
1142 StringRef GnuPubNamesSection;
1143 StringRef AbbrevDWOSection;
1144 StringRef StringDWOSection;
1145 StringRef GnuPubTypesSection;
1146 StringRef CUIndexSection;
1147 StringRef GdbIndexSection;
1148 StringRef TUIndexSection;
1149
1150 SmallVector<SmallString<32>, 4> UncompressedSections;
1151
1152 StringRef *mapSectionToMember(StringRef Name) {
1153 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1154 return &Sec->Data;
1155 return StringSwitch<StringRef *>(Name)
1156 .Case("debug_abbrev", &AbbrevSection)
1157 .Case("debug_aranges", &ARangeSection)
1158 .Case("debug_frame", &DebugFrameSection)
1159 .Case("eh_frame", &EHFrameSection)
1160 .Case("debug_str", &StringSection)
1161 .Case("debug_macinfo", &MacinfoSection)
1162 .Case("debug_pubnames", &PubNamesSection)
1163 .Case("debug_pubtypes", &PubTypesSection)
1164 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1165 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1166 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1167 .Case("debug_str.dwo", &StringDWOSection)
1168 .Case("debug_cu_index", &CUIndexSection)
1169 .Case("debug_tu_index", &TUIndexSection)
1170 .Case("gdb_index", &GdbIndexSection)
1171 // Any more debug info sections go here.
1172 .Default(nullptr);
1173 }
1174
1175 /// If Sec is compressed section, decompresses and updates its contents
1176 /// provided by Data. Otherwise leaves it unchanged.
1177 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1178 StringRef &Data) {
1179 if (!Decompressor::isCompressed(Sec))
1180 return Error::success();
1181
1182 Expected<Decompressor> Decompressor =
1183 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1184 if (!Decompressor)
1185 return Decompressor.takeError();
1186
1187 SmallString<32> Out;
1188 if (auto Err = Decompressor->resizeAndDecompress(Out))
1189 return Err;
1190
1191 UncompressedSections.emplace_back(std::move(Out));
1192 Data = UncompressedSections.back();
1193
1194 return Error::success();
1195 }
1196
1197public:
1198 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1199 uint8_t AddrSize, bool IsLittleEndian)
1200 : IsLittleEndian(IsLittleEndian) {
1201 for (const auto &SecIt : Sections) {
1202 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1203 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001204 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001205 }
1206 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1207 function_ref<ErrorPolicy(Error)> HandleError)
1208 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001209 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1210 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001211
George Rimare1c30f72017-08-15 15:54:43 +00001212 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001213 for (const SectionRef &Section : Obj.sections()) {
1214 StringRef Name;
1215 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001216 ++SectionAmountMap[Name];
1217 SectionNames.push_back({ Name, true });
1218
Rafael Espindolac398e672017-07-19 22:27:28 +00001219 // Skip BSS and Virtual sections, they aren't interesting.
1220 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001221 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001222
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001223 // Skip sections stripped by dsymutil.
1224 if (Section.isStripped())
1225 continue;
1226
Rafael Espindolac398e672017-07-19 22:27:28 +00001227 StringRef Data;
1228 section_iterator RelocatedSection = Section.getRelocatedSection();
1229 // Try to obtain an already relocated version of this section.
1230 // Else use the unrelocated section from the object file. We'll have to
1231 // apply relocations ourselves later.
1232 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1233 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001234
Rafael Espindolac398e672017-07-19 22:27:28 +00001235 if (auto Err = maybeDecompress(Section, Name, Data)) {
1236 ErrorPolicy EP = HandleError(createError(
1237 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001238 if (EP == ErrorPolicy::Halt)
1239 return;
George Rimarfed9f092017-05-17 12:10:51 +00001240 continue;
1241 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001242
1243 // Compressed sections names in GNU style starts from ".z",
1244 // at this point section is decompressed and we drop compression prefix.
1245 Name = Name.substr(
1246 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1247
1248 // Map platform specific debug section names to DWARF standard section
1249 // names.
1250 Name = Obj.mapDebugSectionName(Name);
1251
1252 if (StringRef *SectionData = mapSectionToMember(Name)) {
1253 *SectionData = Data;
1254 if (Name == "debug_ranges") {
1255 // FIXME: Use the other dwo range section when we emit it.
1256 RangeDWOSection.Data = Data;
1257 }
1258 } else if (Name == "debug_types") {
1259 // Find debug_types data by section rather than name as there are
1260 // multiple, comdat grouped, debug_types sections.
1261 TypesSections[Section].Data = Data;
1262 } else if (Name == "debug_types.dwo") {
1263 TypesDWOSections[Section].Data = Data;
1264 }
1265
1266 if (RelocatedSection == Obj.section_end())
1267 continue;
1268
1269 StringRef RelSecName;
1270 StringRef RelSecData;
1271 RelocatedSection->getName(RelSecName);
1272
1273 // If the section we're relocating was relocated already by the JIT,
1274 // then we used the relocated version above, so we do not need to process
1275 // relocations for it now.
1276 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1277 continue;
1278
1279 // In Mach-o files, the relocations do not need to be applied if
1280 // there is no load offset to apply. The value read at the
1281 // relocation point already factors in the section address
1282 // (actually applying the relocations will produce wrong results
1283 // as the section address will be added twice).
1284 if (!L && isa<MachOObjectFile>(&Obj))
1285 continue;
1286
1287 RelSecName = RelSecName.substr(
1288 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1289
1290 // TODO: Add support for relocations in other sections as needed.
1291 // Record relocations for the debug_info and debug_line sections.
1292 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1293 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1294 if (!Map) {
1295 // Find debug_types relocs by section rather than name as there are
1296 // multiple, comdat grouped, debug_types sections.
1297 if (RelSecName == "debug_types")
1298 Map =
1299 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1300 .Relocs;
1301 else if (RelSecName == "debug_types.dwo")
1302 Map = &static_cast<DWARFSectionMap &>(
1303 TypesDWOSections[*RelocatedSection])
1304 .Relocs;
1305 else
1306 continue;
1307 }
1308
1309 if (Section.relocation_begin() == Section.relocation_end())
1310 continue;
1311
1312 // Symbol to [address, section index] cache mapping.
1313 std::map<SymbolRef, SymInfo> AddrCache;
1314 for (const RelocationRef &Reloc : Section.relocations()) {
1315 // FIXME: it's not clear how to correctly handle scattered
1316 // relocations.
1317 if (isRelocScattered(Obj, Reloc))
1318 continue;
1319
1320 Expected<SymInfo> SymInfoOrErr =
1321 getSymbolInfo(Obj, Reloc, L, AddrCache);
1322 if (!SymInfoOrErr) {
1323 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1324 return;
1325 continue;
1326 }
1327
1328 object::RelocVisitor V(Obj);
1329 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1330 if (V.error()) {
1331 SmallString<32> Type;
1332 Reloc.getTypeName(Type);
1333 ErrorPolicy EP = HandleError(
1334 createError("failed to compute relocation: " + Type + ", ",
1335 errorCodeToError(object_error::parse_failed)));
1336 if (EP == ErrorPolicy::Halt)
1337 return;
1338 continue;
1339 }
1340 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1341 Map->insert({Reloc.getOffset(), Rel});
1342 }
Eric Christopher7370b552012-11-12 21:40:38 +00001343 }
George Rimare1c30f72017-08-15 15:54:43 +00001344
1345 for (SectionName &S : SectionNames)
1346 if (SectionAmountMap[S.Name] > 1)
1347 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001348 }
Eric Christopher7370b552012-11-12 21:40:38 +00001349
Rafael Espindolac398e672017-07-19 22:27:28 +00001350 Optional<RelocAddrEntry> find(const DWARFSection &S,
1351 uint64_t Pos) const override {
1352 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1353 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1354 if (AI == Sec.Relocs.end())
1355 return None;
1356 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001357 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001358
George Rimar6957ab52017-08-15 12:32:54 +00001359 const object::ObjectFile *getFile() const override { return Obj; }
1360
George Rimare1c30f72017-08-15 15:54:43 +00001361 ArrayRef<SectionName> getSectionNames() const override {
1362 return SectionNames;
1363 }
1364
Rafael Espindolac398e672017-07-19 22:27:28 +00001365 bool isLittleEndian() const override { return IsLittleEndian; }
1366 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1367 const DWARFSection &getLineDWOSection() const override {
1368 return LineDWOSection;
1369 }
1370 const DWARFSection &getLocDWOSection() const override {
1371 return LocDWOSection;
1372 }
1373 StringRef getStringDWOSection() const override { return StringDWOSection; }
1374 const DWARFSection &getStringOffsetDWOSection() const override {
1375 return StringOffsetDWOSection;
1376 }
1377 const DWARFSection &getRangeDWOSection() const override {
1378 return RangeDWOSection;
1379 }
1380 const DWARFSection &getAddrSection() const override { return AddrSection; }
1381 StringRef getCUIndexSection() const override { return CUIndexSection; }
1382 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1383 StringRef getTUIndexSection() const override { return TUIndexSection; }
1384
1385 // DWARF v5
1386 const DWARFSection &getStringOffsetSection() const override {
1387 return StringOffsetSection;
1388 }
1389
1390 // Sections for DWARF5 split dwarf proposal.
1391 const DWARFSection &getInfoDWOSection() const override {
1392 return InfoDWOSection;
1393 }
1394 void forEachTypesDWOSections(
1395 function_ref<void(const DWARFSection &)> F) const override {
1396 for (auto &P : TypesDWOSections)
1397 F(P.second);
1398 }
1399
1400 StringRef getAbbrevSection() const override { return AbbrevSection; }
1401 const DWARFSection &getLocSection() const override { return LocSection; }
1402 StringRef getARangeSection() const override { return ARangeSection; }
1403 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1404 StringRef getEHFrameSection() const override { return EHFrameSection; }
1405 const DWARFSection &getLineSection() const override { return LineSection; }
1406 StringRef getStringSection() const override { return StringSection; }
1407 const DWARFSection &getRangeSection() const override { return RangeSection; }
1408 StringRef getMacinfoSection() const override { return MacinfoSection; }
1409 StringRef getPubNamesSection() const override { return PubNamesSection; }
1410 StringRef getPubTypesSection() const override { return PubTypesSection; }
1411 StringRef getGnuPubNamesSection() const override {
1412 return GnuPubNamesSection;
1413 }
1414 StringRef getGnuPubTypesSection() const override {
1415 return GnuPubTypesSection;
1416 }
1417 const DWARFSection &getAppleNamesSection() const override {
1418 return AppleNamesSection;
1419 }
1420 const DWARFSection &getAppleTypesSection() const override {
1421 return AppleTypesSection;
1422 }
1423 const DWARFSection &getAppleNamespacesSection() const override {
1424 return AppleNamespacesSection;
1425 }
1426 const DWARFSection &getAppleObjCSection() const override {
1427 return AppleObjCSection;
1428 }
1429
1430 StringRef getFileName() const override { return FileName; }
1431 uint8_t getAddressSize() const override { return AddressSize; }
1432 const DWARFSection &getInfoSection() const override { return InfoSection; }
1433 void forEachTypesSections(
1434 function_ref<void(const DWARFSection &)> F) const override {
1435 for (auto &P : TypesSections)
1436 F(P.second);
1437 }
1438};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001439} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001440
1441std::unique_ptr<DWARFContext>
1442DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001443 function_ref<ErrorPolicy(Error)> HandleError,
1444 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001445 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001446 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001447}
1448
Rafael Espindolac398e672017-07-19 22:27:28 +00001449std::unique_ptr<DWARFContext>
1450DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1451 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001452 auto DObj =
1453 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001454 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001455}
Reid Klecknera0587362017-08-29 21:41:21 +00001456
1457Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1458 // Detect the architecture from the object file. We usually don't need OS
1459 // info to lookup a target and create register info.
1460 Triple TT;
1461 TT.setArch(Triple::ArchType(Obj.getArch()));
1462 TT.setVendor(Triple::UnknownVendor);
1463 TT.setOS(Triple::UnknownOS);
1464 std::string TargetLookupError;
1465 const Target *TheTarget =
1466 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1467 if (!TargetLookupError.empty())
1468 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1469 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1470 return Error::success();
1471}