blob: 02d37f21c38b5365b5d1dfd065244d1e0d42a749 [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
Adrian Prantl84168022017-09-15 17:39:50 +000071static void dumpAccelSection(raw_ostream &OS, const DWARFObject &Obj,
Rafael Espindolac398e672017-07-19 22:27:28 +000072 const DWARFSection &Section,
73 StringRef StringSection, bool LittleEndian) {
74 DWARFDataExtractor AccelSection(Obj, Section, LittleEndian, 0);
Frederic Risse837ec22014-11-14 16:15:53 +000075 DataExtractor StrData(StringSection, LittleEndian, 0);
Paul Robinson17536b92017-06-29 16:52:08 +000076 DWARFAcceleratorTable Accel(AccelSection, StrData);
Frederic Risse837ec22014-11-14 16:15:53 +000077 if (!Accel.extract())
78 return;
79 Accel.dump(OS);
80}
81
Adrian Prantl3dcd1222017-09-13 18:22:59 +000082/// Dump the UUID load command.
83static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
84 auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
85 if (!MachO)
86 return;
87 for (auto LC : MachO->load_commands()) {
88 raw_ostream::uuid_t UUID;
89 if (LC.C.cmd == MachO::LC_UUID) {
90 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
91 OS << "error: UUID load command is too short.\n";
92 return;
93 }
94 OS << "UUID: ";
95 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
96 OS.write_uuid(UUID);
97 OS << ' ' << MachO->getFileFormatName();
98 OS << ' ' << MachO->getFileName() << '\n';
99 }
100 }
101}
102
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000103static void
104dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000105 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000106 const DWARFSection &StringOffsetsSection,
107 StringRef StringSection, bool LittleEndian) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000108 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000109 uint32_t Offset = 0;
110 uint64_t SectionSize = StringOffsetsSection.Data.size();
111
112 while (Offset < SectionSize) {
113 unsigned Version = 0;
114 DwarfFormat Format = DWARF32;
115 unsigned EntrySize = 4;
116 // Perform validation and extract the segment size from the header.
117 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 4)) {
118 OS << "error: invalid contribution to string offsets table in section ."
119 << SectionName << ".\n";
120 return;
121 }
122 uint32_t ContributionStart = Offset;
123 uint64_t ContributionSize = StrOffsetExt.getU32(&Offset);
124 // A contribution size of 0xffffffff indicates DWARF64, with the actual size
125 // in the following 8 bytes. Otherwise, the DWARF standard mandates that
126 // the contribution size must be at most 0xfffffff0.
127 if (ContributionSize == 0xffffffff) {
128 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, 8)) {
129 OS << "error: invalid contribution to string offsets table in section ."
130 << SectionName << ".\n";
131 return;
132 }
133 Format = DWARF64;
134 EntrySize = 8;
135 ContributionSize = StrOffsetExt.getU64(&Offset);
136 } else if (ContributionSize > 0xfffffff0) {
137 OS << "error: invalid contribution to string offsets table in section ."
138 << SectionName << ".\n";
139 return;
140 }
141
142 // We must ensure that we don't read a partial record at the end, so we
143 // validate for a multiple of EntrySize. Also, we're expecting a version
144 // number and padding, which adds an additional 4 bytes.
145 uint64_t ValidationSize =
146 4 + ((ContributionSize + EntrySize - 1) & (-(uint64_t)EntrySize));
147 if (!StrOffsetExt.isValidOffsetForDataOfSize(Offset, ValidationSize)) {
148 OS << "error: contribution to string offsets table in section ."
149 << SectionName << " has invalid length.\n";
150 return;
151 }
152
153 Version = StrOffsetExt.getU16(&Offset);
154 Offset += 2;
155 OS << format("0x%8.8x: ", ContributionStart);
156 OS << "Contribution size = " << ContributionSize
157 << ", Version = " << Version << "\n";
158
159 uint32_t ContributionBase = Offset;
160 DataExtractor StrData(StringSection, LittleEndian, 0);
161 while (Offset - ContributionBase < ContributionSize) {
162 OS << format("0x%8.8x: ", Offset);
163 // FIXME: We can only extract strings in DWARF32 format at the moment.
Paul Robinson17536b92017-06-29 16:52:08 +0000164 uint64_t StringOffset =
165 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000166 if (Format == DWARF32) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000167 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000168 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000169 const char *S = StrData.getCStr(&StringOffset32);
170 if (S)
171 OS << format("\"%s\"", S);
172 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000173 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000174 OS << "\n";
175 }
176 }
177}
178
179// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
180// string offsets section, where each compile or type unit contributes a
181// number of entries (string offsets), with each contribution preceded by
182// a header containing size and version number. Alternatively, it may be a
183// monolithic series of string offsets, as generated by the pre-DWARF v5
184// implementation of split DWARF.
185static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
Rafael Espindolac398e672017-07-19 22:27:28 +0000186 const DWARFObject &Obj,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000187 const DWARFSection &StringOffsetsSection,
188 StringRef StringSection, bool LittleEndian,
189 unsigned MaxVersion) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000190 // If we have at least one (compile or type) unit with DWARF v5 or greater,
191 // we assume that the section is formatted like a DWARF v5 string offsets
192 // section.
193 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000194 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000195 StringSection, LittleEndian);
196 else {
197 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
198 uint32_t offset = 0;
199 uint64_t size = StringOffsetsSection.Data.size();
200 // Ensure that size is a multiple of the size of an entry.
201 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
202 OS << "error: size of ." << SectionName << " is not a multiple of "
203 << sizeof(uint32_t) << ".\n";
204 size &= -(uint64_t)sizeof(uint32_t);
205 }
206 DataExtractor StrData(StringSection, LittleEndian, 0);
207 while (offset < size) {
208 OS << format("0x%8.8x: ", offset);
209 uint32_t StringOffset = strOffsetExt.getU32(&offset);
210 OS << format("%8.8x ", StringOffset);
211 const char *S = StrData.getCStr(&StringOffset);
212 if (S)
213 OS << format("\"%s\"", S);
214 OS << "\n";
215 }
216 }
217}
218
Adrian Prantl057d3362017-09-15 23:04:04 +0000219void DWARFContext::dump(
220 raw_ostream &OS, DIDumpOptions DumpOpts,
221 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
222
223 Optional<uint64_t> DumpOffset;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000224 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000225 bool DumpEH = DumpOpts.DumpEH;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000226
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000227 StringRef Extension = sys::path::extension(DObj->getFileName());
228 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
229
230 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000231 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000232 if (DumpType & DIDT_UUID)
233 dumpUUID(OS, *ObjFile);
234
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000235 // Print a header for each explicitly-requested section.
236 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000237 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000238 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000239 bool ExplicitDWO = Explicit && IsDWO;
240 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
241 StringRef Section) {
242 DumpOffset = DumpOffsets[ID];
243 unsigned Mask = 1U << ID;
244 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
Adrian Prantl84168022017-09-15 17:39:50 +0000245 if (Should)
Adrian Prantl057d3362017-09-15 23:04:04 +0000246 OS << "\n" << Name << " contents:\n";
Adrian Prantl84168022017-09-15 17:39:50 +0000247 return Should;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000248 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000249
250 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000251 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
252 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000253 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000254 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
255 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000256 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000257
Adrian Prantl057d3362017-09-15 23:04:04 +0000258 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
259 DWARFSection Section, cu_iterator_range CUs) {
260 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
261 for (const auto &CU : CUs)
262 if (DumpOffset)
263 CU->getDIEForOffset(DumpOffset.getValue()).dump(OS, 0);
264 else
265 CU->dump(OS, DumpOpts);
266 }
267 };
268 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
269 compile_units());
270 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
271 dwo_compile_units());
David Blaikie622dce42014-01-08 23:29:59 +0000272
Adrian Prantl099d7e42017-09-16 16:58:18 +0000273 auto dumpDebugType = [&](const char *Name,
274 tu_section_iterator_range TUSections) {
275 OS << '\n' << Name << " contents:\n";
276 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
277 for (const auto &TUS : TUSections)
278 for (const auto &TU : TUS)
279 if (DumpOffset)
280 TU->getDIEForOffset(*DumpOffset).dump(OS, 0);
281 else
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000282 TU->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000283 };
284 if ((DumpType & DIDT_DebugTypes)) {
285 if (Explicit || getNumTypeUnits())
286 dumpDebugType(".debug_types", type_unit_sections());
287 if (ExplicitDWO || getNumDWOTypeUnits())
288 dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
David Blaikie03c089c2013-09-23 22:44:47 +0000289 }
290
Adrian Prantl057d3362017-09-15 23:04:04 +0000291 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000292 DObj->getLocSection().Data)) {
Reid Klecknera0587362017-08-29 21:41:21 +0000293 getDebugLoc()->dump(OS, getRegisterInfo());
David Blaikie18e73502013-06-19 21:37:13 +0000294 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000295 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000296 DObj->getLocDWOSection().Data)) {
Reid Klecknera0587362017-08-29 21:41:21 +0000297 getDebugLocDWO()->dump(OS, getRegisterInfo());
David Blaikie9c550ac2014-03-25 01:44:02 +0000298 }
299
Adrian Prantl057d3362017-09-15 23:04:04 +0000300 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrames,
Adrian Prantl84168022017-09-15 17:39:50 +0000301 DObj->getDebugFrameSection())) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000302 getDebugFrame()->dump(OS);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000303 }
304 if (DumpEH && !getEHFrame()->empty()) {
305 OS << "\n.eh_frame contents:\n";
306 getEHFrame()->dump(OS);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000307 }
308
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000309 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000310 if (Explicit || !getDebugMacro()->empty()) {
311 OS << "\n.debug_macinfo contents:\n";
312 getDebugMacro()->dump(OS);
313 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000314 }
315
Adrian Prantl057d3362017-09-15 23:04:04 +0000316 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000317 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000318 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000319 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000320 DWARFDebugArangeSet set;
321 while (set.extract(arangesData, &offset))
322 set.dump(OS);
323 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000324
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000325 uint8_t savedAddressByteSize = 0;
Adrian Prantl057d3362017-09-15 23:04:04 +0000326 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000327 DObj->getLineSection().Data)) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000328 for (const auto &CU : compile_units()) {
329 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000330 auto CUDIE = CU->getUnitDIE();
331 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000332 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000333 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000334 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
335 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000336 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000337 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000338 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000339 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000340 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000341 }
342 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000343
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000344 // FIXME: This seems sketchy.
345 for (const auto &CU : compile_units()) {
346 savedAddressByteSize = CU->getAddressByteSize();
347 break;
David Blaikie65a8efe2015-11-11 19:28:21 +0000348 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000349 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000350 DObj->getLineDWOSection().Data)) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000351 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000352 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
353 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000354 DWARFDebugLine::LineTable LineTable;
355 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
356 LineTable.dump(OS);
357 LineTable.clear();
358 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000359 }
360
Adrian Prantl057d3362017-09-15 23:04:04 +0000361 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000362 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000363 getCUIndex().dump(OS);
364 }
365
Adrian Prantl057d3362017-09-15 23:04:04 +0000366 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000367 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000368 getTUIndex().dump(OS);
369 }
370
Adrian Prantl057d3362017-09-15 23:04:04 +0000371 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000372 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000373 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000374 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000375 uint32_t strOffset = 0;
376 while (const char *s = strData.getCStr(&offset)) {
377 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
378 strOffset = offset;
379 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000380 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000381 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000382 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000383 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000384 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000385 uint32_t strDWOOffset = 0;
386 while (const char *s = strDWOData.getCStr(&offset)) {
387 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
388 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000389 }
David Blaikie66865d62014-01-09 00:13:35 +0000390 }
David Blaikie622dce42014-01-08 23:29:59 +0000391
Adrian Prantl057d3362017-09-15 23:04:04 +0000392 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000393 DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000394 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000395 // sizes, but for simplicity we just use the address byte size of the
396 // last compile unit (there is no easy and fast way to associate address
397 // range list and the compile unit it describes).
398 // FIXME: savedAddressByteSize seems sketchy.
Rafael Espindolac398e672017-07-19 22:27:28 +0000399 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
400 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000401 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000402 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000403 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000404 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000405 }
Eric Christopher962c9082013-01-15 23:56:56 +0000406
Adrian Prantl057d3362017-09-15 23:04:04 +0000407 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000408 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000409 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000410 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000411
Adrian Prantl057d3362017-09-15 23:04:04 +0000412 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000413 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000414 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000415 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000416
Adrian Prantl057d3362017-09-15 23:04:04 +0000417 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000418 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000419 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000420 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000421 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000422
Adrian Prantl057d3362017-09-15 23:04:04 +0000423 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000424 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000425 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000426 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000427 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000428
Adrian Prantl057d3362017-09-15 23:04:04 +0000429 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000430 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000431 dumpStringOffsetsSection(
432 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
433 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000434 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000435 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000436 dumpStringOffsetsSection(
437 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
438 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000439
Adrian Prantl057d3362017-09-15 23:04:04 +0000440 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000441 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000442 getGdbIndex().dump(OS);
443 }
444
Adrian Prantl057d3362017-09-15 23:04:04 +0000445 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000446 DObj->getAppleNamesSection().Data))
447 dumpAccelSection(OS, *DObj, DObj->getAppleNamesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000448 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000449
Adrian Prantl057d3362017-09-15 23:04:04 +0000450 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000451 DObj->getAppleTypesSection().Data))
452 dumpAccelSection(OS, *DObj, DObj->getAppleTypesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000453 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000454
Adrian Prantl057d3362017-09-15 23:04:04 +0000455 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000456 DObj->getAppleNamespacesSection().Data))
457 dumpAccelSection(OS, *DObj, DObj->getAppleNamespacesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000458 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000459
Adrian Prantl057d3362017-09-15 23:04:04 +0000460 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000461 DObj->getAppleObjCSection().Data))
462 dumpAccelSection(OS, *DObj, DObj->getAppleObjCSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000463 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000464}
465
David Blaikie15d85fc2017-05-23 06:48:53 +0000466DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000467 parseDWOCompileUnits();
468
David Blaikieebac0b92017-07-30 08:12:07 +0000469 if (const auto &CUI = getCUIndex()) {
470 if (const auto *R = CUI.getFromHash(Hash))
471 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000472 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000473 return nullptr;
474 }
475
476 // If there's no index, just search through the CUs in the DWO - there's
477 // probably only one unless this is something like LTO - though an in-process
478 // built/cached lookup table could be used in that case to improve repeated
479 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000480 for (const auto &DWOCU : dwo_compile_units())
481 if (DWOCU->getDWOId() == Hash)
482 return DWOCU.get();
483 return nullptr;
484}
485
Greg Claytonc7695a82017-05-02 20:28:33 +0000486DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
487 parseCompileUnits();
488 if (auto *CU = CUs.getUnitForOffset(Offset))
489 return CU->getDIEForOffset(Offset);
490 return DWARFDie();
491}
492
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000493bool DWARFContext::verify(raw_ostream &OS, unsigned DumpType,
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000494 DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000495 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000496 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000497
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000498 Success &= verifier.handleDebugAbbrev();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000499 if (DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000500 Success &= verifier.handleDebugInfo();
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000501 if (DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000502 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000503 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000504 return Success;
505}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000506
David Blaikie82641be2015-11-17 00:39:55 +0000507const DWARFUnitIndex &DWARFContext::getCUIndex() {
508 if (CUIndex)
509 return *CUIndex;
510
Rafael Espindolac398e672017-07-19 22:27:28 +0000511 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000512
David Blaikieb073cb92015-12-02 06:21:34 +0000513 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000514 CUIndex->parse(CUIndexData);
515 return *CUIndex;
516}
517
518const DWARFUnitIndex &DWARFContext::getTUIndex() {
519 if (TUIndex)
520 return *TUIndex;
521
Rafael Espindolac398e672017-07-19 22:27:28 +0000522 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000523
David Blaikieb073cb92015-12-02 06:21:34 +0000524 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000525 TUIndex->parse(TUIndexData);
526 return *TUIndex;
527}
528
George Rimar4f82df52016-09-23 11:01:53 +0000529DWARFGdbIndex &DWARFContext::getGdbIndex() {
530 if (GdbIndex)
531 return *GdbIndex;
532
Rafael Espindolac398e672017-07-19 22:27:28 +0000533 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000534 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
535 GdbIndex->parse(GdbIndexData);
536 return *GdbIndex;
537}
538
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000539const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
540 if (Abbrev)
541 return Abbrev.get();
542
Rafael Espindolac398e672017-07-19 22:27:28 +0000543 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000544
545 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000546 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000547 return Abbrev.get();
548}
549
Eric Christopherda4b2192013-01-02 23:52:13 +0000550const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
551 if (AbbrevDWO)
552 return AbbrevDWO.get();
553
Rafael Espindolac398e672017-07-19 22:27:28 +0000554 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000555 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000556 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000557 return AbbrevDWO.get();
558}
559
David Blaikie18e73502013-06-19 21:37:13 +0000560const DWARFDebugLoc *DWARFContext::getDebugLoc() {
561 if (Loc)
562 return Loc.get();
563
Paul Robinson17536b92017-06-29 16:52:08 +0000564 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000565 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000566 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000567 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000568 getCompileUnitAtIndex(0)->getAddressByteSize());
569 Loc->parse(LocData);
570 }
David Blaikie18e73502013-06-19 21:37:13 +0000571 return Loc.get();
572}
573
David Blaikie9c550ac2014-03-25 01:44:02 +0000574const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
575 if (LocDWO)
576 return LocDWO.get();
577
Rafael Espindolac398e672017-07-19 22:27:28 +0000578 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000579 LocDWO.reset(new DWARFDebugLocDWO());
580 LocDWO->parse(LocData);
581 return LocDWO.get();
582}
583
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000584const DWARFDebugAranges *DWARFContext::getDebugAranges() {
585 if (Aranges)
586 return Aranges.get();
587
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000588 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000589 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000590 return Aranges.get();
591}
592
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000593const DWARFDebugFrame *DWARFContext::getDebugFrame() {
594 if (DebugFrame)
595 return DebugFrame.get();
596
597 // There's a "bug" in the DWARFv3 standard with respect to the target address
598 // size within debug frame sections. While DWARF is supposed to be independent
599 // of its container, FDEs have fields with size being "target address size",
600 // which isn't specified in DWARF in general. It's only specified for CUs, but
601 // .eh_frame can appear without a .debug_info section. Follow the example of
602 // other tools (libdwarf) and extract this from the container (ObjectFile
603 // provides this information). This problem is fixed in DWARFv4
604 // See this dwarf-discuss discussion for more details:
605 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000606 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
607 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000608 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
609 DebugFrame->parse(debugFrameData);
610 return DebugFrame.get();
611}
612
613const DWARFDebugFrame *DWARFContext::getEHFrame() {
614 if (EHFrame)
615 return EHFrame.get();
616
Rafael Espindolac398e672017-07-19 22:27:28 +0000617 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
618 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000619 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000620 DebugFrame->parse(debugFrameData);
621 return DebugFrame.get();
622}
623
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000624const DWARFDebugMacro *DWARFContext::getDebugMacro() {
625 if (Macro)
626 return Macro.get();
627
Rafael Espindolac398e672017-07-19 22:27:28 +0000628 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000629 Macro.reset(new DWARFDebugMacro());
630 Macro->parse(MacinfoData);
631 return Macro.get();
632}
633
Eric Christopher494109b2012-10-16 23:46:25 +0000634const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000635DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000636 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000637 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000638
Greg Claytonc8c10322016-12-13 18:25:19 +0000639 auto UnitDIE = U->getUnitDIE();
640 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000641 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000642
Greg Clayton97d22182017-01-13 21:08:18 +0000643 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000644 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000645 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000646
Greg Clayton52fe1f62016-12-14 22:38:08 +0000647 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000648 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000649 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000650 return lt;
651
Greg Clayton48ff66a2017-05-04 18:29:44 +0000652 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000653 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000654 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000655
Benjamin Kramer679e1752011-09-15 20:43:18 +0000656 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000657 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000658 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000659 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000660}
661
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000662void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000663 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000664}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000665
David Blaikie03c089c2013-09-23 22:44:47 +0000666void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000667 if (!TUs.empty())
668 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000669 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000670 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000671 TUs.back().parse(*this, S);
672 });
David Blaikie03c089c2013-09-23 22:44:47 +0000673}
674
Eric Christopherda4b2192013-01-02 23:52:13 +0000675void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000676 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000677}
678
David Blaikie92d9d622014-01-09 05:08:24 +0000679void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000680 if (!DWOTUs.empty())
681 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000682 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000683 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000684 DWOTUs.back().parseDWO(*this, S);
685 });
David Blaikie92d9d622014-01-09 05:08:24 +0000686}
687
Alexey Samsonov45be7932012-08-30 07:49:50 +0000688DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000689 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000690 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000691}
692
Alexey Samsonov45be7932012-08-30 07:49:50 +0000693DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000694 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000695 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000696 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000697 return getCompileUnitForOffset(CUOffset);
698}
699
David Blaikieefc4eba2017-02-06 20:19:02 +0000700static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
701 uint64_t Address,
702 FunctionNameKind Kind,
703 std::string &FunctionName,
704 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000705 // The address may correspond to instruction in some inlined function,
706 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000707 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000708 SmallVector<DWARFDie, 4> InlinedChain;
709 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000710 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000711 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000712
713 const DWARFDie &DIE = InlinedChain[0];
714 bool FoundResult = false;
715 const char *Name = nullptr;
716 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000717 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000718 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000719 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000720 if (auto DeclLineResult = DIE.getDeclLine()) {
721 StartLine = DeclLineResult;
722 FoundResult = true;
723 }
724
725 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000726}
727
Alexey Samsonov45be7932012-08-30 07:49:50 +0000728DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000729 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000730 DILineInfo Result;
731
Alexey Samsonov45be7932012-08-30 07:49:50 +0000732 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
733 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000734 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000735 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
736 Result.FunctionName,
737 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000738 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000739 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
740 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
741 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000742 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000743 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000744}
David Blaikiea379b1812011-12-20 02:50:00 +0000745
Alexey Samsonovdce67342014-05-15 21:24:32 +0000746DILineInfoTable
747DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
748 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000749 DILineInfoTable Lines;
750 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
751 if (!CU)
752 return Lines;
753
754 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000755 uint32_t StartLine = 0;
756 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
757 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000758
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000759 // If the Specifier says we don't need FileLineInfo, just
760 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000761 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000762 DILineInfo Result;
763 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000764 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000765 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000766 return Lines;
767 }
768
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000769 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000770
771 // Get the index of row we're looking for in the line table.
772 std::vector<uint32_t> RowVector;
773 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
774 return Lines;
775
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000776 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000777 // Take file number and line/column from the row.
778 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000779 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000780 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
781 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000782 Result.FunctionName = FunctionName;
783 Result.Line = Row.Line;
784 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000785 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000786 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000787 }
788
789 return Lines;
790}
791
Alexey Samsonovdce67342014-05-15 21:24:32 +0000792DIInliningInfo
793DWARFContext::getInliningInfoForAddress(uint64_t Address,
794 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000795 DIInliningInfo InliningInfo;
796
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000797 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
798 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000799 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000800
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000801 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000802 SmallVector<DWARFDie, 4> InlinedChain;
803 CU->getInlinedChainForAddress(Address, InlinedChain);
804 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000805 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
806 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000807 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000808 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000809 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000810 if (LineTable &&
811 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
812 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000813 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000814 }
815 return InliningInfo;
816 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000817
Dehao Chenef700d52017-04-17 20:10:39 +0000818 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000819 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
820 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000821 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000822 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000823 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000824 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000825 if (auto DeclLineResult = FunctionDIE.getDeclLine())
826 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000827 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000828 if (i == 0) {
829 // For the topmost frame, initialize the line table of this
830 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000831 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000832 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000833 if (LineTable)
834 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
835 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000836 } else {
837 // Otherwise, use call file, call line and call column from
838 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000839 if (LineTable)
840 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
841 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000842 Frame.Line = CallLine;
843 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000844 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000845 }
846 // Get call file/line/column of a current DIE.
847 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000848 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
849 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000850 }
851 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000852 InliningInfo.addFrame(Frame);
853 }
854 return InliningInfo;
855}
856
David Blaikief9803fb2017-05-23 00:30:42 +0000857std::shared_ptr<DWARFContext>
858DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000859 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000860 DWARFContext *Ctxt = S->Context.get();
861 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
862 }
863
David Blaikie15d85fc2017-05-23 06:48:53 +0000864 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
865
866 if (auto S = Entry->lock()) {
867 DWARFContext *Ctxt = S->Context.get();
868 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
869 }
870
David Blaikie15d85fc2017-05-23 06:48:53 +0000871 Expected<OwningBinary<ObjectFile>> Obj = [&] {
872 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000873 SmallString<128> DWPName;
874 auto Obj = object::ObjectFile::createObjectFile(
875 this->DWPName.empty()
876 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
877 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000878 if (Obj) {
879 Entry = &DWP;
880 return Obj;
881 } else {
882 CheckedForDWP = true;
883 // TODO: Should this error be handled (maybe in a high verbosity mode)
884 // before falling back to .dwo files?
885 consumeError(Obj.takeError());
886 }
887 }
888
889 return object::ObjectFile::createObjectFile(AbsolutePath);
890 }();
891
David Blaikief9803fb2017-05-23 00:30:42 +0000892 if (!Obj) {
893 // TODO: Actually report errors helpfully.
894 consumeError(Obj.takeError());
895 return nullptr;
896 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000897
898 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000899 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000900 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000901 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000902 auto *Ctxt = S->Context.get();
903 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
904}
905
George Rimar702dac62017-04-12 08:59:15 +0000906static Error createError(const Twine &Reason, llvm::Error E) {
907 return make_error<StringError>(Reason + toString(std::move(E)),
908 inconvertibleErrorCode());
909}
910
George Rimara25d3292017-05-27 18:10:23 +0000911/// SymInfo contains information about symbol: it's address
912/// and section index which is -1LL for absolute symbols.
913struct SymInfo {
914 uint64_t Address;
915 uint64_t SectionIndex;
916};
917
918/// Returns the address of symbol relocation used against and a section index.
919/// Used for futher relocations computation. Symbol's section load address is
920static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
921 const RelocationRef &Reloc,
922 const LoadedObjectInfo *L,
923 std::map<SymbolRef, SymInfo> &Cache) {
924 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000925 object::section_iterator RSec = Obj.section_end();
926 object::symbol_iterator Sym = Reloc.getSymbol();
927
George Rimara25d3292017-05-27 18:10:23 +0000928 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000929 // First calculate the address of the symbol or section as it appears
930 // in the object file
931 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000932 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000933 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000934 if (!New)
935 return CacheIt->second;
936
George Rimar702dac62017-04-12 08:59:15 +0000937 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
938 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000939 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000940 SymAddrOrErr.takeError());
941
942 // Also remember what section this symbol is in for later
943 auto SectOrErr = Sym->getSection();
944 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000945 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000946 SectOrErr.takeError());
947
948 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000949 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000950 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
951 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000952 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000953 }
954
George Rimara25d3292017-05-27 18:10:23 +0000955 if (RSec != Obj.section_end())
956 Ret.SectionIndex = RSec->getIndex();
957
George Rimar702dac62017-04-12 08:59:15 +0000958 // If we are given load addresses for the sections, we need to adjust:
959 // SymAddr = (Address of Symbol Or Section in File) -
960 // (Address of Section in File) +
961 // (Load Address of Section)
962 // RSec is now either the section being targeted or the section
963 // containing the symbol being targeted. In either case,
964 // we need to perform the same computation.
965 if (L && RSec != Obj.section_end())
966 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000967 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000968
969 if (CacheIt != Cache.end())
970 CacheIt->second = Ret;
971
George Rimar702dac62017-04-12 08:59:15 +0000972 return Ret;
973}
974
975static bool isRelocScattered(const object::ObjectFile &Obj,
976 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000977 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
978 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000979 return false;
980 // MachO also has relocations that point to sections and
981 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000982 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
983 return MachObj->isRelocationScattered(RelocInfo);
984}
985
Rafael Espindolac398e672017-07-19 22:27:28 +0000986ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000987 errs() << "error: " + toString(std::move(E)) << '\n';
988 return ErrorPolicy::Continue;
989}
990
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000991namespace {
992struct DWARFSectionMap final : public DWARFSection {
993 RelocAddrMap Relocs;
994};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000995
Rafael Espindolac398e672017-07-19 22:27:28 +0000996class DWARFObjInMemory final : public DWARFObject {
997 bool IsLittleEndian;
998 uint8_t AddressSize;
999 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001000 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001001 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001002
Rafael Espindolac398e672017-07-19 22:27:28 +00001003 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1004 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001005
Rafael Espindolac398e672017-07-19 22:27:28 +00001006 TypeSectionMap TypesSections;
1007 TypeSectionMap TypesDWOSections;
1008
1009 DWARFSectionMap InfoSection;
1010 DWARFSectionMap LocSection;
1011 DWARFSectionMap LineSection;
1012 DWARFSectionMap RangeSection;
1013 DWARFSectionMap StringOffsetSection;
1014 DWARFSectionMap InfoDWOSection;
1015 DWARFSectionMap LineDWOSection;
1016 DWARFSectionMap LocDWOSection;
1017 DWARFSectionMap StringOffsetDWOSection;
1018 DWARFSectionMap RangeDWOSection;
1019 DWARFSectionMap AddrSection;
1020 DWARFSectionMap AppleNamesSection;
1021 DWARFSectionMap AppleTypesSection;
1022 DWARFSectionMap AppleNamespacesSection;
1023 DWARFSectionMap AppleObjCSection;
1024
1025 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1026 return StringSwitch<DWARFSectionMap *>(Name)
1027 .Case("debug_info", &InfoSection)
1028 .Case("debug_loc", &LocSection)
1029 .Case("debug_line", &LineSection)
1030 .Case("debug_str_offsets", &StringOffsetSection)
1031 .Case("debug_ranges", &RangeSection)
1032 .Case("debug_info.dwo", &InfoDWOSection)
1033 .Case("debug_loc.dwo", &LocDWOSection)
1034 .Case("debug_line.dwo", &LineDWOSection)
1035 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1036 .Case("debug_addr", &AddrSection)
1037 .Case("apple_names", &AppleNamesSection)
1038 .Case("apple_types", &AppleTypesSection)
1039 .Case("apple_namespaces", &AppleNamespacesSection)
1040 .Case("apple_namespac", &AppleNamespacesSection)
1041 .Case("apple_objc", &AppleObjCSection)
1042 .Default(nullptr);
1043 }
1044
1045 StringRef AbbrevSection;
1046 StringRef ARangeSection;
1047 StringRef DebugFrameSection;
1048 StringRef EHFrameSection;
1049 StringRef StringSection;
1050 StringRef MacinfoSection;
1051 StringRef PubNamesSection;
1052 StringRef PubTypesSection;
1053 StringRef GnuPubNamesSection;
1054 StringRef AbbrevDWOSection;
1055 StringRef StringDWOSection;
1056 StringRef GnuPubTypesSection;
1057 StringRef CUIndexSection;
1058 StringRef GdbIndexSection;
1059 StringRef TUIndexSection;
1060
1061 SmallVector<SmallString<32>, 4> UncompressedSections;
1062
1063 StringRef *mapSectionToMember(StringRef Name) {
1064 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1065 return &Sec->Data;
1066 return StringSwitch<StringRef *>(Name)
1067 .Case("debug_abbrev", &AbbrevSection)
1068 .Case("debug_aranges", &ARangeSection)
1069 .Case("debug_frame", &DebugFrameSection)
1070 .Case("eh_frame", &EHFrameSection)
1071 .Case("debug_str", &StringSection)
1072 .Case("debug_macinfo", &MacinfoSection)
1073 .Case("debug_pubnames", &PubNamesSection)
1074 .Case("debug_pubtypes", &PubTypesSection)
1075 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1076 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1077 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1078 .Case("debug_str.dwo", &StringDWOSection)
1079 .Case("debug_cu_index", &CUIndexSection)
1080 .Case("debug_tu_index", &TUIndexSection)
1081 .Case("gdb_index", &GdbIndexSection)
1082 // Any more debug info sections go here.
1083 .Default(nullptr);
1084 }
1085
1086 /// If Sec is compressed section, decompresses and updates its contents
1087 /// provided by Data. Otherwise leaves it unchanged.
1088 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1089 StringRef &Data) {
1090 if (!Decompressor::isCompressed(Sec))
1091 return Error::success();
1092
1093 Expected<Decompressor> Decompressor =
1094 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1095 if (!Decompressor)
1096 return Decompressor.takeError();
1097
1098 SmallString<32> Out;
1099 if (auto Err = Decompressor->resizeAndDecompress(Out))
1100 return Err;
1101
1102 UncompressedSections.emplace_back(std::move(Out));
1103 Data = UncompressedSections.back();
1104
1105 return Error::success();
1106 }
1107
1108public:
1109 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1110 uint8_t AddrSize, bool IsLittleEndian)
1111 : IsLittleEndian(IsLittleEndian) {
1112 for (const auto &SecIt : Sections) {
1113 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1114 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001115 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001116 }
1117 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1118 function_ref<ErrorPolicy(Error)> HandleError)
1119 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001120 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1121 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001122
George Rimare1c30f72017-08-15 15:54:43 +00001123 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001124 for (const SectionRef &Section : Obj.sections()) {
1125 StringRef Name;
1126 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001127 ++SectionAmountMap[Name];
1128 SectionNames.push_back({ Name, true });
1129
Rafael Espindolac398e672017-07-19 22:27:28 +00001130 // Skip BSS and Virtual sections, they aren't interesting.
1131 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001132 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001133
Rafael Espindolac398e672017-07-19 22:27:28 +00001134 StringRef Data;
1135 section_iterator RelocatedSection = Section.getRelocatedSection();
1136 // Try to obtain an already relocated version of this section.
1137 // Else use the unrelocated section from the object file. We'll have to
1138 // apply relocations ourselves later.
1139 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1140 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001141
Rafael Espindolac398e672017-07-19 22:27:28 +00001142 if (auto Err = maybeDecompress(Section, Name, Data)) {
1143 ErrorPolicy EP = HandleError(createError(
1144 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001145 if (EP == ErrorPolicy::Halt)
1146 return;
George Rimarfed9f092017-05-17 12:10:51 +00001147 continue;
1148 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001149
1150 // Compressed sections names in GNU style starts from ".z",
1151 // at this point section is decompressed and we drop compression prefix.
1152 Name = Name.substr(
1153 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1154
1155 // Map platform specific debug section names to DWARF standard section
1156 // names.
1157 Name = Obj.mapDebugSectionName(Name);
1158
1159 if (StringRef *SectionData = mapSectionToMember(Name)) {
1160 *SectionData = Data;
1161 if (Name == "debug_ranges") {
1162 // FIXME: Use the other dwo range section when we emit it.
1163 RangeDWOSection.Data = Data;
1164 }
1165 } else if (Name == "debug_types") {
1166 // Find debug_types data by section rather than name as there are
1167 // multiple, comdat grouped, debug_types sections.
1168 TypesSections[Section].Data = Data;
1169 } else if (Name == "debug_types.dwo") {
1170 TypesDWOSections[Section].Data = Data;
1171 }
1172
1173 if (RelocatedSection == Obj.section_end())
1174 continue;
1175
1176 StringRef RelSecName;
1177 StringRef RelSecData;
1178 RelocatedSection->getName(RelSecName);
1179
1180 // If the section we're relocating was relocated already by the JIT,
1181 // then we used the relocated version above, so we do not need to process
1182 // relocations for it now.
1183 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1184 continue;
1185
1186 // In Mach-o files, the relocations do not need to be applied if
1187 // there is no load offset to apply. The value read at the
1188 // relocation point already factors in the section address
1189 // (actually applying the relocations will produce wrong results
1190 // as the section address will be added twice).
1191 if (!L && isa<MachOObjectFile>(&Obj))
1192 continue;
1193
1194 RelSecName = RelSecName.substr(
1195 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1196
1197 // TODO: Add support for relocations in other sections as needed.
1198 // Record relocations for the debug_info and debug_line sections.
1199 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1200 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1201 if (!Map) {
1202 // Find debug_types relocs by section rather than name as there are
1203 // multiple, comdat grouped, debug_types sections.
1204 if (RelSecName == "debug_types")
1205 Map =
1206 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1207 .Relocs;
1208 else if (RelSecName == "debug_types.dwo")
1209 Map = &static_cast<DWARFSectionMap &>(
1210 TypesDWOSections[*RelocatedSection])
1211 .Relocs;
1212 else
1213 continue;
1214 }
1215
1216 if (Section.relocation_begin() == Section.relocation_end())
1217 continue;
1218
1219 // Symbol to [address, section index] cache mapping.
1220 std::map<SymbolRef, SymInfo> AddrCache;
1221 for (const RelocationRef &Reloc : Section.relocations()) {
1222 // FIXME: it's not clear how to correctly handle scattered
1223 // relocations.
1224 if (isRelocScattered(Obj, Reloc))
1225 continue;
1226
1227 Expected<SymInfo> SymInfoOrErr =
1228 getSymbolInfo(Obj, Reloc, L, AddrCache);
1229 if (!SymInfoOrErr) {
1230 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1231 return;
1232 continue;
1233 }
1234
1235 object::RelocVisitor V(Obj);
1236 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1237 if (V.error()) {
1238 SmallString<32> Type;
1239 Reloc.getTypeName(Type);
1240 ErrorPolicy EP = HandleError(
1241 createError("failed to compute relocation: " + Type + ", ",
1242 errorCodeToError(object_error::parse_failed)));
1243 if (EP == ErrorPolicy::Halt)
1244 return;
1245 continue;
1246 }
1247 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1248 Map->insert({Reloc.getOffset(), Rel});
1249 }
Eric Christopher7370b552012-11-12 21:40:38 +00001250 }
George Rimare1c30f72017-08-15 15:54:43 +00001251
1252 for (SectionName &S : SectionNames)
1253 if (SectionAmountMap[S.Name] > 1)
1254 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001255 }
Eric Christopher7370b552012-11-12 21:40:38 +00001256
Rafael Espindolac398e672017-07-19 22:27:28 +00001257 Optional<RelocAddrEntry> find(const DWARFSection &S,
1258 uint64_t Pos) const override {
1259 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1260 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1261 if (AI == Sec.Relocs.end())
1262 return None;
1263 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001264 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001265
George Rimar6957ab52017-08-15 12:32:54 +00001266 const object::ObjectFile *getFile() const override { return Obj; }
1267
George Rimare1c30f72017-08-15 15:54:43 +00001268 ArrayRef<SectionName> getSectionNames() const override {
1269 return SectionNames;
1270 }
1271
Rafael Espindolac398e672017-07-19 22:27:28 +00001272 bool isLittleEndian() const override { return IsLittleEndian; }
1273 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1274 const DWARFSection &getLineDWOSection() const override {
1275 return LineDWOSection;
1276 }
1277 const DWARFSection &getLocDWOSection() const override {
1278 return LocDWOSection;
1279 }
1280 StringRef getStringDWOSection() const override { return StringDWOSection; }
1281 const DWARFSection &getStringOffsetDWOSection() const override {
1282 return StringOffsetDWOSection;
1283 }
1284 const DWARFSection &getRangeDWOSection() const override {
1285 return RangeDWOSection;
1286 }
1287 const DWARFSection &getAddrSection() const override { return AddrSection; }
1288 StringRef getCUIndexSection() const override { return CUIndexSection; }
1289 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1290 StringRef getTUIndexSection() const override { return TUIndexSection; }
1291
1292 // DWARF v5
1293 const DWARFSection &getStringOffsetSection() const override {
1294 return StringOffsetSection;
1295 }
1296
1297 // Sections for DWARF5 split dwarf proposal.
1298 const DWARFSection &getInfoDWOSection() const override {
1299 return InfoDWOSection;
1300 }
1301 void forEachTypesDWOSections(
1302 function_ref<void(const DWARFSection &)> F) const override {
1303 for (auto &P : TypesDWOSections)
1304 F(P.second);
1305 }
1306
1307 StringRef getAbbrevSection() const override { return AbbrevSection; }
1308 const DWARFSection &getLocSection() const override { return LocSection; }
1309 StringRef getARangeSection() const override { return ARangeSection; }
1310 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1311 StringRef getEHFrameSection() const override { return EHFrameSection; }
1312 const DWARFSection &getLineSection() const override { return LineSection; }
1313 StringRef getStringSection() const override { return StringSection; }
1314 const DWARFSection &getRangeSection() const override { return RangeSection; }
1315 StringRef getMacinfoSection() const override { return MacinfoSection; }
1316 StringRef getPubNamesSection() const override { return PubNamesSection; }
1317 StringRef getPubTypesSection() const override { return PubTypesSection; }
1318 StringRef getGnuPubNamesSection() const override {
1319 return GnuPubNamesSection;
1320 }
1321 StringRef getGnuPubTypesSection() const override {
1322 return GnuPubTypesSection;
1323 }
1324 const DWARFSection &getAppleNamesSection() const override {
1325 return AppleNamesSection;
1326 }
1327 const DWARFSection &getAppleTypesSection() const override {
1328 return AppleTypesSection;
1329 }
1330 const DWARFSection &getAppleNamespacesSection() const override {
1331 return AppleNamespacesSection;
1332 }
1333 const DWARFSection &getAppleObjCSection() const override {
1334 return AppleObjCSection;
1335 }
1336
1337 StringRef getFileName() const override { return FileName; }
1338 uint8_t getAddressSize() const override { return AddressSize; }
1339 const DWARFSection &getInfoSection() const override { return InfoSection; }
1340 void forEachTypesSections(
1341 function_ref<void(const DWARFSection &)> F) const override {
1342 for (auto &P : TypesSections)
1343 F(P.second);
1344 }
1345};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001346} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001347
1348std::unique_ptr<DWARFContext>
1349DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001350 function_ref<ErrorPolicy(Error)> HandleError,
1351 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001352 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001353 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001354}
1355
Rafael Espindolac398e672017-07-19 22:27:28 +00001356std::unique_ptr<DWARFContext>
1357DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1358 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001359 auto DObj =
1360 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001361 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001362}
Reid Klecknera0587362017-08-29 21:41:21 +00001363
1364Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1365 // Detect the architecture from the object file. We usually don't need OS
1366 // info to lookup a target and create register info.
1367 Triple TT;
1368 TT.setArch(Triple::ArchType(Obj.getArch()));
1369 TT.setVendor(Triple::UnknownVendor);
1370 TT.setOS(Triple::UnknownOS);
1371 std::string TargetLookupError;
1372 const Target *TheTarget =
1373 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1374 if (!TargetLookupError.empty())
1375 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1376 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1377 return Error::success();
1378}