blob: 8bb47c94d54f90a61674410c23a60c4219831779 [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
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000226 StringRef Extension = sys::path::extension(DObj->getFileName());
227 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
228
229 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000230 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000231 if (DumpType & DIDT_UUID)
232 dumpUUID(OS, *ObjFile);
233
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000234 // Print a header for each explicitly-requested section.
235 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000236 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000237 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000238 bool ExplicitDWO = Explicit && IsDWO;
239 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
240 StringRef Section) {
241 DumpOffset = DumpOffsets[ID];
242 unsigned Mask = 1U << ID;
243 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
Adrian Prantl84168022017-09-15 17:39:50 +0000244 if (Should)
Adrian Prantl057d3362017-09-15 23:04:04 +0000245 OS << "\n" << Name << " contents:\n";
Adrian Prantl84168022017-09-15 17:39:50 +0000246 return Should;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000247 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000248
249 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000250 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
251 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000252 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000253 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
254 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000255 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000256
Adrian Prantl057d3362017-09-15 23:04:04 +0000257 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
258 DWARFSection Section, cu_iterator_range CUs) {
259 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
Adrian Prantlc8d86532017-09-18 21:44:40 +0000260 if (DumpOffset)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000261 getDIEForOffset(DumpOffset.getValue())
262 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantlc8d86532017-09-18 21:44:40 +0000263 else
264 for (const auto &CU : CUs)
Adrian Prantl057d3362017-09-15 23:04:04 +0000265 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)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000280 TU->getDIEForOffset(*DumpOffset)
281 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantl099d7e42017-09-16 16:58:18 +0000282 else
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000283 TU->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000284 };
285 if ((DumpType & DIDT_DebugTypes)) {
286 if (Explicit || getNumTypeUnits())
287 dumpDebugType(".debug_types", type_unit_sections());
288 if (ExplicitDWO || getNumDWOTypeUnits())
289 dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
David Blaikie03c089c2013-09-23 22:44:47 +0000290 }
291
Adrian Prantl057d3362017-09-15 23:04:04 +0000292 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000293 DObj->getLocSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000294 getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie18e73502013-06-19 21:37:13 +0000295 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000296 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000297 DObj->getLocDWOSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000298 getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie9c550ac2014-03-25 01:44:02 +0000299 }
300
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000301 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000302 DObj->getDebugFrameSection()))
303 getDebugFrame()->dump(OS, DumpOffset);
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000304
305 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000306 DObj->getEHFrameSection()))
307 getEHFrame()->dump(OS, DumpOffset);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000308
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;
Jonas Devlieghere26f9a0c2017-09-21 20:15:30 +0000338 // Verbose dumping is done during parsing and not on the intermediate
339 // representation.
340 if (DumpOpts.Verbose) {
341 LineTable.parse(lineData, &Offset, &OS);
342 } else {
343 LineTable.parse(lineData, &Offset);
344 LineTable.dump(OS);
345 }
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000346 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000347 }
348 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000349
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000350 // FIXME: This seems sketchy.
351 for (const auto &CU : compile_units()) {
352 savedAddressByteSize = CU->getAddressByteSize();
353 break;
David Blaikie65a8efe2015-11-11 19:28:21 +0000354 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000355 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000356 DObj->getLineDWOSection().Data)) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000357 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000358 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
359 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000360 DWARFDebugLine::LineTable LineTable;
361 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
362 LineTable.dump(OS);
363 LineTable.clear();
364 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000365 }
366
Adrian Prantl057d3362017-09-15 23:04:04 +0000367 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000368 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000369 getCUIndex().dump(OS);
370 }
371
Adrian Prantl057d3362017-09-15 23:04:04 +0000372 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000373 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000374 getTUIndex().dump(OS);
375 }
376
Adrian Prantl057d3362017-09-15 23:04:04 +0000377 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000378 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000379 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000380 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000381 uint32_t strOffset = 0;
382 while (const char *s = strData.getCStr(&offset)) {
383 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
384 strOffset = offset;
385 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000386 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000387 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000388 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000389 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000390 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000391 uint32_t strDWOOffset = 0;
392 while (const char *s = strDWOData.getCStr(&offset)) {
393 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
394 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000395 }
David Blaikie66865d62014-01-09 00:13:35 +0000396 }
David Blaikie622dce42014-01-08 23:29:59 +0000397
Adrian Prantl057d3362017-09-15 23:04:04 +0000398 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000399 DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000400 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000401 // sizes, but for simplicity we just use the address byte size of the
402 // last compile unit (there is no easy and fast way to associate address
403 // range list and the compile unit it describes).
404 // FIXME: savedAddressByteSize seems sketchy.
Rafael Espindolac398e672017-07-19 22:27:28 +0000405 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
406 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000407 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000408 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000409 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000410 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000411 }
Eric Christopher962c9082013-01-15 23:56:56 +0000412
Adrian Prantl057d3362017-09-15 23:04:04 +0000413 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000414 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000415 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000416 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000417
Adrian Prantl057d3362017-09-15 23:04:04 +0000418 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000419 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000420 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000421 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000422
Adrian Prantl057d3362017-09-15 23:04:04 +0000423 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000424 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000425 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000426 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000427 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000428
Adrian Prantl057d3362017-09-15 23:04:04 +0000429 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000430 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000431 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000432 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000433 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000434
Adrian Prantl057d3362017-09-15 23:04:04 +0000435 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000436 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000437 dumpStringOffsetsSection(
438 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
439 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000440 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000441 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000442 dumpStringOffsetsSection(
443 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
444 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000445
Adrian Prantl057d3362017-09-15 23:04:04 +0000446 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000447 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000448 getGdbIndex().dump(OS);
449 }
450
Adrian Prantl057d3362017-09-15 23:04:04 +0000451 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000452 DObj->getAppleNamesSection().Data))
453 dumpAccelSection(OS, *DObj, DObj->getAppleNamesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000454 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000455
Adrian Prantl057d3362017-09-15 23:04:04 +0000456 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000457 DObj->getAppleTypesSection().Data))
458 dumpAccelSection(OS, *DObj, DObj->getAppleTypesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000459 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000460
Adrian Prantl057d3362017-09-15 23:04:04 +0000461 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000462 DObj->getAppleNamespacesSection().Data))
463 dumpAccelSection(OS, *DObj, DObj->getAppleNamespacesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000464 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000465
Adrian Prantl057d3362017-09-15 23:04:04 +0000466 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000467 DObj->getAppleObjCSection().Data))
468 dumpAccelSection(OS, *DObj, DObj->getAppleObjCSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000469 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000470}
471
David Blaikie15d85fc2017-05-23 06:48:53 +0000472DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiee79dda32017-09-19 18:36:11 +0000473 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000474
David Blaikieebac0b92017-07-30 08:12:07 +0000475 if (const auto &CUI = getCUIndex()) {
476 if (const auto *R = CUI.getFromHash(Hash))
David Blaikiee79dda32017-09-19 18:36:11 +0000477 return DWOCUs.getUnitForIndexEntry(*R);
David Blaikieebac0b92017-07-30 08:12:07 +0000478 return nullptr;
479 }
480
481 // If there's no index, just search through the CUs in the DWO - there's
482 // probably only one unless this is something like LTO - though an in-process
483 // built/cached lookup table could be used in that case to improve repeated
484 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000485 for (const auto &DWOCU : dwo_compile_units())
486 if (DWOCU->getDWOId() == Hash)
487 return DWOCU.get();
488 return nullptr;
489}
490
Greg Claytonc7695a82017-05-02 20:28:33 +0000491DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
492 parseCompileUnits();
493 if (auto *CU = CUs.getUnitForOffset(Offset))
494 return CU->getDIEForOffset(Offset);
495 return DWARFDie();
496}
497
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000498bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000499 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000500 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000501
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000502 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000503 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000504 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000505 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000506 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000507 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000508 return Success;
509}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000510
David Blaikie82641be2015-11-17 00:39:55 +0000511const DWARFUnitIndex &DWARFContext::getCUIndex() {
512 if (CUIndex)
513 return *CUIndex;
514
Rafael Espindolac398e672017-07-19 22:27:28 +0000515 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000516
David Blaikieb073cb92015-12-02 06:21:34 +0000517 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000518 CUIndex->parse(CUIndexData);
519 return *CUIndex;
520}
521
522const DWARFUnitIndex &DWARFContext::getTUIndex() {
523 if (TUIndex)
524 return *TUIndex;
525
Rafael Espindolac398e672017-07-19 22:27:28 +0000526 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000527
David Blaikieb073cb92015-12-02 06:21:34 +0000528 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000529 TUIndex->parse(TUIndexData);
530 return *TUIndex;
531}
532
George Rimar4f82df52016-09-23 11:01:53 +0000533DWARFGdbIndex &DWARFContext::getGdbIndex() {
534 if (GdbIndex)
535 return *GdbIndex;
536
Rafael Espindolac398e672017-07-19 22:27:28 +0000537 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000538 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
539 GdbIndex->parse(GdbIndexData);
540 return *GdbIndex;
541}
542
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000543const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
544 if (Abbrev)
545 return Abbrev.get();
546
Rafael Espindolac398e672017-07-19 22:27:28 +0000547 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000548
549 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000550 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000551 return Abbrev.get();
552}
553
Eric Christopherda4b2192013-01-02 23:52:13 +0000554const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
555 if (AbbrevDWO)
556 return AbbrevDWO.get();
557
Rafael Espindolac398e672017-07-19 22:27:28 +0000558 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000559 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000560 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000561 return AbbrevDWO.get();
562}
563
David Blaikie18e73502013-06-19 21:37:13 +0000564const DWARFDebugLoc *DWARFContext::getDebugLoc() {
565 if (Loc)
566 return Loc.get();
567
Paul Robinson17536b92017-06-29 16:52:08 +0000568 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000569 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000570 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000571 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000572 getCompileUnitAtIndex(0)->getAddressByteSize());
573 Loc->parse(LocData);
574 }
David Blaikie18e73502013-06-19 21:37:13 +0000575 return Loc.get();
576}
577
David Blaikie9c550ac2014-03-25 01:44:02 +0000578const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
579 if (LocDWO)
580 return LocDWO.get();
581
Rafael Espindolac398e672017-07-19 22:27:28 +0000582 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000583 LocDWO.reset(new DWARFDebugLocDWO());
584 LocDWO->parse(LocData);
585 return LocDWO.get();
586}
587
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000588const DWARFDebugAranges *DWARFContext::getDebugAranges() {
589 if (Aranges)
590 return Aranges.get();
591
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000592 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000593 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000594 return Aranges.get();
595}
596
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000597const DWARFDebugFrame *DWARFContext::getDebugFrame() {
598 if (DebugFrame)
599 return DebugFrame.get();
600
601 // There's a "bug" in the DWARFv3 standard with respect to the target address
602 // size within debug frame sections. While DWARF is supposed to be independent
603 // of its container, FDEs have fields with size being "target address size",
604 // which isn't specified in DWARF in general. It's only specified for CUs, but
605 // .eh_frame can appear without a .debug_info section. Follow the example of
606 // other tools (libdwarf) and extract this from the container (ObjectFile
607 // provides this information). This problem is fixed in DWARFv4
608 // See this dwarf-discuss discussion for more details:
609 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000610 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
611 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000612 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
613 DebugFrame->parse(debugFrameData);
614 return DebugFrame.get();
615}
616
617const DWARFDebugFrame *DWARFContext::getEHFrame() {
618 if (EHFrame)
619 return EHFrame.get();
620
Rafael Espindolac398e672017-07-19 22:27:28 +0000621 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
622 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000623 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000624 DebugFrame->parse(debugFrameData);
625 return DebugFrame.get();
626}
627
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000628const DWARFDebugMacro *DWARFContext::getDebugMacro() {
629 if (Macro)
630 return Macro.get();
631
Rafael Espindolac398e672017-07-19 22:27:28 +0000632 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000633 Macro.reset(new DWARFDebugMacro());
634 Macro->parse(MacinfoData);
635 return Macro.get();
636}
637
Eric Christopher494109b2012-10-16 23:46:25 +0000638const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000639DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000640 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000641 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000642
Greg Claytonc8c10322016-12-13 18:25:19 +0000643 auto UnitDIE = U->getUnitDIE();
644 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000645 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000646
Greg Clayton97d22182017-01-13 21:08:18 +0000647 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000648 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000649 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000650
Greg Clayton52fe1f62016-12-14 22:38:08 +0000651 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000652 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000653 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000654 return lt;
655
Greg Clayton48ff66a2017-05-04 18:29:44 +0000656 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000657 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000658 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000659
Benjamin Kramer679e1752011-09-15 20:43:18 +0000660 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000661 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000662 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000663 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000664}
665
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000666void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000667 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000668}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000669
David Blaikie03c089c2013-09-23 22:44:47 +0000670void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000671 if (!TUs.empty())
672 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000673 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000674 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000675 TUs.back().parse(*this, S);
676 });
David Blaikie03c089c2013-09-23 22:44:47 +0000677}
678
Eric Christopherda4b2192013-01-02 23:52:13 +0000679void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000680 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000681}
682
David Blaikie92d9d622014-01-09 05:08:24 +0000683void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000684 if (!DWOTUs.empty())
685 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000686 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000687 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000688 DWOTUs.back().parseDWO(*this, S);
689 });
David Blaikie92d9d622014-01-09 05:08:24 +0000690}
691
Alexey Samsonov45be7932012-08-30 07:49:50 +0000692DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000693 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000694 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000695}
696
Alexey Samsonov45be7932012-08-30 07:49:50 +0000697DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000698 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000699 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000700 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000701 return getCompileUnitForOffset(CUOffset);
702}
703
David Blaikieefc4eba2017-02-06 20:19:02 +0000704static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
705 uint64_t Address,
706 FunctionNameKind Kind,
707 std::string &FunctionName,
708 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000709 // The address may correspond to instruction in some inlined function,
710 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000711 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000712 SmallVector<DWARFDie, 4> InlinedChain;
713 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000714 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000715 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000716
717 const DWARFDie &DIE = InlinedChain[0];
718 bool FoundResult = false;
719 const char *Name = nullptr;
720 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000721 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000722 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000723 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000724 if (auto DeclLineResult = DIE.getDeclLine()) {
725 StartLine = DeclLineResult;
726 FoundResult = true;
727 }
728
729 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000730}
731
Alexey Samsonov45be7932012-08-30 07:49:50 +0000732DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000733 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000734 DILineInfo Result;
735
Alexey Samsonov45be7932012-08-30 07:49:50 +0000736 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
737 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000738 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000739 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
740 Result.FunctionName,
741 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000742 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000743 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
744 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
745 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000746 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000747 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000748}
David Blaikiea379b1812011-12-20 02:50:00 +0000749
Alexey Samsonovdce67342014-05-15 21:24:32 +0000750DILineInfoTable
751DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
752 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000753 DILineInfoTable Lines;
754 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
755 if (!CU)
756 return Lines;
757
758 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000759 uint32_t StartLine = 0;
760 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
761 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000762
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000763 // If the Specifier says we don't need FileLineInfo, just
764 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000765 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000766 DILineInfo Result;
767 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000768 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000769 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000770 return Lines;
771 }
772
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000773 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000774
775 // Get the index of row we're looking for in the line table.
776 std::vector<uint32_t> RowVector;
777 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
778 return Lines;
779
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000780 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000781 // Take file number and line/column from the row.
782 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000783 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000784 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
785 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000786 Result.FunctionName = FunctionName;
787 Result.Line = Row.Line;
788 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000789 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000790 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000791 }
792
793 return Lines;
794}
795
Alexey Samsonovdce67342014-05-15 21:24:32 +0000796DIInliningInfo
797DWARFContext::getInliningInfoForAddress(uint64_t Address,
798 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000799 DIInliningInfo InliningInfo;
800
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000801 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
802 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000803 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000804
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000805 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000806 SmallVector<DWARFDie, 4> InlinedChain;
807 CU->getInlinedChainForAddress(Address, InlinedChain);
808 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000809 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
810 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000811 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000812 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000813 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000814 if (LineTable &&
815 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
816 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000817 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000818 }
819 return InliningInfo;
820 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000821
Dehao Chenef700d52017-04-17 20:10:39 +0000822 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000823 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
824 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000825 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000826 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000827 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000828 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000829 if (auto DeclLineResult = FunctionDIE.getDeclLine())
830 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000831 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000832 if (i == 0) {
833 // For the topmost frame, initialize the line table of this
834 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000835 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000836 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000837 if (LineTable)
838 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
839 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000840 } else {
841 // Otherwise, use call file, call line and call column from
842 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000843 if (LineTable)
844 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
845 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000846 Frame.Line = CallLine;
847 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000848 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000849 }
850 // Get call file/line/column of a current DIE.
851 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000852 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
853 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000854 }
855 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000856 InliningInfo.addFrame(Frame);
857 }
858 return InliningInfo;
859}
860
David Blaikief9803fb2017-05-23 00:30:42 +0000861std::shared_ptr<DWARFContext>
862DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000863 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000864 DWARFContext *Ctxt = S->Context.get();
865 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
866 }
867
David Blaikie15d85fc2017-05-23 06:48:53 +0000868 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
869
870 if (auto S = Entry->lock()) {
871 DWARFContext *Ctxt = S->Context.get();
872 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
873 }
874
David Blaikie15d85fc2017-05-23 06:48:53 +0000875 Expected<OwningBinary<ObjectFile>> Obj = [&] {
876 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000877 SmallString<128> DWPName;
878 auto Obj = object::ObjectFile::createObjectFile(
879 this->DWPName.empty()
880 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
881 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000882 if (Obj) {
883 Entry = &DWP;
884 return Obj;
885 } else {
886 CheckedForDWP = true;
887 // TODO: Should this error be handled (maybe in a high verbosity mode)
888 // before falling back to .dwo files?
889 consumeError(Obj.takeError());
890 }
891 }
892
893 return object::ObjectFile::createObjectFile(AbsolutePath);
894 }();
895
David Blaikief9803fb2017-05-23 00:30:42 +0000896 if (!Obj) {
897 // TODO: Actually report errors helpfully.
898 consumeError(Obj.takeError());
899 return nullptr;
900 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000901
902 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000903 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000904 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000905 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000906 auto *Ctxt = S->Context.get();
907 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
908}
909
George Rimar702dac62017-04-12 08:59:15 +0000910static Error createError(const Twine &Reason, llvm::Error E) {
911 return make_error<StringError>(Reason + toString(std::move(E)),
912 inconvertibleErrorCode());
913}
914
George Rimara25d3292017-05-27 18:10:23 +0000915/// SymInfo contains information about symbol: it's address
916/// and section index which is -1LL for absolute symbols.
917struct SymInfo {
918 uint64_t Address;
919 uint64_t SectionIndex;
920};
921
922/// Returns the address of symbol relocation used against and a section index.
923/// Used for futher relocations computation. Symbol's section load address is
924static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
925 const RelocationRef &Reloc,
926 const LoadedObjectInfo *L,
927 std::map<SymbolRef, SymInfo> &Cache) {
928 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000929 object::section_iterator RSec = Obj.section_end();
930 object::symbol_iterator Sym = Reloc.getSymbol();
931
George Rimara25d3292017-05-27 18:10:23 +0000932 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000933 // First calculate the address of the symbol or section as it appears
934 // in the object file
935 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000936 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000937 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000938 if (!New)
939 return CacheIt->second;
940
George Rimar702dac62017-04-12 08:59:15 +0000941 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
942 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000943 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000944 SymAddrOrErr.takeError());
945
946 // Also remember what section this symbol is in for later
947 auto SectOrErr = Sym->getSection();
948 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000949 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000950 SectOrErr.takeError());
951
952 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000953 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000954 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
955 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000956 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000957 }
958
George Rimara25d3292017-05-27 18:10:23 +0000959 if (RSec != Obj.section_end())
960 Ret.SectionIndex = RSec->getIndex();
961
George Rimar702dac62017-04-12 08:59:15 +0000962 // If we are given load addresses for the sections, we need to adjust:
963 // SymAddr = (Address of Symbol Or Section in File) -
964 // (Address of Section in File) +
965 // (Load Address of Section)
966 // RSec is now either the section being targeted or the section
967 // containing the symbol being targeted. In either case,
968 // we need to perform the same computation.
969 if (L && RSec != Obj.section_end())
970 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000971 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000972
973 if (CacheIt != Cache.end())
974 CacheIt->second = Ret;
975
George Rimar702dac62017-04-12 08:59:15 +0000976 return Ret;
977}
978
979static bool isRelocScattered(const object::ObjectFile &Obj,
980 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000981 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
982 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000983 return false;
984 // MachO also has relocations that point to sections and
985 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000986 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
987 return MachObj->isRelocationScattered(RelocInfo);
988}
989
Rafael Espindolac398e672017-07-19 22:27:28 +0000990ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000991 errs() << "error: " + toString(std::move(E)) << '\n';
992 return ErrorPolicy::Continue;
993}
994
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000995namespace {
996struct DWARFSectionMap final : public DWARFSection {
997 RelocAddrMap Relocs;
998};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000999
Rafael Espindolac398e672017-07-19 22:27:28 +00001000class DWARFObjInMemory final : public DWARFObject {
1001 bool IsLittleEndian;
1002 uint8_t AddressSize;
1003 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001004 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001005 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001006
Rafael Espindolac398e672017-07-19 22:27:28 +00001007 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1008 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001009
Rafael Espindolac398e672017-07-19 22:27:28 +00001010 TypeSectionMap TypesSections;
1011 TypeSectionMap TypesDWOSections;
1012
1013 DWARFSectionMap InfoSection;
1014 DWARFSectionMap LocSection;
1015 DWARFSectionMap LineSection;
1016 DWARFSectionMap RangeSection;
1017 DWARFSectionMap StringOffsetSection;
1018 DWARFSectionMap InfoDWOSection;
1019 DWARFSectionMap LineDWOSection;
1020 DWARFSectionMap LocDWOSection;
1021 DWARFSectionMap StringOffsetDWOSection;
1022 DWARFSectionMap RangeDWOSection;
1023 DWARFSectionMap AddrSection;
1024 DWARFSectionMap AppleNamesSection;
1025 DWARFSectionMap AppleTypesSection;
1026 DWARFSectionMap AppleNamespacesSection;
1027 DWARFSectionMap AppleObjCSection;
1028
1029 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1030 return StringSwitch<DWARFSectionMap *>(Name)
1031 .Case("debug_info", &InfoSection)
1032 .Case("debug_loc", &LocSection)
1033 .Case("debug_line", &LineSection)
1034 .Case("debug_str_offsets", &StringOffsetSection)
1035 .Case("debug_ranges", &RangeSection)
1036 .Case("debug_info.dwo", &InfoDWOSection)
1037 .Case("debug_loc.dwo", &LocDWOSection)
1038 .Case("debug_line.dwo", &LineDWOSection)
1039 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1040 .Case("debug_addr", &AddrSection)
1041 .Case("apple_names", &AppleNamesSection)
1042 .Case("apple_types", &AppleTypesSection)
1043 .Case("apple_namespaces", &AppleNamespacesSection)
1044 .Case("apple_namespac", &AppleNamespacesSection)
1045 .Case("apple_objc", &AppleObjCSection)
1046 .Default(nullptr);
1047 }
1048
1049 StringRef AbbrevSection;
1050 StringRef ARangeSection;
1051 StringRef DebugFrameSection;
1052 StringRef EHFrameSection;
1053 StringRef StringSection;
1054 StringRef MacinfoSection;
1055 StringRef PubNamesSection;
1056 StringRef PubTypesSection;
1057 StringRef GnuPubNamesSection;
1058 StringRef AbbrevDWOSection;
1059 StringRef StringDWOSection;
1060 StringRef GnuPubTypesSection;
1061 StringRef CUIndexSection;
1062 StringRef GdbIndexSection;
1063 StringRef TUIndexSection;
1064
1065 SmallVector<SmallString<32>, 4> UncompressedSections;
1066
1067 StringRef *mapSectionToMember(StringRef Name) {
1068 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1069 return &Sec->Data;
1070 return StringSwitch<StringRef *>(Name)
1071 .Case("debug_abbrev", &AbbrevSection)
1072 .Case("debug_aranges", &ARangeSection)
1073 .Case("debug_frame", &DebugFrameSection)
1074 .Case("eh_frame", &EHFrameSection)
1075 .Case("debug_str", &StringSection)
1076 .Case("debug_macinfo", &MacinfoSection)
1077 .Case("debug_pubnames", &PubNamesSection)
1078 .Case("debug_pubtypes", &PubTypesSection)
1079 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1080 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1081 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1082 .Case("debug_str.dwo", &StringDWOSection)
1083 .Case("debug_cu_index", &CUIndexSection)
1084 .Case("debug_tu_index", &TUIndexSection)
1085 .Case("gdb_index", &GdbIndexSection)
1086 // Any more debug info sections go here.
1087 .Default(nullptr);
1088 }
1089
1090 /// If Sec is compressed section, decompresses and updates its contents
1091 /// provided by Data. Otherwise leaves it unchanged.
1092 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1093 StringRef &Data) {
1094 if (!Decompressor::isCompressed(Sec))
1095 return Error::success();
1096
1097 Expected<Decompressor> Decompressor =
1098 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1099 if (!Decompressor)
1100 return Decompressor.takeError();
1101
1102 SmallString<32> Out;
1103 if (auto Err = Decompressor->resizeAndDecompress(Out))
1104 return Err;
1105
1106 UncompressedSections.emplace_back(std::move(Out));
1107 Data = UncompressedSections.back();
1108
1109 return Error::success();
1110 }
1111
1112public:
1113 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1114 uint8_t AddrSize, bool IsLittleEndian)
1115 : IsLittleEndian(IsLittleEndian) {
1116 for (const auto &SecIt : Sections) {
1117 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1118 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001119 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001120 }
1121 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1122 function_ref<ErrorPolicy(Error)> HandleError)
1123 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001124 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1125 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001126
George Rimare1c30f72017-08-15 15:54:43 +00001127 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001128 for (const SectionRef &Section : Obj.sections()) {
1129 StringRef Name;
1130 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001131 ++SectionAmountMap[Name];
1132 SectionNames.push_back({ Name, true });
1133
Rafael Espindolac398e672017-07-19 22:27:28 +00001134 // Skip BSS and Virtual sections, they aren't interesting.
1135 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001136 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001137
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001138 // Skip sections stripped by dsymutil.
1139 if (Section.isStripped())
1140 continue;
1141
Rafael Espindolac398e672017-07-19 22:27:28 +00001142 StringRef Data;
1143 section_iterator RelocatedSection = Section.getRelocatedSection();
1144 // Try to obtain an already relocated version of this section.
1145 // Else use the unrelocated section from the object file. We'll have to
1146 // apply relocations ourselves later.
1147 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1148 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001149
Rafael Espindolac398e672017-07-19 22:27:28 +00001150 if (auto Err = maybeDecompress(Section, Name, Data)) {
1151 ErrorPolicy EP = HandleError(createError(
1152 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001153 if (EP == ErrorPolicy::Halt)
1154 return;
George Rimarfed9f092017-05-17 12:10:51 +00001155 continue;
1156 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001157
1158 // Compressed sections names in GNU style starts from ".z",
1159 // at this point section is decompressed and we drop compression prefix.
1160 Name = Name.substr(
1161 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1162
1163 // Map platform specific debug section names to DWARF standard section
1164 // names.
1165 Name = Obj.mapDebugSectionName(Name);
1166
1167 if (StringRef *SectionData = mapSectionToMember(Name)) {
1168 *SectionData = Data;
1169 if (Name == "debug_ranges") {
1170 // FIXME: Use the other dwo range section when we emit it.
1171 RangeDWOSection.Data = Data;
1172 }
1173 } else if (Name == "debug_types") {
1174 // Find debug_types data by section rather than name as there are
1175 // multiple, comdat grouped, debug_types sections.
1176 TypesSections[Section].Data = Data;
1177 } else if (Name == "debug_types.dwo") {
1178 TypesDWOSections[Section].Data = Data;
1179 }
1180
1181 if (RelocatedSection == Obj.section_end())
1182 continue;
1183
1184 StringRef RelSecName;
1185 StringRef RelSecData;
1186 RelocatedSection->getName(RelSecName);
1187
1188 // If the section we're relocating was relocated already by the JIT,
1189 // then we used the relocated version above, so we do not need to process
1190 // relocations for it now.
1191 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1192 continue;
1193
1194 // In Mach-o files, the relocations do not need to be applied if
1195 // there is no load offset to apply. The value read at the
1196 // relocation point already factors in the section address
1197 // (actually applying the relocations will produce wrong results
1198 // as the section address will be added twice).
1199 if (!L && isa<MachOObjectFile>(&Obj))
1200 continue;
1201
1202 RelSecName = RelSecName.substr(
1203 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1204
1205 // TODO: Add support for relocations in other sections as needed.
1206 // Record relocations for the debug_info and debug_line sections.
1207 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1208 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1209 if (!Map) {
1210 // Find debug_types relocs by section rather than name as there are
1211 // multiple, comdat grouped, debug_types sections.
1212 if (RelSecName == "debug_types")
1213 Map =
1214 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1215 .Relocs;
1216 else if (RelSecName == "debug_types.dwo")
1217 Map = &static_cast<DWARFSectionMap &>(
1218 TypesDWOSections[*RelocatedSection])
1219 .Relocs;
1220 else
1221 continue;
1222 }
1223
1224 if (Section.relocation_begin() == Section.relocation_end())
1225 continue;
1226
1227 // Symbol to [address, section index] cache mapping.
1228 std::map<SymbolRef, SymInfo> AddrCache;
1229 for (const RelocationRef &Reloc : Section.relocations()) {
1230 // FIXME: it's not clear how to correctly handle scattered
1231 // relocations.
1232 if (isRelocScattered(Obj, Reloc))
1233 continue;
1234
1235 Expected<SymInfo> SymInfoOrErr =
1236 getSymbolInfo(Obj, Reloc, L, AddrCache);
1237 if (!SymInfoOrErr) {
1238 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1239 return;
1240 continue;
1241 }
1242
1243 object::RelocVisitor V(Obj);
1244 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1245 if (V.error()) {
1246 SmallString<32> Type;
1247 Reloc.getTypeName(Type);
1248 ErrorPolicy EP = HandleError(
1249 createError("failed to compute relocation: " + Type + ", ",
1250 errorCodeToError(object_error::parse_failed)));
1251 if (EP == ErrorPolicy::Halt)
1252 return;
1253 continue;
1254 }
1255 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1256 Map->insert({Reloc.getOffset(), Rel});
1257 }
Eric Christopher7370b552012-11-12 21:40:38 +00001258 }
George Rimare1c30f72017-08-15 15:54:43 +00001259
1260 for (SectionName &S : SectionNames)
1261 if (SectionAmountMap[S.Name] > 1)
1262 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001263 }
Eric Christopher7370b552012-11-12 21:40:38 +00001264
Rafael Espindolac398e672017-07-19 22:27:28 +00001265 Optional<RelocAddrEntry> find(const DWARFSection &S,
1266 uint64_t Pos) const override {
1267 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1268 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1269 if (AI == Sec.Relocs.end())
1270 return None;
1271 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001272 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001273
George Rimar6957ab52017-08-15 12:32:54 +00001274 const object::ObjectFile *getFile() const override { return Obj; }
1275
George Rimare1c30f72017-08-15 15:54:43 +00001276 ArrayRef<SectionName> getSectionNames() const override {
1277 return SectionNames;
1278 }
1279
Rafael Espindolac398e672017-07-19 22:27:28 +00001280 bool isLittleEndian() const override { return IsLittleEndian; }
1281 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1282 const DWARFSection &getLineDWOSection() const override {
1283 return LineDWOSection;
1284 }
1285 const DWARFSection &getLocDWOSection() const override {
1286 return LocDWOSection;
1287 }
1288 StringRef getStringDWOSection() const override { return StringDWOSection; }
1289 const DWARFSection &getStringOffsetDWOSection() const override {
1290 return StringOffsetDWOSection;
1291 }
1292 const DWARFSection &getRangeDWOSection() const override {
1293 return RangeDWOSection;
1294 }
1295 const DWARFSection &getAddrSection() const override { return AddrSection; }
1296 StringRef getCUIndexSection() const override { return CUIndexSection; }
1297 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1298 StringRef getTUIndexSection() const override { return TUIndexSection; }
1299
1300 // DWARF v5
1301 const DWARFSection &getStringOffsetSection() const override {
1302 return StringOffsetSection;
1303 }
1304
1305 // Sections for DWARF5 split dwarf proposal.
1306 const DWARFSection &getInfoDWOSection() const override {
1307 return InfoDWOSection;
1308 }
1309 void forEachTypesDWOSections(
1310 function_ref<void(const DWARFSection &)> F) const override {
1311 for (auto &P : TypesDWOSections)
1312 F(P.second);
1313 }
1314
1315 StringRef getAbbrevSection() const override { return AbbrevSection; }
1316 const DWARFSection &getLocSection() const override { return LocSection; }
1317 StringRef getARangeSection() const override { return ARangeSection; }
1318 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1319 StringRef getEHFrameSection() const override { return EHFrameSection; }
1320 const DWARFSection &getLineSection() const override { return LineSection; }
1321 StringRef getStringSection() const override { return StringSection; }
1322 const DWARFSection &getRangeSection() const override { return RangeSection; }
1323 StringRef getMacinfoSection() const override { return MacinfoSection; }
1324 StringRef getPubNamesSection() const override { return PubNamesSection; }
1325 StringRef getPubTypesSection() const override { return PubTypesSection; }
1326 StringRef getGnuPubNamesSection() const override {
1327 return GnuPubNamesSection;
1328 }
1329 StringRef getGnuPubTypesSection() const override {
1330 return GnuPubTypesSection;
1331 }
1332 const DWARFSection &getAppleNamesSection() const override {
1333 return AppleNamesSection;
1334 }
1335 const DWARFSection &getAppleTypesSection() const override {
1336 return AppleTypesSection;
1337 }
1338 const DWARFSection &getAppleNamespacesSection() const override {
1339 return AppleNamespacesSection;
1340 }
1341 const DWARFSection &getAppleObjCSection() const override {
1342 return AppleObjCSection;
1343 }
1344
1345 StringRef getFileName() const override { return FileName; }
1346 uint8_t getAddressSize() const override { return AddressSize; }
1347 const DWARFSection &getInfoSection() const override { return InfoSection; }
1348 void forEachTypesSections(
1349 function_ref<void(const DWARFSection &)> F) const override {
1350 for (auto &P : TypesSections)
1351 F(P.second);
1352 }
1353};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001354} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001355
1356std::unique_ptr<DWARFContext>
1357DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001358 function_ref<ErrorPolicy(Error)> HandleError,
1359 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001360 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001361 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001362}
1363
Rafael Espindolac398e672017-07-19 22:27:28 +00001364std::unique_ptr<DWARFContext>
1365DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1366 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001367 auto DObj =
1368 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001369 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001370}
Reid Klecknera0587362017-08-29 21:41:21 +00001371
1372Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1373 // Detect the architecture from the object file. We usually don't need OS
1374 // info to lookup a target and create register info.
1375 Triple TT;
1376 TT.setArch(Triple::ArchType(Obj.getArch()));
1377 TT.setVendor(Triple::UnknownVendor);
1378 TT.setOS(Triple::UnknownOS);
1379 std::string TargetLookupError;
1380 const Target *TheTarget =
1381 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1382 if (!TargetLookupError.empty())
1383 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1384 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1385 return Error::success();
1386}