blob: e9b3c0c132e5986262c2e26a494a458375b57a6a [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
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000083static void
84dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +000085 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000086 const DWARFSection &StringOffsetsSection,
87 StringRef StringSection, bool LittleEndian) {
Rafael Espindolac398e672017-07-19 22:27:28 +000088 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000089 uint32_t Offset = 0;
90 uint64_t SectionSize = StringOffsetsSection.Data.size();
91
92 while (Offset < SectionSize) {
93 unsigned Version = 0;
94 DwarfFormat Format = DWARF32;
95 unsigned EntrySize = 4;
96 // Perform validation and extract the segment size from the header.
97 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
98 OS << "error: invalid contribution to string offsets table in section ."
99 << SectionName << ".\n";
100 return;
101 }
102 uint32_t ContributionStart = Offset;
103 uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
104 // A contribution size of 0xffffffff indicates DWARF64, with the actual size
105 // in the following 8 bytes. Otherwise, the DWARF standard mandates that
106 // the contribution size must be at most 0xfffffff0.
107 if (ContributionSize == 0xffffffff) {
108 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
109 OS << "error: invalid contribution to string offsets table in section ."
110 << SectionName << ".\n";
111 return;
112 }
113 Format = DWARF64;
114 EntrySize = 8;
115 ContributionSize = StrOffsetExt.getU64(&Offset);
116 } else if (ContributionSize > 0xfffffff0) {
117 OS << "error: invalid contribution to string offsets table in section ."
118 << SectionName << ".\n";
119 return;
120 }
121
122 // We must ensure that we don't read a partial record at the end, so we
123 // validate for a multiple of EntrySize. Also, we're expecting a version
124 // number and padding, which adds an additional 4 bytes.
125 uint64_t ValidationSize =
126 4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
127 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
128 OS << "error: contribution to string offsets table in section ."
129 << SectionName << " has invalid length.\n";
130 return;
131 }
132
133 Version = StrOffsetExt.getU16(&Offset);
134 Offset += 2;
135 OS << format("0x%8.8x: ", ContributionStart);
136 OS << "Contribution size = " << ContributionSize
137 << ", Version = " << Version << "\n";
138
139 uint32_t ContributionBase = Offset;
140 DataExtractor StrData(StringSection, LittleEndian, 0);
141 while (Offset - ContributionBase < ContributionSize) {
142 OS << format("0x%8.8x: ", Offset);
143 // FIXME: We can only extract strings in DWARF32 format at the moment.
Paul Robinson17536b92017-06-29 16:52:08 +0000144 uint64_t StringOffset =
145 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000146 if (Format == DWARF32) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000147 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000148 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000149 const char *S = StrData.getCStr(&StringOffset32);
150 if (S)
151 OS << format("\"%s\"", S);
152 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000153 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000154 OS << "\n";
155 }
156 }
157}
158
159// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
160// string offsets section, where each compile or type unit contributes a
161// number of entries (string offsets), with each contribution preceded by
162// a header containing size and version number. Alternatively, it may be a
163// monolithic series of string offsets, as generated by the pre-DWARF v5
164// implementation of split DWARF.
165static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000166 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000167 const DWARFSection &StringOffsetsSection,
168 StringRef StringSection, bool LittleEndian,
169 unsigned MaxVersion) {
170 if (StringOffsetsSection.Data.empty())
171 return;
172 OS << "\n." << SectionName << " contents:\n";
173 // If we have at least one (compile or type) unit with DWARF v5 or greater,
174 // we assume that the section is formatted like a DWARF v5 string offsets
175 // section.
176 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000177 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000178 StringSection, LittleEndian);
179 else {
180 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
181 uint32_t offset = 0;
182 uint64_t size = StringOffsetsSection.Data.size();
183 // Ensure that size is a multiple of the size of an entry.
184 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
185 OS << "error: size of ." << SectionName << " is not a multiple of "
186 << sizeof(uint32_t) << ".\n";
187 size &= -(uint64_t)sizeof(uint32_t);
188 }
189 DataExtractor StrData(StringSection, LittleEndian, 0);
190 while (offset < size) {
191 OS << format("0x%8.8x: ", offset);
192 uint32_t StringOffset = strOffsetExt.getU32(&offset);
193 OS << format("%8.8x ", StringOffset);
194 const char *S = StrData.getCStr(&StringOffset);
195 if (S)
196 OS << format("\"%s\"", S);
197 OS << "\n";
198 }
199 }
200}
201
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +0000202void DWARFContext::dump(raw_ostream &OS, DIDumpOptions DumpOpts) {
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000203 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000204 bool DumpEH = DumpOpts.DumpEH;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000205
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000206 if (DumpType & DIDT_DebugAbbrev) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000207 OS << ".debug_abbrev contents:\n";
208 getDebugAbbrev()->dump(OS);
209 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000210
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000211 if (DumpType & DIDT_DebugAbbrevDwo)
David Blaikie66865d62014-01-09 00:13:35 +0000212 if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
David Blaikie622dce42014-01-08 23:29:59 +0000213 OS << "\n.debug_abbrev.dwo contents:\n";
David Blaikie66865d62014-01-09 00:13:35 +0000214 D->dump(OS);
David Blaikie622dce42014-01-08 23:29:59 +0000215 }
David Blaikie622dce42014-01-08 23:29:59 +0000216
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000217 if (DumpType & DIDT_DebugInfo) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000218 OS << "\n.debug_info contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000219 for (const auto &CU : compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000220 CU->dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000221 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000222
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000223 if ((DumpType & DIDT_DebugInfoDwo) &&
David Blaikie66865d62014-01-09 00:13:35 +0000224 getNumDWOCompileUnits()) {
225 OS << "\n.debug_info.dwo contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000226 for (const auto &DWOCU : dwo_compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000227 DWOCU->dump(OS, DumpOpts);
David Blaikie66865d62014-01-09 00:13:35 +0000228 }
David Blaikie622dce42014-01-08 23:29:59 +0000229
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000230 if ((DumpType & DIDT_DebugTypes) && getNumTypeUnits()) {
David Blaikie03c089c2013-09-23 22:44:47 +0000231 OS << "\n.debug_types contents:\n";
Frederic Riss312a02e2014-09-29 13:56:39 +0000232 for (const auto &TUS : type_unit_sections())
233 for (const auto &TU : TUS)
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000234 TU->dump(OS, DumpOpts);
David Blaikie03c089c2013-09-23 22:44:47 +0000235 }
236
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000237 if ((DumpType & DIDT_DebugTypesDwo) &&
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000238 getNumDWOTypeUnits()) {
239 OS << "\n.debug_types.dwo contents:\n";
Frederic Riss312a02e2014-09-29 13:56:39 +0000240 for (const auto &DWOTUS : dwo_type_unit_sections())
241 for (const auto &DWOTU : DWOTUS)
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000242 DWOTU->dump(OS, DumpOpts);
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000243 }
David Blaikie92d9d622014-01-09 05:08:24 +0000244
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000245 if (DumpType & DIDT_DebugLoc) {
David Blaikie03c089c2013-09-23 22:44:47 +0000246 OS << "\n.debug_loc contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000247 getDebugLoc()->dump(OS, getRegisterInfo());
David Blaikie18e73502013-06-19 21:37:13 +0000248 }
249
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000250 if (DumpType & DIDT_DebugLocDwo) {
David Blaikie9c550ac2014-03-25 01:44:02 +0000251 OS << "\n.debug_loc.dwo contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000252 getDebugLocDWO()->dump(OS, getRegisterInfo());
David Blaikie9c550ac2014-03-25 01:44:02 +0000253 }
254
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000255 if (DumpType & DIDT_DebugFrames) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000256 OS << "\n.debug_frame contents:\n";
257 getDebugFrame()->dump(OS);
Igor Laevsky03a670c2016-01-26 15:09:42 +0000258 if (DumpEH) {
259 OS << "\n.eh_frame contents:\n";
260 getEHFrame()->dump(OS);
261 }
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000262 }
263
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000264 if (DumpType & DIDT_DebugMacro) {
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000265 OS << "\n.debug_macinfo contents:\n";
266 getDebugMacro()->dump(OS);
267 }
268
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000269 uint32_t offset = 0;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000270 if (DumpType & DIDT_DebugAranges) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000271 OS << "\n.debug_aranges contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000272 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000273 DWARFDebugArangeSet set;
274 while (set.extract(arangesData, &offset))
275 set.dump(OS);
276 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000277
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000278 uint8_t savedAddressByteSize = 0;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000279 if (DumpType & DIDT_DebugLine) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000280 OS << "\n.debug_line contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000281 for (const auto &CU : compile_units()) {
282 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000283 auto CUDIE = CU->getUnitDIE();
284 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000285 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000286 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000287 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
288 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000289 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000290 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000291 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000292 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000293 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000294 }
295 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000296
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000297 if (DumpType & DIDT_DebugCUIndex) {
David Blaikie65a8efe2015-11-11 19:28:21 +0000298 OS << "\n.debug_cu_index contents:\n";
David Blaikieb073cb92015-12-02 06:21:34 +0000299 getCUIndex().dump(OS);
David Blaikie65a8efe2015-11-11 19:28:21 +0000300 }
301
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000302 if (DumpType & DIDT_DebugTUIndex) {
David Blaikie51c40282015-11-11 19:40:49 +0000303 OS << "\n.debug_tu_index contents:\n";
David Blaikieb073cb92015-12-02 06:21:34 +0000304 getTUIndex().dump(OS);
David Blaikie51c40282015-11-11 19:40:49 +0000305 }
306
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000307 if (DumpType & DIDT_DebugLineDwo) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000308 OS << "\n.debug_line.dwo contents:\n";
309 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000310 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
311 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000312 DWARFDebugLine::LineTable LineTable;
313 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
314 LineTable.dump(OS);
315 LineTable.clear();
316 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000317 }
318
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000319 if (DumpType & DIDT_DebugStr) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000320 OS << "\n.debug_str contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000321 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000322 offset = 0;
323 uint32_t strOffset = 0;
324 while (const char *s = strData.getCStr(&offset)) {
325 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
326 strOffset = offset;
327 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000328 }
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000329
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000330 if ((DumpType & DIDT_DebugStrDwo) &&
Rafael Espindolac398e672017-07-19 22:27:28 +0000331 !DObj->getStringDWOSection().empty()) {
David Blaikie66865d62014-01-09 00:13:35 +0000332 OS << "\n.debug_str.dwo contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000333 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
David Blaikie66865d62014-01-09 00:13:35 +0000334 offset = 0;
335 uint32_t strDWOOffset = 0;
336 while (const char *s = strDWOData.getCStr(&offset)) {
337 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
338 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000339 }
David Blaikie66865d62014-01-09 00:13:35 +0000340 }
David Blaikie622dce42014-01-08 23:29:59 +0000341
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000342 if (DumpType & DIDT_DebugRanges) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000343 OS << "\n.debug_ranges contents:\n";
344 // In fact, different compile units may have different address byte
345 // sizes, but for simplicity we just use the address byte size of the last
346 // compile unit (there is no easy and fast way to associate address range
347 // list and the compile unit it describes).
Rafael Espindolac398e672017-07-19 22:27:28 +0000348 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
349 isLittleEndian(), savedAddressByteSize);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000350 offset = 0;
351 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000352 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000353 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000354 }
Eric Christopher962c9082013-01-15 23:56:56 +0000355
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000356 if (DumpType & DIDT_DebugPubnames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000357 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000358 .dump("debug_pubnames", OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000359
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000360 if (DumpType & DIDT_DebugPubtypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000361 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000362 .dump("debug_pubtypes", OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000363
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000364 if (DumpType & DIDT_DebugGnuPubnames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000365 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000366 true /* GnuStyle */)
367 .dump("debug_gnu_pubnames", OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000368
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000369 if (DumpType & DIDT_DebugGnuPubtypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000370 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000371 true /* GnuStyle */)
372 .dump("debug_gnu_pubtypes", OS);
David Blaikie404d3042013-09-19 23:01:29 +0000373
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000374 if (DumpType & DIDT_DebugStrOffsets)
Rafael Espindolac398e672017-07-19 22:27:28 +0000375 dumpStringOffsetsSection(
376 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
377 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000378
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000379 if (DumpType & DIDT_DebugStrOffsetsDwo) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000380 dumpStringOffsetsSection(
381 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
382 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
David Blaikie66865d62014-01-09 00:13:35 +0000383 }
Frederic Risse837ec22014-11-14 16:15:53 +0000384
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000385 if ((DumpType & DIDT_GdbIndex) &&
Rafael Espindolac398e672017-07-19 22:27:28 +0000386 !DObj->getGdbIndexSection().empty()) {
George Rimar4f82df52016-09-23 11:01:53 +0000387 OS << "\n.gnu_index contents:\n";
388 getGdbIndex().dump(OS);
389 }
390
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000391 if (DumpType & DIDT_AppleNames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000392 dumpAccelSection(OS, "apple_names", *DObj, DObj->getAppleNamesSection(),
393 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000394
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000395 if (DumpType & DIDT_AppleTypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000396 dumpAccelSection(OS, "apple_types", *DObj, DObj->getAppleTypesSection(),
397 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000398
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000399 if (DumpType & DIDT_AppleNamespaces)
Rafael Espindolac398e672017-07-19 22:27:28 +0000400 dumpAccelSection(OS, "apple_namespaces", *DObj,
401 DObj->getAppleNamespacesSection(),
402 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000403
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000404 if (DumpType & DIDT_AppleObjC)
Rafael Espindolac398e672017-07-19 22:27:28 +0000405 dumpAccelSection(OS, "apple_objc", *DObj, DObj->getAppleObjCSection(),
406 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000407}
408
David Blaikie15d85fc2017-05-23 06:48:53 +0000409DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000410 parseDWOCompileUnits();
411
David Blaikieebac0b92017-07-30 08:12:07 +0000412 if (const auto &CUI = getCUIndex()) {
413 if (const auto *R = CUI.getFromHash(Hash))
414 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000415 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000416 return nullptr;
417 }
418
419 // If there's no index, just search through the CUs in the DWO - there's
420 // probably only one unless this is something like LTO - though an in-process
421 // built/cached lookup table could be used in that case to improve repeated
422 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000423 for (const auto &DWOCU : dwo_compile_units())
424 if (DWOCU->getDWOId() == Hash)
425 return DWOCU.get();
426 return nullptr;
427}
428
Greg Claytonc7695a82017-05-02 20:28:33 +0000429DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
430 parseCompileUnits();
431 if (auto *CU = CUs.getUnitForOffset(Offset))
432 return CU->getDIEForOffset(Offset);
433 return DWARFDie();
434}
435
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000436bool DWARFContext::verify(raw_ostream &OS, uint64_t DumpType,
437 DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000438 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000439 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000440
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000441 Success &= verifier.handleDebugAbbrev();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000442 if (DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000443 Success &= verifier.handleDebugInfo();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000444 if (DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000445 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000446 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000447 return Success;
448}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000449
David Blaikie82641be2015-11-17 00:39:55 +0000450const DWARFUnitIndex &DWARFContext::getCUIndex() {
451 if (CUIndex)
452 return *CUIndex;
453
Rafael Espindolac398e672017-07-19 22:27:28 +0000454 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000455
David Blaikieb073cb92015-12-02 06:21:34 +0000456 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000457 CUIndex->parse(CUIndexData);
458 return *CUIndex;
459}
460
461const DWARFUnitIndex &DWARFContext::getTUIndex() {
462 if (TUIndex)
463 return *TUIndex;
464
Rafael Espindolac398e672017-07-19 22:27:28 +0000465 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000466
David Blaikieb073cb92015-12-02 06:21:34 +0000467 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000468 TUIndex->parse(TUIndexData);
469 return *TUIndex;
470}
471
George Rimar4f82df52016-09-23 11:01:53 +0000472DWARFGdbIndex &DWARFContext::getGdbIndex() {
473 if (GdbIndex)
474 return *GdbIndex;
475
Rafael Espindolac398e672017-07-19 22:27:28 +0000476 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000477 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
478 GdbIndex->parse(GdbIndexData);
479 return *GdbIndex;
480}
481
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000482const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
483 if (Abbrev)
484 return Abbrev.get();
485
Rafael Espindolac398e672017-07-19 22:27:28 +0000486 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000487
488 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000489 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000490 return Abbrev.get();
491}
492
Eric Christopherda4b2192013-01-02 23:52:13 +0000493const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
494 if (AbbrevDWO)
495 return AbbrevDWO.get();
496
Rafael Espindolac398e672017-07-19 22:27:28 +0000497 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000498 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000499 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000500 return AbbrevDWO.get();
501}
502
David Blaikie18e73502013-06-19 21:37:13 +0000503const DWARFDebugLoc *DWARFContext::getDebugLoc() {
504 if (Loc)
505 return Loc.get();
506
Paul Robinson17536b92017-06-29 16:52:08 +0000507 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000508 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000509 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000510 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000511 getCompileUnitAtIndex(0)->getAddressByteSize());
512 Loc->parse(LocData);
513 }
David Blaikie18e73502013-06-19 21:37:13 +0000514 return Loc.get();
515}
516
David Blaikie9c550ac2014-03-25 01:44:02 +0000517const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
518 if (LocDWO)
519 return LocDWO.get();
520
Rafael Espindolac398e672017-07-19 22:27:28 +0000521 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000522 LocDWO.reset(new DWARFDebugLocDWO());
523 LocDWO->parse(LocData);
524 return LocDWO.get();
525}
526
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000527const DWARFDebugAranges *DWARFContext::getDebugAranges() {
528 if (Aranges)
529 return Aranges.get();
530
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000531 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000532 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000533 return Aranges.get();
534}
535
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000536const DWARFDebugFrame *DWARFContext::getDebugFrame() {
537 if (DebugFrame)
538 return DebugFrame.get();
539
540 // There's a "bug" in the DWARFv3 standard with respect to the target address
541 // size within debug frame sections. While DWARF is supposed to be independent
542 // of its container, FDEs have fields with size being "target address size",
543 // which isn't specified in DWARF in general. It's only specified for CUs, but
544 // .eh_frame can appear without a .debug_info section. Follow the example of
545 // other tools (libdwarf) and extract this from the container (ObjectFile
546 // provides this information). This problem is fixed in DWARFv4
547 // See this dwarf-discuss discussion for more details:
548 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000549 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
550 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000551 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
552 DebugFrame->parse(debugFrameData);
553 return DebugFrame.get();
554}
555
556const DWARFDebugFrame *DWARFContext::getEHFrame() {
557 if (EHFrame)
558 return EHFrame.get();
559
Rafael Espindolac398e672017-07-19 22:27:28 +0000560 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
561 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000562 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000563 DebugFrame->parse(debugFrameData);
564 return DebugFrame.get();
565}
566
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000567const DWARFDebugMacro *DWARFContext::getDebugMacro() {
568 if (Macro)
569 return Macro.get();
570
Rafael Espindolac398e672017-07-19 22:27:28 +0000571 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000572 Macro.reset(new DWARFDebugMacro());
573 Macro->parse(MacinfoData);
574 return Macro.get();
575}
576
Eric Christopher494109b2012-10-16 23:46:25 +0000577const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000578DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000579 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000580 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000581
Greg Claytonc8c10322016-12-13 18:25:19 +0000582 auto UnitDIE = U->getUnitDIE();
583 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000584 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000585
Greg Clayton97d22182017-01-13 21:08:18 +0000586 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000587 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000588 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000589
Greg Clayton52fe1f62016-12-14 22:38:08 +0000590 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000591 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000592 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000593 return lt;
594
Greg Clayton48ff66a2017-05-04 18:29:44 +0000595 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000596 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000597 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000598
Benjamin Kramer679e1752011-09-15 20:43:18 +0000599 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000600 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000601 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000602 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000603}
604
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000605void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000606 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000607}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000608
David Blaikie03c089c2013-09-23 22:44:47 +0000609void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000610 if (!TUs.empty())
611 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000612 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000613 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000614 TUs.back().parse(*this, S);
615 });
David Blaikie03c089c2013-09-23 22:44:47 +0000616}
617
Eric Christopherda4b2192013-01-02 23:52:13 +0000618void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000619 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000620}
621
David Blaikie92d9d622014-01-09 05:08:24 +0000622void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000623 if (!DWOTUs.empty())
624 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000625 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000626 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000627 DWOTUs.back().parseDWO(*this, S);
628 });
David Blaikie92d9d622014-01-09 05:08:24 +0000629}
630
Alexey Samsonov45be7932012-08-30 07:49:50 +0000631DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000632 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000633 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000634}
635
Alexey Samsonov45be7932012-08-30 07:49:50 +0000636DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000637 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000638 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000639 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000640 return getCompileUnitForOffset(CUOffset);
641}
642
David Blaikieefc4eba2017-02-06 20:19:02 +0000643static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
644 uint64_t Address,
645 FunctionNameKind Kind,
646 std::string &FunctionName,
647 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000648 // The address may correspond to instruction in some inlined function,
649 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000650 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000651 SmallVector<DWARFDie, 4> InlinedChain;
652 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000653 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000654 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000655
656 const DWARFDie &DIE = InlinedChain[0];
657 bool FoundResult = false;
658 const char *Name = nullptr;
659 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000660 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000661 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000662 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000663 if (auto DeclLineResult = DIE.getDeclLine()) {
664 StartLine = DeclLineResult;
665 FoundResult = true;
666 }
667
668 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000669}
670
Alexey Samsonov45be7932012-08-30 07:49:50 +0000671DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000672 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000673 DILineInfo Result;
674
Alexey Samsonov45be7932012-08-30 07:49:50 +0000675 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
676 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000677 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000678 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
679 Result.FunctionName,
680 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000681 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000682 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
683 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
684 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000685 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000686 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000687}
David Blaikiea379b1812011-12-20 02:50:00 +0000688
Alexey Samsonovdce67342014-05-15 21:24:32 +0000689DILineInfoTable
690DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
691 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000692 DILineInfoTable Lines;
693 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
694 if (!CU)
695 return Lines;
696
697 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000698 uint32_t StartLine = 0;
699 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
700 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000701
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000702 // If the Specifier says we don't need FileLineInfo, just
703 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000704 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000705 DILineInfo Result;
706 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000707 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000708 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000709 return Lines;
710 }
711
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000712 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000713
714 // Get the index of row we're looking for in the line table.
715 std::vector<uint32_t> RowVector;
716 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
717 return Lines;
718
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000719 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000720 // Take file number and line/column from the row.
721 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000722 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000723 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
724 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000725 Result.FunctionName = FunctionName;
726 Result.Line = Row.Line;
727 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000728 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000729 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000730 }
731
732 return Lines;
733}
734
Alexey Samsonovdce67342014-05-15 21:24:32 +0000735DIInliningInfo
736DWARFContext::getInliningInfoForAddress(uint64_t Address,
737 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000738 DIInliningInfo InliningInfo;
739
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000740 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
741 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000742 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000743
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000744 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000745 SmallVector<DWARFDie, 4> InlinedChain;
746 CU->getInlinedChainForAddress(Address, InlinedChain);
747 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000748 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
749 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000750 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000751 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000752 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000753 if (LineTable &&
754 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
755 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000756 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000757 }
758 return InliningInfo;
759 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000760
Dehao Chenef700d52017-04-17 20:10:39 +0000761 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000762 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
763 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000764 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000765 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000766 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000767 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000768 if (auto DeclLineResult = FunctionDIE.getDeclLine())
769 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000770 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000771 if (i == 0) {
772 // For the topmost frame, initialize the line table of this
773 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000774 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000775 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000776 if (LineTable)
777 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
778 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000779 } else {
780 // Otherwise, use call file, call line and call column from
781 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000782 if (LineTable)
783 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
784 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000785 Frame.Line = CallLine;
786 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000787 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000788 }
789 // Get call file/line/column of a current DIE.
790 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000791 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
792 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000793 }
794 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000795 InliningInfo.addFrame(Frame);
796 }
797 return InliningInfo;
798}
799
David Blaikief9803fb2017-05-23 00:30:42 +0000800std::shared_ptr<DWARFContext>
801DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000802 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000803 DWARFContext *Ctxt = S->Context.get();
804 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
805 }
806
David Blaikie15d85fc2017-05-23 06:48:53 +0000807 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
808
809 if (auto S = Entry->lock()) {
810 DWARFContext *Ctxt = S->Context.get();
811 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
812 }
813
David Blaikie15d85fc2017-05-23 06:48:53 +0000814 Expected<OwningBinary<ObjectFile>> Obj = [&] {
815 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000816 SmallString<128> DWPName;
817 auto Obj = object::ObjectFile::createObjectFile(
818 this->DWPName.empty()
819 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
820 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000821 if (Obj) {
822 Entry = &DWP;
823 return Obj;
824 } else {
825 CheckedForDWP = true;
826 // TODO: Should this error be handled (maybe in a high verbosity mode)
827 // before falling back to .dwo files?
828 consumeError(Obj.takeError());
829 }
830 }
831
832 return object::ObjectFile::createObjectFile(AbsolutePath);
833 }();
834
David Blaikief9803fb2017-05-23 00:30:42 +0000835 if (!Obj) {
836 // TODO: Actually report errors helpfully.
837 consumeError(Obj.takeError());
838 return nullptr;
839 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000840
841 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000842 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000843 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000844 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000845 auto *Ctxt = S->Context.get();
846 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
847}
848
George Rimar702dac62017-04-12 08:59:15 +0000849static Error createError(const Twine &Reason, llvm::Error E) {
850 return make_error<StringError>(Reason + toString(std::move(E)),
851 inconvertibleErrorCode());
852}
853
George Rimara25d3292017-05-27 18:10:23 +0000854/// SymInfo contains information about symbol: it's address
855/// and section index which is -1LL for absolute symbols.
856struct SymInfo {
857 uint64_t Address;
858 uint64_t SectionIndex;
859};
860
861/// Returns the address of symbol relocation used against and a section index.
862/// Used for futher relocations computation. Symbol's section load address is
863static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
864 const RelocationRef &Reloc,
865 const LoadedObjectInfo *L,
866 std::map<SymbolRef, SymInfo> &Cache) {
867 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000868 object::section_iterator RSec = Obj.section_end();
869 object::symbol_iterator Sym = Reloc.getSymbol();
870
George Rimara25d3292017-05-27 18:10:23 +0000871 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000872 // First calculate the address of the symbol or section as it appears
873 // in the object file
874 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000875 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000876 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000877 if (!New)
878 return CacheIt->second;
879
George Rimar702dac62017-04-12 08:59:15 +0000880 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
881 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000882 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000883 SymAddrOrErr.takeError());
884
885 // Also remember what section this symbol is in for later
886 auto SectOrErr = Sym->getSection();
887 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000888 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000889 SectOrErr.takeError());
890
891 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000892 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000893 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
894 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000895 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000896 }
897
George Rimara25d3292017-05-27 18:10:23 +0000898 if (RSec != Obj.section_end())
899 Ret.SectionIndex = RSec->getIndex();
900
George Rimar702dac62017-04-12 08:59:15 +0000901 // If we are given load addresses for the sections, we need to adjust:
902 // SymAddr = (Address of Symbol Or Section in File) -
903 // (Address of Section in File) +
904 // (Load Address of Section)
905 // RSec is now either the section being targeted or the section
906 // containing the symbol being targeted. In either case,
907 // we need to perform the same computation.
908 if (L && RSec != Obj.section_end())
909 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000910 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000911
912 if (CacheIt != Cache.end())
913 CacheIt->second = Ret;
914
George Rimar702dac62017-04-12 08:59:15 +0000915 return Ret;
916}
917
918static bool isRelocScattered(const object::ObjectFile &Obj,
919 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000920 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
921 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000922 return false;
923 // MachO also has relocations that point to sections and
924 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000925 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
926 return MachObj->isRelocationScattered(RelocInfo);
927}
928
Rafael Espindolac398e672017-07-19 22:27:28 +0000929ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000930 errs() << "error: " + toString(std::move(E)) << '\n';
931 return ErrorPolicy::Continue;
932}
933
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000934namespace {
935struct DWARFSectionMap final : public DWARFSection {
936 RelocAddrMap Relocs;
937};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000938
Rafael Espindolac398e672017-07-19 22:27:28 +0000939class DWARFObjInMemory final : public DWARFObject {
940 bool IsLittleEndian;
941 uint8_t AddressSize;
942 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +0000943 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +0000944 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000945
Rafael Espindolac398e672017-07-19 22:27:28 +0000946 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
947 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +0000948
Rafael Espindolac398e672017-07-19 22:27:28 +0000949 TypeSectionMap TypesSections;
950 TypeSectionMap TypesDWOSections;
951
952 DWARFSectionMap InfoSection;
953 DWARFSectionMap LocSection;
954 DWARFSectionMap LineSection;
955 DWARFSectionMap RangeSection;
956 DWARFSectionMap StringOffsetSection;
957 DWARFSectionMap InfoDWOSection;
958 DWARFSectionMap LineDWOSection;
959 DWARFSectionMap LocDWOSection;
960 DWARFSectionMap StringOffsetDWOSection;
961 DWARFSectionMap RangeDWOSection;
962 DWARFSectionMap AddrSection;
963 DWARFSectionMap AppleNamesSection;
964 DWARFSectionMap AppleTypesSection;
965 DWARFSectionMap AppleNamespacesSection;
966 DWARFSectionMap AppleObjCSection;
967
968 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
969 return StringSwitch<DWARFSectionMap *>(Name)
970 .Case("debug_info", &InfoSection)
971 .Case("debug_loc", &LocSection)
972 .Case("debug_line", &LineSection)
973 .Case("debug_str_offsets", &StringOffsetSection)
974 .Case("debug_ranges", &RangeSection)
975 .Case("debug_info.dwo", &InfoDWOSection)
976 .Case("debug_loc.dwo", &LocDWOSection)
977 .Case("debug_line.dwo", &LineDWOSection)
978 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
979 .Case("debug_addr", &AddrSection)
980 .Case("apple_names", &AppleNamesSection)
981 .Case("apple_types", &AppleTypesSection)
982 .Case("apple_namespaces", &AppleNamespacesSection)
983 .Case("apple_namespac", &AppleNamespacesSection)
984 .Case("apple_objc", &AppleObjCSection)
985 .Default(nullptr);
986 }
987
988 StringRef AbbrevSection;
989 StringRef ARangeSection;
990 StringRef DebugFrameSection;
991 StringRef EHFrameSection;
992 StringRef StringSection;
993 StringRef MacinfoSection;
994 StringRef PubNamesSection;
995 StringRef PubTypesSection;
996 StringRef GnuPubNamesSection;
997 StringRef AbbrevDWOSection;
998 StringRef StringDWOSection;
999 StringRef GnuPubTypesSection;
1000 StringRef CUIndexSection;
1001 StringRef GdbIndexSection;
1002 StringRef TUIndexSection;
1003
1004 SmallVector<SmallString<32>, 4> UncompressedSections;
1005
1006 StringRef *mapSectionToMember(StringRef Name) {
1007 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1008 return &Sec->Data;
1009 return StringSwitch<StringRef *>(Name)
1010 .Case("debug_abbrev", &AbbrevSection)
1011 .Case("debug_aranges", &ARangeSection)
1012 .Case("debug_frame", &DebugFrameSection)
1013 .Case("eh_frame", &EHFrameSection)
1014 .Case("debug_str", &StringSection)
1015 .Case("debug_macinfo", &MacinfoSection)
1016 .Case("debug_pubnames", &PubNamesSection)
1017 .Case("debug_pubtypes", &PubTypesSection)
1018 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1019 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1020 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1021 .Case("debug_str.dwo", &StringDWOSection)
1022 .Case("debug_cu_index", &CUIndexSection)
1023 .Case("debug_tu_index", &TUIndexSection)
1024 .Case("gdb_index", &GdbIndexSection)
1025 // Any more debug info sections go here.
1026 .Default(nullptr);
1027 }
1028
1029 /// If Sec is compressed section, decompresses and updates its contents
1030 /// provided by Data. Otherwise leaves it unchanged.
1031 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1032 StringRef &Data) {
1033 if (!Decompressor::isCompressed(Sec))
1034 return Error::success();
1035
1036 Expected<Decompressor> Decompressor =
1037 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1038 if (!Decompressor)
1039 return Decompressor.takeError();
1040
1041 SmallString<32> Out;
1042 if (auto Err = Decompressor->resizeAndDecompress(Out))
1043 return Err;
1044
1045 UncompressedSections.emplace_back(std::move(Out));
1046 Data = UncompressedSections.back();
1047
1048 return Error::success();
1049 }
1050
1051public:
1052 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1053 uint8_t AddrSize, bool IsLittleEndian)
1054 : IsLittleEndian(IsLittleEndian) {
1055 for (const auto &SecIt : Sections) {
1056 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1057 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001058 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001059 }
1060 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1061 function_ref<ErrorPolicy(Error)> HandleError)
1062 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001063 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1064 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001065
George Rimare1c30f72017-08-15 15:54:43 +00001066 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001067 for (const SectionRef &Section : Obj.sections()) {
1068 StringRef Name;
1069 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001070 ++SectionAmountMap[Name];
1071 SectionNames.push_back({ Name, true });
1072
Rafael Espindolac398e672017-07-19 22:27:28 +00001073 // Skip BSS and Virtual sections, they aren't interesting.
1074 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001075 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001076
Rafael Espindolac398e672017-07-19 22:27:28 +00001077 StringRef Data;
1078 section_iterator RelocatedSection = Section.getRelocatedSection();
1079 // Try to obtain an already relocated version of this section.
1080 // Else use the unrelocated section from the object file. We'll have to
1081 // apply relocations ourselves later.
1082 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1083 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001084
Rafael Espindolac398e672017-07-19 22:27:28 +00001085 if (auto Err = maybeDecompress(Section, Name, Data)) {
1086 ErrorPolicy EP = HandleError(createError(
1087 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001088 if (EP == ErrorPolicy::Halt)
1089 return;
George Rimarfed9f092017-05-17 12:10:51 +00001090 continue;
1091 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001092
1093 // Compressed sections names in GNU style starts from ".z",
1094 // at this point section is decompressed and we drop compression prefix.
1095 Name = Name.substr(
1096 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1097
1098 // Map platform specific debug section names to DWARF standard section
1099 // names.
1100 Name = Obj.mapDebugSectionName(Name);
1101
1102 if (StringRef *SectionData = mapSectionToMember(Name)) {
1103 *SectionData = Data;
1104 if (Name == "debug_ranges") {
1105 // FIXME: Use the other dwo range section when we emit it.
1106 RangeDWOSection.Data = Data;
1107 }
1108 } else if (Name == "debug_types") {
1109 // Find debug_types data by section rather than name as there are
1110 // multiple, comdat grouped, debug_types sections.
1111 TypesSections[Section].Data = Data;
1112 } else if (Name == "debug_types.dwo") {
1113 TypesDWOSections[Section].Data = Data;
1114 }
1115
1116 if (RelocatedSection == Obj.section_end())
1117 continue;
1118
1119 StringRef RelSecName;
1120 StringRef RelSecData;
1121 RelocatedSection->getName(RelSecName);
1122
1123 // If the section we're relocating was relocated already by the JIT,
1124 // then we used the relocated version above, so we do not need to process
1125 // relocations for it now.
1126 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1127 continue;
1128
1129 // In Mach-o files, the relocations do not need to be applied if
1130 // there is no load offset to apply. The value read at the
1131 // relocation point already factors in the section address
1132 // (actually applying the relocations will produce wrong results
1133 // as the section address will be added twice).
1134 if (!L && isa<MachOObjectFile>(&Obj))
1135 continue;
1136
1137 RelSecName = RelSecName.substr(
1138 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1139
1140 // TODO: Add support for relocations in other sections as needed.
1141 // Record relocations for the debug_info and debug_line sections.
1142 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1143 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1144 if (!Map) {
1145 // Find debug_types relocs by section rather than name as there are
1146 // multiple, comdat grouped, debug_types sections.
1147 if (RelSecName == "debug_types")
1148 Map =
1149 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1150 .Relocs;
1151 else if (RelSecName == "debug_types.dwo")
1152 Map = &static_cast<DWARFSectionMap &>(
1153 TypesDWOSections[*RelocatedSection])
1154 .Relocs;
1155 else
1156 continue;
1157 }
1158
1159 if (Section.relocation_begin() == Section.relocation_end())
1160 continue;
1161
1162 // Symbol to [address, section index] cache mapping.
1163 std::map<SymbolRef, SymInfo> AddrCache;
1164 for (const RelocationRef &Reloc : Section.relocations()) {
1165 // FIXME: it's not clear how to correctly handle scattered
1166 // relocations.
1167 if (isRelocScattered(Obj, Reloc))
1168 continue;
1169
1170 Expected<SymInfo> SymInfoOrErr =
1171 getSymbolInfo(Obj, Reloc, L, AddrCache);
1172 if (!SymInfoOrErr) {
1173 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1174 return;
1175 continue;
1176 }
1177
1178 object::RelocVisitor V(Obj);
1179 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1180 if (V.error()) {
1181 SmallString<32> Type;
1182 Reloc.getTypeName(Type);
1183 ErrorPolicy EP = HandleError(
1184 createError("failed to compute relocation: " + Type + ", ",
1185 errorCodeToError(object_error::parse_failed)));
1186 if (EP == ErrorPolicy::Halt)
1187 return;
1188 continue;
1189 }
1190 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1191 Map->insert({Reloc.getOffset(), Rel});
1192 }
Eric Christopher7370b552012-11-12 21:40:38 +00001193 }
George Rimare1c30f72017-08-15 15:54:43 +00001194
1195 for (SectionName &S : SectionNames)
1196 if (SectionAmountMap[S.Name] > 1)
1197 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001198 }
Eric Christopher7370b552012-11-12 21:40:38 +00001199
Rafael Espindolac398e672017-07-19 22:27:28 +00001200 Optional<RelocAddrEntry> find(const DWARFSection &S,
1201 uint64_t Pos) const override {
1202 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1203 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1204 if (AI == Sec.Relocs.end())
1205 return None;
1206 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001207 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001208
George Rimar6957ab52017-08-15 12:32:54 +00001209 const object::ObjectFile *getFile() const override { return Obj; }
1210
George Rimare1c30f72017-08-15 15:54:43 +00001211 ArrayRef<SectionName> getSectionNames() const override {
1212 return SectionNames;
1213 }
1214
Rafael Espindolac398e672017-07-19 22:27:28 +00001215 bool isLittleEndian() const override { return IsLittleEndian; }
1216 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1217 const DWARFSection &getLineDWOSection() const override {
1218 return LineDWOSection;
1219 }
1220 const DWARFSection &getLocDWOSection() const override {
1221 return LocDWOSection;
1222 }
1223 StringRef getStringDWOSection() const override { return StringDWOSection; }
1224 const DWARFSection &getStringOffsetDWOSection() const override {
1225 return StringOffsetDWOSection;
1226 }
1227 const DWARFSection &getRangeDWOSection() const override {
1228 return RangeDWOSection;
1229 }
1230 const DWARFSection &getAddrSection() const override { return AddrSection; }
1231 StringRef getCUIndexSection() const override { return CUIndexSection; }
1232 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1233 StringRef getTUIndexSection() const override { return TUIndexSection; }
1234
1235 // DWARF v5
1236 const DWARFSection &getStringOffsetSection() const override {
1237 return StringOffsetSection;
1238 }
1239
1240 // Sections for DWARF5 split dwarf proposal.
1241 const DWARFSection &getInfoDWOSection() const override {
1242 return InfoDWOSection;
1243 }
1244 void forEachTypesDWOSections(
1245 function_ref<void(const DWARFSection &)> F) const override {
1246 for (auto &P : TypesDWOSections)
1247 F(P.second);
1248 }
1249
1250 StringRef getAbbrevSection() const override { return AbbrevSection; }
1251 const DWARFSection &getLocSection() const override { return LocSection; }
1252 StringRef getARangeSection() const override { return ARangeSection; }
1253 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1254 StringRef getEHFrameSection() const override { return EHFrameSection; }
1255 const DWARFSection &getLineSection() const override { return LineSection; }
1256 StringRef getStringSection() const override { return StringSection; }
1257 const DWARFSection &getRangeSection() const override { return RangeSection; }
1258 StringRef getMacinfoSection() const override { return MacinfoSection; }
1259 StringRef getPubNamesSection() const override { return PubNamesSection; }
1260 StringRef getPubTypesSection() const override { return PubTypesSection; }
1261 StringRef getGnuPubNamesSection() const override {
1262 return GnuPubNamesSection;
1263 }
1264 StringRef getGnuPubTypesSection() const override {
1265 return GnuPubTypesSection;
1266 }
1267 const DWARFSection &getAppleNamesSection() const override {
1268 return AppleNamesSection;
1269 }
1270 const DWARFSection &getAppleTypesSection() const override {
1271 return AppleTypesSection;
1272 }
1273 const DWARFSection &getAppleNamespacesSection() const override {
1274 return AppleNamespacesSection;
1275 }
1276 const DWARFSection &getAppleObjCSection() const override {
1277 return AppleObjCSection;
1278 }
1279
1280 StringRef getFileName() const override { return FileName; }
1281 uint8_t getAddressSize() const override { return AddressSize; }
1282 const DWARFSection &getInfoSection() const override { return InfoSection; }
1283 void forEachTypesSections(
1284 function_ref<void(const DWARFSection &)> F) const override {
1285 for (auto &P : TypesSections)
1286 F(P.second);
1287 }
1288};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001289} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001290
1291std::unique_ptr<DWARFContext>
1292DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001293 function_ref<ErrorPolicy(Error)> HandleError,
1294 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001295 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001296 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001297}
1298
Rafael Espindolac398e672017-07-19 22:27:28 +00001299std::unique_ptr<DWARFContext>
1300DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1301 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001302 auto DObj =
1303 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001304 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001305}
Reid Klecknera0587362017-08-29 21:41:21 +00001306
1307Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1308 // Detect the architecture from the object file. We usually don't need OS
1309 // info to lookup a target and create register info.
1310 Triple TT;
1311 TT.setArch(Triple::ArchType(Obj.getArch()));
1312 TT.setVendor(Triple::UnknownVendor);
1313 TT.setOS(Triple::UnknownOS);
1314 std::string TargetLookupError;
1315 const Target *TheTarget =
1316 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1317 if (!TargetLookupError.empty())
1318 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1319 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1320 return Error::success();
1321}