blob: eaf26bfa295851e342545f8e83976e1f960cb9d4 [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"
George Rimar4bf30832017-01-11 15:26:41 +000034#include "llvm/Object/Decompressor.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000035#include "llvm/Object/MachO.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000036#include "llvm/Object/ObjectFile.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000037#include "llvm/Object/RelocVisitor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000038#include "llvm/Support/Casting.h"
39#include "llvm/Support/DataExtractor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000040#include "llvm/Support/Error.h"
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +000041#include "llvm/Support/Format.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000042#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramera6002fd2011-09-14 01:09:52 +000043#include "llvm/Support/raw_ostream.h"
Benjamin Kramer2602ca62011-09-15 20:43:22 +000044#include <algorithm>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000045#include <cstdint>
Greg Claytonc7695a82017-05-02 20:28:33 +000046#include <map>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000047#include <string>
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000048#include <tuple>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000049#include <utility>
50#include <vector>
51
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000052using namespace llvm;
Benjamin Kramer6dda0322011-09-15 18:02:20 +000053using namespace dwarf;
Rafael Espindola4f60a382013-05-30 03:05:14 +000054using namespace object;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000055
Chandler Carruthe96dd892014-04-21 22:55:11 +000056#define DEBUG_TYPE "dwarf"
57
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000058using DWARFLineTable = DWARFDebugLine::LineTable;
59using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
60using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
Eric Christopher494109b2012-10-16 23:46:25 +000061
Frederic Riss7c500472014-11-14 19:30:08 +000062static void dumpAccelSection(raw_ostream &OS, StringRef Name,
Rafael Espindolac398e672017-07-19 22:27:28 +000063 const DWARFObject &Obj,
64 const DWARFSection &Section,
65 StringRef StringSection, bool LittleEndian) {
66 DWARFDataExtractor AccelSection(Obj, Section, LittleEndian, 0);
Frederic Risse837ec22014-11-14 16:15:53 +000067 DataExtractor StrData(StringSection, LittleEndian, 0);
68 OS << "\n." << Name << " contents:\n";
Paul Robinson17536b92017-06-29 16:52:08 +000069 DWARFAcceleratorTable Accel(AccelSection, StrData);
Frederic Risse837ec22014-11-14 16:15:53 +000070 if (!Accel.extract())
71 return;
72 Accel.dump(OS);
73}
74
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000075static void
76dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +000077 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000078 const DWARFSection &StringOffsetsSection,
79 StringRef StringSection, bool LittleEndian) {
Rafael Espindolac398e672017-07-19 22:27:28 +000080 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +000081 uint32_t Offset = 0;
82 uint64_t SectionSize = StringOffsetsSection.Data.size();
83
84 while (Offset < SectionSize) {
85 unsigned Version = 0;
86 DwarfFormat Format = DWARF32;
87 unsigned EntrySize = 4;
88 // Perform validation and extract the segment size from the header.
89 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
90 OS << "error: invalid contribution to string offsets table in section ."
91 << SectionName << ".\n";
92 return;
93 }
94 uint32_t ContributionStart = Offset;
95 uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
96 // A contribution size of 0xffffffff indicates DWARF64, with the actual size
97 // in the following 8 bytes. Otherwise, the DWARF standard mandates that
98 // the contribution size must be at most 0xfffffff0.
99 if (ContributionSize == 0xffffffff) {
100 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
101 OS << "error: invalid contribution to string offsets table in section ."
102 << SectionName << ".\n";
103 return;
104 }
105 Format = DWARF64;
106 EntrySize = 8;
107 ContributionSize = StrOffsetExt.getU64(&Offset);
108 } else if (ContributionSize > 0xfffffff0) {
109 OS << "error: invalid contribution to string offsets table in section ."
110 << SectionName << ".\n";
111 return;
112 }
113
114 // We must ensure that we don't read a partial record at the end, so we
115 // validate for a multiple of EntrySize. Also, we're expecting a version
116 // number and padding, which adds an additional 4 bytes.
117 uint64_t ValidationSize =
118 4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
119 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
120 OS << "error: contribution to string offsets table in section ."
121 << SectionName << " has invalid length.\n";
122 return;
123 }
124
125 Version = StrOffsetExt.getU16(&Offset);
126 Offset += 2;
127 OS << format("0x%8.8x: ", ContributionStart);
128 OS << "Contribution size = " << ContributionSize
129 << ", Version = " << Version << "\n";
130
131 uint32_t ContributionBase = Offset;
132 DataExtractor StrData(StringSection, LittleEndian, 0);
133 while (Offset - ContributionBase < ContributionSize) {
134 OS << format("0x%8.8x: ", Offset);
135 // FIXME: We can only extract strings in DWARF32 format at the moment.
Paul Robinson17536b92017-06-29 16:52:08 +0000136 uint64_t StringOffset =
137 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000138 if (Format == DWARF32) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000139 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000140 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000141 const char *S = StrData.getCStr(&StringOffset32);
142 if (S)
143 OS << format("\"%s\"", S);
144 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000145 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000146 OS << "\n";
147 }
148 }
149}
150
151// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
152// string offsets section, where each compile or type unit contributes a
153// number of entries (string offsets), with each contribution preceded by
154// a header containing size and version number. Alternatively, it may be a
155// monolithic series of string offsets, as generated by the pre-DWARF v5
156// implementation of split DWARF.
157static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000158 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000159 const DWARFSection &StringOffsetsSection,
160 StringRef StringSection, bool LittleEndian,
161 unsigned MaxVersion) {
162 if (StringOffsetsSection.Data.empty())
163 return;
164 OS << "\n." << SectionName << " contents:\n";
165 // If we have at least one (compile or type) unit with DWARF v5 or greater,
166 // we assume that the section is formatted like a DWARF v5 string offsets
167 // section.
168 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000169 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000170 StringSection, LittleEndian);
171 else {
172 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
173 uint32_t offset = 0;
174 uint64_t size = StringOffsetsSection.Data.size();
175 // Ensure that size is a multiple of the size of an entry.
176 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
177 OS << "error: size of ." << SectionName << " is not a multiple of "
178 << sizeof(uint32_t) << ".\n";
179 size &= -(uint64_t)sizeof(uint32_t);
180 }
181 DataExtractor StrData(StringSection, LittleEndian, 0);
182 while (offset < size) {
183 OS << format("0x%8.8x: ", offset);
184 uint32_t StringOffset = strOffsetExt.getU32(&offset);
185 OS << format("%8.8x ", StringOffset);
186 const char *S = StrData.getCStr(&StringOffset);
187 if (S)
188 OS << format("\"%s\"", S);
189 OS << "\n";
190 }
191 }
192}
193
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +0000194void DWARFContext::dump(raw_ostream &OS, DIDumpOptions DumpOpts) {
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000195 DIDumpType DumpType = DumpOpts.DumpType;
196 bool DumpEH = DumpOpts.DumpEH;
197 bool SummarizeTypes = DumpOpts.SummarizeTypes;
198
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000199 if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
200 OS << ".debug_abbrev contents:\n";
201 getDebugAbbrev()->dump(OS);
202 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000203
David Blaikie66865d62014-01-09 00:13:35 +0000204 if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
205 if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
David Blaikie622dce42014-01-08 23:29:59 +0000206 OS << "\n.debug_abbrev.dwo contents:\n";
David Blaikie66865d62014-01-09 00:13:35 +0000207 D->dump(OS);
David Blaikie622dce42014-01-08 23:29:59 +0000208 }
David Blaikie622dce42014-01-08 23:29:59 +0000209
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000210 if (DumpType == DIDT_All || DumpType == DIDT_Info) {
211 OS << "\n.debug_info contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000212 for (const auto &CU : compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000213 CU->dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000214 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000215
David Blaikie66865d62014-01-09 00:13:35 +0000216 if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
217 getNumDWOCompileUnits()) {
218 OS << "\n.debug_info.dwo contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000219 for (const auto &DWOCU : dwo_compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000220 DWOCU->dump(OS, DumpOpts);
David Blaikie66865d62014-01-09 00:13:35 +0000221 }
David Blaikie622dce42014-01-08 23:29:59 +0000222
David Blaikie66865d62014-01-09 00:13:35 +0000223 if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
David Blaikie03c089c2013-09-23 22:44:47 +0000224 OS << "\n.debug_types contents:\n";
Frederic Riss312a02e2014-09-29 13:56:39 +0000225 for (const auto &TUS : type_unit_sections())
226 for (const auto &TU : TUS)
David Blaikie50cc27e2016-10-18 21:09:48 +0000227 TU->dump(OS, SummarizeTypes);
David Blaikie03c089c2013-09-23 22:44:47 +0000228 }
229
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000230 if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
231 getNumDWOTypeUnits()) {
232 OS << "\n.debug_types.dwo contents:\n";
Frederic Riss312a02e2014-09-29 13:56:39 +0000233 for (const auto &DWOTUS : dwo_type_unit_sections())
234 for (const auto &DWOTU : DWOTUS)
David Blaikie50cc27e2016-10-18 21:09:48 +0000235 DWOTU->dump(OS, SummarizeTypes);
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000236 }
David Blaikie92d9d622014-01-09 05:08:24 +0000237
David Blaikie18e73502013-06-19 21:37:13 +0000238 if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
David Blaikie03c089c2013-09-23 22:44:47 +0000239 OS << "\n.debug_loc contents:\n";
David Blaikie18e73502013-06-19 21:37:13 +0000240 getDebugLoc()->dump(OS);
241 }
242
David Blaikie9c550ac2014-03-25 01:44:02 +0000243 if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
244 OS << "\n.debug_loc.dwo contents:\n";
245 getDebugLocDWO()->dump(OS);
246 }
247
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000248 if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
249 OS << "\n.debug_frame contents:\n";
250 getDebugFrame()->dump(OS);
Igor Laevsky03a670c2016-01-26 15:09:42 +0000251 if (DumpEH) {
252 OS << "\n.eh_frame contents:\n";
253 getEHFrame()->dump(OS);
254 }
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000255 }
256
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000257 if (DumpType == DIDT_All || DumpType == DIDT_Macro) {
258 OS << "\n.debug_macinfo contents:\n";
259 getDebugMacro()->dump(OS);
260 }
261
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000262 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000263 if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
264 OS << "\n.debug_aranges contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000265 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000266 DWARFDebugArangeSet set;
267 while (set.extract(arangesData, &offset))
268 set.dump(OS);
269 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000270
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000271 uint8_t savedAddressByteSize = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000272 if (DumpType == DIDT_All || DumpType == DIDT_Line) {
273 OS << "\n.debug_line contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000274 for (const auto &CU : compile_units()) {
275 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000276 auto CUDIE = CU->getUnitDIE();
277 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000278 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000279 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000280 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
281 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000282 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000283 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000284 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000285 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000286 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000287 }
288 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000289
David Blaikie65a8efe2015-11-11 19:28:21 +0000290 if (DumpType == DIDT_All || DumpType == DIDT_CUIndex) {
291 OS << "\n.debug_cu_index contents:\n";
David Blaikieb073cb92015-12-02 06:21:34 +0000292 getCUIndex().dump(OS);
David Blaikie65a8efe2015-11-11 19:28:21 +0000293 }
294
David Blaikie51c40282015-11-11 19:40:49 +0000295 if (DumpType == DIDT_All || DumpType == DIDT_TUIndex) {
296 OS << "\n.debug_tu_index contents:\n";
David Blaikieb073cb92015-12-02 06:21:34 +0000297 getTUIndex().dump(OS);
David Blaikie51c40282015-11-11 19:40:49 +0000298 }
299
David Blaikie1d4736e2014-02-24 23:58:54 +0000300 if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
301 OS << "\n.debug_line.dwo contents:\n";
302 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000303 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
304 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000305 DWARFDebugLine::LineTable LineTable;
306 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
307 LineTable.dump(OS);
308 LineTable.clear();
309 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000310 }
311
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000312 if (DumpType == DIDT_All || DumpType == DIDT_Str) {
313 OS << "\n.debug_str contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000314 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000315 offset = 0;
316 uint32_t strOffset = 0;
317 while (const char *s = strData.getCStr(&offset)) {
318 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
319 strOffset = offset;
320 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000321 }
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000322
David Blaikie66865d62014-01-09 00:13:35 +0000323 if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
Rafael Espindolac398e672017-07-19 22:27:28 +0000324 !DObj->getStringDWOSection().empty()) {
David Blaikie66865d62014-01-09 00:13:35 +0000325 OS << "\n.debug_str.dwo contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000326 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
David Blaikie66865d62014-01-09 00:13:35 +0000327 offset = 0;
328 uint32_t strDWOOffset = 0;
329 while (const char *s = strDWOData.getCStr(&offset)) {
330 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
331 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000332 }
David Blaikie66865d62014-01-09 00:13:35 +0000333 }
David Blaikie622dce42014-01-08 23:29:59 +0000334
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000335 if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
336 OS << "\n.debug_ranges contents:\n";
337 // In fact, different compile units may have different address byte
338 // sizes, but for simplicity we just use the address byte size of the last
339 // compile unit (there is no easy and fast way to associate address range
340 // list and the compile unit it describes).
Rafael Espindolac398e672017-07-19 22:27:28 +0000341 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
342 isLittleEndian(), savedAddressByteSize);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000343 offset = 0;
344 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000345 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000346 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000347 }
Eric Christopher962c9082013-01-15 23:56:56 +0000348
Eric Christopher0de53592013-09-25 23:02:36 +0000349 if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000350 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000351 .dump("debug_pubnames", OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000352
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000353 if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000354 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000355 .dump("debug_pubtypes", OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000356
David Blaikieecd21ff2013-09-24 19:50:00 +0000357 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000358 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000359 true /* GnuStyle */)
360 .dump("debug_gnu_pubnames", OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000361
362 if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000363 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000364 true /* GnuStyle */)
365 .dump("debug_gnu_pubtypes", OS);
David Blaikie404d3042013-09-19 23:01:29 +0000366
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000367 if (DumpType == DIDT_All || DumpType == DIDT_StrOffsets)
Rafael Espindolac398e672017-07-19 22:27:28 +0000368 dumpStringOffsetsSection(
369 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
370 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000371
372 if (DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000373 dumpStringOffsetsSection(
374 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
375 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
David Blaikie66865d62014-01-09 00:13:35 +0000376 }
Frederic Risse837ec22014-11-14 16:15:53 +0000377
George Rimar4f82df52016-09-23 11:01:53 +0000378 if ((DumpType == DIDT_All || DumpType == DIDT_GdbIndex) &&
Rafael Espindolac398e672017-07-19 22:27:28 +0000379 !DObj->getGdbIndexSection().empty()) {
George Rimar4f82df52016-09-23 11:01:53 +0000380 OS << "\n.gnu_index contents:\n";
381 getGdbIndex().dump(OS);
382 }
383
Frederic Risse837ec22014-11-14 16:15:53 +0000384 if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
Rafael Espindolac398e672017-07-19 22:27:28 +0000385 dumpAccelSection(OS, "apple_names", *DObj, DObj->getAppleNamesSection(),
386 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000387
388 if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
Rafael Espindolac398e672017-07-19 22:27:28 +0000389 dumpAccelSection(OS, "apple_types", *DObj, DObj->getAppleTypesSection(),
390 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000391
392 if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
Rafael Espindolac398e672017-07-19 22:27:28 +0000393 dumpAccelSection(OS, "apple_namespaces", *DObj,
394 DObj->getAppleNamespacesSection(),
395 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000396
397 if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
Rafael Espindolac398e672017-07-19 22:27:28 +0000398 dumpAccelSection(OS, "apple_objc", *DObj, DObj->getAppleObjCSection(),
399 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000400}
401
David Blaikie15d85fc2017-05-23 06:48:53 +0000402DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000403 parseDWOCompileUnits();
404
David Blaikieebac0b92017-07-30 08:12:07 +0000405 if (const auto &CUI = getCUIndex()) {
406 if (const auto *R = CUI.getFromHash(Hash))
407 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000408 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000409 return nullptr;
410 }
411
412 // If there's no index, just search through the CUs in the DWO - there's
413 // probably only one unless this is something like LTO - though an in-process
414 // built/cached lookup table could be used in that case to improve repeated
415 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000416 for (const auto &DWOCU : dwo_compile_units())
417 if (DWOCU->getDWOId() == Hash)
418 return DWOCU.get();
419 return nullptr;
420}
421
Greg Claytonc7695a82017-05-02 20:28:33 +0000422DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
423 parseCompileUnits();
424 if (auto *CU = CUs.getUnitForOffset(Offset))
425 return CU->getDIEForOffset(Offset);
426 return DWARFDie();
427}
428
Greg Claytonc7695a82017-05-02 20:28:33 +0000429bool DWARFContext::verify(raw_ostream &OS, DIDumpType DumpType) {
430 bool Success = true;
Greg Claytonb8c162b2017-05-03 16:02:29 +0000431 DWARFVerifier verifier(OS, *this);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000432
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000433 Success &= verifier.handleDebugAbbrev();
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000434 if (DumpType == DIDT_All || DumpType == DIDT_Info)
435 Success &= verifier.handleDebugInfo();
436 if (DumpType == DIDT_All || DumpType == DIDT_Line)
437 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000438 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000439 return Success;
440}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000441
David Blaikie82641be2015-11-17 00:39:55 +0000442const DWARFUnitIndex &DWARFContext::getCUIndex() {
443 if (CUIndex)
444 return *CUIndex;
445
Rafael Espindolac398e672017-07-19 22:27:28 +0000446 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000447
David Blaikieb073cb92015-12-02 06:21:34 +0000448 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000449 CUIndex->parse(CUIndexData);
450 return *CUIndex;
451}
452
453const DWARFUnitIndex &DWARFContext::getTUIndex() {
454 if (TUIndex)
455 return *TUIndex;
456
Rafael Espindolac398e672017-07-19 22:27:28 +0000457 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000458
David Blaikieb073cb92015-12-02 06:21:34 +0000459 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000460 TUIndex->parse(TUIndexData);
461 return *TUIndex;
462}
463
George Rimar4f82df52016-09-23 11:01:53 +0000464DWARFGdbIndex &DWARFContext::getGdbIndex() {
465 if (GdbIndex)
466 return *GdbIndex;
467
Rafael Espindolac398e672017-07-19 22:27:28 +0000468 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000469 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
470 GdbIndex->parse(GdbIndexData);
471 return *GdbIndex;
472}
473
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000474const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
475 if (Abbrev)
476 return Abbrev.get();
477
Rafael Espindolac398e672017-07-19 22:27:28 +0000478 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000479
480 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000481 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000482 return Abbrev.get();
483}
484
Eric Christopherda4b2192013-01-02 23:52:13 +0000485const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
486 if (AbbrevDWO)
487 return AbbrevDWO.get();
488
Rafael Espindolac398e672017-07-19 22:27:28 +0000489 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000490 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000491 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000492 return AbbrevDWO.get();
493}
494
David Blaikie18e73502013-06-19 21:37:13 +0000495const DWARFDebugLoc *DWARFContext::getDebugLoc() {
496 if (Loc)
497 return Loc.get();
498
Paul Robinson17536b92017-06-29 16:52:08 +0000499 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000500 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000501 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000502 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000503 getCompileUnitAtIndex(0)->getAddressByteSize());
504 Loc->parse(LocData);
505 }
David Blaikie18e73502013-06-19 21:37:13 +0000506 return Loc.get();
507}
508
David Blaikie9c550ac2014-03-25 01:44:02 +0000509const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
510 if (LocDWO)
511 return LocDWO.get();
512
Rafael Espindolac398e672017-07-19 22:27:28 +0000513 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000514 LocDWO.reset(new DWARFDebugLocDWO());
515 LocDWO->parse(LocData);
516 return LocDWO.get();
517}
518
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000519const DWARFDebugAranges *DWARFContext::getDebugAranges() {
520 if (Aranges)
521 return Aranges.get();
522
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000523 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000524 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000525 return Aranges.get();
526}
527
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000528const DWARFDebugFrame *DWARFContext::getDebugFrame() {
529 if (DebugFrame)
530 return DebugFrame.get();
531
532 // There's a "bug" in the DWARFv3 standard with respect to the target address
533 // size within debug frame sections. While DWARF is supposed to be independent
534 // of its container, FDEs have fields with size being "target address size",
535 // which isn't specified in DWARF in general. It's only specified for CUs, but
536 // .eh_frame can appear without a .debug_info section. Follow the example of
537 // other tools (libdwarf) and extract this from the container (ObjectFile
538 // provides this information). This problem is fixed in DWARFv4
539 // See this dwarf-discuss discussion for more details:
540 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000541 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
542 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000543 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
544 DebugFrame->parse(debugFrameData);
545 return DebugFrame.get();
546}
547
548const DWARFDebugFrame *DWARFContext::getEHFrame() {
549 if (EHFrame)
550 return EHFrame.get();
551
Rafael Espindolac398e672017-07-19 22:27:28 +0000552 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
553 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000554 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000555 DebugFrame->parse(debugFrameData);
556 return DebugFrame.get();
557}
558
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000559const DWARFDebugMacro *DWARFContext::getDebugMacro() {
560 if (Macro)
561 return Macro.get();
562
Rafael Espindolac398e672017-07-19 22:27:28 +0000563 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000564 Macro.reset(new DWARFDebugMacro());
565 Macro->parse(MacinfoData);
566 return Macro.get();
567}
568
Eric Christopher494109b2012-10-16 23:46:25 +0000569const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000570DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000571 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000572 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000573
Greg Claytonc8c10322016-12-13 18:25:19 +0000574 auto UnitDIE = U->getUnitDIE();
575 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000576 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000577
Greg Clayton97d22182017-01-13 21:08:18 +0000578 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000579 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000580 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000581
Greg Clayton52fe1f62016-12-14 22:38:08 +0000582 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000583 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000584 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000585 return lt;
586
Greg Clayton48ff66a2017-05-04 18:29:44 +0000587 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000588 if (stmtOffset >= U->getLineSection().Data.size())
Greg Clayton48ff66a2017-05-04 18:29:44 +0000589 return nullptr;
590
Benjamin Kramer679e1752011-09-15 20:43:18 +0000591 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000592 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000593 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000594 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000595}
596
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000597void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000598 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000599}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000600
David Blaikie03c089c2013-09-23 22:44:47 +0000601void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000602 if (!TUs.empty())
603 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000604 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000605 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000606 TUs.back().parse(*this, S);
607 });
David Blaikie03c089c2013-09-23 22:44:47 +0000608}
609
Eric Christopherda4b2192013-01-02 23:52:13 +0000610void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000611 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000612}
613
David Blaikie92d9d622014-01-09 05:08:24 +0000614void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000615 if (!DWOTUs.empty())
616 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000617 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000618 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000619 DWOTUs.back().parseDWO(*this, S);
620 });
David Blaikie92d9d622014-01-09 05:08:24 +0000621}
622
Alexey Samsonov45be7932012-08-30 07:49:50 +0000623DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000624 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000625 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000626}
627
Alexey Samsonov45be7932012-08-30 07:49:50 +0000628DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000629 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000630 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000631 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000632 return getCompileUnitForOffset(CUOffset);
633}
634
David Blaikieefc4eba2017-02-06 20:19:02 +0000635static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
636 uint64_t Address,
637 FunctionNameKind Kind,
638 std::string &FunctionName,
639 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000640 // The address may correspond to instruction in some inlined function,
641 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000642 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000643 SmallVector<DWARFDie, 4> InlinedChain;
644 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000645 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000646 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000647
648 const DWARFDie &DIE = InlinedChain[0];
649 bool FoundResult = false;
650 const char *Name = nullptr;
651 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000652 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000653 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000654 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000655 if (auto DeclLineResult = DIE.getDeclLine()) {
656 StartLine = DeclLineResult;
657 FoundResult = true;
658 }
659
660 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000661}
662
Alexey Samsonov45be7932012-08-30 07:49:50 +0000663DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000664 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000665 DILineInfo Result;
666
Alexey Samsonov45be7932012-08-30 07:49:50 +0000667 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
668 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000669 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000670 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
671 Result.FunctionName,
672 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000673 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000674 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
675 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
676 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000677 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000678 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000679}
David Blaikiea379b1812011-12-20 02:50:00 +0000680
Alexey Samsonovdce67342014-05-15 21:24:32 +0000681DILineInfoTable
682DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
683 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000684 DILineInfoTable Lines;
685 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
686 if (!CU)
687 return Lines;
688
689 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000690 uint32_t StartLine = 0;
691 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
692 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000693
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000694 // If the Specifier says we don't need FileLineInfo, just
695 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000696 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000697 DILineInfo Result;
698 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000699 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000700 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000701 return Lines;
702 }
703
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000704 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000705
706 // Get the index of row we're looking for in the line table.
707 std::vector<uint32_t> RowVector;
708 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
709 return Lines;
710
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000711 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000712 // Take file number and line/column from the row.
713 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000714 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000715 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
716 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000717 Result.FunctionName = FunctionName;
718 Result.Line = Row.Line;
719 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000720 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000721 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000722 }
723
724 return Lines;
725}
726
Alexey Samsonovdce67342014-05-15 21:24:32 +0000727DIInliningInfo
728DWARFContext::getInliningInfoForAddress(uint64_t Address,
729 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000730 DIInliningInfo InliningInfo;
731
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000732 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
733 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000734 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000735
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000736 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000737 SmallVector<DWARFDie, 4> InlinedChain;
738 CU->getInlinedChainForAddress(Address, InlinedChain);
739 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000740 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
741 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000742 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000743 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000744 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000745 if (LineTable &&
746 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
747 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000748 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000749 }
750 return InliningInfo;
751 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000752
Dehao Chenef700d52017-04-17 20:10:39 +0000753 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000754 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
755 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000756 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000757 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000758 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000759 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000760 if (auto DeclLineResult = FunctionDIE.getDeclLine())
761 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000762 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000763 if (i == 0) {
764 // For the topmost frame, initialize the line table of this
765 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000766 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000767 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000768 if (LineTable)
769 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
770 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000771 } else {
772 // Otherwise, use call file, call line and call column from
773 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000774 if (LineTable)
775 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
776 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000777 Frame.Line = CallLine;
778 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000779 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000780 }
781 // Get call file/line/column of a current DIE.
782 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000783 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
784 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000785 }
786 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000787 InliningInfo.addFrame(Frame);
788 }
789 return InliningInfo;
790}
791
David Blaikief9803fb2017-05-23 00:30:42 +0000792std::shared_ptr<DWARFContext>
793DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000794 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000795 DWARFContext *Ctxt = S->Context.get();
796 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
797 }
798
David Blaikie15d85fc2017-05-23 06:48:53 +0000799 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
800
801 if (auto S = Entry->lock()) {
802 DWARFContext *Ctxt = S->Context.get();
803 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
804 }
805
David Blaikie15d85fc2017-05-23 06:48:53 +0000806 Expected<OwningBinary<ObjectFile>> Obj = [&] {
807 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000808 SmallString<128> DWPName;
809 auto Obj = object::ObjectFile::createObjectFile(
810 this->DWPName.empty()
811 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
812 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000813 if (Obj) {
814 Entry = &DWP;
815 return Obj;
816 } else {
817 CheckedForDWP = true;
818 // TODO: Should this error be handled (maybe in a high verbosity mode)
819 // before falling back to .dwo files?
820 consumeError(Obj.takeError());
821 }
822 }
823
824 return object::ObjectFile::createObjectFile(AbsolutePath);
825 }();
826
David Blaikief9803fb2017-05-23 00:30:42 +0000827 if (!Obj) {
828 // TODO: Actually report errors helpfully.
829 consumeError(Obj.takeError());
830 return nullptr;
831 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000832
833 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000834 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000835 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000836 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000837 auto *Ctxt = S->Context.get();
838 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
839}
840
George Rimar702dac62017-04-12 08:59:15 +0000841static Error createError(const Twine &Reason, llvm::Error E) {
842 return make_error<StringError>(Reason + toString(std::move(E)),
843 inconvertibleErrorCode());
844}
845
George Rimara25d3292017-05-27 18:10:23 +0000846/// SymInfo contains information about symbol: it's address
847/// and section index which is -1LL for absolute symbols.
848struct SymInfo {
849 uint64_t Address;
850 uint64_t SectionIndex;
851};
852
853/// Returns the address of symbol relocation used against and a section index.
854/// Used for futher relocations computation. Symbol's section load address is
855static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
856 const RelocationRef &Reloc,
857 const LoadedObjectInfo *L,
858 std::map<SymbolRef, SymInfo> &Cache) {
859 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000860 object::section_iterator RSec = Obj.section_end();
861 object::symbol_iterator Sym = Reloc.getSymbol();
862
George Rimara25d3292017-05-27 18:10:23 +0000863 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000864 // First calculate the address of the symbol or section as it appears
865 // in the object file
866 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000867 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000868 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000869 if (!New)
870 return CacheIt->second;
871
George Rimar702dac62017-04-12 08:59:15 +0000872 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
873 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000874 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000875 SymAddrOrErr.takeError());
876
877 // Also remember what section this symbol is in for later
878 auto SectOrErr = Sym->getSection();
879 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000880 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000881 SectOrErr.takeError());
882
883 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000884 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000885 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
886 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000887 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000888 }
889
George Rimara25d3292017-05-27 18:10:23 +0000890 if (RSec != Obj.section_end())
891 Ret.SectionIndex = RSec->getIndex();
892
George Rimar702dac62017-04-12 08:59:15 +0000893 // If we are given load addresses for the sections, we need to adjust:
894 // SymAddr = (Address of Symbol Or Section in File) -
895 // (Address of Section in File) +
896 // (Load Address of Section)
897 // RSec is now either the section being targeted or the section
898 // containing the symbol being targeted. In either case,
899 // we need to perform the same computation.
900 if (L && RSec != Obj.section_end())
901 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000902 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000903
904 if (CacheIt != Cache.end())
905 CacheIt->second = Ret;
906
George Rimar702dac62017-04-12 08:59:15 +0000907 return Ret;
908}
909
910static bool isRelocScattered(const object::ObjectFile &Obj,
911 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000912 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
913 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000914 return false;
915 // MachO also has relocations that point to sections and
916 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000917 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
918 return MachObj->isRelocationScattered(RelocInfo);
919}
920
Rafael Espindolac398e672017-07-19 22:27:28 +0000921ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000922 errs() << "error: " + toString(std::move(E)) << '\n';
923 return ErrorPolicy::Continue;
924}
925
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000926namespace {
927struct DWARFSectionMap final : public DWARFSection {
928 RelocAddrMap Relocs;
929};
930} // namespace
931
Rafael Espindolac398e672017-07-19 22:27:28 +0000932class DWARFObjInMemory final : public DWARFObject {
933 bool IsLittleEndian;
934 uint8_t AddressSize;
935 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +0000936 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +0000937 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000938
Rafael Espindolac398e672017-07-19 22:27:28 +0000939 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
940 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +0000941
Rafael Espindolac398e672017-07-19 22:27:28 +0000942 TypeSectionMap TypesSections;
943 TypeSectionMap TypesDWOSections;
944
945 DWARFSectionMap InfoSection;
946 DWARFSectionMap LocSection;
947 DWARFSectionMap LineSection;
948 DWARFSectionMap RangeSection;
949 DWARFSectionMap StringOffsetSection;
950 DWARFSectionMap InfoDWOSection;
951 DWARFSectionMap LineDWOSection;
952 DWARFSectionMap LocDWOSection;
953 DWARFSectionMap StringOffsetDWOSection;
954 DWARFSectionMap RangeDWOSection;
955 DWARFSectionMap AddrSection;
956 DWARFSectionMap AppleNamesSection;
957 DWARFSectionMap AppleTypesSection;
958 DWARFSectionMap AppleNamespacesSection;
959 DWARFSectionMap AppleObjCSection;
960
961 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
962 return StringSwitch<DWARFSectionMap *>(Name)
963 .Case("debug_info", &InfoSection)
964 .Case("debug_loc", &LocSection)
965 .Case("debug_line", &LineSection)
966 .Case("debug_str_offsets", &StringOffsetSection)
967 .Case("debug_ranges", &RangeSection)
968 .Case("debug_info.dwo", &InfoDWOSection)
969 .Case("debug_loc.dwo", &LocDWOSection)
970 .Case("debug_line.dwo", &LineDWOSection)
971 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
972 .Case("debug_addr", &AddrSection)
973 .Case("apple_names", &AppleNamesSection)
974 .Case("apple_types", &AppleTypesSection)
975 .Case("apple_namespaces", &AppleNamespacesSection)
976 .Case("apple_namespac", &AppleNamespacesSection)
977 .Case("apple_objc", &AppleObjCSection)
978 .Default(nullptr);
979 }
980
981 StringRef AbbrevSection;
982 StringRef ARangeSection;
983 StringRef DebugFrameSection;
984 StringRef EHFrameSection;
985 StringRef StringSection;
986 StringRef MacinfoSection;
987 StringRef PubNamesSection;
988 StringRef PubTypesSection;
989 StringRef GnuPubNamesSection;
990 StringRef AbbrevDWOSection;
991 StringRef StringDWOSection;
992 StringRef GnuPubTypesSection;
993 StringRef CUIndexSection;
994 StringRef GdbIndexSection;
995 StringRef TUIndexSection;
996
997 SmallVector<SmallString<32>, 4> UncompressedSections;
998
999 StringRef *mapSectionToMember(StringRef Name) {
1000 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1001 return &Sec->Data;
1002 return StringSwitch<StringRef *>(Name)
1003 .Case("debug_abbrev", &AbbrevSection)
1004 .Case("debug_aranges", &ARangeSection)
1005 .Case("debug_frame", &DebugFrameSection)
1006 .Case("eh_frame", &EHFrameSection)
1007 .Case("debug_str", &StringSection)
1008 .Case("debug_macinfo", &MacinfoSection)
1009 .Case("debug_pubnames", &PubNamesSection)
1010 .Case("debug_pubtypes", &PubTypesSection)
1011 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1012 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1013 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1014 .Case("debug_str.dwo", &StringDWOSection)
1015 .Case("debug_cu_index", &CUIndexSection)
1016 .Case("debug_tu_index", &TUIndexSection)
1017 .Case("gdb_index", &GdbIndexSection)
1018 // Any more debug info sections go here.
1019 .Default(nullptr);
1020 }
1021
1022 /// If Sec is compressed section, decompresses and updates its contents
1023 /// provided by Data. Otherwise leaves it unchanged.
1024 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1025 StringRef &Data) {
1026 if (!Decompressor::isCompressed(Sec))
1027 return Error::success();
1028
1029 Expected<Decompressor> Decompressor =
1030 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1031 if (!Decompressor)
1032 return Decompressor.takeError();
1033
1034 SmallString<32> Out;
1035 if (auto Err = Decompressor->resizeAndDecompress(Out))
1036 return Err;
1037
1038 UncompressedSections.emplace_back(std::move(Out));
1039 Data = UncompressedSections.back();
1040
1041 return Error::success();
1042 }
1043
1044public:
1045 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1046 uint8_t AddrSize, bool IsLittleEndian)
1047 : IsLittleEndian(IsLittleEndian) {
1048 for (const auto &SecIt : Sections) {
1049 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1050 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001051 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001052 }
1053 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1054 function_ref<ErrorPolicy(Error)> HandleError)
1055 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001056 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1057 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001058
George Rimare1c30f72017-08-15 15:54:43 +00001059 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001060 for (const SectionRef &Section : Obj.sections()) {
1061 StringRef Name;
1062 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001063 ++SectionAmountMap[Name];
1064 SectionNames.push_back({ Name, true });
1065
Rafael Espindolac398e672017-07-19 22:27:28 +00001066 // Skip BSS and Virtual sections, they aren't interesting.
1067 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001068 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001069
Rafael Espindolac398e672017-07-19 22:27:28 +00001070 StringRef Data;
1071 section_iterator RelocatedSection = Section.getRelocatedSection();
1072 // Try to obtain an already relocated version of this section.
1073 // Else use the unrelocated section from the object file. We'll have to
1074 // apply relocations ourselves later.
1075 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1076 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001077
Rafael Espindolac398e672017-07-19 22:27:28 +00001078 if (auto Err = maybeDecompress(Section, Name, Data)) {
1079 ErrorPolicy EP = HandleError(createError(
1080 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001081 if (EP == ErrorPolicy::Halt)
1082 return;
George Rimarfed9f092017-05-17 12:10:51 +00001083 continue;
1084 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001085
1086 // Compressed sections names in GNU style starts from ".z",
1087 // at this point section is decompressed and we drop compression prefix.
1088 Name = Name.substr(
1089 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1090
1091 // Map platform specific debug section names to DWARF standard section
1092 // names.
1093 Name = Obj.mapDebugSectionName(Name);
1094
1095 if (StringRef *SectionData = mapSectionToMember(Name)) {
1096 *SectionData = Data;
1097 if (Name == "debug_ranges") {
1098 // FIXME: Use the other dwo range section when we emit it.
1099 RangeDWOSection.Data = Data;
1100 }
1101 } else if (Name == "debug_types") {
1102 // Find debug_types data by section rather than name as there are
1103 // multiple, comdat grouped, debug_types sections.
1104 TypesSections[Section].Data = Data;
1105 } else if (Name == "debug_types.dwo") {
1106 TypesDWOSections[Section].Data = Data;
1107 }
1108
1109 if (RelocatedSection == Obj.section_end())
1110 continue;
1111
1112 StringRef RelSecName;
1113 StringRef RelSecData;
1114 RelocatedSection->getName(RelSecName);
1115
1116 // If the section we're relocating was relocated already by the JIT,
1117 // then we used the relocated version above, so we do not need to process
1118 // relocations for it now.
1119 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1120 continue;
1121
1122 // In Mach-o files, the relocations do not need to be applied if
1123 // there is no load offset to apply. The value read at the
1124 // relocation point already factors in the section address
1125 // (actually applying the relocations will produce wrong results
1126 // as the section address will be added twice).
1127 if (!L && isa<MachOObjectFile>(&Obj))
1128 continue;
1129
1130 RelSecName = RelSecName.substr(
1131 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1132
1133 // TODO: Add support for relocations in other sections as needed.
1134 // Record relocations for the debug_info and debug_line sections.
1135 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1136 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1137 if (!Map) {
1138 // Find debug_types relocs by section rather than name as there are
1139 // multiple, comdat grouped, debug_types sections.
1140 if (RelSecName == "debug_types")
1141 Map =
1142 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1143 .Relocs;
1144 else if (RelSecName == "debug_types.dwo")
1145 Map = &static_cast<DWARFSectionMap &>(
1146 TypesDWOSections[*RelocatedSection])
1147 .Relocs;
1148 else
1149 continue;
1150 }
1151
1152 if (Section.relocation_begin() == Section.relocation_end())
1153 continue;
1154
1155 // Symbol to [address, section index] cache mapping.
1156 std::map<SymbolRef, SymInfo> AddrCache;
1157 for (const RelocationRef &Reloc : Section.relocations()) {
1158 // FIXME: it's not clear how to correctly handle scattered
1159 // relocations.
1160 if (isRelocScattered(Obj, Reloc))
1161 continue;
1162
1163 Expected<SymInfo> SymInfoOrErr =
1164 getSymbolInfo(Obj, Reloc, L, AddrCache);
1165 if (!SymInfoOrErr) {
1166 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1167 return;
1168 continue;
1169 }
1170
1171 object::RelocVisitor V(Obj);
1172 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1173 if (V.error()) {
1174 SmallString<32> Type;
1175 Reloc.getTypeName(Type);
1176 ErrorPolicy EP = HandleError(
1177 createError("failed to compute relocation: " + Type + ", ",
1178 errorCodeToError(object_error::parse_failed)));
1179 if (EP == ErrorPolicy::Halt)
1180 return;
1181 continue;
1182 }
1183 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1184 Map->insert({Reloc.getOffset(), Rel});
1185 }
Eric Christopher7370b552012-11-12 21:40:38 +00001186 }
George Rimare1c30f72017-08-15 15:54:43 +00001187
1188 for (SectionName &S : SectionNames)
1189 if (SectionAmountMap[S.Name] > 1)
1190 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001191 }
Eric Christopher7370b552012-11-12 21:40:38 +00001192
Rafael Espindolac398e672017-07-19 22:27:28 +00001193 Optional<RelocAddrEntry> find(const DWARFSection &S,
1194 uint64_t Pos) const override {
1195 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1196 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1197 if (AI == Sec.Relocs.end())
1198 return None;
1199 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001200 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001201
George Rimar6957ab52017-08-15 12:32:54 +00001202 const object::ObjectFile *getFile() const override { return Obj; }
1203
George Rimare1c30f72017-08-15 15:54:43 +00001204 ArrayRef<SectionName> getSectionNames() const override {
1205 return SectionNames;
1206 }
1207
Rafael Espindolac398e672017-07-19 22:27:28 +00001208 bool isLittleEndian() const override { return IsLittleEndian; }
1209 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1210 const DWARFSection &getLineDWOSection() const override {
1211 return LineDWOSection;
1212 }
1213 const DWARFSection &getLocDWOSection() const override {
1214 return LocDWOSection;
1215 }
1216 StringRef getStringDWOSection() const override { return StringDWOSection; }
1217 const DWARFSection &getStringOffsetDWOSection() const override {
1218 return StringOffsetDWOSection;
1219 }
1220 const DWARFSection &getRangeDWOSection() const override {
1221 return RangeDWOSection;
1222 }
1223 const DWARFSection &getAddrSection() const override { return AddrSection; }
1224 StringRef getCUIndexSection() const override { return CUIndexSection; }
1225 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1226 StringRef getTUIndexSection() const override { return TUIndexSection; }
1227
1228 // DWARF v5
1229 const DWARFSection &getStringOffsetSection() const override {
1230 return StringOffsetSection;
1231 }
1232
1233 // Sections for DWARF5 split dwarf proposal.
1234 const DWARFSection &getInfoDWOSection() const override {
1235 return InfoDWOSection;
1236 }
1237 void forEachTypesDWOSections(
1238 function_ref<void(const DWARFSection &)> F) const override {
1239 for (auto &P : TypesDWOSections)
1240 F(P.second);
1241 }
1242
1243 StringRef getAbbrevSection() const override { return AbbrevSection; }
1244 const DWARFSection &getLocSection() const override { return LocSection; }
1245 StringRef getARangeSection() const override { return ARangeSection; }
1246 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1247 StringRef getEHFrameSection() const override { return EHFrameSection; }
1248 const DWARFSection &getLineSection() const override { return LineSection; }
1249 StringRef getStringSection() const override { return StringSection; }
1250 const DWARFSection &getRangeSection() const override { return RangeSection; }
1251 StringRef getMacinfoSection() const override { return MacinfoSection; }
1252 StringRef getPubNamesSection() const override { return PubNamesSection; }
1253 StringRef getPubTypesSection() const override { return PubTypesSection; }
1254 StringRef getGnuPubNamesSection() const override {
1255 return GnuPubNamesSection;
1256 }
1257 StringRef getGnuPubTypesSection() const override {
1258 return GnuPubTypesSection;
1259 }
1260 const DWARFSection &getAppleNamesSection() const override {
1261 return AppleNamesSection;
1262 }
1263 const DWARFSection &getAppleTypesSection() const override {
1264 return AppleTypesSection;
1265 }
1266 const DWARFSection &getAppleNamespacesSection() const override {
1267 return AppleNamespacesSection;
1268 }
1269 const DWARFSection &getAppleObjCSection() const override {
1270 return AppleObjCSection;
1271 }
1272
1273 StringRef getFileName() const override { return FileName; }
1274 uint8_t getAddressSize() const override { return AddressSize; }
1275 const DWARFSection &getInfoSection() const override { return InfoSection; }
1276 void forEachTypesSections(
1277 function_ref<void(const DWARFSection &)> F) const override {
1278 for (auto &P : TypesSections)
1279 F(P.second);
1280 }
1281};
1282
1283std::unique_ptr<DWARFContext>
1284DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001285 function_ref<ErrorPolicy(Error)> HandleError,
1286 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001287 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001288 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001289}
1290
Rafael Espindolac398e672017-07-19 22:27:28 +00001291std::unique_ptr<DWARFContext>
1292DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1293 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001294 auto DObj =
1295 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001296 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001297}