blob: 6dac25996d2a5054aef8b5092963206ce8e3600f [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();
233 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All)
234 outs() << ObjFile->getFileName() << ":\tfile format "
235 << ObjFile->getFileFormatName() << "\n\n";
236 if (DumpType & DIDT_UUID)
237 dumpUUID(OS, *ObjFile);
238
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000239 // Print a header for each explicitly-requested section.
240 // Otherwise just print one for non-empty sections.
241 bool Explicit = DumpType != DIDT_All && !IsDWO;
242 auto shouldDump = [&](unsigned DIDT_Section, StringRef Section) {
243 return (DumpType & DIDT_Section) && (Explicit || !Section.empty());
244 };
245 // Only print empty .dwo section headers when dumping a .dwo file.
246 bool ExplicitDWO = Explicit && IsDWO;
247 auto shouldDumpDWO = [&](unsigned DIDT_Section, StringRef Section) {
248 return (DumpType & DIDT_Section) && (ExplicitDWO || !Section.empty());
249 };
250
251 // Dump individual sections.
252 if (shouldDump(DIDT_DebugAbbrev, DObj->getAbbrevSection())) {
253 OS << "\n.debug_abbrev contents:\n";
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000254 getDebugAbbrev()->dump(OS);
255 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000256 if (shouldDumpDWO(DIDT_DebugAbbrev, DObj->getAbbrevDWOSection())) {
257 OS << "\n.debug_abbrev.dwo contents:\n";
258 getDebugAbbrevDWO()->dump(OS);
259 }
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000260
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000261 if (shouldDump(DIDT_DebugInfo, DObj->getInfoSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000262 OS << "\n.debug_info contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000263 for (const auto &CU : compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000264 CU->dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000265 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000266 if (shouldDumpDWO(DIDT_DebugInfo, DObj->getInfoDWOSection().Data)) {
David Blaikie66865d62014-01-09 00:13:35 +0000267 OS << "\n.debug_info.dwo contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000268 for (const auto &DWOCU : dwo_compile_units())
Adrian Prantl318d1192017-06-06 23:28:45 +0000269 DWOCU->dump(OS, DumpOpts);
David Blaikie66865d62014-01-09 00:13:35 +0000270 }
David Blaikie622dce42014-01-08 23:29:59 +0000271
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000272 if ((DumpType & DIDT_DebugTypes)) {
273 if (Explicit || getNumTypeUnits()) {
274 OS << "\n.debug_types contents:\n";
275 for (const auto &TUS : type_unit_sections())
276 for (const auto &TU : TUS)
277 TU->dump(OS, DumpOpts);
278 }
279 if (ExplicitDWO || getNumDWOTypeUnits()) {
280 OS << "\n.debug_types.dwo contents:\n";
281 for (const auto &DWOTUS : dwo_type_unit_sections())
282 for (const auto &DWOTU : DWOTUS)
283 DWOTU->dump(OS, DumpOpts);
284 }
David Blaikie03c089c2013-09-23 22:44:47 +0000285 }
286
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000287 if (shouldDump(DIDT_DebugLoc, DObj->getLocSection().Data)) {
David Blaikie03c089c2013-09-23 22:44:47 +0000288 OS << "\n.debug_loc contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000289 getDebugLoc()->dump(OS, getRegisterInfo());
David Blaikie18e73502013-06-19 21:37:13 +0000290 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000291 if (shouldDumpDWO(DIDT_DebugLoc, DObj->getLocDWOSection().Data)) {
David Blaikie9c550ac2014-03-25 01:44:02 +0000292 OS << "\n.debug_loc.dwo contents:\n";
Reid Klecknera0587362017-08-29 21:41:21 +0000293 getDebugLocDWO()->dump(OS, getRegisterInfo());
David Blaikie9c550ac2014-03-25 01:44:02 +0000294 }
295
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000296 if (shouldDump(DIDT_DebugFrames, DObj->getDebugFrameSection())) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000297 OS << "\n.debug_frame contents:\n";
298 getDebugFrame()->dump(OS);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000299 }
300 if (DumpEH && !getEHFrame()->empty()) {
301 OS << "\n.eh_frame contents:\n";
302 getEHFrame()->dump(OS);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000303 }
304
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000305 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000306 if (Explicit || !getDebugMacro()->empty()) {
307 OS << "\n.debug_macinfo contents:\n";
308 getDebugMacro()->dump(OS);
309 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000310 }
311
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000312 if (shouldDump(DIDT_DebugAranges, DObj->getARangeSection())) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000313 OS << "\n.debug_aranges contents:\n";
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000314 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000315 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000316 DWARFDebugArangeSet set;
317 while (set.extract(arangesData, &offset))
318 set.dump(OS);
319 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000320
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000321 uint8_t savedAddressByteSize = 0;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000322 if (shouldDump(DIDT_DebugLine, DObj->getLineSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000323 OS << "\n.debug_line contents:\n";
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000324 for (const auto &CU : compile_units()) {
325 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000326 auto CUDIE = CU->getUnitDIE();
327 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000328 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000329 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000330 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
331 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000332 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000333 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000334 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000335 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000336 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000337 }
338 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000339
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000340 // FIXME: This seems sketchy.
341 for (const auto &CU : compile_units()) {
342 savedAddressByteSize = CU->getAddressByteSize();
343 break;
David Blaikie65a8efe2015-11-11 19:28:21 +0000344 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000345 if (shouldDumpDWO(DIDT_DebugLine, DObj->getLineDWOSection().Data)) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000346 OS << "\n.debug_line.dwo contents:\n";
347 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000348 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
349 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000350 DWARFDebugLine::LineTable LineTable;
351 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
352 LineTable.dump(OS);
353 LineTable.clear();
354 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000355 }
356
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000357 if (shouldDump(DIDT_DebugCUIndex, DObj->getCUIndexSection())) {
358 OS << "\n.debug_cu_index contents:\n";
359 getCUIndex().dump(OS);
360 }
361
362 if (shouldDump(DIDT_DebugTUIndex, DObj->getTUIndexSection())) {
363 OS << "\n.debug_tu_index contents:\n";
364 getTUIndex().dump(OS);
365 }
366
367 if (shouldDump(DIDT_DebugStr, DObj->getStringSection())) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000368 OS << "\n.debug_str contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000369 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000370 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000371 uint32_t strOffset = 0;
372 while (const char *s = strData.getCStr(&offset)) {
373 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
374 strOffset = offset;
375 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000376 }
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000377 if (shouldDumpDWO(DIDT_DebugStr, DObj->getStringDWOSection())) {
David Blaikie66865d62014-01-09 00:13:35 +0000378 OS << "\n.debug_str.dwo contents:\n";
Rafael Espindolac398e672017-07-19 22:27:28 +0000379 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000380 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000381 uint32_t strDWOOffset = 0;
382 while (const char *s = strDWOData.getCStr(&offset)) {
383 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
384 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000385 }
David Blaikie66865d62014-01-09 00:13:35 +0000386 }
David Blaikie622dce42014-01-08 23:29:59 +0000387
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000388 if (shouldDump(DIDT_DebugRanges, DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000389 OS << "\n.debug_ranges contents:\n";
390 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000391 // sizes, but for simplicity we just use the address byte size of the
392 // last compile unit (there is no easy and fast way to associate address
393 // range list and the compile unit it describes).
394 // FIXME: savedAddressByteSize seems sketchy.
Rafael Espindolac398e672017-07-19 22:27:28 +0000395 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
396 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000397 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000398 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000399 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000400 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000401 }
Eric Christopher962c9082013-01-15 23:56:56 +0000402
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000403 if (shouldDump(DIDT_DebugPubnames, DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000404 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000405 .dump("debug_pubnames", OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000406
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000407 if (shouldDump(DIDT_DebugPubtypes, DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000408 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
George Rimare71e33f2016-12-17 09:10:32 +0000409 .dump("debug_pubtypes", OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000410
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000411 if (shouldDump(DIDT_DebugGnuPubnames, DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000412 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000413 true /* GnuStyle */)
414 .dump("debug_gnu_pubnames", OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000415
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000416 if (shouldDump(DIDT_DebugGnuPubtypes, DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000417 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000418 true /* GnuStyle */)
419 .dump("debug_gnu_pubtypes", OS);
David Blaikie404d3042013-09-19 23:01:29 +0000420
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000421 if (shouldDump(DIDT_DebugStrOffsets, DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000422 dumpStringOffsetsSection(
423 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
424 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000425 if (shouldDumpDWO(DIDT_DebugStrOffsets,
426 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000427 dumpStringOffsetsSection(
428 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
429 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000430
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000431 if (shouldDump(DIDT_GdbIndex, DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000432 OS << "\n.gnu_index contents:\n";
433 getGdbIndex().dump(OS);
434 }
435
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000436 if (shouldDump(DIDT_AppleNames, DObj->getAppleNamesSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000437 dumpAccelSection(OS, "apple_names", *DObj, DObj->getAppleNamesSection(),
438 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000439
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000440 if (shouldDump(DIDT_AppleTypes, DObj->getAppleTypesSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000441 dumpAccelSection(OS, "apple_types", *DObj, DObj->getAppleTypesSection(),
442 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000443
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000444 if (shouldDump(DIDT_AppleNamespaces, DObj->getAppleNamespacesSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000445 dumpAccelSection(OS, "apple_namespaces", *DObj,
446 DObj->getAppleNamespacesSection(),
447 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000448
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000449 if (shouldDump(DIDT_AppleObjC, DObj->getAppleObjCSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000450 dumpAccelSection(OS, "apple_objc", *DObj, DObj->getAppleObjCSection(),
451 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000452}
453
David Blaikie15d85fc2017-05-23 06:48:53 +0000454DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000455 parseDWOCompileUnits();
456
David Blaikieebac0b92017-07-30 08:12:07 +0000457 if (const auto &CUI = getCUIndex()) {
458 if (const auto *R = CUI.getFromHash(Hash))
459 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000460 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000461 return nullptr;
462 }
463
464 // If there's no index, just search through the CUs in the DWO - there's
465 // probably only one unless this is something like LTO - though an in-process
466 // built/cached lookup table could be used in that case to improve repeated
467 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000468 for (const auto &DWOCU : dwo_compile_units())
469 if (DWOCU->getDWOId() == Hash)
470 return DWOCU.get();
471 return nullptr;
472}
473
Greg Claytonc7695a82017-05-02 20:28:33 +0000474DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
475 parseCompileUnits();
476 if (auto *CU = CUs.getUnitForOffset(Offset))
477 return CU->getDIEForOffset(Offset);
478 return DWARFDie();
479}
480
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000481bool DWARFContext::verify(raw_ostream &OS, unsigned DumpType,
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000482 DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000483 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000484 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000485
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000486 Success &= verifier.handleDebugAbbrev();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000487 if (DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000488 Success &= verifier.handleDebugInfo();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000489 if (DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000490 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000491 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000492 return Success;
493}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000494
David Blaikie82641be2015-11-17 00:39:55 +0000495const DWARFUnitIndex &DWARFContext::getCUIndex() {
496 if (CUIndex)
497 return *CUIndex;
498
Rafael Espindolac398e672017-07-19 22:27:28 +0000499 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000500
David Blaikieb073cb92015-12-02 06:21:34 +0000501 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000502 CUIndex->parse(CUIndexData);
503 return *CUIndex;
504}
505
506const DWARFUnitIndex &DWARFContext::getTUIndex() {
507 if (TUIndex)
508 return *TUIndex;
509
Rafael Espindolac398e672017-07-19 22:27:28 +0000510 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000511
David Blaikieb073cb92015-12-02 06:21:34 +0000512 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000513 TUIndex->parse(TUIndexData);
514 return *TUIndex;
515}
516
George Rimar4f82df52016-09-23 11:01:53 +0000517DWARFGdbIndex &DWARFContext::getGdbIndex() {
518 if (GdbIndex)
519 return *GdbIndex;
520
Rafael Espindolac398e672017-07-19 22:27:28 +0000521 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000522 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
523 GdbIndex->parse(GdbIndexData);
524 return *GdbIndex;
525}
526
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000527const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
528 if (Abbrev)
529 return Abbrev.get();
530
Rafael Espindolac398e672017-07-19 22:27:28 +0000531 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000532
533 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000534 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000535 return Abbrev.get();
536}
537
Eric Christopherda4b2192013-01-02 23:52:13 +0000538const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
539 if (AbbrevDWO)
540 return AbbrevDWO.get();
541
Rafael Espindolac398e672017-07-19 22:27:28 +0000542 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000543 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000544 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000545 return AbbrevDWO.get();
546}
547
David Blaikie18e73502013-06-19 21:37:13 +0000548const DWARFDebugLoc *DWARFContext::getDebugLoc() {
549 if (Loc)
550 return Loc.get();
551
Paul Robinson17536b92017-06-29 16:52:08 +0000552 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000553 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000554 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000555 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000556 getCompileUnitAtIndex(0)->getAddressByteSize());
557 Loc->parse(LocData);
558 }
David Blaikie18e73502013-06-19 21:37:13 +0000559 return Loc.get();
560}
561
David Blaikie9c550ac2014-03-25 01:44:02 +0000562const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
563 if (LocDWO)
564 return LocDWO.get();
565
Rafael Espindolac398e672017-07-19 22:27:28 +0000566 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000567 LocDWO.reset(new DWARFDebugLocDWO());
568 LocDWO->parse(LocData);
569 return LocDWO.get();
570}
571
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000572const DWARFDebugAranges *DWARFContext::getDebugAranges() {
573 if (Aranges)
574 return Aranges.get();
575
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000576 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000577 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000578 return Aranges.get();
579}
580
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000581const DWARFDebugFrame *DWARFContext::getDebugFrame() {
582 if (DebugFrame)
583 return DebugFrame.get();
584
585 // There's a "bug" in the DWARFv3 standard with respect to the target address
586 // size within debug frame sections. While DWARF is supposed to be independent
587 // of its container, FDEs have fields with size being "target address size",
588 // which isn't specified in DWARF in general. It's only specified for CUs, but
589 // .eh_frame can appear without a .debug_info section. Follow the example of
590 // other tools (libdwarf) and extract this from the container (ObjectFile
591 // provides this information). This problem is fixed in DWARFv4
592 // See this dwarf-discuss discussion for more details:
593 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000594 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
595 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000596 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
597 DebugFrame->parse(debugFrameData);
598 return DebugFrame.get();
599}
600
601const DWARFDebugFrame *DWARFContext::getEHFrame() {
602 if (EHFrame)
603 return EHFrame.get();
604
Rafael Espindolac398e672017-07-19 22:27:28 +0000605 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
606 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000607 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000608 DebugFrame->parse(debugFrameData);
609 return DebugFrame.get();
610}
611
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000612const DWARFDebugMacro *DWARFContext::getDebugMacro() {
613 if (Macro)
614 return Macro.get();
615
Rafael Espindolac398e672017-07-19 22:27:28 +0000616 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000617 Macro.reset(new DWARFDebugMacro());
618 Macro->parse(MacinfoData);
619 return Macro.get();
620}
621
Eric Christopher494109b2012-10-16 23:46:25 +0000622const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000623DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000624 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000625 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000626
Greg Claytonc8c10322016-12-13 18:25:19 +0000627 auto UnitDIE = U->getUnitDIE();
628 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000629 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000630
Greg Clayton97d22182017-01-13 21:08:18 +0000631 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000632 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000633 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000634
Greg Clayton52fe1f62016-12-14 22:38:08 +0000635 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000636 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000637 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000638 return lt;
639
Greg Clayton48ff66a2017-05-04 18:29:44 +0000640 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000641 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000642 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000643
Benjamin Kramer679e1752011-09-15 20:43:18 +0000644 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000645 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000646 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000647 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000648}
649
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000650void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000651 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000652}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000653
David Blaikie03c089c2013-09-23 22:44:47 +0000654void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000655 if (!TUs.empty())
656 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000657 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000658 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000659 TUs.back().parse(*this, S);
660 });
David Blaikie03c089c2013-09-23 22:44:47 +0000661}
662
Eric Christopherda4b2192013-01-02 23:52:13 +0000663void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000664 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000665}
666
David Blaikie92d9d622014-01-09 05:08:24 +0000667void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000668 if (!DWOTUs.empty())
669 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000670 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000671 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000672 DWOTUs.back().parseDWO(*this, S);
673 });
David Blaikie92d9d622014-01-09 05:08:24 +0000674}
675
Alexey Samsonov45be7932012-08-30 07:49:50 +0000676DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000677 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000678 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000679}
680
Alexey Samsonov45be7932012-08-30 07:49:50 +0000681DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000682 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000683 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000684 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000685 return getCompileUnitForOffset(CUOffset);
686}
687
David Blaikieefc4eba2017-02-06 20:19:02 +0000688static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
689 uint64_t Address,
690 FunctionNameKind Kind,
691 std::string &FunctionName,
692 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000693 // The address may correspond to instruction in some inlined function,
694 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000695 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000696 SmallVector<DWARFDie, 4> InlinedChain;
697 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000698 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000699 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000700
701 const DWARFDie &DIE = InlinedChain[0];
702 bool FoundResult = false;
703 const char *Name = nullptr;
704 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000705 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000706 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000707 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000708 if (auto DeclLineResult = DIE.getDeclLine()) {
709 StartLine = DeclLineResult;
710 FoundResult = true;
711 }
712
713 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000714}
715
Alexey Samsonov45be7932012-08-30 07:49:50 +0000716DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000717 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000718 DILineInfo Result;
719
Alexey Samsonov45be7932012-08-30 07:49:50 +0000720 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
721 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000722 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000723 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
724 Result.FunctionName,
725 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000726 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000727 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
728 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
729 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000730 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000731 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000732}
David Blaikiea379b1812011-12-20 02:50:00 +0000733
Alexey Samsonovdce67342014-05-15 21:24:32 +0000734DILineInfoTable
735DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
736 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000737 DILineInfoTable Lines;
738 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
739 if (!CU)
740 return Lines;
741
742 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000743 uint32_t StartLine = 0;
744 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
745 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000746
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000747 // If the Specifier says we don't need FileLineInfo, just
748 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000749 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000750 DILineInfo Result;
751 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000752 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000753 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000754 return Lines;
755 }
756
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000757 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000758
759 // Get the index of row we're looking for in the line table.
760 std::vector<uint32_t> RowVector;
761 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
762 return Lines;
763
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000764 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000765 // Take file number and line/column from the row.
766 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000767 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000768 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
769 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000770 Result.FunctionName = FunctionName;
771 Result.Line = Row.Line;
772 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000773 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000774 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000775 }
776
777 return Lines;
778}
779
Alexey Samsonovdce67342014-05-15 21:24:32 +0000780DIInliningInfo
781DWARFContext::getInliningInfoForAddress(uint64_t Address,
782 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000783 DIInliningInfo InliningInfo;
784
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000785 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
786 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000787 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000788
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000789 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000790 SmallVector<DWARFDie, 4> InlinedChain;
791 CU->getInlinedChainForAddress(Address, InlinedChain);
792 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000793 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
794 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000795 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000796 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000797 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000798 if (LineTable &&
799 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
800 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000801 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000802 }
803 return InliningInfo;
804 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000805
Dehao Chenef700d52017-04-17 20:10:39 +0000806 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000807 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
808 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000809 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000810 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000811 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000812 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000813 if (auto DeclLineResult = FunctionDIE.getDeclLine())
814 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000815 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000816 if (i == 0) {
817 // For the topmost frame, initialize the line table of this
818 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000819 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000820 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000821 if (LineTable)
822 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
823 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000824 } else {
825 // Otherwise, use call file, call line and call column from
826 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000827 if (LineTable)
828 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
829 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000830 Frame.Line = CallLine;
831 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000832 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000833 }
834 // Get call file/line/column of a current DIE.
835 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000836 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
837 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000838 }
839 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000840 InliningInfo.addFrame(Frame);
841 }
842 return InliningInfo;
843}
844
David Blaikief9803fb2017-05-23 00:30:42 +0000845std::shared_ptr<DWARFContext>
846DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000847 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000848 DWARFContext *Ctxt = S->Context.get();
849 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
850 }
851
David Blaikie15d85fc2017-05-23 06:48:53 +0000852 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
853
854 if (auto S = Entry->lock()) {
855 DWARFContext *Ctxt = S->Context.get();
856 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
857 }
858
David Blaikie15d85fc2017-05-23 06:48:53 +0000859 Expected<OwningBinary<ObjectFile>> Obj = [&] {
860 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000861 SmallString<128> DWPName;
862 auto Obj = object::ObjectFile::createObjectFile(
863 this->DWPName.empty()
864 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
865 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000866 if (Obj) {
867 Entry = &DWP;
868 return Obj;
869 } else {
870 CheckedForDWP = true;
871 // TODO: Should this error be handled (maybe in a high verbosity mode)
872 // before falling back to .dwo files?
873 consumeError(Obj.takeError());
874 }
875 }
876
877 return object::ObjectFile::createObjectFile(AbsolutePath);
878 }();
879
David Blaikief9803fb2017-05-23 00:30:42 +0000880 if (!Obj) {
881 // TODO: Actually report errors helpfully.
882 consumeError(Obj.takeError());
883 return nullptr;
884 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000885
886 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000887 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000888 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000889 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000890 auto *Ctxt = S->Context.get();
891 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
892}
893
George Rimar702dac62017-04-12 08:59:15 +0000894static Error createError(const Twine &Reason, llvm::Error E) {
895 return make_error<StringError>(Reason + toString(std::move(E)),
896 inconvertibleErrorCode());
897}
898
George Rimara25d3292017-05-27 18:10:23 +0000899/// SymInfo contains information about symbol: it's address
900/// and section index which is -1LL for absolute symbols.
901struct SymInfo {
902 uint64_t Address;
903 uint64_t SectionIndex;
904};
905
906/// Returns the address of symbol relocation used against and a section index.
907/// Used for futher relocations computation. Symbol's section load address is
908static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
909 const RelocationRef &Reloc,
910 const LoadedObjectInfo *L,
911 std::map<SymbolRef, SymInfo> &Cache) {
912 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000913 object::section_iterator RSec = Obj.section_end();
914 object::symbol_iterator Sym = Reloc.getSymbol();
915
George Rimara25d3292017-05-27 18:10:23 +0000916 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000917 // First calculate the address of the symbol or section as it appears
918 // in the object file
919 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000920 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000921 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000922 if (!New)
923 return CacheIt->second;
924
George Rimar702dac62017-04-12 08:59:15 +0000925 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
926 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000927 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000928 SymAddrOrErr.takeError());
929
930 // Also remember what section this symbol is in for later
931 auto SectOrErr = Sym->getSection();
932 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000933 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000934 SectOrErr.takeError());
935
936 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000937 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000938 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
939 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000940 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000941 }
942
George Rimara25d3292017-05-27 18:10:23 +0000943 if (RSec != Obj.section_end())
944 Ret.SectionIndex = RSec->getIndex();
945
George Rimar702dac62017-04-12 08:59:15 +0000946 // If we are given load addresses for the sections, we need to adjust:
947 // SymAddr = (Address of Symbol Or Section in File) -
948 // (Address of Section in File) +
949 // (Load Address of Section)
950 // RSec is now either the section being targeted or the section
951 // containing the symbol being targeted. In either case,
952 // we need to perform the same computation.
953 if (L && RSec != Obj.section_end())
954 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000955 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000956
957 if (CacheIt != Cache.end())
958 CacheIt->second = Ret;
959
George Rimar702dac62017-04-12 08:59:15 +0000960 return Ret;
961}
962
963static bool isRelocScattered(const object::ObjectFile &Obj,
964 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000965 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
966 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000967 return false;
968 // MachO also has relocations that point to sections and
969 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000970 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
971 return MachObj->isRelocationScattered(RelocInfo);
972}
973
Rafael Espindolac398e672017-07-19 22:27:28 +0000974ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000975 errs() << "error: " + toString(std::move(E)) << '\n';
976 return ErrorPolicy::Continue;
977}
978
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000979namespace {
980struct DWARFSectionMap final : public DWARFSection {
981 RelocAddrMap Relocs;
982};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000983
Rafael Espindolac398e672017-07-19 22:27:28 +0000984class DWARFObjInMemory final : public DWARFObject {
985 bool IsLittleEndian;
986 uint8_t AddressSize;
987 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +0000988 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +0000989 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +0000990
Rafael Espindolac398e672017-07-19 22:27:28 +0000991 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
992 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +0000993
Rafael Espindolac398e672017-07-19 22:27:28 +0000994 TypeSectionMap TypesSections;
995 TypeSectionMap TypesDWOSections;
996
997 DWARFSectionMap InfoSection;
998 DWARFSectionMap LocSection;
999 DWARFSectionMap LineSection;
1000 DWARFSectionMap RangeSection;
1001 DWARFSectionMap StringOffsetSection;
1002 DWARFSectionMap InfoDWOSection;
1003 DWARFSectionMap LineDWOSection;
1004 DWARFSectionMap LocDWOSection;
1005 DWARFSectionMap StringOffsetDWOSection;
1006 DWARFSectionMap RangeDWOSection;
1007 DWARFSectionMap AddrSection;
1008 DWARFSectionMap AppleNamesSection;
1009 DWARFSectionMap AppleTypesSection;
1010 DWARFSectionMap AppleNamespacesSection;
1011 DWARFSectionMap AppleObjCSection;
1012
1013 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1014 return StringSwitch<DWARFSectionMap *>(Name)
1015 .Case("debug_info", &InfoSection)
1016 .Case("debug_loc", &LocSection)
1017 .Case("debug_line", &LineSection)
1018 .Case("debug_str_offsets", &StringOffsetSection)
1019 .Case("debug_ranges", &RangeSection)
1020 .Case("debug_info.dwo", &InfoDWOSection)
1021 .Case("debug_loc.dwo", &LocDWOSection)
1022 .Case("debug_line.dwo", &LineDWOSection)
1023 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1024 .Case("debug_addr", &AddrSection)
1025 .Case("apple_names", &AppleNamesSection)
1026 .Case("apple_types", &AppleTypesSection)
1027 .Case("apple_namespaces", &AppleNamespacesSection)
1028 .Case("apple_namespac", &AppleNamespacesSection)
1029 .Case("apple_objc", &AppleObjCSection)
1030 .Default(nullptr);
1031 }
1032
1033 StringRef AbbrevSection;
1034 StringRef ARangeSection;
1035 StringRef DebugFrameSection;
1036 StringRef EHFrameSection;
1037 StringRef StringSection;
1038 StringRef MacinfoSection;
1039 StringRef PubNamesSection;
1040 StringRef PubTypesSection;
1041 StringRef GnuPubNamesSection;
1042 StringRef AbbrevDWOSection;
1043 StringRef StringDWOSection;
1044 StringRef GnuPubTypesSection;
1045 StringRef CUIndexSection;
1046 StringRef GdbIndexSection;
1047 StringRef TUIndexSection;
1048
1049 SmallVector<SmallString<32>, 4> UncompressedSections;
1050
1051 StringRef *mapSectionToMember(StringRef Name) {
1052 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1053 return &Sec->Data;
1054 return StringSwitch<StringRef *>(Name)
1055 .Case("debug_abbrev", &AbbrevSection)
1056 .Case("debug_aranges", &ARangeSection)
1057 .Case("debug_frame", &DebugFrameSection)
1058 .Case("eh_frame", &EHFrameSection)
1059 .Case("debug_str", &StringSection)
1060 .Case("debug_macinfo", &MacinfoSection)
1061 .Case("debug_pubnames", &PubNamesSection)
1062 .Case("debug_pubtypes", &PubTypesSection)
1063 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1064 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1065 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1066 .Case("debug_str.dwo", &StringDWOSection)
1067 .Case("debug_cu_index", &CUIndexSection)
1068 .Case("debug_tu_index", &TUIndexSection)
1069 .Case("gdb_index", &GdbIndexSection)
1070 // Any more debug info sections go here.
1071 .Default(nullptr);
1072 }
1073
1074 /// If Sec is compressed section, decompresses and updates its contents
1075 /// provided by Data. Otherwise leaves it unchanged.
1076 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1077 StringRef &Data) {
1078 if (!Decompressor::isCompressed(Sec))
1079 return Error::success();
1080
1081 Expected<Decompressor> Decompressor =
1082 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1083 if (!Decompressor)
1084 return Decompressor.takeError();
1085
1086 SmallString<32> Out;
1087 if (auto Err = Decompressor->resizeAndDecompress(Out))
1088 return Err;
1089
1090 UncompressedSections.emplace_back(std::move(Out));
1091 Data = UncompressedSections.back();
1092
1093 return Error::success();
1094 }
1095
1096public:
1097 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1098 uint8_t AddrSize, bool IsLittleEndian)
1099 : IsLittleEndian(IsLittleEndian) {
1100 for (const auto &SecIt : Sections) {
1101 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1102 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001103 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001104 }
1105 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1106 function_ref<ErrorPolicy(Error)> HandleError)
1107 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001108 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1109 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001110
George Rimare1c30f72017-08-15 15:54:43 +00001111 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001112 for (const SectionRef &Section : Obj.sections()) {
1113 StringRef Name;
1114 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001115 ++SectionAmountMap[Name];
1116 SectionNames.push_back({ Name, true });
1117
Rafael Espindolac398e672017-07-19 22:27:28 +00001118 // Skip BSS and Virtual sections, they aren't interesting.
1119 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001120 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001121
Rafael Espindolac398e672017-07-19 22:27:28 +00001122 StringRef Data;
1123 section_iterator RelocatedSection = Section.getRelocatedSection();
1124 // Try to obtain an already relocated version of this section.
1125 // Else use the unrelocated section from the object file. We'll have to
1126 // apply relocations ourselves later.
1127 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1128 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001129
Rafael Espindolac398e672017-07-19 22:27:28 +00001130 if (auto Err = maybeDecompress(Section, Name, Data)) {
1131 ErrorPolicy EP = HandleError(createError(
1132 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001133 if (EP == ErrorPolicy::Halt)
1134 return;
George Rimarfed9f092017-05-17 12:10:51 +00001135 continue;
1136 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001137
1138 // Compressed sections names in GNU style starts from ".z",
1139 // at this point section is decompressed and we drop compression prefix.
1140 Name = Name.substr(
1141 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1142
1143 // Map platform specific debug section names to DWARF standard section
1144 // names.
1145 Name = Obj.mapDebugSectionName(Name);
1146
1147 if (StringRef *SectionData = mapSectionToMember(Name)) {
1148 *SectionData = Data;
1149 if (Name == "debug_ranges") {
1150 // FIXME: Use the other dwo range section when we emit it.
1151 RangeDWOSection.Data = Data;
1152 }
1153 } else if (Name == "debug_types") {
1154 // Find debug_types data by section rather than name as there are
1155 // multiple, comdat grouped, debug_types sections.
1156 TypesSections[Section].Data = Data;
1157 } else if (Name == "debug_types.dwo") {
1158 TypesDWOSections[Section].Data = Data;
1159 }
1160
1161 if (RelocatedSection == Obj.section_end())
1162 continue;
1163
1164 StringRef RelSecName;
1165 StringRef RelSecData;
1166 RelocatedSection->getName(RelSecName);
1167
1168 // If the section we're relocating was relocated already by the JIT,
1169 // then we used the relocated version above, so we do not need to process
1170 // relocations for it now.
1171 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1172 continue;
1173
1174 // In Mach-o files, the relocations do not need to be applied if
1175 // there is no load offset to apply. The value read at the
1176 // relocation point already factors in the section address
1177 // (actually applying the relocations will produce wrong results
1178 // as the section address will be added twice).
1179 if (!L && isa<MachOObjectFile>(&Obj))
1180 continue;
1181
1182 RelSecName = RelSecName.substr(
1183 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1184
1185 // TODO: Add support for relocations in other sections as needed.
1186 // Record relocations for the debug_info and debug_line sections.
1187 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1188 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1189 if (!Map) {
1190 // Find debug_types relocs by section rather than name as there are
1191 // multiple, comdat grouped, debug_types sections.
1192 if (RelSecName == "debug_types")
1193 Map =
1194 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1195 .Relocs;
1196 else if (RelSecName == "debug_types.dwo")
1197 Map = &static_cast<DWARFSectionMap &>(
1198 TypesDWOSections[*RelocatedSection])
1199 .Relocs;
1200 else
1201 continue;
1202 }
1203
1204 if (Section.relocation_begin() == Section.relocation_end())
1205 continue;
1206
1207 // Symbol to [address, section index] cache mapping.
1208 std::map<SymbolRef, SymInfo> AddrCache;
1209 for (const RelocationRef &Reloc : Section.relocations()) {
1210 // FIXME: it's not clear how to correctly handle scattered
1211 // relocations.
1212 if (isRelocScattered(Obj, Reloc))
1213 continue;
1214
1215 Expected<SymInfo> SymInfoOrErr =
1216 getSymbolInfo(Obj, Reloc, L, AddrCache);
1217 if (!SymInfoOrErr) {
1218 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1219 return;
1220 continue;
1221 }
1222
1223 object::RelocVisitor V(Obj);
1224 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1225 if (V.error()) {
1226 SmallString<32> Type;
1227 Reloc.getTypeName(Type);
1228 ErrorPolicy EP = HandleError(
1229 createError("failed to compute relocation: " + Type + ", ",
1230 errorCodeToError(object_error::parse_failed)));
1231 if (EP == ErrorPolicy::Halt)
1232 return;
1233 continue;
1234 }
1235 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1236 Map->insert({Reloc.getOffset(), Rel});
1237 }
Eric Christopher7370b552012-11-12 21:40:38 +00001238 }
George Rimare1c30f72017-08-15 15:54:43 +00001239
1240 for (SectionName &S : SectionNames)
1241 if (SectionAmountMap[S.Name] > 1)
1242 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001243 }
Eric Christopher7370b552012-11-12 21:40:38 +00001244
Rafael Espindolac398e672017-07-19 22:27:28 +00001245 Optional<RelocAddrEntry> find(const DWARFSection &S,
1246 uint64_t Pos) const override {
1247 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1248 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1249 if (AI == Sec.Relocs.end())
1250 return None;
1251 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001252 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001253
George Rimar6957ab52017-08-15 12:32:54 +00001254 const object::ObjectFile *getFile() const override { return Obj; }
1255
George Rimare1c30f72017-08-15 15:54:43 +00001256 ArrayRef<SectionName> getSectionNames() const override {
1257 return SectionNames;
1258 }
1259
Rafael Espindolac398e672017-07-19 22:27:28 +00001260 bool isLittleEndian() const override { return IsLittleEndian; }
1261 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1262 const DWARFSection &getLineDWOSection() const override {
1263 return LineDWOSection;
1264 }
1265 const DWARFSection &getLocDWOSection() const override {
1266 return LocDWOSection;
1267 }
1268 StringRef getStringDWOSection() const override { return StringDWOSection; }
1269 const DWARFSection &getStringOffsetDWOSection() const override {
1270 return StringOffsetDWOSection;
1271 }
1272 const DWARFSection &getRangeDWOSection() const override {
1273 return RangeDWOSection;
1274 }
1275 const DWARFSection &getAddrSection() const override { return AddrSection; }
1276 StringRef getCUIndexSection() const override { return CUIndexSection; }
1277 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1278 StringRef getTUIndexSection() const override { return TUIndexSection; }
1279
1280 // DWARF v5
1281 const DWARFSection &getStringOffsetSection() const override {
1282 return StringOffsetSection;
1283 }
1284
1285 // Sections for DWARF5 split dwarf proposal.
1286 const DWARFSection &getInfoDWOSection() const override {
1287 return InfoDWOSection;
1288 }
1289 void forEachTypesDWOSections(
1290 function_ref<void(const DWARFSection &)> F) const override {
1291 for (auto &P : TypesDWOSections)
1292 F(P.second);
1293 }
1294
1295 StringRef getAbbrevSection() const override { return AbbrevSection; }
1296 const DWARFSection &getLocSection() const override { return LocSection; }
1297 StringRef getARangeSection() const override { return ARangeSection; }
1298 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1299 StringRef getEHFrameSection() const override { return EHFrameSection; }
1300 const DWARFSection &getLineSection() const override { return LineSection; }
1301 StringRef getStringSection() const override { return StringSection; }
1302 const DWARFSection &getRangeSection() const override { return RangeSection; }
1303 StringRef getMacinfoSection() const override { return MacinfoSection; }
1304 StringRef getPubNamesSection() const override { return PubNamesSection; }
1305 StringRef getPubTypesSection() const override { return PubTypesSection; }
1306 StringRef getGnuPubNamesSection() const override {
1307 return GnuPubNamesSection;
1308 }
1309 StringRef getGnuPubTypesSection() const override {
1310 return GnuPubTypesSection;
1311 }
1312 const DWARFSection &getAppleNamesSection() const override {
1313 return AppleNamesSection;
1314 }
1315 const DWARFSection &getAppleTypesSection() const override {
1316 return AppleTypesSection;
1317 }
1318 const DWARFSection &getAppleNamespacesSection() const override {
1319 return AppleNamespacesSection;
1320 }
1321 const DWARFSection &getAppleObjCSection() const override {
1322 return AppleObjCSection;
1323 }
1324
1325 StringRef getFileName() const override { return FileName; }
1326 uint8_t getAddressSize() const override { return AddressSize; }
1327 const DWARFSection &getInfoSection() const override { return InfoSection; }
1328 void forEachTypesSections(
1329 function_ref<void(const DWARFSection &)> F) const override {
1330 for (auto &P : TypesSections)
1331 F(P.second);
1332 }
1333};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001334} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001335
1336std::unique_ptr<DWARFContext>
1337DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001338 function_ref<ErrorPolicy(Error)> HandleError,
1339 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001340 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001341 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001342}
1343
Rafael Espindolac398e672017-07-19 22:27:28 +00001344std::unique_ptr<DWARFContext>
1345DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1346 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001347 auto DObj =
1348 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001349 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001350}
Reid Klecknera0587362017-08-29 21:41:21 +00001351
1352Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1353 // Detect the architecture from the object file. We usually don't need OS
1354 // info to lookup a target and create register info.
1355 Triple TT;
1356 TT.setArch(Triple::ArchType(Obj.getArch()));
1357 TT.setVendor(Triple::UnknownVendor);
1358 TT.setOS(Triple::UnknownOS);
1359 std::string TargetLookupError;
1360 const Target *TheTarget =
1361 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1362 if (!TargetLookupError.empty())
1363 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1364 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1365 return Error::success();
1366}