blob: e96678bc87c993bb0006a3024c216974b091abae [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);
345 if (It != LineToUnit.end()) {
346 U = It->second;
347 LineData.setAddressSize(U->getAddressByteSize());
348 }
349 DWARFDebugLine::LineTable LineTable;
350 if (DumpOffset && Offset != *DumpOffset) {
351 // Find the size of this part of the line table section and skip it.
352 unsigned OldOffset = Offset;
353 LineTable.Prologue.parse(LineData, &Offset, U);
354 Offset = OldOffset + LineTable.Prologue.TotalLength +
355 LineTable.Prologue.sizeofTotalLength();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000356 continue;
Paul Robinson63811a42017-11-22 15:33:17 +0000357 }
358 // Verbose dumping is done during parsing and not on the intermediate
359 // representation.
360 OS << "debug_line[" << format("0x%8.8x", Offset) << "]\n";
361 if (DumpOpts.Verbose) {
362 LineTable.parse(LineData, &Offset, U, &OS);
363 } else {
364 LineTable.parse(LineData, &Offset, U);
365 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000366 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000367 }
368 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000369
Adrian Prantl057d3362017-09-15 23:04:04 +0000370 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000371 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000372 LineToUnitMap LineToUnit =
373 buildLineToUnitMap(dwo_compile_units(), dwo_type_unit_sections());
374 unsigned Offset = 0;
375 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
376 isLittleEndian(), 0);
377 while (Offset < LineData.getData().size()) {
378 DWARFUnit *U = nullptr;
379 auto It = LineToUnit.find(Offset);
380 if (It != LineToUnit.end())
381 U = It->second;
382 DWARFDebugLine::LineTable LineTable;
383 if (!LineTable.Prologue.parse(LineData, &Offset, U))
384 break;
Alexey Samsonov110d5952014-04-30 00:09:19 +0000385 LineTable.dump(OS);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000386 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000387 }
388
Adrian Prantl057d3362017-09-15 23:04:04 +0000389 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000390 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000391 getCUIndex().dump(OS);
392 }
393
Adrian Prantl057d3362017-09-15 23:04:04 +0000394 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000395 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000396 getTUIndex().dump(OS);
397 }
398
Adrian Prantl057d3362017-09-15 23:04:04 +0000399 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000400 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000401 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000402 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000403 uint32_t strOffset = 0;
404 while (const char *s = strData.getCStr(&offset)) {
405 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
406 strOffset = offset;
407 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000408 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000409 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000410 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000411 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000412 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000413 uint32_t strDWOOffset = 0;
414 while (const char *s = strDWOData.getCStr(&offset)) {
415 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
416 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000417 }
David Blaikie66865d62014-01-09 00:13:35 +0000418 }
David Blaikie622dce42014-01-08 23:29:59 +0000419
Adrian Prantl057d3362017-09-15 23:04:04 +0000420 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000421 DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000422 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000423 // sizes, but for simplicity we just use the address byte size of the
424 // last compile unit (there is no easy and fast way to associate address
425 // range list and the compile unit it describes).
426 // FIXME: savedAddressByteSize seems sketchy.
Paul Robinson63811a42017-11-22 15:33:17 +0000427 uint8_t savedAddressByteSize = 0;
428 for (const auto &CU : compile_units()) {
429 savedAddressByteSize = CU->getAddressByteSize();
430 break;
431 }
Rafael Espindolac398e672017-07-19 22:27:28 +0000432 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
433 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000434 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000435 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000436 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000437 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000438 }
Eric Christopher962c9082013-01-15 23:56:56 +0000439
Adrian Prantl057d3362017-09-15 23:04:04 +0000440 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000441 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000442 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000443 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000444
Adrian Prantl057d3362017-09-15 23:04:04 +0000445 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000446 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000447 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000448 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000449
Adrian Prantl057d3362017-09-15 23:04:04 +0000450 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000451 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000452 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000453 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000454 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000455
Adrian Prantl057d3362017-09-15 23:04:04 +0000456 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000457 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000458 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000459 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000460 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000461
Adrian Prantl057d3362017-09-15 23:04:04 +0000462 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000463 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000464 dumpStringOffsetsSection(
465 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
466 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000467 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000468 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000469 dumpStringOffsetsSection(
470 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
471 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000472
Adrian Prantl057d3362017-09-15 23:04:04 +0000473 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000474 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000475 getGdbIndex().dump(OS);
476 }
477
Adrian Prantl057d3362017-09-15 23:04:04 +0000478 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000479 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000480 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000481
Adrian Prantl057d3362017-09-15 23:04:04 +0000482 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000483 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000484 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000485
Adrian Prantl057d3362017-09-15 23:04:04 +0000486 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000487 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000488 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000489
Adrian Prantl057d3362017-09-15 23:04:04 +0000490 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000491 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000492 getAppleObjC().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000493}
494
David Blaikie15d85fc2017-05-23 06:48:53 +0000495DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiee79dda32017-09-19 18:36:11 +0000496 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000497
David Blaikieebac0b92017-07-30 08:12:07 +0000498 if (const auto &CUI = getCUIndex()) {
499 if (const auto *R = CUI.getFromHash(Hash))
David Blaikiee79dda32017-09-19 18:36:11 +0000500 return DWOCUs.getUnitForIndexEntry(*R);
David Blaikieebac0b92017-07-30 08:12:07 +0000501 return nullptr;
502 }
503
504 // If there's no index, just search through the CUs in the DWO - there's
505 // probably only one unless this is something like LTO - though an in-process
506 // built/cached lookup table could be used in that case to improve repeated
507 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000508 for (const auto &DWOCU : dwo_compile_units())
509 if (DWOCU->getDWOId() == Hash)
510 return DWOCU.get();
511 return nullptr;
512}
513
Greg Claytonc7695a82017-05-02 20:28:33 +0000514DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
515 parseCompileUnits();
516 if (auto *CU = CUs.getUnitForOffset(Offset))
517 return CU->getDIEForOffset(Offset);
518 return DWARFDie();
519}
520
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000521bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000522 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000523 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000524
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000525 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000526 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000527 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000528 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000529 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000530 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000531 return Success;
532}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000533
David Blaikie82641be2015-11-17 00:39:55 +0000534const DWARFUnitIndex &DWARFContext::getCUIndex() {
535 if (CUIndex)
536 return *CUIndex;
537
Rafael Espindolac398e672017-07-19 22:27:28 +0000538 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000539
David Blaikieb073cb92015-12-02 06:21:34 +0000540 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000541 CUIndex->parse(CUIndexData);
542 return *CUIndex;
543}
544
545const DWARFUnitIndex &DWARFContext::getTUIndex() {
546 if (TUIndex)
547 return *TUIndex;
548
Rafael Espindolac398e672017-07-19 22:27:28 +0000549 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000550
David Blaikieb073cb92015-12-02 06:21:34 +0000551 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000552 TUIndex->parse(TUIndexData);
553 return *TUIndex;
554}
555
George Rimar4f82df52016-09-23 11:01:53 +0000556DWARFGdbIndex &DWARFContext::getGdbIndex() {
557 if (GdbIndex)
558 return *GdbIndex;
559
Rafael Espindolac398e672017-07-19 22:27:28 +0000560 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000561 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
562 GdbIndex->parse(GdbIndexData);
563 return *GdbIndex;
564}
565
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000566const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
567 if (Abbrev)
568 return Abbrev.get();
569
Rafael Espindolac398e672017-07-19 22:27:28 +0000570 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000571
572 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000573 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000574 return Abbrev.get();
575}
576
Eric Christopherda4b2192013-01-02 23:52:13 +0000577const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
578 if (AbbrevDWO)
579 return AbbrevDWO.get();
580
Rafael Espindolac398e672017-07-19 22:27:28 +0000581 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000582 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000583 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000584 return AbbrevDWO.get();
585}
586
David Blaikie18e73502013-06-19 21:37:13 +0000587const DWARFDebugLoc *DWARFContext::getDebugLoc() {
588 if (Loc)
589 return Loc.get();
590
Paul Robinson17536b92017-06-29 16:52:08 +0000591 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000592 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000593 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000594 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000595 getCompileUnitAtIndex(0)->getAddressByteSize());
596 Loc->parse(LocData);
597 }
David Blaikie18e73502013-06-19 21:37:13 +0000598 return Loc.get();
599}
600
David Blaikie9c550ac2014-03-25 01:44:02 +0000601const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
602 if (LocDWO)
603 return LocDWO.get();
604
Rafael Espindolac398e672017-07-19 22:27:28 +0000605 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000606 LocDWO.reset(new DWARFDebugLocDWO());
607 LocDWO->parse(LocData);
608 return LocDWO.get();
609}
610
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000611const DWARFDebugAranges *DWARFContext::getDebugAranges() {
612 if (Aranges)
613 return Aranges.get();
614
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000615 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000616 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000617 return Aranges.get();
618}
619
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000620const DWARFDebugFrame *DWARFContext::getDebugFrame() {
621 if (DebugFrame)
622 return DebugFrame.get();
623
624 // There's a "bug" in the DWARFv3 standard with respect to the target address
625 // size within debug frame sections. While DWARF is supposed to be independent
626 // of its container, FDEs have fields with size being "target address size",
627 // which isn't specified in DWARF in general. It's only specified for CUs, but
628 // .eh_frame can appear without a .debug_info section. Follow the example of
629 // other tools (libdwarf) and extract this from the container (ObjectFile
630 // provides this information). This problem is fixed in DWARFv4
631 // See this dwarf-discuss discussion for more details:
632 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000633 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
634 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000635 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
636 DebugFrame->parse(debugFrameData);
637 return DebugFrame.get();
638}
639
640const DWARFDebugFrame *DWARFContext::getEHFrame() {
641 if (EHFrame)
642 return EHFrame.get();
643
Rafael Espindolac398e672017-07-19 22:27:28 +0000644 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
645 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000646 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000647 DebugFrame->parse(debugFrameData);
648 return DebugFrame.get();
649}
650
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000651const DWARFDebugMacro *DWARFContext::getDebugMacro() {
652 if (Macro)
653 return Macro.get();
654
Rafael Espindolac398e672017-07-19 22:27:28 +0000655 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000656 Macro.reset(new DWARFDebugMacro());
657 Macro->parse(MacinfoData);
658 return Macro.get();
659}
660
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000661static DWARFAcceleratorTable &
662getAccelTable(std::unique_ptr<DWARFAcceleratorTable> &Cache,
663 const DWARFObject &Obj, const DWARFSection &Section,
664 StringRef StringSection, bool IsLittleEndian) {
665 if (Cache)
666 return *Cache;
667 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
668 DataExtractor StrData(StringSection, IsLittleEndian, 0);
669 Cache.reset(new DWARFAcceleratorTable(AccelSection, StrData));
670 Cache->extract();
671 return *Cache;
672}
673
674const DWARFAcceleratorTable &DWARFContext::getAppleNames() {
675 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
676 DObj->getStringSection(), isLittleEndian());
677}
678
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000679const DWARFAcceleratorTable &DWARFContext::getAppleTypes() {
680 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
681 DObj->getStringSection(), isLittleEndian());
682}
683
Adrian Prantlf51e7802017-09-29 00:52:33 +0000684const DWARFAcceleratorTable &DWARFContext::getAppleNamespaces() {
685 return getAccelTable(AppleNamespaces, *DObj,
686 DObj->getAppleNamespacesSection(),
687 DObj->getStringSection(), isLittleEndian());
688}
689
690const DWARFAcceleratorTable &DWARFContext::getAppleObjC() {
691 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
692 DObj->getStringSection(), isLittleEndian());
693}
694
Eric Christopher494109b2012-10-16 23:46:25 +0000695const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000696DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000697 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000698 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000699
Greg Claytonc8c10322016-12-13 18:25:19 +0000700 auto UnitDIE = U->getUnitDIE();
701 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000702 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000703
Greg Clayton97d22182017-01-13 21:08:18 +0000704 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000705 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000706 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000707
Greg Clayton52fe1f62016-12-14 22:38:08 +0000708 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000709 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000710 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000711 return lt;
712
Greg Clayton48ff66a2017-05-04 18:29:44 +0000713 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000714 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000715 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000716
Benjamin Kramer679e1752011-09-15 20:43:18 +0000717 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000718 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000719 U->getAddressByteSize());
Paul Robinsone5400f82017-11-07 19:57:12 +0000720 return Line->getOrParseLineTable(lineData, stmtOffset, U);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000721}
722
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000723void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000724 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000725}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000726
David Blaikie03c089c2013-09-23 22:44:47 +0000727void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000728 if (!TUs.empty())
729 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000730 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000731 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000732 TUs.back().parse(*this, S);
733 });
David Blaikie03c089c2013-09-23 22:44:47 +0000734}
735
Eric Christopherda4b2192013-01-02 23:52:13 +0000736void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000737 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000738}
739
David Blaikie92d9d622014-01-09 05:08:24 +0000740void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000741 if (!DWOTUs.empty())
742 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000743 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000744 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000745 DWOTUs.back().parseDWO(*this, S);
746 });
David Blaikie92d9d622014-01-09 05:08:24 +0000747}
748
Alexey Samsonov45be7932012-08-30 07:49:50 +0000749DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000750 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000751 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000752}
753
Alexey Samsonov45be7932012-08-30 07:49:50 +0000754DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000755 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000756 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000757 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000758 return getCompileUnitForOffset(CUOffset);
759}
760
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000761DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
762 DIEsForAddress Result;
763
764 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
765 if (!CU)
766 return Result;
767
768 Result.CompileUnit = CU;
769 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
770
771 std::vector<DWARFDie> Worklist;
772 Worklist.push_back(Result.FunctionDIE);
773 while (!Worklist.empty()) {
774 DWARFDie DIE = Worklist.back();
775 Worklist.pop_back();
776
777 if (DIE.getTag() == DW_TAG_lexical_block &&
778 DIE.addressRangeContainsAddress(Address)) {
779 Result.BlockDIE = DIE;
780 break;
781 }
782
783 for (auto Child : DIE)
784 Worklist.push_back(Child);
785 }
786
787 return Result;
788}
789
David Blaikieefc4eba2017-02-06 20:19:02 +0000790static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
791 uint64_t Address,
792 FunctionNameKind Kind,
793 std::string &FunctionName,
794 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000795 // The address may correspond to instruction in some inlined function,
796 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000797 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000798 SmallVector<DWARFDie, 4> InlinedChain;
799 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000800 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000801 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000802
803 const DWARFDie &DIE = InlinedChain[0];
804 bool FoundResult = false;
805 const char *Name = nullptr;
806 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000807 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000808 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000809 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000810 if (auto DeclLineResult = DIE.getDeclLine()) {
811 StartLine = DeclLineResult;
812 FoundResult = true;
813 }
814
815 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000816}
817
Alexey Samsonov45be7932012-08-30 07:49:50 +0000818DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000819 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000820 DILineInfo Result;
821
Alexey Samsonov45be7932012-08-30 07:49:50 +0000822 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
823 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000824 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000825 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
826 Result.FunctionName,
827 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000828 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000829 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
830 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
831 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000832 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000833 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000834}
David Blaikiea379b1812011-12-20 02:50:00 +0000835
Alexey Samsonovdce67342014-05-15 21:24:32 +0000836DILineInfoTable
837DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
838 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000839 DILineInfoTable Lines;
840 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
841 if (!CU)
842 return Lines;
843
844 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000845 uint32_t StartLine = 0;
846 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
847 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000848
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000849 // If the Specifier says we don't need FileLineInfo, just
850 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000851 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000852 DILineInfo Result;
853 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000854 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000855 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000856 return Lines;
857 }
858
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000859 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000860
861 // Get the index of row we're looking for in the line table.
862 std::vector<uint32_t> RowVector;
863 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
864 return Lines;
865
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000866 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000867 // Take file number and line/column from the row.
868 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000869 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000870 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
871 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000872 Result.FunctionName = FunctionName;
873 Result.Line = Row.Line;
874 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000875 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000876 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000877 }
878
879 return Lines;
880}
881
Alexey Samsonovdce67342014-05-15 21:24:32 +0000882DIInliningInfo
883DWARFContext::getInliningInfoForAddress(uint64_t Address,
884 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000885 DIInliningInfo InliningInfo;
886
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000887 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
888 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000889 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000890
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000891 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000892 SmallVector<DWARFDie, 4> InlinedChain;
893 CU->getInlinedChainForAddress(Address, InlinedChain);
894 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000895 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
896 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000897 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000898 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000899 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000900 if (LineTable &&
901 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
902 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000903 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000904 }
905 return InliningInfo;
906 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000907
Dehao Chenef700d52017-04-17 20:10:39 +0000908 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000909 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
910 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000911 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000912 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000913 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000914 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000915 if (auto DeclLineResult = FunctionDIE.getDeclLine())
916 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000917 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000918 if (i == 0) {
919 // For the topmost frame, initialize the line table of this
920 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000921 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000922 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000923 if (LineTable)
924 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
925 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000926 } else {
927 // Otherwise, use call file, call line and call column from
928 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000929 if (LineTable)
930 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
931 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000932 Frame.Line = CallLine;
933 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000934 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000935 }
936 // Get call file/line/column of a current DIE.
937 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000938 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
939 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000940 }
941 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000942 InliningInfo.addFrame(Frame);
943 }
944 return InliningInfo;
945}
946
David Blaikief9803fb2017-05-23 00:30:42 +0000947std::shared_ptr<DWARFContext>
948DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000949 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000950 DWARFContext *Ctxt = S->Context.get();
951 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
952 }
953
David Blaikie15d85fc2017-05-23 06:48:53 +0000954 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
955
956 if (auto S = Entry->lock()) {
957 DWARFContext *Ctxt = S->Context.get();
958 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
959 }
960
David Blaikie15d85fc2017-05-23 06:48:53 +0000961 Expected<OwningBinary<ObjectFile>> Obj = [&] {
962 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000963 SmallString<128> DWPName;
964 auto Obj = object::ObjectFile::createObjectFile(
965 this->DWPName.empty()
966 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
967 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000968 if (Obj) {
969 Entry = &DWP;
970 return Obj;
971 } else {
972 CheckedForDWP = true;
973 // TODO: Should this error be handled (maybe in a high verbosity mode)
974 // before falling back to .dwo files?
975 consumeError(Obj.takeError());
976 }
977 }
978
979 return object::ObjectFile::createObjectFile(AbsolutePath);
980 }();
981
David Blaikief9803fb2017-05-23 00:30:42 +0000982 if (!Obj) {
983 // TODO: Actually report errors helpfully.
984 consumeError(Obj.takeError());
985 return nullptr;
986 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000987
988 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000989 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000990 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000991 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000992 auto *Ctxt = S->Context.get();
993 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
994}
995
George Rimar702dac62017-04-12 08:59:15 +0000996static Error createError(const Twine &Reason, llvm::Error E) {
997 return make_error<StringError>(Reason + toString(std::move(E)),
998 inconvertibleErrorCode());
999}
1000
George Rimara25d3292017-05-27 18:10:23 +00001001/// SymInfo contains information about symbol: it's address
1002/// and section index which is -1LL for absolute symbols.
1003struct SymInfo {
1004 uint64_t Address;
1005 uint64_t SectionIndex;
1006};
1007
1008/// Returns the address of symbol relocation used against and a section index.
1009/// Used for futher relocations computation. Symbol's section load address is
1010static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1011 const RelocationRef &Reloc,
1012 const LoadedObjectInfo *L,
1013 std::map<SymbolRef, SymInfo> &Cache) {
1014 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001015 object::section_iterator RSec = Obj.section_end();
1016 object::symbol_iterator Sym = Reloc.getSymbol();
1017
George Rimara25d3292017-05-27 18:10:23 +00001018 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001019 // First calculate the address of the symbol or section as it appears
1020 // in the object file
1021 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001022 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001023 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001024 if (!New)
1025 return CacheIt->second;
1026
George Rimar702dac62017-04-12 08:59:15 +00001027 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1028 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001029 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001030 SymAddrOrErr.takeError());
1031
1032 // Also remember what section this symbol is in for later
1033 auto SectOrErr = Sym->getSection();
1034 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001035 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001036 SectOrErr.takeError());
1037
1038 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001039 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001040 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1041 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001042 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001043 }
1044
George Rimara25d3292017-05-27 18:10:23 +00001045 if (RSec != Obj.section_end())
1046 Ret.SectionIndex = RSec->getIndex();
1047
George Rimar702dac62017-04-12 08:59:15 +00001048 // If we are given load addresses for the sections, we need to adjust:
1049 // SymAddr = (Address of Symbol Or Section in File) -
1050 // (Address of Section in File) +
1051 // (Load Address of Section)
1052 // RSec is now either the section being targeted or the section
1053 // containing the symbol being targeted. In either case,
1054 // we need to perform the same computation.
1055 if (L && RSec != Obj.section_end())
1056 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001057 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001058
1059 if (CacheIt != Cache.end())
1060 CacheIt->second = Ret;
1061
George Rimar702dac62017-04-12 08:59:15 +00001062 return Ret;
1063}
1064
1065static bool isRelocScattered(const object::ObjectFile &Obj,
1066 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001067 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1068 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001069 return false;
1070 // MachO also has relocations that point to sections and
1071 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001072 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1073 return MachObj->isRelocationScattered(RelocInfo);
1074}
1075
Rafael Espindolac398e672017-07-19 22:27:28 +00001076ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +00001077 errs() << "error: " + toString(std::move(E)) << '\n';
1078 return ErrorPolicy::Continue;
1079}
1080
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001081namespace {
1082struct DWARFSectionMap final : public DWARFSection {
1083 RelocAddrMap Relocs;
1084};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001085
Rafael Espindolac398e672017-07-19 22:27:28 +00001086class DWARFObjInMemory final : public DWARFObject {
1087 bool IsLittleEndian;
1088 uint8_t AddressSize;
1089 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001090 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001091 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001092
Rafael Espindolac398e672017-07-19 22:27:28 +00001093 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1094 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001095
Rafael Espindolac398e672017-07-19 22:27:28 +00001096 TypeSectionMap TypesSections;
1097 TypeSectionMap TypesDWOSections;
1098
1099 DWARFSectionMap InfoSection;
1100 DWARFSectionMap LocSection;
1101 DWARFSectionMap LineSection;
1102 DWARFSectionMap RangeSection;
1103 DWARFSectionMap StringOffsetSection;
1104 DWARFSectionMap InfoDWOSection;
1105 DWARFSectionMap LineDWOSection;
1106 DWARFSectionMap LocDWOSection;
1107 DWARFSectionMap StringOffsetDWOSection;
1108 DWARFSectionMap RangeDWOSection;
1109 DWARFSectionMap AddrSection;
1110 DWARFSectionMap AppleNamesSection;
1111 DWARFSectionMap AppleTypesSection;
1112 DWARFSectionMap AppleNamespacesSection;
1113 DWARFSectionMap AppleObjCSection;
1114
1115 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1116 return StringSwitch<DWARFSectionMap *>(Name)
1117 .Case("debug_info", &InfoSection)
1118 .Case("debug_loc", &LocSection)
1119 .Case("debug_line", &LineSection)
1120 .Case("debug_str_offsets", &StringOffsetSection)
1121 .Case("debug_ranges", &RangeSection)
1122 .Case("debug_info.dwo", &InfoDWOSection)
1123 .Case("debug_loc.dwo", &LocDWOSection)
1124 .Case("debug_line.dwo", &LineDWOSection)
1125 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1126 .Case("debug_addr", &AddrSection)
1127 .Case("apple_names", &AppleNamesSection)
1128 .Case("apple_types", &AppleTypesSection)
1129 .Case("apple_namespaces", &AppleNamespacesSection)
1130 .Case("apple_namespac", &AppleNamespacesSection)
1131 .Case("apple_objc", &AppleObjCSection)
1132 .Default(nullptr);
1133 }
1134
1135 StringRef AbbrevSection;
1136 StringRef ARangeSection;
1137 StringRef DebugFrameSection;
1138 StringRef EHFrameSection;
1139 StringRef StringSection;
1140 StringRef MacinfoSection;
1141 StringRef PubNamesSection;
1142 StringRef PubTypesSection;
1143 StringRef GnuPubNamesSection;
1144 StringRef AbbrevDWOSection;
1145 StringRef StringDWOSection;
1146 StringRef GnuPubTypesSection;
1147 StringRef CUIndexSection;
1148 StringRef GdbIndexSection;
1149 StringRef TUIndexSection;
1150
1151 SmallVector<SmallString<32>, 4> UncompressedSections;
1152
1153 StringRef *mapSectionToMember(StringRef Name) {
1154 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1155 return &Sec->Data;
1156 return StringSwitch<StringRef *>(Name)
1157 .Case("debug_abbrev", &AbbrevSection)
1158 .Case("debug_aranges", &ARangeSection)
1159 .Case("debug_frame", &DebugFrameSection)
1160 .Case("eh_frame", &EHFrameSection)
1161 .Case("debug_str", &StringSection)
1162 .Case("debug_macinfo", &MacinfoSection)
1163 .Case("debug_pubnames", &PubNamesSection)
1164 .Case("debug_pubtypes", &PubTypesSection)
1165 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1166 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1167 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1168 .Case("debug_str.dwo", &StringDWOSection)
1169 .Case("debug_cu_index", &CUIndexSection)
1170 .Case("debug_tu_index", &TUIndexSection)
1171 .Case("gdb_index", &GdbIndexSection)
1172 // Any more debug info sections go here.
1173 .Default(nullptr);
1174 }
1175
1176 /// If Sec is compressed section, decompresses and updates its contents
1177 /// provided by Data. Otherwise leaves it unchanged.
1178 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1179 StringRef &Data) {
1180 if (!Decompressor::isCompressed(Sec))
1181 return Error::success();
1182
1183 Expected<Decompressor> Decompressor =
1184 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1185 if (!Decompressor)
1186 return Decompressor.takeError();
1187
1188 SmallString<32> Out;
1189 if (auto Err = Decompressor->resizeAndDecompress(Out))
1190 return Err;
1191
1192 UncompressedSections.emplace_back(std::move(Out));
1193 Data = UncompressedSections.back();
1194
1195 return Error::success();
1196 }
1197
1198public:
1199 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1200 uint8_t AddrSize, bool IsLittleEndian)
1201 : IsLittleEndian(IsLittleEndian) {
1202 for (const auto &SecIt : Sections) {
1203 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1204 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001205 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001206 }
1207 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1208 function_ref<ErrorPolicy(Error)> HandleError)
1209 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001210 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1211 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001212
George Rimare1c30f72017-08-15 15:54:43 +00001213 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001214 for (const SectionRef &Section : Obj.sections()) {
1215 StringRef Name;
1216 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001217 ++SectionAmountMap[Name];
1218 SectionNames.push_back({ Name, true });
1219
Rafael Espindolac398e672017-07-19 22:27:28 +00001220 // Skip BSS and Virtual sections, they aren't interesting.
1221 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001222 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001223
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001224 // Skip sections stripped by dsymutil.
1225 if (Section.isStripped())
1226 continue;
1227
Rafael Espindolac398e672017-07-19 22:27:28 +00001228 StringRef Data;
1229 section_iterator RelocatedSection = Section.getRelocatedSection();
1230 // Try to obtain an already relocated version of this section.
1231 // Else use the unrelocated section from the object file. We'll have to
1232 // apply relocations ourselves later.
1233 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1234 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001235
Rafael Espindolac398e672017-07-19 22:27:28 +00001236 if (auto Err = maybeDecompress(Section, Name, Data)) {
1237 ErrorPolicy EP = HandleError(createError(
1238 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001239 if (EP == ErrorPolicy::Halt)
1240 return;
George Rimarfed9f092017-05-17 12:10:51 +00001241 continue;
1242 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001243
1244 // Compressed sections names in GNU style starts from ".z",
1245 // at this point section is decompressed and we drop compression prefix.
1246 Name = Name.substr(
1247 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1248
1249 // Map platform specific debug section names to DWARF standard section
1250 // names.
1251 Name = Obj.mapDebugSectionName(Name);
1252
1253 if (StringRef *SectionData = mapSectionToMember(Name)) {
1254 *SectionData = Data;
1255 if (Name == "debug_ranges") {
1256 // FIXME: Use the other dwo range section when we emit it.
1257 RangeDWOSection.Data = Data;
1258 }
1259 } else if (Name == "debug_types") {
1260 // Find debug_types data by section rather than name as there are
1261 // multiple, comdat grouped, debug_types sections.
1262 TypesSections[Section].Data = Data;
1263 } else if (Name == "debug_types.dwo") {
1264 TypesDWOSections[Section].Data = Data;
1265 }
1266
1267 if (RelocatedSection == Obj.section_end())
1268 continue;
1269
1270 StringRef RelSecName;
1271 StringRef RelSecData;
1272 RelocatedSection->getName(RelSecName);
1273
1274 // If the section we're relocating was relocated already by the JIT,
1275 // then we used the relocated version above, so we do not need to process
1276 // relocations for it now.
1277 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1278 continue;
1279
1280 // In Mach-o files, the relocations do not need to be applied if
1281 // there is no load offset to apply. The value read at the
1282 // relocation point already factors in the section address
1283 // (actually applying the relocations will produce wrong results
1284 // as the section address will be added twice).
1285 if (!L && isa<MachOObjectFile>(&Obj))
1286 continue;
1287
1288 RelSecName = RelSecName.substr(
1289 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1290
1291 // TODO: Add support for relocations in other sections as needed.
1292 // Record relocations for the debug_info and debug_line sections.
1293 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1294 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1295 if (!Map) {
1296 // Find debug_types relocs by section rather than name as there are
1297 // multiple, comdat grouped, debug_types sections.
1298 if (RelSecName == "debug_types")
1299 Map =
1300 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1301 .Relocs;
1302 else if (RelSecName == "debug_types.dwo")
1303 Map = &static_cast<DWARFSectionMap &>(
1304 TypesDWOSections[*RelocatedSection])
1305 .Relocs;
1306 else
1307 continue;
1308 }
1309
1310 if (Section.relocation_begin() == Section.relocation_end())
1311 continue;
1312
1313 // Symbol to [address, section index] cache mapping.
1314 std::map<SymbolRef, SymInfo> AddrCache;
1315 for (const RelocationRef &Reloc : Section.relocations()) {
1316 // FIXME: it's not clear how to correctly handle scattered
1317 // relocations.
1318 if (isRelocScattered(Obj, Reloc))
1319 continue;
1320
1321 Expected<SymInfo> SymInfoOrErr =
1322 getSymbolInfo(Obj, Reloc, L, AddrCache);
1323 if (!SymInfoOrErr) {
1324 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1325 return;
1326 continue;
1327 }
1328
1329 object::RelocVisitor V(Obj);
1330 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1331 if (V.error()) {
1332 SmallString<32> Type;
1333 Reloc.getTypeName(Type);
1334 ErrorPolicy EP = HandleError(
1335 createError("failed to compute relocation: " + Type + ", ",
1336 errorCodeToError(object_error::parse_failed)));
1337 if (EP == ErrorPolicy::Halt)
1338 return;
1339 continue;
1340 }
1341 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1342 Map->insert({Reloc.getOffset(), Rel});
1343 }
Eric Christopher7370b552012-11-12 21:40:38 +00001344 }
George Rimare1c30f72017-08-15 15:54:43 +00001345
1346 for (SectionName &S : SectionNames)
1347 if (SectionAmountMap[S.Name] > 1)
1348 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001349 }
Eric Christopher7370b552012-11-12 21:40:38 +00001350
Rafael Espindolac398e672017-07-19 22:27:28 +00001351 Optional<RelocAddrEntry> find(const DWARFSection &S,
1352 uint64_t Pos) const override {
1353 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1354 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1355 if (AI == Sec.Relocs.end())
1356 return None;
1357 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001358 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001359
George Rimar6957ab52017-08-15 12:32:54 +00001360 const object::ObjectFile *getFile() const override { return Obj; }
1361
George Rimare1c30f72017-08-15 15:54:43 +00001362 ArrayRef<SectionName> getSectionNames() const override {
1363 return SectionNames;
1364 }
1365
Rafael Espindolac398e672017-07-19 22:27:28 +00001366 bool isLittleEndian() const override { return IsLittleEndian; }
1367 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1368 const DWARFSection &getLineDWOSection() const override {
1369 return LineDWOSection;
1370 }
1371 const DWARFSection &getLocDWOSection() const override {
1372 return LocDWOSection;
1373 }
1374 StringRef getStringDWOSection() const override { return StringDWOSection; }
1375 const DWARFSection &getStringOffsetDWOSection() const override {
1376 return StringOffsetDWOSection;
1377 }
1378 const DWARFSection &getRangeDWOSection() const override {
1379 return RangeDWOSection;
1380 }
1381 const DWARFSection &getAddrSection() const override { return AddrSection; }
1382 StringRef getCUIndexSection() const override { return CUIndexSection; }
1383 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1384 StringRef getTUIndexSection() const override { return TUIndexSection; }
1385
1386 // DWARF v5
1387 const DWARFSection &getStringOffsetSection() const override {
1388 return StringOffsetSection;
1389 }
1390
1391 // Sections for DWARF5 split dwarf proposal.
1392 const DWARFSection &getInfoDWOSection() const override {
1393 return InfoDWOSection;
1394 }
1395 void forEachTypesDWOSections(
1396 function_ref<void(const DWARFSection &)> F) const override {
1397 for (auto &P : TypesDWOSections)
1398 F(P.second);
1399 }
1400
1401 StringRef getAbbrevSection() const override { return AbbrevSection; }
1402 const DWARFSection &getLocSection() const override { return LocSection; }
1403 StringRef getARangeSection() const override { return ARangeSection; }
1404 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1405 StringRef getEHFrameSection() const override { return EHFrameSection; }
1406 const DWARFSection &getLineSection() const override { return LineSection; }
1407 StringRef getStringSection() const override { return StringSection; }
1408 const DWARFSection &getRangeSection() const override { return RangeSection; }
1409 StringRef getMacinfoSection() const override { return MacinfoSection; }
1410 StringRef getPubNamesSection() const override { return PubNamesSection; }
1411 StringRef getPubTypesSection() const override { return PubTypesSection; }
1412 StringRef getGnuPubNamesSection() const override {
1413 return GnuPubNamesSection;
1414 }
1415 StringRef getGnuPubTypesSection() const override {
1416 return GnuPubTypesSection;
1417 }
1418 const DWARFSection &getAppleNamesSection() const override {
1419 return AppleNamesSection;
1420 }
1421 const DWARFSection &getAppleTypesSection() const override {
1422 return AppleTypesSection;
1423 }
1424 const DWARFSection &getAppleNamespacesSection() const override {
1425 return AppleNamespacesSection;
1426 }
1427 const DWARFSection &getAppleObjCSection() const override {
1428 return AppleObjCSection;
1429 }
1430
1431 StringRef getFileName() const override { return FileName; }
1432 uint8_t getAddressSize() const override { return AddressSize; }
1433 const DWARFSection &getInfoSection() const override { return InfoSection; }
1434 void forEachTypesSections(
1435 function_ref<void(const DWARFSection &)> F) const override {
1436 for (auto &P : TypesSections)
1437 F(P.second);
1438 }
1439};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001440} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001441
1442std::unique_ptr<DWARFContext>
1443DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001444 function_ref<ErrorPolicy(Error)> HandleError,
1445 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001446 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001447 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001448}
1449
Rafael Espindolac398e672017-07-19 22:27:28 +00001450std::unique_ptr<DWARFContext>
1451DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1452 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001453 auto DObj =
1454 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001455 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001456}
Reid Klecknera0587362017-08-29 21:41:21 +00001457
1458Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1459 // Detect the architecture from the object file. We usually don't need OS
1460 // info to lookup a target and create register info.
1461 Triple TT;
1462 TT.setArch(Triple::ArchType(Obj.getArch()));
1463 TT.setVendor(Triple::UnknownVendor);
1464 TT.setOS(Triple::UnknownOS);
1465 std::string TargetLookupError;
1466 const Target *TheTarget =
1467 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1468 if (!TargetLookupError.empty())
1469 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1470 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1471 return Error::success();
1472}