blob: a5defa90eb35f277f13d91fa6aa0117c3e1a52f4 [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";
Paul Robinsonab69b472017-12-01 18:25:30 +0000360 unsigned OldOffset = Offset;
Paul Robinson63811a42017-11-22 15:33:17 +0000361 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 }
Paul Robinsonab69b472017-12-01 18:25:30 +0000367 // Check for unparseable prologue, to avoid infinite loops.
368 if (OldOffset == Offset)
369 break;
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000370 }
371 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000372
Adrian Prantl057d3362017-09-15 23:04:04 +0000373 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000374 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000375 LineToUnitMap LineToUnit =
376 buildLineToUnitMap(dwo_compile_units(), dwo_type_unit_sections());
377 unsigned Offset = 0;
378 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
379 isLittleEndian(), 0);
380 while (Offset < LineData.getData().size()) {
381 DWARFUnit *U = nullptr;
382 auto It = LineToUnit.find(Offset);
383 if (It != LineToUnit.end())
384 U = It->second;
385 DWARFDebugLine::LineTable LineTable;
Paul Robinson6ca1dd62017-11-22 18:23:55 +0000386 unsigned OldOffset = Offset;
Paul Robinson63811a42017-11-22 15:33:17 +0000387 if (!LineTable.Prologue.parse(LineData, &Offset, U))
388 break;
Paul Robinson6ca1dd62017-11-22 18:23:55 +0000389 if (!DumpOffset || OldOffset == *DumpOffset)
390 LineTable.dump(OS);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000391 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000392 }
393
Adrian Prantl057d3362017-09-15 23:04:04 +0000394 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000395 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000396 getCUIndex().dump(OS);
397 }
398
Adrian Prantl057d3362017-09-15 23:04:04 +0000399 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000400 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000401 getTUIndex().dump(OS);
402 }
403
Adrian Prantl057d3362017-09-15 23:04:04 +0000404 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000405 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000406 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000407 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000408 uint32_t strOffset = 0;
409 while (const char *s = strData.getCStr(&offset)) {
410 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
411 strOffset = offset;
412 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000413 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000414 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000415 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000416 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000417 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000418 uint32_t strDWOOffset = 0;
419 while (const char *s = strDWOData.getCStr(&offset)) {
420 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
421 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000422 }
David Blaikie66865d62014-01-09 00:13:35 +0000423 }
David Blaikie622dce42014-01-08 23:29:59 +0000424
Adrian Prantl057d3362017-09-15 23:04:04 +0000425 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000426 DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000427 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000428 // sizes, but for simplicity we just use the address byte size of the
429 // last compile unit (there is no easy and fast way to associate address
430 // range list and the compile unit it describes).
431 // FIXME: savedAddressByteSize seems sketchy.
Paul Robinson63811a42017-11-22 15:33:17 +0000432 uint8_t savedAddressByteSize = 0;
433 for (const auto &CU : compile_units()) {
434 savedAddressByteSize = CU->getAddressByteSize();
435 break;
436 }
Rafael Espindolac398e672017-07-19 22:27:28 +0000437 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
438 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000439 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000440 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000441 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000442 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000443 }
Eric Christopher962c9082013-01-15 23:56:56 +0000444
Adrian Prantl057d3362017-09-15 23:04:04 +0000445 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000446 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000447 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000448 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000449
Adrian Prantl057d3362017-09-15 23:04:04 +0000450 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000451 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000452 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000453 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000454
Adrian Prantl057d3362017-09-15 23:04:04 +0000455 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000456 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000457 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000458 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000459 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000460
Adrian Prantl057d3362017-09-15 23:04:04 +0000461 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000462 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000463 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000464 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000465 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000466
Adrian Prantl057d3362017-09-15 23:04:04 +0000467 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000468 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000469 dumpStringOffsetsSection(
470 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
471 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000472 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000473 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000474 dumpStringOffsetsSection(
475 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
476 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000477
Adrian Prantl057d3362017-09-15 23:04:04 +0000478 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000479 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000480 getGdbIndex().dump(OS);
481 }
482
Adrian Prantl057d3362017-09-15 23:04:04 +0000483 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000484 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000485 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000486
Adrian Prantl057d3362017-09-15 23:04:04 +0000487 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000488 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000489 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000490
Adrian Prantl057d3362017-09-15 23:04:04 +0000491 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000492 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000493 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000494
Adrian Prantl057d3362017-09-15 23:04:04 +0000495 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000496 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000497 getAppleObjC().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000498}
499
David Blaikie15d85fc2017-05-23 06:48:53 +0000500DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiee79dda32017-09-19 18:36:11 +0000501 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000502
David Blaikieebac0b92017-07-30 08:12:07 +0000503 if (const auto &CUI = getCUIndex()) {
504 if (const auto *R = CUI.getFromHash(Hash))
David Blaikiee79dda32017-09-19 18:36:11 +0000505 return DWOCUs.getUnitForIndexEntry(*R);
David Blaikieebac0b92017-07-30 08:12:07 +0000506 return nullptr;
507 }
508
509 // If there's no index, just search through the CUs in the DWO - there's
510 // probably only one unless this is something like LTO - though an in-process
511 // built/cached lookup table could be used in that case to improve repeated
512 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000513 for (const auto &DWOCU : dwo_compile_units())
514 if (DWOCU->getDWOId() == Hash)
515 return DWOCU.get();
516 return nullptr;
517}
518
Greg Claytonc7695a82017-05-02 20:28:33 +0000519DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
520 parseCompileUnits();
521 if (auto *CU = CUs.getUnitForOffset(Offset))
522 return CU->getDIEForOffset(Offset);
523 return DWARFDie();
524}
525
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000526bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000527 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000528 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000529
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000530 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000531 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000532 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000533 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000534 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000535 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000536 return Success;
537}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000538
David Blaikie82641be2015-11-17 00:39:55 +0000539const DWARFUnitIndex &DWARFContext::getCUIndex() {
540 if (CUIndex)
541 return *CUIndex;
542
Rafael Espindolac398e672017-07-19 22:27:28 +0000543 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000544
David Blaikieb073cb92015-12-02 06:21:34 +0000545 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000546 CUIndex->parse(CUIndexData);
547 return *CUIndex;
548}
549
550const DWARFUnitIndex &DWARFContext::getTUIndex() {
551 if (TUIndex)
552 return *TUIndex;
553
Rafael Espindolac398e672017-07-19 22:27:28 +0000554 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000555
David Blaikieb073cb92015-12-02 06:21:34 +0000556 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000557 TUIndex->parse(TUIndexData);
558 return *TUIndex;
559}
560
George Rimar4f82df52016-09-23 11:01:53 +0000561DWARFGdbIndex &DWARFContext::getGdbIndex() {
562 if (GdbIndex)
563 return *GdbIndex;
564
Rafael Espindolac398e672017-07-19 22:27:28 +0000565 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000566 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
567 GdbIndex->parse(GdbIndexData);
568 return *GdbIndex;
569}
570
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000571const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
572 if (Abbrev)
573 return Abbrev.get();
574
Rafael Espindolac398e672017-07-19 22:27:28 +0000575 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000576
577 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000578 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000579 return Abbrev.get();
580}
581
Eric Christopherda4b2192013-01-02 23:52:13 +0000582const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
583 if (AbbrevDWO)
584 return AbbrevDWO.get();
585
Rafael Espindolac398e672017-07-19 22:27:28 +0000586 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000587 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000588 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000589 return AbbrevDWO.get();
590}
591
David Blaikie18e73502013-06-19 21:37:13 +0000592const DWARFDebugLoc *DWARFContext::getDebugLoc() {
593 if (Loc)
594 return Loc.get();
595
Paul Robinson17536b92017-06-29 16:52:08 +0000596 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000597 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000598 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000599 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000600 getCompileUnitAtIndex(0)->getAddressByteSize());
601 Loc->parse(LocData);
602 }
David Blaikie18e73502013-06-19 21:37:13 +0000603 return Loc.get();
604}
605
David Blaikie9c550ac2014-03-25 01:44:02 +0000606const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
607 if (LocDWO)
608 return LocDWO.get();
609
Rafael Espindolac398e672017-07-19 22:27:28 +0000610 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000611 LocDWO.reset(new DWARFDebugLocDWO());
612 LocDWO->parse(LocData);
613 return LocDWO.get();
614}
615
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000616const DWARFDebugAranges *DWARFContext::getDebugAranges() {
617 if (Aranges)
618 return Aranges.get();
619
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000620 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000621 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000622 return Aranges.get();
623}
624
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000625const DWARFDebugFrame *DWARFContext::getDebugFrame() {
626 if (DebugFrame)
627 return DebugFrame.get();
628
629 // There's a "bug" in the DWARFv3 standard with respect to the target address
630 // size within debug frame sections. While DWARF is supposed to be independent
631 // of its container, FDEs have fields with size being "target address size",
632 // which isn't specified in DWARF in general. It's only specified for CUs, but
633 // .eh_frame can appear without a .debug_info section. Follow the example of
634 // other tools (libdwarf) and extract this from the container (ObjectFile
635 // provides this information). This problem is fixed in DWARFv4
636 // See this dwarf-discuss discussion for more details:
637 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000638 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
639 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000640 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
641 DebugFrame->parse(debugFrameData);
642 return DebugFrame.get();
643}
644
645const DWARFDebugFrame *DWARFContext::getEHFrame() {
646 if (EHFrame)
647 return EHFrame.get();
648
Rafael Espindolac398e672017-07-19 22:27:28 +0000649 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
650 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000651 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000652 DebugFrame->parse(debugFrameData);
653 return DebugFrame.get();
654}
655
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000656const DWARFDebugMacro *DWARFContext::getDebugMacro() {
657 if (Macro)
658 return Macro.get();
659
Rafael Espindolac398e672017-07-19 22:27:28 +0000660 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000661 Macro.reset(new DWARFDebugMacro());
662 Macro->parse(MacinfoData);
663 return Macro.get();
664}
665
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000666static DWARFAcceleratorTable &
667getAccelTable(std::unique_ptr<DWARFAcceleratorTable> &Cache,
668 const DWARFObject &Obj, const DWARFSection &Section,
669 StringRef StringSection, bool IsLittleEndian) {
670 if (Cache)
671 return *Cache;
672 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
673 DataExtractor StrData(StringSection, IsLittleEndian, 0);
674 Cache.reset(new DWARFAcceleratorTable(AccelSection, StrData));
Jonas Devlieghereba915892017-12-11 18:22:47 +0000675 if (Error E = Cache->extract())
676 llvm::consumeError(std::move(E));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000677 return *Cache;
678}
679
680const DWARFAcceleratorTable &DWARFContext::getAppleNames() {
681 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
682 DObj->getStringSection(), isLittleEndian());
683}
684
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000685const DWARFAcceleratorTable &DWARFContext::getAppleTypes() {
686 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
687 DObj->getStringSection(), isLittleEndian());
688}
689
Adrian Prantlf51e7802017-09-29 00:52:33 +0000690const DWARFAcceleratorTable &DWARFContext::getAppleNamespaces() {
691 return getAccelTable(AppleNamespaces, *DObj,
692 DObj->getAppleNamespacesSection(),
693 DObj->getStringSection(), isLittleEndian());
694}
695
696const DWARFAcceleratorTable &DWARFContext::getAppleObjC() {
697 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
698 DObj->getStringSection(), isLittleEndian());
699}
700
Eric Christopher494109b2012-10-16 23:46:25 +0000701const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000702DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000703 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000704 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000705
Greg Claytonc8c10322016-12-13 18:25:19 +0000706 auto UnitDIE = U->getUnitDIE();
707 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000708 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000709
Greg Clayton97d22182017-01-13 21:08:18 +0000710 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000711 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000712 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000713
Greg Clayton52fe1f62016-12-14 22:38:08 +0000714 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000715 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000716 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000717 return lt;
718
Greg Clayton48ff66a2017-05-04 18:29:44 +0000719 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000720 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000721 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000722
Benjamin Kramer679e1752011-09-15 20:43:18 +0000723 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000724 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000725 U->getAddressByteSize());
Paul Robinsone5400f82017-11-07 19:57:12 +0000726 return Line->getOrParseLineTable(lineData, stmtOffset, U);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000727}
728
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000729void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000730 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000731}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000732
David Blaikie03c089c2013-09-23 22:44:47 +0000733void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000734 if (!TUs.empty())
735 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000736 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000737 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000738 TUs.back().parse(*this, S);
739 });
David Blaikie03c089c2013-09-23 22:44:47 +0000740}
741
Eric Christopherda4b2192013-01-02 23:52:13 +0000742void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000743 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000744}
745
David Blaikie92d9d622014-01-09 05:08:24 +0000746void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000747 if (!DWOTUs.empty())
748 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000749 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000750 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000751 DWOTUs.back().parseDWO(*this, S);
752 });
David Blaikie92d9d622014-01-09 05:08:24 +0000753}
754
Alexey Samsonov45be7932012-08-30 07:49:50 +0000755DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000756 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000757 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000758}
759
Alexey Samsonov45be7932012-08-30 07:49:50 +0000760DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000761 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000762 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000763 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000764 return getCompileUnitForOffset(CUOffset);
765}
766
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000767DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
768 DIEsForAddress Result;
769
770 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
771 if (!CU)
772 return Result;
773
774 Result.CompileUnit = CU;
775 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
776
777 std::vector<DWARFDie> Worklist;
778 Worklist.push_back(Result.FunctionDIE);
779 while (!Worklist.empty()) {
780 DWARFDie DIE = Worklist.back();
781 Worklist.pop_back();
782
783 if (DIE.getTag() == DW_TAG_lexical_block &&
784 DIE.addressRangeContainsAddress(Address)) {
785 Result.BlockDIE = DIE;
786 break;
787 }
788
789 for (auto Child : DIE)
790 Worklist.push_back(Child);
791 }
792
793 return Result;
794}
795
David Blaikieefc4eba2017-02-06 20:19:02 +0000796static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
797 uint64_t Address,
798 FunctionNameKind Kind,
799 std::string &FunctionName,
800 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000801 // The address may correspond to instruction in some inlined function,
802 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000803 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000804 SmallVector<DWARFDie, 4> InlinedChain;
805 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000806 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000807 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000808
809 const DWARFDie &DIE = InlinedChain[0];
810 bool FoundResult = false;
811 const char *Name = nullptr;
812 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000813 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000814 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000815 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000816 if (auto DeclLineResult = DIE.getDeclLine()) {
817 StartLine = DeclLineResult;
818 FoundResult = true;
819 }
820
821 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000822}
823
Alexey Samsonov45be7932012-08-30 07:49:50 +0000824DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000825 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000826 DILineInfo Result;
827
Alexey Samsonov45be7932012-08-30 07:49:50 +0000828 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
829 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000830 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000831 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
832 Result.FunctionName,
833 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000834 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000835 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
836 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
837 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000838 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000839 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000840}
David Blaikiea379b1812011-12-20 02:50:00 +0000841
Alexey Samsonovdce67342014-05-15 21:24:32 +0000842DILineInfoTable
843DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
844 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000845 DILineInfoTable Lines;
846 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
847 if (!CU)
848 return Lines;
849
850 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000851 uint32_t StartLine = 0;
852 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
853 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000854
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000855 // If the Specifier says we don't need FileLineInfo, just
856 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000857 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000858 DILineInfo Result;
859 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000860 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000861 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000862 return Lines;
863 }
864
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000865 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000866
867 // Get the index of row we're looking for in the line table.
868 std::vector<uint32_t> RowVector;
869 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
870 return Lines;
871
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000872 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000873 // Take file number and line/column from the row.
874 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000875 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000876 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
877 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000878 Result.FunctionName = FunctionName;
879 Result.Line = Row.Line;
880 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000881 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000882 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000883 }
884
885 return Lines;
886}
887
Alexey Samsonovdce67342014-05-15 21:24:32 +0000888DIInliningInfo
889DWARFContext::getInliningInfoForAddress(uint64_t Address,
890 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000891 DIInliningInfo InliningInfo;
892
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000893 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
894 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000895 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000896
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000897 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000898 SmallVector<DWARFDie, 4> InlinedChain;
899 CU->getInlinedChainForAddress(Address, InlinedChain);
900 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000901 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
902 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000903 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000904 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000905 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000906 if (LineTable &&
907 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
908 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000909 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000910 }
911 return InliningInfo;
912 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000913
Dehao Chenef700d52017-04-17 20:10:39 +0000914 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000915 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
916 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000917 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000918 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000919 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000920 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000921 if (auto DeclLineResult = FunctionDIE.getDeclLine())
922 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000923 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000924 if (i == 0) {
925 // For the topmost frame, initialize the line table of this
926 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000927 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000928 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000929 if (LineTable)
930 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
931 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000932 } else {
933 // Otherwise, use call file, call line and call column from
934 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000935 if (LineTable)
936 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
937 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000938 Frame.Line = CallLine;
939 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000940 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000941 }
942 // Get call file/line/column of a current DIE.
943 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000944 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
945 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000946 }
947 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000948 InliningInfo.addFrame(Frame);
949 }
950 return InliningInfo;
951}
952
David Blaikief9803fb2017-05-23 00:30:42 +0000953std::shared_ptr<DWARFContext>
954DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000955 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000956 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 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
961
962 if (auto S = Entry->lock()) {
963 DWARFContext *Ctxt = S->Context.get();
964 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
965 }
966
David Blaikie15d85fc2017-05-23 06:48:53 +0000967 Expected<OwningBinary<ObjectFile>> Obj = [&] {
968 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000969 SmallString<128> DWPName;
970 auto Obj = object::ObjectFile::createObjectFile(
971 this->DWPName.empty()
972 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
973 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000974 if (Obj) {
975 Entry = &DWP;
976 return Obj;
977 } else {
978 CheckedForDWP = true;
979 // TODO: Should this error be handled (maybe in a high verbosity mode)
980 // before falling back to .dwo files?
981 consumeError(Obj.takeError());
982 }
983 }
984
985 return object::ObjectFile::createObjectFile(AbsolutePath);
986 }();
987
David Blaikief9803fb2017-05-23 00:30:42 +0000988 if (!Obj) {
989 // TODO: Actually report errors helpfully.
990 consumeError(Obj.takeError());
991 return nullptr;
992 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000993
994 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000995 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000996 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000997 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000998 auto *Ctxt = S->Context.get();
999 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1000}
1001
George Rimar702dac62017-04-12 08:59:15 +00001002static Error createError(const Twine &Reason, llvm::Error E) {
1003 return make_error<StringError>(Reason + toString(std::move(E)),
1004 inconvertibleErrorCode());
1005}
1006
George Rimara25d3292017-05-27 18:10:23 +00001007/// SymInfo contains information about symbol: it's address
1008/// and section index which is -1LL for absolute symbols.
1009struct SymInfo {
1010 uint64_t Address;
1011 uint64_t SectionIndex;
1012};
1013
1014/// Returns the address of symbol relocation used against and a section index.
1015/// Used for futher relocations computation. Symbol's section load address is
1016static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1017 const RelocationRef &Reloc,
1018 const LoadedObjectInfo *L,
1019 std::map<SymbolRef, SymInfo> &Cache) {
1020 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001021 object::section_iterator RSec = Obj.section_end();
1022 object::symbol_iterator Sym = Reloc.getSymbol();
1023
George Rimara25d3292017-05-27 18:10:23 +00001024 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001025 // First calculate the address of the symbol or section as it appears
1026 // in the object file
1027 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001028 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001029 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001030 if (!New)
1031 return CacheIt->second;
1032
George Rimar702dac62017-04-12 08:59:15 +00001033 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1034 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001035 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001036 SymAddrOrErr.takeError());
1037
1038 // Also remember what section this symbol is in for later
1039 auto SectOrErr = Sym->getSection();
1040 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001041 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001042 SectOrErr.takeError());
1043
1044 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001045 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001046 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1047 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001048 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001049 }
1050
George Rimara25d3292017-05-27 18:10:23 +00001051 if (RSec != Obj.section_end())
1052 Ret.SectionIndex = RSec->getIndex();
1053
George Rimar702dac62017-04-12 08:59:15 +00001054 // If we are given load addresses for the sections, we need to adjust:
1055 // SymAddr = (Address of Symbol Or Section in File) -
1056 // (Address of Section in File) +
1057 // (Load Address of Section)
1058 // RSec is now either the section being targeted or the section
1059 // containing the symbol being targeted. In either case,
1060 // we need to perform the same computation.
1061 if (L && RSec != Obj.section_end())
1062 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001063 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001064
1065 if (CacheIt != Cache.end())
1066 CacheIt->second = Ret;
1067
George Rimar702dac62017-04-12 08:59:15 +00001068 return Ret;
1069}
1070
1071static bool isRelocScattered(const object::ObjectFile &Obj,
1072 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001073 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1074 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001075 return false;
1076 // MachO also has relocations that point to sections and
1077 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001078 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1079 return MachObj->isRelocationScattered(RelocInfo);
1080}
1081
Rafael Espindolac398e672017-07-19 22:27:28 +00001082ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +00001083 errs() << "error: " + toString(std::move(E)) << '\n';
1084 return ErrorPolicy::Continue;
1085}
1086
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001087namespace {
1088struct DWARFSectionMap final : public DWARFSection {
1089 RelocAddrMap Relocs;
1090};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001091
Rafael Espindolac398e672017-07-19 22:27:28 +00001092class DWARFObjInMemory final : public DWARFObject {
1093 bool IsLittleEndian;
1094 uint8_t AddressSize;
1095 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001096 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001097 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001098
Rafael Espindolac398e672017-07-19 22:27:28 +00001099 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1100 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001101
Rafael Espindolac398e672017-07-19 22:27:28 +00001102 TypeSectionMap TypesSections;
1103 TypeSectionMap TypesDWOSections;
1104
1105 DWARFSectionMap InfoSection;
1106 DWARFSectionMap LocSection;
1107 DWARFSectionMap LineSection;
1108 DWARFSectionMap RangeSection;
1109 DWARFSectionMap StringOffsetSection;
1110 DWARFSectionMap InfoDWOSection;
1111 DWARFSectionMap LineDWOSection;
1112 DWARFSectionMap LocDWOSection;
1113 DWARFSectionMap StringOffsetDWOSection;
1114 DWARFSectionMap RangeDWOSection;
1115 DWARFSectionMap AddrSection;
1116 DWARFSectionMap AppleNamesSection;
1117 DWARFSectionMap AppleTypesSection;
1118 DWARFSectionMap AppleNamespacesSection;
1119 DWARFSectionMap AppleObjCSection;
1120
1121 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1122 return StringSwitch<DWARFSectionMap *>(Name)
1123 .Case("debug_info", &InfoSection)
1124 .Case("debug_loc", &LocSection)
1125 .Case("debug_line", &LineSection)
1126 .Case("debug_str_offsets", &StringOffsetSection)
1127 .Case("debug_ranges", &RangeSection)
1128 .Case("debug_info.dwo", &InfoDWOSection)
1129 .Case("debug_loc.dwo", &LocDWOSection)
1130 .Case("debug_line.dwo", &LineDWOSection)
1131 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1132 .Case("debug_addr", &AddrSection)
1133 .Case("apple_names", &AppleNamesSection)
1134 .Case("apple_types", &AppleTypesSection)
1135 .Case("apple_namespaces", &AppleNamespacesSection)
1136 .Case("apple_namespac", &AppleNamespacesSection)
1137 .Case("apple_objc", &AppleObjCSection)
1138 .Default(nullptr);
1139 }
1140
1141 StringRef AbbrevSection;
1142 StringRef ARangeSection;
1143 StringRef DebugFrameSection;
1144 StringRef EHFrameSection;
1145 StringRef StringSection;
1146 StringRef MacinfoSection;
1147 StringRef PubNamesSection;
1148 StringRef PubTypesSection;
1149 StringRef GnuPubNamesSection;
1150 StringRef AbbrevDWOSection;
1151 StringRef StringDWOSection;
1152 StringRef GnuPubTypesSection;
1153 StringRef CUIndexSection;
1154 StringRef GdbIndexSection;
1155 StringRef TUIndexSection;
1156
1157 SmallVector<SmallString<32>, 4> UncompressedSections;
1158
1159 StringRef *mapSectionToMember(StringRef Name) {
1160 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1161 return &Sec->Data;
1162 return StringSwitch<StringRef *>(Name)
1163 .Case("debug_abbrev", &AbbrevSection)
1164 .Case("debug_aranges", &ARangeSection)
1165 .Case("debug_frame", &DebugFrameSection)
1166 .Case("eh_frame", &EHFrameSection)
1167 .Case("debug_str", &StringSection)
1168 .Case("debug_macinfo", &MacinfoSection)
1169 .Case("debug_pubnames", &PubNamesSection)
1170 .Case("debug_pubtypes", &PubTypesSection)
1171 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1172 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1173 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1174 .Case("debug_str.dwo", &StringDWOSection)
1175 .Case("debug_cu_index", &CUIndexSection)
1176 .Case("debug_tu_index", &TUIndexSection)
1177 .Case("gdb_index", &GdbIndexSection)
1178 // Any more debug info sections go here.
1179 .Default(nullptr);
1180 }
1181
1182 /// If Sec is compressed section, decompresses and updates its contents
1183 /// provided by Data. Otherwise leaves it unchanged.
1184 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1185 StringRef &Data) {
1186 if (!Decompressor::isCompressed(Sec))
1187 return Error::success();
1188
1189 Expected<Decompressor> Decompressor =
1190 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1191 if (!Decompressor)
1192 return Decompressor.takeError();
1193
1194 SmallString<32> Out;
1195 if (auto Err = Decompressor->resizeAndDecompress(Out))
1196 return Err;
1197
1198 UncompressedSections.emplace_back(std::move(Out));
1199 Data = UncompressedSections.back();
1200
1201 return Error::success();
1202 }
1203
1204public:
1205 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1206 uint8_t AddrSize, bool IsLittleEndian)
1207 : IsLittleEndian(IsLittleEndian) {
1208 for (const auto &SecIt : Sections) {
1209 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1210 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001211 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001212 }
1213 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1214 function_ref<ErrorPolicy(Error)> HandleError)
1215 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001216 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1217 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001218
George Rimare1c30f72017-08-15 15:54:43 +00001219 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001220 for (const SectionRef &Section : Obj.sections()) {
1221 StringRef Name;
1222 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001223 ++SectionAmountMap[Name];
1224 SectionNames.push_back({ Name, true });
1225
Rafael Espindolac398e672017-07-19 22:27:28 +00001226 // Skip BSS and Virtual sections, they aren't interesting.
1227 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001228 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001229
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001230 // Skip sections stripped by dsymutil.
1231 if (Section.isStripped())
1232 continue;
1233
Rafael Espindolac398e672017-07-19 22:27:28 +00001234 StringRef Data;
1235 section_iterator RelocatedSection = Section.getRelocatedSection();
1236 // Try to obtain an already relocated version of this section.
1237 // Else use the unrelocated section from the object file. We'll have to
1238 // apply relocations ourselves later.
1239 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1240 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001241
Rafael Espindolac398e672017-07-19 22:27:28 +00001242 if (auto Err = maybeDecompress(Section, Name, Data)) {
1243 ErrorPolicy EP = HandleError(createError(
1244 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001245 if (EP == ErrorPolicy::Halt)
1246 return;
George Rimarfed9f092017-05-17 12:10:51 +00001247 continue;
1248 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001249
1250 // Compressed sections names in GNU style starts from ".z",
1251 // at this point section is decompressed and we drop compression prefix.
1252 Name = Name.substr(
1253 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1254
1255 // Map platform specific debug section names to DWARF standard section
1256 // names.
1257 Name = Obj.mapDebugSectionName(Name);
1258
1259 if (StringRef *SectionData = mapSectionToMember(Name)) {
1260 *SectionData = Data;
1261 if (Name == "debug_ranges") {
1262 // FIXME: Use the other dwo range section when we emit it.
1263 RangeDWOSection.Data = Data;
1264 }
1265 } else if (Name == "debug_types") {
1266 // Find debug_types data by section rather than name as there are
1267 // multiple, comdat grouped, debug_types sections.
1268 TypesSections[Section].Data = Data;
1269 } else if (Name == "debug_types.dwo") {
1270 TypesDWOSections[Section].Data = Data;
1271 }
1272
1273 if (RelocatedSection == Obj.section_end())
1274 continue;
1275
1276 StringRef RelSecName;
1277 StringRef RelSecData;
1278 RelocatedSection->getName(RelSecName);
1279
1280 // If the section we're relocating was relocated already by the JIT,
1281 // then we used the relocated version above, so we do not need to process
1282 // relocations for it now.
1283 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1284 continue;
1285
1286 // In Mach-o files, the relocations do not need to be applied if
1287 // there is no load offset to apply. The value read at the
1288 // relocation point already factors in the section address
1289 // (actually applying the relocations will produce wrong results
1290 // as the section address will be added twice).
1291 if (!L && isa<MachOObjectFile>(&Obj))
1292 continue;
1293
1294 RelSecName = RelSecName.substr(
1295 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1296
1297 // TODO: Add support for relocations in other sections as needed.
1298 // Record relocations for the debug_info and debug_line sections.
1299 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1300 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1301 if (!Map) {
1302 // Find debug_types relocs by section rather than name as there are
1303 // multiple, comdat grouped, debug_types sections.
1304 if (RelSecName == "debug_types")
1305 Map =
1306 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1307 .Relocs;
1308 else if (RelSecName == "debug_types.dwo")
1309 Map = &static_cast<DWARFSectionMap &>(
1310 TypesDWOSections[*RelocatedSection])
1311 .Relocs;
1312 else
1313 continue;
1314 }
1315
1316 if (Section.relocation_begin() == Section.relocation_end())
1317 continue;
1318
1319 // Symbol to [address, section index] cache mapping.
1320 std::map<SymbolRef, SymInfo> AddrCache;
1321 for (const RelocationRef &Reloc : Section.relocations()) {
1322 // FIXME: it's not clear how to correctly handle scattered
1323 // relocations.
1324 if (isRelocScattered(Obj, Reloc))
1325 continue;
1326
1327 Expected<SymInfo> SymInfoOrErr =
1328 getSymbolInfo(Obj, Reloc, L, AddrCache);
1329 if (!SymInfoOrErr) {
1330 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1331 return;
1332 continue;
1333 }
1334
1335 object::RelocVisitor V(Obj);
1336 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1337 if (V.error()) {
1338 SmallString<32> Type;
1339 Reloc.getTypeName(Type);
1340 ErrorPolicy EP = HandleError(
1341 createError("failed to compute relocation: " + Type + ", ",
1342 errorCodeToError(object_error::parse_failed)));
1343 if (EP == ErrorPolicy::Halt)
1344 return;
1345 continue;
1346 }
1347 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1348 Map->insert({Reloc.getOffset(), Rel});
1349 }
Eric Christopher7370b552012-11-12 21:40:38 +00001350 }
George Rimare1c30f72017-08-15 15:54:43 +00001351
1352 for (SectionName &S : SectionNames)
1353 if (SectionAmountMap[S.Name] > 1)
1354 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001355 }
Eric Christopher7370b552012-11-12 21:40:38 +00001356
Rafael Espindolac398e672017-07-19 22:27:28 +00001357 Optional<RelocAddrEntry> find(const DWARFSection &S,
1358 uint64_t Pos) const override {
1359 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1360 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1361 if (AI == Sec.Relocs.end())
1362 return None;
1363 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001364 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001365
George Rimar6957ab52017-08-15 12:32:54 +00001366 const object::ObjectFile *getFile() const override { return Obj; }
1367
George Rimare1c30f72017-08-15 15:54:43 +00001368 ArrayRef<SectionName> getSectionNames() const override {
1369 return SectionNames;
1370 }
1371
Rafael Espindolac398e672017-07-19 22:27:28 +00001372 bool isLittleEndian() const override { return IsLittleEndian; }
1373 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1374 const DWARFSection &getLineDWOSection() const override {
1375 return LineDWOSection;
1376 }
1377 const DWARFSection &getLocDWOSection() const override {
1378 return LocDWOSection;
1379 }
1380 StringRef getStringDWOSection() const override { return StringDWOSection; }
1381 const DWARFSection &getStringOffsetDWOSection() const override {
1382 return StringOffsetDWOSection;
1383 }
1384 const DWARFSection &getRangeDWOSection() const override {
1385 return RangeDWOSection;
1386 }
1387 const DWARFSection &getAddrSection() const override { return AddrSection; }
1388 StringRef getCUIndexSection() const override { return CUIndexSection; }
1389 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1390 StringRef getTUIndexSection() const override { return TUIndexSection; }
1391
1392 // DWARF v5
1393 const DWARFSection &getStringOffsetSection() const override {
1394 return StringOffsetSection;
1395 }
1396
1397 // Sections for DWARF5 split dwarf proposal.
1398 const DWARFSection &getInfoDWOSection() const override {
1399 return InfoDWOSection;
1400 }
1401 void forEachTypesDWOSections(
1402 function_ref<void(const DWARFSection &)> F) const override {
1403 for (auto &P : TypesDWOSections)
1404 F(P.second);
1405 }
1406
1407 StringRef getAbbrevSection() const override { return AbbrevSection; }
1408 const DWARFSection &getLocSection() const override { return LocSection; }
1409 StringRef getARangeSection() const override { return ARangeSection; }
1410 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1411 StringRef getEHFrameSection() const override { return EHFrameSection; }
1412 const DWARFSection &getLineSection() const override { return LineSection; }
1413 StringRef getStringSection() const override { return StringSection; }
1414 const DWARFSection &getRangeSection() const override { return RangeSection; }
1415 StringRef getMacinfoSection() const override { return MacinfoSection; }
1416 StringRef getPubNamesSection() const override { return PubNamesSection; }
1417 StringRef getPubTypesSection() const override { return PubTypesSection; }
1418 StringRef getGnuPubNamesSection() const override {
1419 return GnuPubNamesSection;
1420 }
1421 StringRef getGnuPubTypesSection() const override {
1422 return GnuPubTypesSection;
1423 }
1424 const DWARFSection &getAppleNamesSection() const override {
1425 return AppleNamesSection;
1426 }
1427 const DWARFSection &getAppleTypesSection() const override {
1428 return AppleTypesSection;
1429 }
1430 const DWARFSection &getAppleNamespacesSection() const override {
1431 return AppleNamespacesSection;
1432 }
1433 const DWARFSection &getAppleObjCSection() const override {
1434 return AppleObjCSection;
1435 }
1436
1437 StringRef getFileName() const override { return FileName; }
1438 uint8_t getAddressSize() const override { return AddressSize; }
1439 const DWARFSection &getInfoSection() const override { return InfoSection; }
1440 void forEachTypesSections(
1441 function_ref<void(const DWARFSection &)> F) const override {
1442 for (auto &P : TypesSections)
1443 F(P.second);
1444 }
1445};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001446} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001447
1448std::unique_ptr<DWARFContext>
1449DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001450 function_ref<ErrorPolicy(Error)> HandleError,
1451 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001452 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001453 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001454}
1455
Rafael Espindolac398e672017-07-19 22:27:28 +00001456std::unique_ptr<DWARFContext>
1457DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1458 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001459 auto DObj =
1460 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001461 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001462}
Reid Klecknera0587362017-08-29 21:41:21 +00001463
1464Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1465 // Detect the architecture from the object file. We usually don't need OS
1466 // info to lookup a target and create register info.
1467 Triple TT;
1468 TT.setArch(Triple::ArchType(Obj.getArch()));
1469 TT.setVendor(Triple::UnknownVendor);
1470 TT.setOS(Triple::UnknownOS);
1471 std::string TargetLookupError;
1472 const Target *TheTarget =
1473 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1474 if (!TargetLookupError.empty())
1475 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1476 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1477 return Error::success();
1478}