blob: 02c91d2464c82528ab965aee1715896c6835e3dc [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"
Reid Klecknera0587362017-08-29 21:41:21 +000044#include "llvm/Support/TargetRegistry.h"
Benjamin Kramera6002fd2011-09-14 01:09:52 +000045#include "llvm/Support/raw_ostream.h"
Benjamin Kramer2602ca62011-09-15 20:43:22 +000046#include <algorithm>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000047#include <cstdint>
Greg Claytonc7695a82017-05-02 20:28:33 +000048#include <map>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000049#include <string>
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000050#include <tuple>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000051#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
Frederic Riss7c500472014-11-14 19:30:08 +000070static void dumpAccelSection(raw_ostream &OS, StringRef Name,
Rafael Espindolac398e672017-07-19 22:27:28 +000071 const DWARFObject &Obj,
72 const DWARFSection &Section,
73 StringRef StringSection, bool LittleEndian) {
74 DWARFDataExtractor AccelSection(Obj, Section, LittleEndian, 0);
Frederic Risse837ec22014-11-14 16:15:53 +000075 DataExtractor StrData(StringSection, LittleEndian, 0);
76 OS << "\n." << Name << " contents:\n";
Paul Robinson17536b92017-06-29 16:52:08 +000077 DWARFAcceleratorTable Accel(AccelSection, StrData);
Frederic Risse837ec22014-11-14 16:15:53 +000078 if (!Accel.extract())
79 return;
80 Accel.dump(OS);
81}
82
Adrian Prantl3dcd1222017-09-13 18:22:59 +000083/// Dump the UUID load command.
84static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
85 auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
86 if (!MachO)
87 return;
88 for (auto LC : MachO->load_commands()) {
89 raw_ostream::uuid_t UUID;
90 if (LC.C.cmd == MachO::LC_UUID) {
91 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
92 OS << "error: UUID load command is too short.\n";
93 return;
94 }
95 OS << "UUID: ";
96 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
97 OS.write_uuid(UUID);
98 OS << ' ' << MachO->getFileFormatName();
99 OS << ' ' << MachO->getFileName() << '\n';
100 }
101 }
102}
103
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000104static void
105dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000106 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000107 const DWARFSection &StringOffsetsSection,
108 StringRef StringSection, bool LittleEndian) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000109 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000110 uint32_t Offset = 0;
111 uint64_t SectionSize = StringOffsetsSection.Data.size();
112
113 while (Offset < SectionSize) {
114 unsigned Version = 0;
115 DwarfFormat Format = DWARF32;
116 unsigned EntrySize = 4;
117 // Perform validation and extract the segment size from the header.
118 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
119 OS << "error: invalid contribution to string offsets table in section ."
120 << SectionName << ".\n";
121 return;
122 }
123 uint32_t ContributionStart = Offset;
124 uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
125 // A contribution size of 0xffffffff indicates DWARF64, with the actual size
126 // in the following 8 bytes. Otherwise, the DWARF standard mandates that
127 // the contribution size must be at most 0xfffffff0.
128 if (ContributionSize == 0xffffffff) {
129 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
130 OS << "error: invalid contribution to string offsets table in section ."
131 << SectionName << ".\n";
132 return;
133 }
134 Format = DWARF64;
135 EntrySize = 8;
136 ContributionSize = StrOffsetExt.getU64(&Offset);
137 } else if (ContributionSize > 0xfffffff0) {
138 OS << "error: invalid contribution to string offsets table in section ."
139 << SectionName << ".\n";
140 return;
141 }
142
143 // We must ensure that we don't read a partial record at the end, so we
144 // validate for a multiple of EntrySize. Also, we're expecting a version
145 // number and padding, which adds an additional 4 bytes.
146 uint64_t ValidationSize =
147 4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
148 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
149 OS << "error: contribution to string offsets table in section ."
150 << SectionName << " has invalid length.\n";
151 return;
152 }
153
154 Version = StrOffsetExt.getU16(&Offset);
155 Offset += 2;
156 OS << format("0x%8.8x: ", ContributionStart);
157 OS << "Contribution size = " << ContributionSize
158 << ", Version = " << Version << "\n";
159
160 uint32_t ContributionBase = Offset;
161 DataExtractor StrData(StringSection, LittleEndian, 0);
162 while (Offset - ContributionBase < ContributionSize) {
163 OS << format("0x%8.8x: ", Offset);
164 // FIXME: We can only extract strings in DWARF32 format at the moment.
Paul Robinson17536b92017-06-29 16:52:08 +0000165 uint64_t StringOffset =
166 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000167 if (Format == DWARF32) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000168 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000169 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000170 const char *S = StrData.getCStr(&StringOffset32);
171 if (S)
172 OS << format("\"%s\"", S);
173 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000174 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000175 OS << "\n";
176 }
177 }
178}
179
180// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
181// string offsets section, where each compile or type unit contributes a
182// number of entries (string offsets), with each contribution preceded by
183// a header containing size and version number. Alternatively, it may be a
184// monolithic series of string offsets, as generated by the pre-DWARF v5
185// implementation of split DWARF.
186static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000187 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000188 const DWARFSection &StringOffsetsSection,
189 StringRef StringSection, bool LittleEndian,
190 unsigned MaxVersion) {
191 if (StringOffsetsSection.Data.empty())
192 return;
193 OS << "\n." << SectionName << " contents:\n";
194 // If we have at least one (compile or type) unit with DWARF v5 or greater,
195 // we assume that the section is formatted like a DWARF v5 string offsets
196 // section.
197 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000198 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000199 StringSection, LittleEndian);
200 else {
201 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
202 uint32_t offset = 0;
203 uint64_t size = StringOffsetsSection.Data.size();
204 // Ensure that size is a multiple of the size of an entry.
205 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
206 OS << "error: size of ." << SectionName << " is not a multiple of "
207 << sizeof(uint32_t) << ".\n";
208 size &= -(uint64_t)sizeof(uint32_t);
209 }
210 DataExtractor StrData(StringSection, LittleEndian, 0);
211 while (offset < size) {
212 OS << format("0x%8.8x: ", offset);
213 uint32_t StringOffset = strOffsetExt.getU32(&offset);
214 OS << format("%8.8x ", StringOffset);
215 const char *S = StrData.getCStr(&StringOffset);
216 if (S)
217 OS << format("\"%s\"", S);
218 OS << "\n";
219 }
220 }
221}
222
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +0000223void DWARFContext::dump(raw_ostream &OS, DIDumpOptions DumpOpts) {
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000224 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000225 bool DumpEH = DumpOpts.DumpEH;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000226
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000227 const auto *ObjFile = DObj->getFile();
228 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All)
229 outs() << ObjFile->getFileName() << ":\tfile format "
230 << ObjFile->getFileFormatName() << "\n\n";
231 if (DumpType & DIDT_UUID)
232 dumpUUID(OS, *ObjFile);
233
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000234 if (DumpType & DIDT_DebugAbbrev) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000235 OS << ".debug_abbrev contents:\n";
236 getDebugAbbrev()->dump(OS);
237 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000238
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000239 if (DumpType & DIDT_DebugAbbrevDwo)
David Blaikie66865d62014-01-09 00:13:35 +0000240 if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
David Blaikie622dce42014-01-08 23:29:59 +0000241 OS << "\n.debug_abbrev.dwo contents:\n";
David Blaikie66865d62014-01-09 00:13:35 +0000242 D->dump(OS);
David Blaikie622dce42014-01-08 23:29:59 +0000243 }
David Blaikie622dce42014-01-08 23:29:59 +0000244
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000245 if (DumpType & DIDT_DebugInfo) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000246 OS << "\n.debug_info contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000247 for (const auto &CU : compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000248 CU->dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000249 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000250
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000251 if ((DumpType & DIDT_DebugInfoDwo) &&
David Blaikie66865d62014-01-09 00:13:35 +0000252 getNumDWOCompileUnits()) {
253 OS << "\n.debug_info.dwo contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000254 for (const auto &DWOCU : dwo_compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000255 DWOCU->dump(OS, DumpOpts);
David Blaikie66865d62014-01-09 00:13:35 +0000256 }
David Blaikie622dce42014-01-08 23:29:59 +0000257
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000258 if ((DumpType & DIDT_DebugTypes) && getNumTypeUnits()) {
David Blaikie03c089c2013-09-23 22:44:47 +0000259 OS << "\n.debug_types contents:\n";
Frederic Riss312a02e2014-09-29 13:56:39 +0000260 for (const auto &TUS : type_unit_sections())
261 for (const auto &TU : TUS)
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000262 TU->dump(OS, DumpOpts);
David Blaikie03c089c2013-09-23 22:44:47 +0000263 }
264
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000265 if ((DumpType & DIDT_DebugTypesDwo) &&
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000266 getNumDWOTypeUnits()) {
267 OS << "\n.debug_types.dwo contents:\n";
Frederic Riss312a02e2014-09-29 13:56:39 +0000268 for (const auto &DWOTUS : dwo_type_unit_sections())
269 for (const auto &DWOTU : DWOTUS)
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000270 DWOTU->dump(OS, DumpOpts);
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000271 }
David Blaikie92d9d622014-01-09 05:08:24 +0000272
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000273 if (DumpType & DIDT_DebugLoc) {
David Blaikie03c089c2013-09-23 22:44:47 +0000274 OS << "\n.debug_loc contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000275 getDebugLoc()->dump(OS, getRegisterInfo());
David Blaikie18e73502013-06-19 21:37:13 +0000276 }
277
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000278 if (DumpType & DIDT_DebugLocDwo) {
David Blaikie9c550ac2014-03-25 01:44:02 +0000279 OS << "\n.debug_loc.dwo contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000280 getDebugLocDWO()->dump(OS, getRegisterInfo());
David Blaikie9c550ac2014-03-25 01:44:02 +0000281 }
282
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000283 if (DumpType & DIDT_DebugFrames) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000284 OS << "\n.debug_frame contents:\n";
285 getDebugFrame()->dump(OS);
Igor Laevsky03a670c2016-01-26 15:09:42 +0000286 if (DumpEH) {
287 OS << "\n.eh_frame contents:\n";
288 getEHFrame()->dump(OS);
289 }
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000290 }
291
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000292 if (DumpType & DIDT_DebugMacro) {
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000293 OS << "\n.debug_macinfo contents:\n";
294 getDebugMacro()->dump(OS);
295 }
296
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000297 uint32_t offset = 0;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000298 if (DumpType & DIDT_DebugAranges) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000299 OS << "\n.debug_aranges contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000300 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000301 DWARFDebugArangeSet set;
302 while (set.extract(arangesData, &offset))
303 set.dump(OS);
304 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000305
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000306 uint8_t savedAddressByteSize = 0;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000307 if (DumpType & DIDT_DebugLine) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000308 OS << "\n.debug_line contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000309 for (const auto &CU : compile_units()) {
310 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000311 auto CUDIE = CU->getUnitDIE();
312 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000313 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000314 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000315 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
316 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000317 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000318 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000319 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000320 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000321 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000322 }
323 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000324
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000325 if (DumpType & DIDT_DebugCUIndex) {
David Blaikie65a8efe2015-11-11 19:28:21 +0000326 OS << "\n.debug_cu_index contents:\n";
David Blaikieb073cb92015-12-02 06:21:34 +0000327 getCUIndex().dump(OS);
David Blaikie65a8efe2015-11-11 19:28:21 +0000328 }
329
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000330 if (DumpType & DIDT_DebugTUIndex) {
David Blaikie51c40282015-11-11 19:40:49 +0000331 OS << "\n.debug_tu_index contents:\n";
David Blaikieb073cb92015-12-02 06:21:34 +0000332 getTUIndex().dump(OS);
David Blaikie51c40282015-11-11 19:40:49 +0000333 }
334
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000335 if (DumpType & DIDT_DebugLineDwo) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000336 OS << "\n.debug_line.dwo contents:\n";
337 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000338 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
339 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000340 DWARFDebugLine::LineTable LineTable;
341 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
342 LineTable.dump(OS);
343 LineTable.clear();
344 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000345 }
346
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000347 if (DumpType & DIDT_DebugStr) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000348 OS << "\n.debug_str contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000349 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000350 offset = 0;
351 uint32_t strOffset = 0;
352 while (const char *s = strData.getCStr(&offset)) {
353 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
354 strOffset = offset;
355 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000356 }
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000357
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000358 if ((DumpType & DIDT_DebugStrDwo) &&
Rafael Espindolac398e672017-07-19 22:27:28 +0000359 !DObj->getStringDWOSection().empty()) {
David Blaikie66865d62014-01-09 00:13:35 +0000360 OS << "\n.debug_str.dwo contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000361 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
David Blaikie66865d62014-01-09 00:13:35 +0000362 offset = 0;
363 uint32_t strDWOOffset = 0;
364 while (const char *s = strDWOData.getCStr(&offset)) {
365 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
366 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000367 }
David Blaikie66865d62014-01-09 00:13:35 +0000368 }
David Blaikie622dce42014-01-08 23:29:59 +0000369
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000370 if (DumpType & DIDT_DebugRanges) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000371 OS << "\n.debug_ranges contents:\n";
372 // In fact, different compile units may have different address byte
373 // sizes, but for simplicity we just use the address byte size of the last
374 // compile unit (there is no easy and fast way to associate address range
375 // list and the compile unit it describes).
Rafael Espindolac398e672017-07-19 22:27:28 +0000376 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
377 isLittleEndian(), savedAddressByteSize);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000378 offset = 0;
379 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000380 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000381 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000382 }
Eric Christopher962c9082013-01-15 23:56:56 +0000383
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000384 if (DumpType & DIDT_DebugPubnames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000385 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000386 .dump("debug_pubnames", OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000387
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000388 if (DumpType & DIDT_DebugPubtypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000389 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000390 .dump("debug_pubtypes", OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000391
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000392 if (DumpType & DIDT_DebugGnuPubnames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000393 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000394 true /* GnuStyle */)
395 .dump("debug_gnu_pubnames", OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000396
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000397 if (DumpType & DIDT_DebugGnuPubtypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000398 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000399 true /* GnuStyle */)
400 .dump("debug_gnu_pubtypes", OS);
David Blaikie404d3042013-09-19 23:01:29 +0000401
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000402 if (DumpType & DIDT_DebugStrOffsets)
Rafael Espindolac398e672017-07-19 22:27:28 +0000403 dumpStringOffsetsSection(
404 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
405 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000406
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000407 if (DumpType & DIDT_DebugStrOffsetsDwo) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000408 dumpStringOffsetsSection(
409 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
410 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
David Blaikie66865d62014-01-09 00:13:35 +0000411 }
Frederic Risse837ec22014-11-14 16:15:53 +0000412
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000413 if ((DumpType & DIDT_GdbIndex) &&
Rafael Espindolac398e672017-07-19 22:27:28 +0000414 !DObj->getGdbIndexSection().empty()) {
George Rimar4f82df52016-09-23 11:01:53 +0000415 OS << "\n.gnu_index contents:\n";
416 getGdbIndex().dump(OS);
417 }
418
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000419 if (DumpType & DIDT_AppleNames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000420 dumpAccelSection(OS, "apple_names", *DObj, DObj->getAppleNamesSection(),
421 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000422
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000423 if (DumpType & DIDT_AppleTypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000424 dumpAccelSection(OS, "apple_types", *DObj, DObj->getAppleTypesSection(),
425 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000426
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000427 if (DumpType & DIDT_AppleNamespaces)
Rafael Espindolac398e672017-07-19 22:27:28 +0000428 dumpAccelSection(OS, "apple_namespaces", *DObj,
429 DObj->getAppleNamespacesSection(),
430 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000431
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000432 if (DumpType & DIDT_AppleObjC)
Rafael Espindolac398e672017-07-19 22:27:28 +0000433 dumpAccelSection(OS, "apple_objc", *DObj, DObj->getAppleObjCSection(),
434 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000435}
436
David Blaikie15d85fc2017-05-23 06:48:53 +0000437DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000438 parseDWOCompileUnits();
439
David Blaikieebac0b92017-07-30 08:12:07 +0000440 if (const auto &CUI = getCUIndex()) {
441 if (const auto *R = CUI.getFromHash(Hash))
442 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000443 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000444 return nullptr;
445 }
446
447 // If there's no index, just search through the CUs in the DWO - there's
448 // probably only one unless this is something like LTO - though an in-process
449 // built/cached lookup table could be used in that case to improve repeated
450 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000451 for (const auto &DWOCU : dwo_compile_units())
452 if (DWOCU->getDWOId() == Hash)
453 return DWOCU.get();
454 return nullptr;
455}
456
Greg Claytonc7695a82017-05-02 20:28:33 +0000457DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
458 parseCompileUnits();
459 if (auto *CU = CUs.getUnitForOffset(Offset))
460 return CU->getDIEForOffset(Offset);
461 return DWARFDie();
462}
463
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000464bool DWARFContext::verify(raw_ostream &OS, uint64_t DumpType,
465 DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000466 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000467 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000468
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000469 Success &= verifier.handleDebugAbbrev();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000470 if (DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000471 Success &= verifier.handleDebugInfo();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000472 if (DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000473 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000474 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000475 return Success;
476}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000477
David Blaikie82641be2015-11-17 00:39:55 +0000478const DWARFUnitIndex &DWARFContext::getCUIndex() {
479 if (CUIndex)
480 return *CUIndex;
481
Rafael Espindolac398e672017-07-19 22:27:28 +0000482 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000483
David Blaikieb073cb92015-12-02 06:21:34 +0000484 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000485 CUIndex->parse(CUIndexData);
486 return *CUIndex;
487}
488
489const DWARFUnitIndex &DWARFContext::getTUIndex() {
490 if (TUIndex)
491 return *TUIndex;
492
Rafael Espindolac398e672017-07-19 22:27:28 +0000493 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000494
David Blaikieb073cb92015-12-02 06:21:34 +0000495 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000496 TUIndex->parse(TUIndexData);
497 return *TUIndex;
498}
499
George Rimar4f82df52016-09-23 11:01:53 +0000500DWARFGdbIndex &DWARFContext::getGdbIndex() {
501 if (GdbIndex)
502 return *GdbIndex;
503
Rafael Espindolac398e672017-07-19 22:27:28 +0000504 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000505 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
506 GdbIndex->parse(GdbIndexData);
507 return *GdbIndex;
508}
509
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000510const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
511 if (Abbrev)
512 return Abbrev.get();
513
Rafael Espindolac398e672017-07-19 22:27:28 +0000514 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000515
516 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000517 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000518 return Abbrev.get();
519}
520
Eric Christopherda4b2192013-01-02 23:52:13 +0000521const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
522 if (AbbrevDWO)
523 return AbbrevDWO.get();
524
Rafael Espindolac398e672017-07-19 22:27:28 +0000525 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000526 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000527 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000528 return AbbrevDWO.get();
529}
530
David Blaikie18e73502013-06-19 21:37:13 +0000531const DWARFDebugLoc *DWARFContext::getDebugLoc() {
532 if (Loc)
533 return Loc.get();
534
Paul Robinson17536b92017-06-29 16:52:08 +0000535 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000536 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000537 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000538 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000539 getCompileUnitAtIndex(0)->getAddressByteSize());
540 Loc->parse(LocData);
541 }
David Blaikie18e73502013-06-19 21:37:13 +0000542 return Loc.get();
543}
544
David Blaikie9c550ac2014-03-25 01:44:02 +0000545const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
546 if (LocDWO)
547 return LocDWO.get();
548
Rafael Espindolac398e672017-07-19 22:27:28 +0000549 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000550 LocDWO.reset(new DWARFDebugLocDWO());
551 LocDWO->parse(LocData);
552 return LocDWO.get();
553}
554
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000555const DWARFDebugAranges *DWARFContext::getDebugAranges() {
556 if (Aranges)
557 return Aranges.get();
558
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000559 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000560 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000561 return Aranges.get();
562}
563
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000564const DWARFDebugFrame *DWARFContext::getDebugFrame() {
565 if (DebugFrame)
566 return DebugFrame.get();
567
568 // There's a "bug" in the DWARFv3 standard with respect to the target address
569 // size within debug frame sections. While DWARF is supposed to be independent
570 // of its container, FDEs have fields with size being "target address size",
571 // which isn't specified in DWARF in general. It's only specified for CUs, but
572 // .eh_frame can appear without a .debug_info section. Follow the example of
573 // other tools (libdwarf) and extract this from the container (ObjectFile
574 // provides this information). This problem is fixed in DWARFv4
575 // See this dwarf-discuss discussion for more details:
576 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000577 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
578 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000579 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
580 DebugFrame->parse(debugFrameData);
581 return DebugFrame.get();
582}
583
584const DWARFDebugFrame *DWARFContext::getEHFrame() {
585 if (EHFrame)
586 return EHFrame.get();
587
Rafael Espindolac398e672017-07-19 22:27:28 +0000588 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
589 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000590 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000591 DebugFrame->parse(debugFrameData);
592 return DebugFrame.get();
593}
594
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000595const DWARFDebugMacro *DWARFContext::getDebugMacro() {
596 if (Macro)
597 return Macro.get();
598
Rafael Espindolac398e672017-07-19 22:27:28 +0000599 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000600 Macro.reset(new DWARFDebugMacro());
601 Macro->parse(MacinfoData);
602 return Macro.get();
603}
604
Eric Christopher494109b2012-10-16 23:46:25 +0000605const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000606DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000607 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000608 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000609
Greg Claytonc8c10322016-12-13 18:25:19 +0000610 auto UnitDIE = U->getUnitDIE();
611 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000612 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000613
Greg Clayton97d22182017-01-13 21:08:18 +0000614 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000615 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000616 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000617
Greg Clayton52fe1f62016-12-14 22:38:08 +0000618 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000619 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000620 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000621 return lt;
622
Greg Clayton48ff66a2017-05-04 18:29:44 +0000623 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000624 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000625 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000626
Benjamin Kramer679e1752011-09-15 20:43:18 +0000627 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000628 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000629 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000630 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000631}
632
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000633void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000634 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000635}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000636
David Blaikie03c089c2013-09-23 22:44:47 +0000637void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000638 if (!TUs.empty())
639 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000640 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000641 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000642 TUs.back().parse(*this, S);
643 });
David Blaikie03c089c2013-09-23 22:44:47 +0000644}
645
Eric Christopherda4b2192013-01-02 23:52:13 +0000646void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000647 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000648}
649
David Blaikie92d9d622014-01-09 05:08:24 +0000650void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000651 if (!DWOTUs.empty())
652 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000653 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000654 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000655 DWOTUs.back().parseDWO(*this, S);
656 });
David Blaikie92d9d622014-01-09 05:08:24 +0000657}
658
Alexey Samsonov45be7932012-08-30 07:49:50 +0000659DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000660 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000661 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000662}
663
Alexey Samsonov45be7932012-08-30 07:49:50 +0000664DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000665 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000666 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000667 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000668 return getCompileUnitForOffset(CUOffset);
669}
670
David Blaikieefc4eba2017-02-06 20:19:02 +0000671static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
672 uint64_t Address,
673 FunctionNameKind Kind,
674 std::string &FunctionName,
675 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000676 // The address may correspond to instruction in some inlined function,
677 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000678 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000679 SmallVector<DWARFDie, 4> InlinedChain;
680 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000681 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000682 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000683
684 const DWARFDie &DIE = InlinedChain[0];
685 bool FoundResult = false;
686 const char *Name = nullptr;
687 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000688 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000689 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000690 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000691 if (auto DeclLineResult = DIE.getDeclLine()) {
692 StartLine = DeclLineResult;
693 FoundResult = true;
694 }
695
696 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000697}
698
Alexey Samsonov45be7932012-08-30 07:49:50 +0000699DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000700 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000701 DILineInfo Result;
702
Alexey Samsonov45be7932012-08-30 07:49:50 +0000703 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
704 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000705 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000706 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
707 Result.FunctionName,
708 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000709 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000710 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
711 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
712 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000713 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000714 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000715}
David Blaikiea379b1812011-12-20 02:50:00 +0000716
Alexey Samsonovdce67342014-05-15 21:24:32 +0000717DILineInfoTable
718DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
719 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000720 DILineInfoTable Lines;
721 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
722 if (!CU)
723 return Lines;
724
725 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000726 uint32_t StartLine = 0;
727 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
728 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000729
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000730 // If the Specifier says we don't need FileLineInfo, just
731 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000732 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000733 DILineInfo Result;
734 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000735 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000736 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000737 return Lines;
738 }
739
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000740 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000741
742 // Get the index of row we're looking for in the line table.
743 std::vector<uint32_t> RowVector;
744 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
745 return Lines;
746
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000747 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000748 // Take file number and line/column from the row.
749 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000750 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000751 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
752 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000753 Result.FunctionName = FunctionName;
754 Result.Line = Row.Line;
755 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000756 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000757 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000758 }
759
760 return Lines;
761}
762
Alexey Samsonovdce67342014-05-15 21:24:32 +0000763DIInliningInfo
764DWARFContext::getInliningInfoForAddress(uint64_t Address,
765 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000766 DIInliningInfo InliningInfo;
767
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000768 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
769 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000770 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000771
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000772 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000773 SmallVector<DWARFDie, 4> InlinedChain;
774 CU->getInlinedChainForAddress(Address, InlinedChain);
775 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000776 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
777 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000778 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000779 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000780 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000781 if (LineTable &&
782 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
783 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000784 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000785 }
786 return InliningInfo;
787 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000788
Dehao Chenef700d52017-04-17 20:10:39 +0000789 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000790 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
791 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000792 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000793 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000794 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000795 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000796 if (auto DeclLineResult = FunctionDIE.getDeclLine())
797 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000798 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000799 if (i == 0) {
800 // For the topmost frame, initialize the line table of this
801 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000802 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000803 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000804 if (LineTable)
805 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
806 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000807 } else {
808 // Otherwise, use call file, call line and call column from
809 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000810 if (LineTable)
811 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
812 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000813 Frame.Line = CallLine;
814 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000815 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000816 }
817 // Get call file/line/column of a current DIE.
818 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000819 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
820 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000821 }
822 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000823 InliningInfo.addFrame(Frame);
824 }
825 return InliningInfo;
826}
827
David Blaikief9803fb2017-05-23 00:30:42 +0000828std::shared_ptr<DWARFContext>
829DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000830 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000831 DWARFContext *Ctxt = S->Context.get();
832 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
833 }
834
David Blaikie15d85fc2017-05-23 06:48:53 +0000835 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
836
837 if (auto S = Entry->lock()) {
838 DWARFContext *Ctxt = S->Context.get();
839 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
840 }
841
David Blaikie15d85fc2017-05-23 06:48:53 +0000842 Expected<OwningBinary<ObjectFile>> Obj = [&] {
843 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000844 SmallString<128> DWPName;
845 auto Obj = object::ObjectFile::createObjectFile(
846 this->DWPName.empty()
847 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
848 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000849 if (Obj) {
850 Entry = &DWP;
851 return Obj;
852 } else {
853 CheckedForDWP = true;
854 // TODO: Should this error be handled (maybe in a high verbosity mode)
855 // before falling back to .dwo files?
856 consumeError(Obj.takeError());
857 }
858 }
859
860 return object::ObjectFile::createObjectFile(AbsolutePath);
861 }();
862
David Blaikief9803fb2017-05-23 00:30:42 +0000863 if (!Obj) {
864 // TODO: Actually report errors helpfully.
865 consumeError(Obj.takeError());
866 return nullptr;
867 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000868
869 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000870 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000871 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000872 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000873 auto *Ctxt = S->Context.get();
874 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
875}
876
George Rimar702dac62017-04-12 08:59:15 +0000877static Error createError(const Twine &Reason, llvm::Error E) {
878 return make_error<StringError>(Reason + toString(std::move(E)),
879 inconvertibleErrorCode());
880}
881
George Rimara25d3292017-05-27 18:10:23 +0000882/// SymInfo contains information about symbol: it's address
883/// and section index which is -1LL for absolute symbols.
884struct SymInfo {
885 uint64_t Address;
886 uint64_t SectionIndex;
887};
888
889/// Returns the address of symbol relocation used against and a section index.
890/// Used for futher relocations computation. Symbol's section load address is
891static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
892 const RelocationRef &Reloc,
893 const LoadedObjectInfo *L,
894 std::map<SymbolRef, SymInfo> &Cache) {
895 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000896 object::section_iterator RSec = Obj.section_end();
897 object::symbol_iterator Sym = Reloc.getSymbol();
898
George Rimara25d3292017-05-27 18:10:23 +0000899 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000900 // First calculate the address of the symbol or section as it appears
901 // in the object file
902 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000903 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000904 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000905 if (!New)
906 return CacheIt->second;
907
George Rimar702dac62017-04-12 08:59:15 +0000908 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
909 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000910 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000911 SymAddrOrErr.takeError());
912
913 // Also remember what section this symbol is in for later
914 auto SectOrErr = Sym->getSection();
915 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000916 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000917 SectOrErr.takeError());
918
919 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000920 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000921 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
922 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000923 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000924 }
925
George Rimara25d3292017-05-27 18:10:23 +0000926 if (RSec != Obj.section_end())
927 Ret.SectionIndex = RSec->getIndex();
928
George Rimar702dac62017-04-12 08:59:15 +0000929 // If we are given load addresses for the sections, we need to adjust:
930 // SymAddr = (Address of Symbol Or Section in File) -
931 // (Address of Section in File) +
932 // (Load Address of Section)
933 // RSec is now either the section being targeted or the section
934 // containing the symbol being targeted. In either case,
935 // we need to perform the same computation.
936 if (L && RSec != Obj.section_end())
937 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000938 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000939
940 if (CacheIt != Cache.end())
941 CacheIt->second = Ret;
942
George Rimar702dac62017-04-12 08:59:15 +0000943 return Ret;
944}
945
946static bool isRelocScattered(const object::ObjectFile &Obj,
947 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000948 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
949 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000950 return false;
951 // MachO also has relocations that point to sections and
952 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000953 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
954 return MachObj->isRelocationScattered(RelocInfo);
955}
956
Rafael Espindolac398e672017-07-19 22:27:28 +0000957ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000958 errs() << "error: " + toString(std::move(E)) << '\n';
959 return ErrorPolicy::Continue;
960}
961
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000962namespace {
963struct DWARFSectionMap final : public DWARFSection {
964 RelocAddrMap Relocs;
965};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000966
Rafael Espindolac398e672017-07-19 22:27:28 +0000967class DWARFObjInMemory final : public DWARFObject {
968 bool IsLittleEndian;
969 uint8_t AddressSize;
970 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +0000971 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +0000972 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000973
Rafael Espindolac398e672017-07-19 22:27:28 +0000974 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
975 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +0000976
Rafael Espindolac398e672017-07-19 22:27:28 +0000977 TypeSectionMap TypesSections;
978 TypeSectionMap TypesDWOSections;
979
980 DWARFSectionMap InfoSection;
981 DWARFSectionMap LocSection;
982 DWARFSectionMap LineSection;
983 DWARFSectionMap RangeSection;
984 DWARFSectionMap StringOffsetSection;
985 DWARFSectionMap InfoDWOSection;
986 DWARFSectionMap LineDWOSection;
987 DWARFSectionMap LocDWOSection;
988 DWARFSectionMap StringOffsetDWOSection;
989 DWARFSectionMap RangeDWOSection;
990 DWARFSectionMap AddrSection;
991 DWARFSectionMap AppleNamesSection;
992 DWARFSectionMap AppleTypesSection;
993 DWARFSectionMap AppleNamespacesSection;
994 DWARFSectionMap AppleObjCSection;
995
996 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
997 return StringSwitch<DWARFSectionMap *>(Name)
998 .Case("debug_info", &InfoSection)
999 .Case("debug_loc", &LocSection)
1000 .Case("debug_line", &LineSection)
1001 .Case("debug_str_offsets", &StringOffsetSection)
1002 .Case("debug_ranges", &RangeSection)
1003 .Case("debug_info.dwo", &InfoDWOSection)
1004 .Case("debug_loc.dwo", &LocDWOSection)
1005 .Case("debug_line.dwo", &LineDWOSection)
1006 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1007 .Case("debug_addr", &AddrSection)
1008 .Case("apple_names", &AppleNamesSection)
1009 .Case("apple_types", &AppleTypesSection)
1010 .Case("apple_namespaces", &AppleNamespacesSection)
1011 .Case("apple_namespac", &AppleNamespacesSection)
1012 .Case("apple_objc", &AppleObjCSection)
1013 .Default(nullptr);
1014 }
1015
1016 StringRef AbbrevSection;
1017 StringRef ARangeSection;
1018 StringRef DebugFrameSection;
1019 StringRef EHFrameSection;
1020 StringRef StringSection;
1021 StringRef MacinfoSection;
1022 StringRef PubNamesSection;
1023 StringRef PubTypesSection;
1024 StringRef GnuPubNamesSection;
1025 StringRef AbbrevDWOSection;
1026 StringRef StringDWOSection;
1027 StringRef GnuPubTypesSection;
1028 StringRef CUIndexSection;
1029 StringRef GdbIndexSection;
1030 StringRef TUIndexSection;
1031
1032 SmallVector<SmallString<32>, 4> UncompressedSections;
1033
1034 StringRef *mapSectionToMember(StringRef Name) {
1035 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1036 return &Sec->Data;
1037 return StringSwitch<StringRef *>(Name)
1038 .Case("debug_abbrev", &AbbrevSection)
1039 .Case("debug_aranges", &ARangeSection)
1040 .Case("debug_frame", &DebugFrameSection)
1041 .Case("eh_frame", &EHFrameSection)
1042 .Case("debug_str", &StringSection)
1043 .Case("debug_macinfo", &MacinfoSection)
1044 .Case("debug_pubnames", &PubNamesSection)
1045 .Case("debug_pubtypes", &PubTypesSection)
1046 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1047 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1048 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1049 .Case("debug_str.dwo", &StringDWOSection)
1050 .Case("debug_cu_index", &CUIndexSection)
1051 .Case("debug_tu_index", &TUIndexSection)
1052 .Case("gdb_index", &GdbIndexSection)
1053 // Any more debug info sections go here.
1054 .Default(nullptr);
1055 }
1056
1057 /// If Sec is compressed section, decompresses and updates its contents
1058 /// provided by Data. Otherwise leaves it unchanged.
1059 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1060 StringRef &Data) {
1061 if (!Decompressor::isCompressed(Sec))
1062 return Error::success();
1063
1064 Expected<Decompressor> Decompressor =
1065 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1066 if (!Decompressor)
1067 return Decompressor.takeError();
1068
1069 SmallString<32> Out;
1070 if (auto Err = Decompressor->resizeAndDecompress(Out))
1071 return Err;
1072
1073 UncompressedSections.emplace_back(std::move(Out));
1074 Data = UncompressedSections.back();
1075
1076 return Error::success();
1077 }
1078
1079public:
1080 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1081 uint8_t AddrSize, bool IsLittleEndian)
1082 : IsLittleEndian(IsLittleEndian) {
1083 for (const auto &SecIt : Sections) {
1084 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1085 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001086 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001087 }
1088 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1089 function_ref<ErrorPolicy(Error)> HandleError)
1090 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001091 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1092 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001093
George Rimare1c30f72017-08-15 15:54:43 +00001094 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001095 for (const SectionRef &Section : Obj.sections()) {
1096 StringRef Name;
1097 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001098 ++SectionAmountMap[Name];
1099 SectionNames.push_back({ Name, true });
1100
Rafael Espindolac398e672017-07-19 22:27:28 +00001101 // Skip BSS and Virtual sections, they aren't interesting.
1102 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001103 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001104
Rafael Espindolac398e672017-07-19 22:27:28 +00001105 StringRef Data;
1106 section_iterator RelocatedSection = Section.getRelocatedSection();
1107 // Try to obtain an already relocated version of this section.
1108 // Else use the unrelocated section from the object file. We'll have to
1109 // apply relocations ourselves later.
1110 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1111 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001112
Rafael Espindolac398e672017-07-19 22:27:28 +00001113 if (auto Err = maybeDecompress(Section, Name, Data)) {
1114 ErrorPolicy EP = HandleError(createError(
1115 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001116 if (EP == ErrorPolicy::Halt)
1117 return;
George Rimarfed9f092017-05-17 12:10:51 +00001118 continue;
1119 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001120
1121 // Compressed sections names in GNU style starts from ".z",
1122 // at this point section is decompressed and we drop compression prefix.
1123 Name = Name.substr(
1124 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1125
1126 // Map platform specific debug section names to DWARF standard section
1127 // names.
1128 Name = Obj.mapDebugSectionName(Name);
1129
1130 if (StringRef *SectionData = mapSectionToMember(Name)) {
1131 *SectionData = Data;
1132 if (Name == "debug_ranges") {
1133 // FIXME: Use the other dwo range section when we emit it.
1134 RangeDWOSection.Data = Data;
1135 }
1136 } else if (Name == "debug_types") {
1137 // Find debug_types data by section rather than name as there are
1138 // multiple, comdat grouped, debug_types sections.
1139 TypesSections[Section].Data = Data;
1140 } else if (Name == "debug_types.dwo") {
1141 TypesDWOSections[Section].Data = Data;
1142 }
1143
1144 if (RelocatedSection == Obj.section_end())
1145 continue;
1146
1147 StringRef RelSecName;
1148 StringRef RelSecData;
1149 RelocatedSection->getName(RelSecName);
1150
1151 // If the section we're relocating was relocated already by the JIT,
1152 // then we used the relocated version above, so we do not need to process
1153 // relocations for it now.
1154 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1155 continue;
1156
1157 // In Mach-o files, the relocations do not need to be applied if
1158 // there is no load offset to apply. The value read at the
1159 // relocation point already factors in the section address
1160 // (actually applying the relocations will produce wrong results
1161 // as the section address will be added twice).
1162 if (!L && isa<MachOObjectFile>(&Obj))
1163 continue;
1164
1165 RelSecName = RelSecName.substr(
1166 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1167
1168 // TODO: Add support for relocations in other sections as needed.
1169 // Record relocations for the debug_info and debug_line sections.
1170 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1171 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1172 if (!Map) {
1173 // Find debug_types relocs by section rather than name as there are
1174 // multiple, comdat grouped, debug_types sections.
1175 if (RelSecName == "debug_types")
1176 Map =
1177 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1178 .Relocs;
1179 else if (RelSecName == "debug_types.dwo")
1180 Map = &static_cast<DWARFSectionMap &>(
1181 TypesDWOSections[*RelocatedSection])
1182 .Relocs;
1183 else
1184 continue;
1185 }
1186
1187 if (Section.relocation_begin() == Section.relocation_end())
1188 continue;
1189
1190 // Symbol to [address, section index] cache mapping.
1191 std::map<SymbolRef, SymInfo> AddrCache;
1192 for (const RelocationRef &Reloc : Section.relocations()) {
1193 // FIXME: it's not clear how to correctly handle scattered
1194 // relocations.
1195 if (isRelocScattered(Obj, Reloc))
1196 continue;
1197
1198 Expected<SymInfo> SymInfoOrErr =
1199 getSymbolInfo(Obj, Reloc, L, AddrCache);
1200 if (!SymInfoOrErr) {
1201 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1202 return;
1203 continue;
1204 }
1205
1206 object::RelocVisitor V(Obj);
1207 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1208 if (V.error()) {
1209 SmallString<32> Type;
1210 Reloc.getTypeName(Type);
1211 ErrorPolicy EP = HandleError(
1212 createError("failed to compute relocation: " + Type + ", ",
1213 errorCodeToError(object_error::parse_failed)));
1214 if (EP == ErrorPolicy::Halt)
1215 return;
1216 continue;
1217 }
1218 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1219 Map->insert({Reloc.getOffset(), Rel});
1220 }
Eric Christopher7370b552012-11-12 21:40:38 +00001221 }
George Rimare1c30f72017-08-15 15:54:43 +00001222
1223 for (SectionName &S : SectionNames)
1224 if (SectionAmountMap[S.Name] > 1)
1225 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001226 }
Eric Christopher7370b552012-11-12 21:40:38 +00001227
Rafael Espindolac398e672017-07-19 22:27:28 +00001228 Optional<RelocAddrEntry> find(const DWARFSection &S,
1229 uint64_t Pos) const override {
1230 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1231 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1232 if (AI == Sec.Relocs.end())
1233 return None;
1234 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001235 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001236
George Rimar6957ab52017-08-15 12:32:54 +00001237 const object::ObjectFile *getFile() const override { return Obj; }
1238
George Rimare1c30f72017-08-15 15:54:43 +00001239 ArrayRef<SectionName> getSectionNames() const override {
1240 return SectionNames;
1241 }
1242
Rafael Espindolac398e672017-07-19 22:27:28 +00001243 bool isLittleEndian() const override { return IsLittleEndian; }
1244 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1245 const DWARFSection &getLineDWOSection() const override {
1246 return LineDWOSection;
1247 }
1248 const DWARFSection &getLocDWOSection() const override {
1249 return LocDWOSection;
1250 }
1251 StringRef getStringDWOSection() const override { return StringDWOSection; }
1252 const DWARFSection &getStringOffsetDWOSection() const override {
1253 return StringOffsetDWOSection;
1254 }
1255 const DWARFSection &getRangeDWOSection() const override {
1256 return RangeDWOSection;
1257 }
1258 const DWARFSection &getAddrSection() const override { return AddrSection; }
1259 StringRef getCUIndexSection() const override { return CUIndexSection; }
1260 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1261 StringRef getTUIndexSection() const override { return TUIndexSection; }
1262
1263 // DWARF v5
1264 const DWARFSection &getStringOffsetSection() const override {
1265 return StringOffsetSection;
1266 }
1267
1268 // Sections for DWARF5 split dwarf proposal.
1269 const DWARFSection &getInfoDWOSection() const override {
1270 return InfoDWOSection;
1271 }
1272 void forEachTypesDWOSections(
1273 function_ref<void(const DWARFSection &)> F) const override {
1274 for (auto &P : TypesDWOSections)
1275 F(P.second);
1276 }
1277
1278 StringRef getAbbrevSection() const override { return AbbrevSection; }
1279 const DWARFSection &getLocSection() const override { return LocSection; }
1280 StringRef getARangeSection() const override { return ARangeSection; }
1281 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1282 StringRef getEHFrameSection() const override { return EHFrameSection; }
1283 const DWARFSection &getLineSection() const override { return LineSection; }
1284 StringRef getStringSection() const override { return StringSection; }
1285 const DWARFSection &getRangeSection() const override { return RangeSection; }
1286 StringRef getMacinfoSection() const override { return MacinfoSection; }
1287 StringRef getPubNamesSection() const override { return PubNamesSection; }
1288 StringRef getPubTypesSection() const override { return PubTypesSection; }
1289 StringRef getGnuPubNamesSection() const override {
1290 return GnuPubNamesSection;
1291 }
1292 StringRef getGnuPubTypesSection() const override {
1293 return GnuPubTypesSection;
1294 }
1295 const DWARFSection &getAppleNamesSection() const override {
1296 return AppleNamesSection;
1297 }
1298 const DWARFSection &getAppleTypesSection() const override {
1299 return AppleTypesSection;
1300 }
1301 const DWARFSection &getAppleNamespacesSection() const override {
1302 return AppleNamespacesSection;
1303 }
1304 const DWARFSection &getAppleObjCSection() const override {
1305 return AppleObjCSection;
1306 }
1307
1308 StringRef getFileName() const override { return FileName; }
1309 uint8_t getAddressSize() const override { return AddressSize; }
1310 const DWARFSection &getInfoSection() const override { return InfoSection; }
1311 void forEachTypesSections(
1312 function_ref<void(const DWARFSection &)> F) const override {
1313 for (auto &P : TypesSections)
1314 F(P.second);
1315 }
1316};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001317} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001318
1319std::unique_ptr<DWARFContext>
1320DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001321 function_ref<ErrorPolicy(Error)> HandleError,
1322 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001323 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001324 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001325}
1326
Rafael Espindolac398e672017-07-19 22:27:28 +00001327std::unique_ptr<DWARFContext>
1328DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1329 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001330 auto DObj =
1331 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001332 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001333}
Reid Klecknera0587362017-08-29 21:41:21 +00001334
1335Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1336 // Detect the architecture from the object file. We usually don't need OS
1337 // info to lookup a target and create register info.
1338 Triple TT;
1339 TT.setArch(Triple::ArchType(Obj.getArch()));
1340 TT.setVendor(Triple::UnknownVendor);
1341 TT.setOS(Triple::UnknownOS);
1342 std::string TargetLookupError;
1343 const Target *TheTarget =
1344 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1345 if (!TargetLookupError.empty())
1346 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1347 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1348 return Error::success();
1349}