blob: d8034d08c27399fc08b16a2470cbc01b45fdccd7 [file] [log] [blame]
Eugene Zelenko28db7e62017-03-01 01:14:23 +00001//===- DWARFContext.cpp ---------------------------------------------------===//
Benjamin Krameraa2f78f2011-09-13 19:42:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Greg Claytonb8c162b2017-05-03 16:02:29 +000010#include "llvm/DebugInfo/DWARF/DWARFContext.h"
11#include "llvm/ADT/STLExtras.h"
Alexey Samsonove16e16a2012-07-19 07:03:58 +000012#include "llvm/ADT/SmallString.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000013#include "llvm/ADT/SmallVector.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000014#include "llvm/ADT/StringRef.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000015#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000016#include "llvm/BinaryFormat/Dwarf.h"
Zachary Turner82af9432015-01-30 18:07:45 +000017#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000018#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000019#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000021#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000022#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
23#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
24#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
25#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
George Rimare71e33f2016-12-17 09:10:32 +000026#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000027#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
28#include "llvm/DebugInfo/DWARF/DWARFDie.h"
29#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
30#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
31#include "llvm/DebugInfo/DWARF/DWARFSection.h"
David Blaikie65a8efe2015-11-11 19:28:21 +000032#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000033#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Reid Klecknera0587362017-08-29 21:41:21 +000034#include "llvm/MC/MCRegisterInfo.h"
George Rimar4bf30832017-01-11 15:26:41 +000035#include "llvm/Object/Decompressor.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000036#include "llvm/Object/MachO.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000037#include "llvm/Object/ObjectFile.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000038#include "llvm/Object/RelocVisitor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000039#include "llvm/Support/Casting.h"
40#include "llvm/Support/DataExtractor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000041#include "llvm/Support/Error.h"
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +000042#include "llvm/Support/Format.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000043#include "llvm/Support/MemoryBuffer.h"
Adrian Prantl3ae35eb2017-09-13 22:09:01 +000044#include "llvm/Support/Path.h"
Reid Klecknera0587362017-08-29 21:41:21 +000045#include "llvm/Support/TargetRegistry.h"
Benjamin Kramera6002fd2011-09-14 01:09:52 +000046#include "llvm/Support/raw_ostream.h"
Benjamin Kramer2602ca62011-09-15 20:43:22 +000047#include <algorithm>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000048#include <cstdint>
Greg Claytonc7695a82017-05-02 20:28:33 +000049#include <map>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000050#include <string>
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000051#include <tuple>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000052#include <utility>
53#include <vector>
54
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000055using namespace llvm;
Benjamin Kramer6dda0322011-09-15 18:02:20 +000056using namespace dwarf;
Rafael Espindola4f60a382013-05-30 03:05:14 +000057using namespace object;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000058
Chandler Carruthe96dd892014-04-21 22:55:11 +000059#define DEBUG_TYPE "dwarf"
60
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000061using DWARFLineTable = DWARFDebugLine::LineTable;
62using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
63using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
Eric Christopher494109b2012-10-16 23:46:25 +000064
Reid Klecknera0587362017-08-29 21:41:21 +000065DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
66 std::string DWPName)
67 : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
68
69DWARFContext::~DWARFContext() = default;
70
Frederic Riss7c500472014-11-14 19:30:08 +000071static void dumpAccelSection(raw_ostream &OS, StringRef Name,
Rafael Espindolac398e672017-07-19 22:27:28 +000072 const DWARFObject &Obj,
73 const DWARFSection &Section,
74 StringRef StringSection, bool LittleEndian) {
75 DWARFDataExtractor AccelSection(Obj, Section, LittleEndian, 0);
Frederic Risse837ec22014-11-14 16:15:53 +000076 DataExtractor StrData(StringSection, LittleEndian, 0);
77 OS << "\n." << Name << " contents:\n";
Paul Robinson17536b92017-06-29 16:52:08 +000078 DWARFAcceleratorTable Accel(AccelSection, StrData);
Frederic Risse837ec22014-11-14 16:15:53 +000079 if (!Accel.extract())
80 return;
81 Accel.dump(OS);
82}
83
Adrian Prantl3dcd1222017-09-13 18:22:59 +000084/// Dump the UUID load command.
85static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
86 auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
87 if (!MachO)
88 return;
89 for (auto LC : MachO->load_commands()) {
90 raw_ostream::uuid_t UUID;
91 if (LC.C.cmd == MachO::LC_UUID) {
92 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
93 OS << "error: UUID load command is too short.\n";
94 return;
95 }
96 OS << "UUID: ";
97 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
98 OS.write_uuid(UUID);
99 OS << ' ' << MachO->getFileFormatName();
100 OS << ' ' << MachO->getFileName() << '\n';
101 }
102 }
103}
104
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000105static void
106dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000107 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000108 const DWARFSection &StringOffsetsSection,
109 StringRef StringSection, bool LittleEndian) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000110 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000111 uint32_t Offset = 0;
112 uint64_t SectionSize = StringOffsetsSection.Data.size();
113
114 while (Offset < SectionSize) {
115 unsigned Version = 0;
116 DwarfFormat Format = DWARF32;
117 unsigned EntrySize = 4;
118 // Perform validation and extract the segment size from the header.
119 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
120 OS << "error: invalid contribution to string offsets table in section ."
121 << SectionName << ".\n";
122 return;
123 }
124 uint32_t ContributionStart = Offset;
125 uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
126 // A contribution size of 0xffffffff indicates DWARF64, with the actual size
127 // in the following 8 bytes. Otherwise, the DWARF standard mandates that
128 // the contribution size must be at most 0xfffffff0.
129 if (ContributionSize == 0xffffffff) {
130 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
131 OS << "error: invalid contribution to string offsets table in section ."
132 << SectionName << ".\n";
133 return;
134 }
135 Format = DWARF64;
136 EntrySize = 8;
137 ContributionSize = StrOffsetExt.getU64(&Offset);
138 } else if (ContributionSize > 0xfffffff0) {
139 OS << "error: invalid contribution to string offsets table in section ."
140 << SectionName << ".\n";
141 return;
142 }
143
144 // We must ensure that we don't read a partial record at the end, so we
145 // validate for a multiple of EntrySize. Also, we're expecting a version
146 // number and padding, which adds an additional 4 bytes.
147 uint64_t ValidationSize =
148 4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
149 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
150 OS << "error: contribution to string offsets table in section ."
151 << SectionName << " has invalid length.\n";
152 return;
153 }
154
155 Version = StrOffsetExt.getU16(&Offset);
156 Offset += 2;
157 OS << format("0x%8.8x: ", ContributionStart);
158 OS << "Contribution size = " << ContributionSize
159 << ", Version = " << Version << "\n";
160
161 uint32_t ContributionBase = Offset;
162 DataExtractor StrData(StringSection, LittleEndian, 0);
163 while (Offset - ContributionBase < ContributionSize) {
164 OS << format("0x%8.8x: ", Offset);
165 // FIXME: We can only extract strings in DWARF32 format at the moment.
Paul Robinson17536b92017-06-29 16:52:08 +0000166 uint64_t StringOffset =
167 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000168 if (Format == DWARF32) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000169 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000170 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000171 const char *S = StrData.getCStr(&StringOffset32);
172 if (S)
173 OS << format("\"%s\"", S);
174 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000175 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000176 OS << "\n";
177 }
178 }
179}
180
181// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
182// string offsets section, where each compile or type unit contributes a
183// number of entries (string offsets), with each contribution preceded by
184// a header containing size and version number. Alternatively, it may be a
185// monolithic series of string offsets, as generated by the pre-DWARF v5
186// implementation of split DWARF.
187static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000188 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000189 const DWARFSection &StringOffsetsSection,
190 StringRef StringSection, bool LittleEndian,
191 unsigned MaxVersion) {
192 if (StringOffsetsSection.Data.empty())
193 return;
194 OS << "\n." << SectionName << " contents:\n";
195 // If we have at least one (compile or type) unit with DWARF v5 or greater,
196 // we assume that the section is formatted like a DWARF v5 string offsets
197 // section.
198 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000199 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000200 StringSection, LittleEndian);
201 else {
202 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
203 uint32_t offset = 0;
204 uint64_t size = StringOffsetsSection.Data.size();
205 // Ensure that size is a multiple of the size of an entry.
206 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
207 OS << "error: size of ." << SectionName << " is not a multiple of "
208 << sizeof(uint32_t) << ".\n";
209 size &= -(uint64_t)sizeof(uint32_t);
210 }
211 DataExtractor StrData(StringSection, LittleEndian, 0);
212 while (offset < size) {
213 OS << format("0x%8.8x: ", offset);
214 uint32_t StringOffset = strOffsetExt.getU32(&offset);
215 OS << format("%8.8x ", StringOffset);
216 const char *S = StrData.getCStr(&StringOffset);
217 if (S)
218 OS << format("\"%s\"", S);
219 OS << "\n";
220 }
221 }
222}
223
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +0000224void DWARFContext::dump(raw_ostream &OS, DIDumpOptions DumpOpts) {
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000225 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000226 bool DumpEH = DumpOpts.DumpEH;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000227
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000228 StringRef Extension = sys::path::extension(DObj->getFileName());
229 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
230
231 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000232 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000233 if (DumpType & DIDT_UUID)
234 dumpUUID(OS, *ObjFile);
235
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000236 // Print a header for each explicitly-requested section.
237 // Otherwise just print one for non-empty sections.
238 bool Explicit = DumpType != DIDT_All && !IsDWO;
239 auto shouldDump = [&](unsigned DIDT_Section, StringRef Section) {
240 return (DumpType & DIDT_Section) && (Explicit || !Section.empty());
241 };
242 // Only print empty .dwo section headers when dumping a .dwo file.
243 bool ExplicitDWO = Explicit && IsDWO;
244 auto shouldDumpDWO = [&](unsigned DIDT_Section, StringRef Section) {
245 return (DumpType & DIDT_Section) && (ExplicitDWO || !Section.empty());
246 };
247
248 // Dump individual sections.
249 if (shouldDump(DIDT_DebugAbbrev, DObj->getAbbrevSection())) {
250 OS << "\n.debug_abbrev contents:\n";
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000251 getDebugAbbrev()->dump(OS);
252 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000253 if (shouldDumpDWO(DIDT_DebugAbbrev, DObj->getAbbrevDWOSection())) {
254 OS << "\n.debug_abbrev.dwo contents:\n";
255 getDebugAbbrevDWO()->dump(OS);
256 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000257
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000258 if (shouldDump(DIDT_DebugInfo, DObj->getInfoSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000259 OS << "\n.debug_info contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000260 for (const auto &CU : compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000261 CU->dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000262 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000263 if (shouldDumpDWO(DIDT_DebugInfo, DObj->getInfoDWOSection().Data)) {
David Blaikie66865d62014-01-09 00:13:35 +0000264 OS << "\n.debug_info.dwo contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000265 for (const auto &DWOCU : dwo_compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000266 DWOCU->dump(OS, DumpOpts);
David Blaikie66865d62014-01-09 00:13:35 +0000267 }
David Blaikie622dce42014-01-08 23:29:59 +0000268
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000269 if ((DumpType & DIDT_DebugTypes)) {
270 if (Explicit || getNumTypeUnits()) {
271 OS << "\n.debug_types contents:\n";
272 for (const auto &TUS : type_unit_sections())
273 for (const auto &TU : TUS)
274 TU->dump(OS, DumpOpts);
275 }
276 if (ExplicitDWO || getNumDWOTypeUnits()) {
277 OS << "\n.debug_types.dwo contents:\n";
278 for (const auto &DWOTUS : dwo_type_unit_sections())
279 for (const auto &DWOTU : DWOTUS)
280 DWOTU->dump(OS, DumpOpts);
281 }
David Blaikie03c089c2013-09-23 22:44:47 +0000282 }
283
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000284 if (shouldDump(DIDT_DebugLoc, DObj->getLocSection().Data)) {
David Blaikie03c089c2013-09-23 22:44:47 +0000285 OS << "\n.debug_loc contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000286 getDebugLoc()->dump(OS, getRegisterInfo());
David Blaikie18e73502013-06-19 21:37:13 +0000287 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000288 if (shouldDumpDWO(DIDT_DebugLoc, DObj->getLocDWOSection().Data)) {
David Blaikie9c550ac2014-03-25 01:44:02 +0000289 OS << "\n.debug_loc.dwo contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000290 getDebugLocDWO()->dump(OS, getRegisterInfo());
David Blaikie9c550ac2014-03-25 01:44:02 +0000291 }
292
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000293 if (shouldDump(DIDT_DebugFrames, DObj->getDebugFrameSection())) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000294 OS << "\n.debug_frame contents:\n";
295 getDebugFrame()->dump(OS);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000296 }
297 if (DumpEH && !getEHFrame()->empty()) {
298 OS << "\n.eh_frame contents:\n";
299 getEHFrame()->dump(OS);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000300 }
301
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000302 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000303 if (Explicit || !getDebugMacro()->empty()) {
304 OS << "\n.debug_macinfo contents:\n";
305 getDebugMacro()->dump(OS);
306 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000307 }
308
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000309 if (shouldDump(DIDT_DebugAranges, DObj->getARangeSection())) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000310 OS << "\n.debug_aranges contents:\n";
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000311 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000312 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000313 DWARFDebugArangeSet set;
314 while (set.extract(arangesData, &offset))
315 set.dump(OS);
316 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000317
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000318 uint8_t savedAddressByteSize = 0;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000319 if (shouldDump(DIDT_DebugLine, DObj->getLineSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000320 OS << "\n.debug_line contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000321 for (const auto &CU : compile_units()) {
322 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000323 auto CUDIE = CU->getUnitDIE();
324 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000325 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000326 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000327 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
328 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000329 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000330 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000331 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000332 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000333 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000334 }
335 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000336
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000337 // FIXME: This seems sketchy.
338 for (const auto &CU : compile_units()) {
339 savedAddressByteSize = CU->getAddressByteSize();
340 break;
David Blaikie65a8efe2015-11-11 19:28:21 +0000341 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000342 if (shouldDumpDWO(DIDT_DebugLine, DObj->getLineDWOSection().Data)) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000343 OS << "\n.debug_line.dwo contents:\n";
344 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000345 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
346 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000347 DWARFDebugLine::LineTable LineTable;
348 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
349 LineTable.dump(OS);
350 LineTable.clear();
351 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000352 }
353
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000354 if (shouldDump(DIDT_DebugCUIndex, DObj->getCUIndexSection())) {
355 OS << "\n.debug_cu_index contents:\n";
356 getCUIndex().dump(OS);
357 }
358
359 if (shouldDump(DIDT_DebugTUIndex, DObj->getTUIndexSection())) {
360 OS << "\n.debug_tu_index contents:\n";
361 getTUIndex().dump(OS);
362 }
363
364 if (shouldDump(DIDT_DebugStr, DObj->getStringSection())) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000365 OS << "\n.debug_str contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000366 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000367 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000368 uint32_t strOffset = 0;
369 while (const char *s = strData.getCStr(&offset)) {
370 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
371 strOffset = offset;
372 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000373 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000374 if (shouldDumpDWO(DIDT_DebugStr, DObj->getStringDWOSection())) {
David Blaikie66865d62014-01-09 00:13:35 +0000375 OS << "\n.debug_str.dwo contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000376 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000377 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000378 uint32_t strDWOOffset = 0;
379 while (const char *s = strDWOData.getCStr(&offset)) {
380 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
381 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000382 }
David Blaikie66865d62014-01-09 00:13:35 +0000383 }
David Blaikie622dce42014-01-08 23:29:59 +0000384
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000385 if (shouldDump(DIDT_DebugRanges, DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000386 OS << "\n.debug_ranges contents:\n";
387 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000388 // sizes, but for simplicity we just use the address byte size of the
389 // last compile unit (there is no easy and fast way to associate address
390 // range list and the compile unit it describes).
391 // FIXME: savedAddressByteSize seems sketchy.
Rafael Espindolac398e672017-07-19 22:27:28 +0000392 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
393 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000394 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000395 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000396 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000397 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000398 }
Eric Christopher962c9082013-01-15 23:56:56 +0000399
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000400 if (shouldDump(DIDT_DebugPubnames, DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000401 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000402 .dump("debug_pubnames", OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000403
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000404 if (shouldDump(DIDT_DebugPubtypes, DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000405 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000406 .dump("debug_pubtypes", OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000407
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000408 if (shouldDump(DIDT_DebugGnuPubnames, DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000409 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000410 true /* GnuStyle */)
411 .dump("debug_gnu_pubnames", OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000412
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000413 if (shouldDump(DIDT_DebugGnuPubtypes, DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000414 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000415 true /* GnuStyle */)
416 .dump("debug_gnu_pubtypes", OS);
David Blaikie404d3042013-09-19 23:01:29 +0000417
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000418 if (shouldDump(DIDT_DebugStrOffsets, DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000419 dumpStringOffsetsSection(
420 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
421 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000422 if (shouldDumpDWO(DIDT_DebugStrOffsets,
423 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000424 dumpStringOffsetsSection(
425 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
426 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000427
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000428 if (shouldDump(DIDT_GdbIndex, DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000429 OS << "\n.gnu_index contents:\n";
430 getGdbIndex().dump(OS);
431 }
432
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000433 if (shouldDump(DIDT_AppleNames, DObj->getAppleNamesSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000434 dumpAccelSection(OS, "apple_names", *DObj, DObj->getAppleNamesSection(),
435 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000436
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000437 if (shouldDump(DIDT_AppleTypes, DObj->getAppleTypesSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000438 dumpAccelSection(OS, "apple_types", *DObj, DObj->getAppleTypesSection(),
439 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000440
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000441 if (shouldDump(DIDT_AppleNamespaces, DObj->getAppleNamespacesSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000442 dumpAccelSection(OS, "apple_namespaces", *DObj,
443 DObj->getAppleNamespacesSection(),
444 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000445
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000446 if (shouldDump(DIDT_AppleObjC, DObj->getAppleObjCSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000447 dumpAccelSection(OS, "apple_objc", *DObj, DObj->getAppleObjCSection(),
448 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000449}
450
David Blaikie15d85fc2017-05-23 06:48:53 +0000451DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000452 parseDWOCompileUnits();
453
David Blaikieebac0b92017-07-30 08:12:07 +0000454 if (const auto &CUI = getCUIndex()) {
455 if (const auto *R = CUI.getFromHash(Hash))
456 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000457 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000458 return nullptr;
459 }
460
461 // If there's no index, just search through the CUs in the DWO - there's
462 // probably only one unless this is something like LTO - though an in-process
463 // built/cached lookup table could be used in that case to improve repeated
464 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000465 for (const auto &DWOCU : dwo_compile_units())
466 if (DWOCU->getDWOId() == Hash)
467 return DWOCU.get();
468 return nullptr;
469}
470
Greg Claytonc7695a82017-05-02 20:28:33 +0000471DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
472 parseCompileUnits();
473 if (auto *CU = CUs.getUnitForOffset(Offset))
474 return CU->getDIEForOffset(Offset);
475 return DWARFDie();
476}
477
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000478bool DWARFContext::verify(raw_ostream &OS, unsigned DumpType,
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000479 DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000480 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000481 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000482
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000483 Success &= verifier.handleDebugAbbrev();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000484 if (DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000485 Success &= verifier.handleDebugInfo();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000486 if (DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000487 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000488 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000489 return Success;
490}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000491
David Blaikie82641be2015-11-17 00:39:55 +0000492const DWARFUnitIndex &DWARFContext::getCUIndex() {
493 if (CUIndex)
494 return *CUIndex;
495
Rafael Espindolac398e672017-07-19 22:27:28 +0000496 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000497
David Blaikieb073cb92015-12-02 06:21:34 +0000498 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000499 CUIndex->parse(CUIndexData);
500 return *CUIndex;
501}
502
503const DWARFUnitIndex &DWARFContext::getTUIndex() {
504 if (TUIndex)
505 return *TUIndex;
506
Rafael Espindolac398e672017-07-19 22:27:28 +0000507 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000508
David Blaikieb073cb92015-12-02 06:21:34 +0000509 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000510 TUIndex->parse(TUIndexData);
511 return *TUIndex;
512}
513
George Rimar4f82df52016-09-23 11:01:53 +0000514DWARFGdbIndex &DWARFContext::getGdbIndex() {
515 if (GdbIndex)
516 return *GdbIndex;
517
Rafael Espindolac398e672017-07-19 22:27:28 +0000518 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000519 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
520 GdbIndex->parse(GdbIndexData);
521 return *GdbIndex;
522}
523
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000524const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
525 if (Abbrev)
526 return Abbrev.get();
527
Rafael Espindolac398e672017-07-19 22:27:28 +0000528 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000529
530 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000531 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000532 return Abbrev.get();
533}
534
Eric Christopherda4b2192013-01-02 23:52:13 +0000535const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
536 if (AbbrevDWO)
537 return AbbrevDWO.get();
538
Rafael Espindolac398e672017-07-19 22:27:28 +0000539 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000540 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000541 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000542 return AbbrevDWO.get();
543}
544
David Blaikie18e73502013-06-19 21:37:13 +0000545const DWARFDebugLoc *DWARFContext::getDebugLoc() {
546 if (Loc)
547 return Loc.get();
548
Paul Robinson17536b92017-06-29 16:52:08 +0000549 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000550 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000551 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000552 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000553 getCompileUnitAtIndex(0)->getAddressByteSize());
554 Loc->parse(LocData);
555 }
David Blaikie18e73502013-06-19 21:37:13 +0000556 return Loc.get();
557}
558
David Blaikie9c550ac2014-03-25 01:44:02 +0000559const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
560 if (LocDWO)
561 return LocDWO.get();
562
Rafael Espindolac398e672017-07-19 22:27:28 +0000563 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000564 LocDWO.reset(new DWARFDebugLocDWO());
565 LocDWO->parse(LocData);
566 return LocDWO.get();
567}
568
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000569const DWARFDebugAranges *DWARFContext::getDebugAranges() {
570 if (Aranges)
571 return Aranges.get();
572
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000573 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000574 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000575 return Aranges.get();
576}
577
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000578const DWARFDebugFrame *DWARFContext::getDebugFrame() {
579 if (DebugFrame)
580 return DebugFrame.get();
581
582 // There's a "bug" in the DWARFv3 standard with respect to the target address
583 // size within debug frame sections. While DWARF is supposed to be independent
584 // of its container, FDEs have fields with size being "target address size",
585 // which isn't specified in DWARF in general. It's only specified for CUs, but
586 // .eh_frame can appear without a .debug_info section. Follow the example of
587 // other tools (libdwarf) and extract this from the container (ObjectFile
588 // provides this information). This problem is fixed in DWARFv4
589 // See this dwarf-discuss discussion for more details:
590 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000591 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
592 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000593 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
594 DebugFrame->parse(debugFrameData);
595 return DebugFrame.get();
596}
597
598const DWARFDebugFrame *DWARFContext::getEHFrame() {
599 if (EHFrame)
600 return EHFrame.get();
601
Rafael Espindolac398e672017-07-19 22:27:28 +0000602 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
603 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000604 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000605 DebugFrame->parse(debugFrameData);
606 return DebugFrame.get();
607}
608
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000609const DWARFDebugMacro *DWARFContext::getDebugMacro() {
610 if (Macro)
611 return Macro.get();
612
Rafael Espindolac398e672017-07-19 22:27:28 +0000613 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000614 Macro.reset(new DWARFDebugMacro());
615 Macro->parse(MacinfoData);
616 return Macro.get();
617}
618
Eric Christopher494109b2012-10-16 23:46:25 +0000619const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000620DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000621 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000622 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000623
Greg Claytonc8c10322016-12-13 18:25:19 +0000624 auto UnitDIE = U->getUnitDIE();
625 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000626 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000627
Greg Clayton97d22182017-01-13 21:08:18 +0000628 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000629 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000630 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000631
Greg Clayton52fe1f62016-12-14 22:38:08 +0000632 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000633 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000634 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000635 return lt;
636
Greg Clayton48ff66a2017-05-04 18:29:44 +0000637 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000638 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000639 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000640
Benjamin Kramer679e1752011-09-15 20:43:18 +0000641 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000642 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000643 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000644 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000645}
646
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000647void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000648 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000649}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000650
David Blaikie03c089c2013-09-23 22:44:47 +0000651void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000652 if (!TUs.empty())
653 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000654 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000655 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000656 TUs.back().parse(*this, S);
657 });
David Blaikie03c089c2013-09-23 22:44:47 +0000658}
659
Eric Christopherda4b2192013-01-02 23:52:13 +0000660void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000661 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000662}
663
David Blaikie92d9d622014-01-09 05:08:24 +0000664void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000665 if (!DWOTUs.empty())
666 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000667 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000668 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000669 DWOTUs.back().parseDWO(*this, S);
670 });
David Blaikie92d9d622014-01-09 05:08:24 +0000671}
672
Alexey Samsonov45be7932012-08-30 07:49:50 +0000673DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000674 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000675 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000676}
677
Alexey Samsonov45be7932012-08-30 07:49:50 +0000678DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000679 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000680 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000681 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000682 return getCompileUnitForOffset(CUOffset);
683}
684
David Blaikieefc4eba2017-02-06 20:19:02 +0000685static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
686 uint64_t Address,
687 FunctionNameKind Kind,
688 std::string &FunctionName,
689 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000690 // The address may correspond to instruction in some inlined function,
691 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000692 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000693 SmallVector<DWARFDie, 4> InlinedChain;
694 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000695 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000696 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000697
698 const DWARFDie &DIE = InlinedChain[0];
699 bool FoundResult = false;
700 const char *Name = nullptr;
701 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000702 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000703 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000704 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000705 if (auto DeclLineResult = DIE.getDeclLine()) {
706 StartLine = DeclLineResult;
707 FoundResult = true;
708 }
709
710 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000711}
712
Alexey Samsonov45be7932012-08-30 07:49:50 +0000713DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000714 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000715 DILineInfo Result;
716
Alexey Samsonov45be7932012-08-30 07:49:50 +0000717 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
718 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000719 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000720 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
721 Result.FunctionName,
722 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000723 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000724 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
725 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
726 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000727 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000728 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000729}
David Blaikiea379b1812011-12-20 02:50:00 +0000730
Alexey Samsonovdce67342014-05-15 21:24:32 +0000731DILineInfoTable
732DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
733 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000734 DILineInfoTable Lines;
735 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
736 if (!CU)
737 return Lines;
738
739 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000740 uint32_t StartLine = 0;
741 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
742 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000743
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000744 // If the Specifier says we don't need FileLineInfo, just
745 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000746 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000747 DILineInfo Result;
748 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000749 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000750 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000751 return Lines;
752 }
753
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000754 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000755
756 // Get the index of row we're looking for in the line table.
757 std::vector<uint32_t> RowVector;
758 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
759 return Lines;
760
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000761 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000762 // Take file number and line/column from the row.
763 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000764 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000765 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
766 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000767 Result.FunctionName = FunctionName;
768 Result.Line = Row.Line;
769 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000770 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000771 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000772 }
773
774 return Lines;
775}
776
Alexey Samsonovdce67342014-05-15 21:24:32 +0000777DIInliningInfo
778DWARFContext::getInliningInfoForAddress(uint64_t Address,
779 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000780 DIInliningInfo InliningInfo;
781
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000782 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
783 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000784 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000785
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000786 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000787 SmallVector<DWARFDie, 4> InlinedChain;
788 CU->getInlinedChainForAddress(Address, InlinedChain);
789 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000790 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
791 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000792 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000793 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000794 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000795 if (LineTable &&
796 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
797 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000798 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000799 }
800 return InliningInfo;
801 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000802
Dehao Chenef700d52017-04-17 20:10:39 +0000803 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000804 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
805 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000806 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000807 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000808 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000809 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000810 if (auto DeclLineResult = FunctionDIE.getDeclLine())
811 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000812 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000813 if (i == 0) {
814 // For the topmost frame, initialize the line table of this
815 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000816 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000817 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000818 if (LineTable)
819 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
820 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000821 } else {
822 // Otherwise, use call file, call line and call column from
823 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000824 if (LineTable)
825 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
826 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000827 Frame.Line = CallLine;
828 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000829 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000830 }
831 // Get call file/line/column of a current DIE.
832 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000833 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
834 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000835 }
836 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000837 InliningInfo.addFrame(Frame);
838 }
839 return InliningInfo;
840}
841
David Blaikief9803fb2017-05-23 00:30:42 +0000842std::shared_ptr<DWARFContext>
843DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000844 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000845 DWARFContext *Ctxt = S->Context.get();
846 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
847 }
848
David Blaikie15d85fc2017-05-23 06:48:53 +0000849 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
850
851 if (auto S = Entry->lock()) {
852 DWARFContext *Ctxt = S->Context.get();
853 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
854 }
855
David Blaikie15d85fc2017-05-23 06:48:53 +0000856 Expected<OwningBinary<ObjectFile>> Obj = [&] {
857 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000858 SmallString<128> DWPName;
859 auto Obj = object::ObjectFile::createObjectFile(
860 this->DWPName.empty()
861 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
862 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000863 if (Obj) {
864 Entry = &DWP;
865 return Obj;
866 } else {
867 CheckedForDWP = true;
868 // TODO: Should this error be handled (maybe in a high verbosity mode)
869 // before falling back to .dwo files?
870 consumeError(Obj.takeError());
871 }
872 }
873
874 return object::ObjectFile::createObjectFile(AbsolutePath);
875 }();
876
David Blaikief9803fb2017-05-23 00:30:42 +0000877 if (!Obj) {
878 // TODO: Actually report errors helpfully.
879 consumeError(Obj.takeError());
880 return nullptr;
881 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000882
883 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000884 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000885 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000886 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000887 auto *Ctxt = S->Context.get();
888 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
889}
890
George Rimar702dac62017-04-12 08:59:15 +0000891static Error createError(const Twine &Reason, llvm::Error E) {
892 return make_error<StringError>(Reason + toString(std::move(E)),
893 inconvertibleErrorCode());
894}
895
George Rimara25d3292017-05-27 18:10:23 +0000896/// SymInfo contains information about symbol: it's address
897/// and section index which is -1LL for absolute symbols.
898struct SymInfo {
899 uint64_t Address;
900 uint64_t SectionIndex;
901};
902
903/// Returns the address of symbol relocation used against and a section index.
904/// Used for futher relocations computation. Symbol's section load address is
905static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
906 const RelocationRef &Reloc,
907 const LoadedObjectInfo *L,
908 std::map<SymbolRef, SymInfo> &Cache) {
909 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000910 object::section_iterator RSec = Obj.section_end();
911 object::symbol_iterator Sym = Reloc.getSymbol();
912
George Rimara25d3292017-05-27 18:10:23 +0000913 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000914 // First calculate the address of the symbol or section as it appears
915 // in the object file
916 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000917 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000918 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000919 if (!New)
920 return CacheIt->second;
921
George Rimar702dac62017-04-12 08:59:15 +0000922 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
923 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000924 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000925 SymAddrOrErr.takeError());
926
927 // Also remember what section this symbol is in for later
928 auto SectOrErr = Sym->getSection();
929 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000930 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000931 SectOrErr.takeError());
932
933 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000934 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000935 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
936 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000937 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000938 }
939
George Rimara25d3292017-05-27 18:10:23 +0000940 if (RSec != Obj.section_end())
941 Ret.SectionIndex = RSec->getIndex();
942
George Rimar702dac62017-04-12 08:59:15 +0000943 // If we are given load addresses for the sections, we need to adjust:
944 // SymAddr = (Address of Symbol Or Section in File) -
945 // (Address of Section in File) +
946 // (Load Address of Section)
947 // RSec is now either the section being targeted or the section
948 // containing the symbol being targeted. In either case,
949 // we need to perform the same computation.
950 if (L && RSec != Obj.section_end())
951 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000952 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000953
954 if (CacheIt != Cache.end())
955 CacheIt->second = Ret;
956
George Rimar702dac62017-04-12 08:59:15 +0000957 return Ret;
958}
959
960static bool isRelocScattered(const object::ObjectFile &Obj,
961 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000962 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
963 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000964 return false;
965 // MachO also has relocations that point to sections and
966 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000967 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
968 return MachObj->isRelocationScattered(RelocInfo);
969}
970
Rafael Espindolac398e672017-07-19 22:27:28 +0000971ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000972 errs() << "error: " + toString(std::move(E)) << '\n';
973 return ErrorPolicy::Continue;
974}
975
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000976namespace {
977struct DWARFSectionMap final : public DWARFSection {
978 RelocAddrMap Relocs;
979};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000980
Rafael Espindolac398e672017-07-19 22:27:28 +0000981class DWARFObjInMemory final : public DWARFObject {
982 bool IsLittleEndian;
983 uint8_t AddressSize;
984 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +0000985 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +0000986 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000987
Rafael Espindolac398e672017-07-19 22:27:28 +0000988 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
989 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +0000990
Rafael Espindolac398e672017-07-19 22:27:28 +0000991 TypeSectionMap TypesSections;
992 TypeSectionMap TypesDWOSections;
993
994 DWARFSectionMap InfoSection;
995 DWARFSectionMap LocSection;
996 DWARFSectionMap LineSection;
997 DWARFSectionMap RangeSection;
998 DWARFSectionMap StringOffsetSection;
999 DWARFSectionMap InfoDWOSection;
1000 DWARFSectionMap LineDWOSection;
1001 DWARFSectionMap LocDWOSection;
1002 DWARFSectionMap StringOffsetDWOSection;
1003 DWARFSectionMap RangeDWOSection;
1004 DWARFSectionMap AddrSection;
1005 DWARFSectionMap AppleNamesSection;
1006 DWARFSectionMap AppleTypesSection;
1007 DWARFSectionMap AppleNamespacesSection;
1008 DWARFSectionMap AppleObjCSection;
1009
1010 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1011 return StringSwitch<DWARFSectionMap *>(Name)
1012 .Case("debug_info", &InfoSection)
1013 .Case("debug_loc", &LocSection)
1014 .Case("debug_line", &LineSection)
1015 .Case("debug_str_offsets", &StringOffsetSection)
1016 .Case("debug_ranges", &RangeSection)
1017 .Case("debug_info.dwo", &InfoDWOSection)
1018 .Case("debug_loc.dwo", &LocDWOSection)
1019 .Case("debug_line.dwo", &LineDWOSection)
1020 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1021 .Case("debug_addr", &AddrSection)
1022 .Case("apple_names", &AppleNamesSection)
1023 .Case("apple_types", &AppleTypesSection)
1024 .Case("apple_namespaces", &AppleNamespacesSection)
1025 .Case("apple_namespac", &AppleNamespacesSection)
1026 .Case("apple_objc", &AppleObjCSection)
1027 .Default(nullptr);
1028 }
1029
1030 StringRef AbbrevSection;
1031 StringRef ARangeSection;
1032 StringRef DebugFrameSection;
1033 StringRef EHFrameSection;
1034 StringRef StringSection;
1035 StringRef MacinfoSection;
1036 StringRef PubNamesSection;
1037 StringRef PubTypesSection;
1038 StringRef GnuPubNamesSection;
1039 StringRef AbbrevDWOSection;
1040 StringRef StringDWOSection;
1041 StringRef GnuPubTypesSection;
1042 StringRef CUIndexSection;
1043 StringRef GdbIndexSection;
1044 StringRef TUIndexSection;
1045
1046 SmallVector<SmallString<32>, 4> UncompressedSections;
1047
1048 StringRef *mapSectionToMember(StringRef Name) {
1049 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1050 return &Sec->Data;
1051 return StringSwitch<StringRef *>(Name)
1052 .Case("debug_abbrev", &AbbrevSection)
1053 .Case("debug_aranges", &ARangeSection)
1054 .Case("debug_frame", &DebugFrameSection)
1055 .Case("eh_frame", &EHFrameSection)
1056 .Case("debug_str", &StringSection)
1057 .Case("debug_macinfo", &MacinfoSection)
1058 .Case("debug_pubnames", &PubNamesSection)
1059 .Case("debug_pubtypes", &PubTypesSection)
1060 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1061 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1062 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1063 .Case("debug_str.dwo", &StringDWOSection)
1064 .Case("debug_cu_index", &CUIndexSection)
1065 .Case("debug_tu_index", &TUIndexSection)
1066 .Case("gdb_index", &GdbIndexSection)
1067 // Any more debug info sections go here.
1068 .Default(nullptr);
1069 }
1070
1071 /// If Sec is compressed section, decompresses and updates its contents
1072 /// provided by Data. Otherwise leaves it unchanged.
1073 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1074 StringRef &Data) {
1075 if (!Decompressor::isCompressed(Sec))
1076 return Error::success();
1077
1078 Expected<Decompressor> Decompressor =
1079 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1080 if (!Decompressor)
1081 return Decompressor.takeError();
1082
1083 SmallString<32> Out;
1084 if (auto Err = Decompressor->resizeAndDecompress(Out))
1085 return Err;
1086
1087 UncompressedSections.emplace_back(std::move(Out));
1088 Data = UncompressedSections.back();
1089
1090 return Error::success();
1091 }
1092
1093public:
1094 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1095 uint8_t AddrSize, bool IsLittleEndian)
1096 : IsLittleEndian(IsLittleEndian) {
1097 for (const auto &SecIt : Sections) {
1098 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1099 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001100 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001101 }
1102 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1103 function_ref<ErrorPolicy(Error)> HandleError)
1104 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001105 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1106 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001107
George Rimare1c30f72017-08-15 15:54:43 +00001108 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001109 for (const SectionRef &Section : Obj.sections()) {
1110 StringRef Name;
1111 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001112 ++SectionAmountMap[Name];
1113 SectionNames.push_back({ Name, true });
1114
Rafael Espindolac398e672017-07-19 22:27:28 +00001115 // Skip BSS and Virtual sections, they aren't interesting.
1116 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001117 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001118
Rafael Espindolac398e672017-07-19 22:27:28 +00001119 StringRef Data;
1120 section_iterator RelocatedSection = Section.getRelocatedSection();
1121 // Try to obtain an already relocated version of this section.
1122 // Else use the unrelocated section from the object file. We'll have to
1123 // apply relocations ourselves later.
1124 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1125 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001126
Rafael Espindolac398e672017-07-19 22:27:28 +00001127 if (auto Err = maybeDecompress(Section, Name, Data)) {
1128 ErrorPolicy EP = HandleError(createError(
1129 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001130 if (EP == ErrorPolicy::Halt)
1131 return;
George Rimarfed9f092017-05-17 12:10:51 +00001132 continue;
1133 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001134
1135 // Compressed sections names in GNU style starts from ".z",
1136 // at this point section is decompressed and we drop compression prefix.
1137 Name = Name.substr(
1138 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1139
1140 // Map platform specific debug section names to DWARF standard section
1141 // names.
1142 Name = Obj.mapDebugSectionName(Name);
1143
1144 if (StringRef *SectionData = mapSectionToMember(Name)) {
1145 *SectionData = Data;
1146 if (Name == "debug_ranges") {
1147 // FIXME: Use the other dwo range section when we emit it.
1148 RangeDWOSection.Data = Data;
1149 }
1150 } else if (Name == "debug_types") {
1151 // Find debug_types data by section rather than name as there are
1152 // multiple, comdat grouped, debug_types sections.
1153 TypesSections[Section].Data = Data;
1154 } else if (Name == "debug_types.dwo") {
1155 TypesDWOSections[Section].Data = Data;
1156 }
1157
1158 if (RelocatedSection == Obj.section_end())
1159 continue;
1160
1161 StringRef RelSecName;
1162 StringRef RelSecData;
1163 RelocatedSection->getName(RelSecName);
1164
1165 // If the section we're relocating was relocated already by the JIT,
1166 // then we used the relocated version above, so we do not need to process
1167 // relocations for it now.
1168 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1169 continue;
1170
1171 // In Mach-o files, the relocations do not need to be applied if
1172 // there is no load offset to apply. The value read at the
1173 // relocation point already factors in the section address
1174 // (actually applying the relocations will produce wrong results
1175 // as the section address will be added twice).
1176 if (!L && isa<MachOObjectFile>(&Obj))
1177 continue;
1178
1179 RelSecName = RelSecName.substr(
1180 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1181
1182 // TODO: Add support for relocations in other sections as needed.
1183 // Record relocations for the debug_info and debug_line sections.
1184 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1185 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1186 if (!Map) {
1187 // Find debug_types relocs by section rather than name as there are
1188 // multiple, comdat grouped, debug_types sections.
1189 if (RelSecName == "debug_types")
1190 Map =
1191 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1192 .Relocs;
1193 else if (RelSecName == "debug_types.dwo")
1194 Map = &static_cast<DWARFSectionMap &>(
1195 TypesDWOSections[*RelocatedSection])
1196 .Relocs;
1197 else
1198 continue;
1199 }
1200
1201 if (Section.relocation_begin() == Section.relocation_end())
1202 continue;
1203
1204 // Symbol to [address, section index] cache mapping.
1205 std::map<SymbolRef, SymInfo> AddrCache;
1206 for (const RelocationRef &Reloc : Section.relocations()) {
1207 // FIXME: it's not clear how to correctly handle scattered
1208 // relocations.
1209 if (isRelocScattered(Obj, Reloc))
1210 continue;
1211
1212 Expected<SymInfo> SymInfoOrErr =
1213 getSymbolInfo(Obj, Reloc, L, AddrCache);
1214 if (!SymInfoOrErr) {
1215 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1216 return;
1217 continue;
1218 }
1219
1220 object::RelocVisitor V(Obj);
1221 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1222 if (V.error()) {
1223 SmallString<32> Type;
1224 Reloc.getTypeName(Type);
1225 ErrorPolicy EP = HandleError(
1226 createError("failed to compute relocation: " + Type + ", ",
1227 errorCodeToError(object_error::parse_failed)));
1228 if (EP == ErrorPolicy::Halt)
1229 return;
1230 continue;
1231 }
1232 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1233 Map->insert({Reloc.getOffset(), Rel});
1234 }
Eric Christopher7370b552012-11-12 21:40:38 +00001235 }
George Rimare1c30f72017-08-15 15:54:43 +00001236
1237 for (SectionName &S : SectionNames)
1238 if (SectionAmountMap[S.Name] > 1)
1239 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001240 }
Eric Christopher7370b552012-11-12 21:40:38 +00001241
Rafael Espindolac398e672017-07-19 22:27:28 +00001242 Optional<RelocAddrEntry> find(const DWARFSection &S,
1243 uint64_t Pos) const override {
1244 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1245 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1246 if (AI == Sec.Relocs.end())
1247 return None;
1248 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001249 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001250
George Rimar6957ab52017-08-15 12:32:54 +00001251 const object::ObjectFile *getFile() const override { return Obj; }
1252
George Rimare1c30f72017-08-15 15:54:43 +00001253 ArrayRef<SectionName> getSectionNames() const override {
1254 return SectionNames;
1255 }
1256
Rafael Espindolac398e672017-07-19 22:27:28 +00001257 bool isLittleEndian() const override { return IsLittleEndian; }
1258 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1259 const DWARFSection &getLineDWOSection() const override {
1260 return LineDWOSection;
1261 }
1262 const DWARFSection &getLocDWOSection() const override {
1263 return LocDWOSection;
1264 }
1265 StringRef getStringDWOSection() const override { return StringDWOSection; }
1266 const DWARFSection &getStringOffsetDWOSection() const override {
1267 return StringOffsetDWOSection;
1268 }
1269 const DWARFSection &getRangeDWOSection() const override {
1270 return RangeDWOSection;
1271 }
1272 const DWARFSection &getAddrSection() const override { return AddrSection; }
1273 StringRef getCUIndexSection() const override { return CUIndexSection; }
1274 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1275 StringRef getTUIndexSection() const override { return TUIndexSection; }
1276
1277 // DWARF v5
1278 const DWARFSection &getStringOffsetSection() const override {
1279 return StringOffsetSection;
1280 }
1281
1282 // Sections for DWARF5 split dwarf proposal.
1283 const DWARFSection &getInfoDWOSection() const override {
1284 return InfoDWOSection;
1285 }
1286 void forEachTypesDWOSections(
1287 function_ref<void(const DWARFSection &)> F) const override {
1288 for (auto &P : TypesDWOSections)
1289 F(P.second);
1290 }
1291
1292 StringRef getAbbrevSection() const override { return AbbrevSection; }
1293 const DWARFSection &getLocSection() const override { return LocSection; }
1294 StringRef getARangeSection() const override { return ARangeSection; }
1295 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1296 StringRef getEHFrameSection() const override { return EHFrameSection; }
1297 const DWARFSection &getLineSection() const override { return LineSection; }
1298 StringRef getStringSection() const override { return StringSection; }
1299 const DWARFSection &getRangeSection() const override { return RangeSection; }
1300 StringRef getMacinfoSection() const override { return MacinfoSection; }
1301 StringRef getPubNamesSection() const override { return PubNamesSection; }
1302 StringRef getPubTypesSection() const override { return PubTypesSection; }
1303 StringRef getGnuPubNamesSection() const override {
1304 return GnuPubNamesSection;
1305 }
1306 StringRef getGnuPubTypesSection() const override {
1307 return GnuPubTypesSection;
1308 }
1309 const DWARFSection &getAppleNamesSection() const override {
1310 return AppleNamesSection;
1311 }
1312 const DWARFSection &getAppleTypesSection() const override {
1313 return AppleTypesSection;
1314 }
1315 const DWARFSection &getAppleNamespacesSection() const override {
1316 return AppleNamespacesSection;
1317 }
1318 const DWARFSection &getAppleObjCSection() const override {
1319 return AppleObjCSection;
1320 }
1321
1322 StringRef getFileName() const override { return FileName; }
1323 uint8_t getAddressSize() const override { return AddressSize; }
1324 const DWARFSection &getInfoSection() const override { return InfoSection; }
1325 void forEachTypesSections(
1326 function_ref<void(const DWARFSection &)> F) const override {
1327 for (auto &P : TypesSections)
1328 F(P.second);
1329 }
1330};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001331} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001332
1333std::unique_ptr<DWARFContext>
1334DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001335 function_ref<ErrorPolicy(Error)> HandleError,
1336 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001337 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001338 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001339}
1340
Rafael Espindolac398e672017-07-19 22:27:28 +00001341std::unique_ptr<DWARFContext>
1342DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1343 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001344 auto DObj =
1345 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001346 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001347}
Reid Klecknera0587362017-08-29 21:41:21 +00001348
1349Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1350 // Detect the architecture from the object file. We usually don't need OS
1351 // info to lookup a target and create register info.
1352 Triple TT;
1353 TT.setArch(Triple::ArchType(Obj.getArch()));
1354 TT.setVendor(Triple::UnknownVendor);
1355 TT.setOS(Triple::UnknownOS);
1356 std::string TargetLookupError;
1357 const Target *TheTarget =
1358 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1359 if (!TargetLookupError.empty())
1360 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1361 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1362 return Error::success();
1363}