blob: 0e28954f5c1c273b03a7cecd9c62862dde73719e [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)
261 getDIEForOffset(DumpOffset.getValue()).dump(OS, 0, 0, DumpOpts);
262 else
263 for (const auto &CU : CUs)
Adrian Prantl057d3362017-09-15 23:04:04 +0000264 CU->dump(OS, DumpOpts);
265 }
266 };
267 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
268 compile_units());
269 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
270 dwo_compile_units());
David Blaikie622dce42014-01-08 23:29:59 +0000271
Adrian Prantl099d7e42017-09-16 16:58:18 +0000272 auto dumpDebugType = [&](const char *Name,
273 tu_section_iterator_range TUSections) {
274 OS << '\n' << Name << " contents:\n";
275 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
276 for (const auto &TUS : TUSections)
277 for (const auto &TU : TUS)
278 if (DumpOffset)
Adrian Prantldc7d4602017-09-18 19:55:00 +0000279 TU->getDIEForOffset(*DumpOffset).dump(OS, 0, 0, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000280 else
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000281 TU->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000282 };
283 if ((DumpType & DIDT_DebugTypes)) {
284 if (Explicit || getNumTypeUnits())
285 dumpDebugType(".debug_types", type_unit_sections());
286 if (ExplicitDWO || getNumDWOTypeUnits())
287 dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
David Blaikie03c089c2013-09-23 22:44:47 +0000288 }
289
Adrian Prantl057d3362017-09-15 23:04:04 +0000290 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000291 DObj->getLocSection().Data)) {
Reid Klecknera0587362017-08-29 21:41:21 +0000292 getDebugLoc()->dump(OS, getRegisterInfo());
David Blaikie18e73502013-06-19 21:37:13 +0000293 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000294 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000295 DObj->getLocDWOSection().Data)) {
Reid Klecknera0587362017-08-29 21:41:21 +0000296 getDebugLocDWO()->dump(OS, getRegisterInfo());
David Blaikie9c550ac2014-03-25 01:44:02 +0000297 }
298
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000299 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
Adrian Prantl84168022017-09-15 17:39:50 +0000300 DObj->getDebugFrameSection())) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000301 getDebugFrame()->dump(OS);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000302 }
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000303
304 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
305 DObj->getEHFrameSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000306 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 Blaikiee79dda32017-09-19 18:36:11 +0000467 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000468
David Blaikieebac0b92017-07-30 08:12:07 +0000469 if (const auto &CUI = getCUIndex()) {
470 if (const auto *R = CUI.getFromHash(Hash))
David Blaikiee79dda32017-09-19 18:36:11 +0000471 return DWOCUs.getUnitForIndexEntry(*R);
David Blaikieebac0b92017-07-30 08:12:07 +0000472 return nullptr;
473 }
474
475 // If there's no index, just search through the CUs in the DWO - there's
476 // probably only one unless this is something like LTO - though an in-process
477 // built/cached lookup table could be used in that case to improve repeated
478 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000479 for (const auto &DWOCU : dwo_compile_units())
480 if (DWOCU->getDWOId() == Hash)
481 return DWOCU.get();
482 return nullptr;
483}
484
Greg Claytonc7695a82017-05-02 20:28:33 +0000485DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
486 parseCompileUnits();
487 if (auto *CU = CUs.getUnitForOffset(Offset))
488 return CU->getDIEForOffset(Offset);
489 return DWARFDie();
490}
491
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000492bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000493 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000494 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000495
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000496 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000497 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000498 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000499 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000500 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000501 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000502 return Success;
503}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000504
David Blaikie82641be2015-11-17 00:39:55 +0000505const DWARFUnitIndex &DWARFContext::getCUIndex() {
506 if (CUIndex)
507 return *CUIndex;
508
Rafael Espindolac398e672017-07-19 22:27:28 +0000509 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000510
David Blaikieb073cb92015-12-02 06:21:34 +0000511 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000512 CUIndex->parse(CUIndexData);
513 return *CUIndex;
514}
515
516const DWARFUnitIndex &DWARFContext::getTUIndex() {
517 if (TUIndex)
518 return *TUIndex;
519
Rafael Espindolac398e672017-07-19 22:27:28 +0000520 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000521
David Blaikieb073cb92015-12-02 06:21:34 +0000522 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000523 TUIndex->parse(TUIndexData);
524 return *TUIndex;
525}
526
George Rimar4f82df52016-09-23 11:01:53 +0000527DWARFGdbIndex &DWARFContext::getGdbIndex() {
528 if (GdbIndex)
529 return *GdbIndex;
530
Rafael Espindolac398e672017-07-19 22:27:28 +0000531 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000532 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
533 GdbIndex->parse(GdbIndexData);
534 return *GdbIndex;
535}
536
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000537const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
538 if (Abbrev)
539 return Abbrev.get();
540
Rafael Espindolac398e672017-07-19 22:27:28 +0000541 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000542
543 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000544 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000545 return Abbrev.get();
546}
547
Eric Christopherda4b2192013-01-02 23:52:13 +0000548const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
549 if (AbbrevDWO)
550 return AbbrevDWO.get();
551
Rafael Espindolac398e672017-07-19 22:27:28 +0000552 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000553 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000554 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000555 return AbbrevDWO.get();
556}
557
David Blaikie18e73502013-06-19 21:37:13 +0000558const DWARFDebugLoc *DWARFContext::getDebugLoc() {
559 if (Loc)
560 return Loc.get();
561
Paul Robinson17536b92017-06-29 16:52:08 +0000562 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000563 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000564 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000565 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000566 getCompileUnitAtIndex(0)->getAddressByteSize());
567 Loc->parse(LocData);
568 }
David Blaikie18e73502013-06-19 21:37:13 +0000569 return Loc.get();
570}
571
David Blaikie9c550ac2014-03-25 01:44:02 +0000572const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
573 if (LocDWO)
574 return LocDWO.get();
575
Rafael Espindolac398e672017-07-19 22:27:28 +0000576 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000577 LocDWO.reset(new DWARFDebugLocDWO());
578 LocDWO->parse(LocData);
579 return LocDWO.get();
580}
581
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000582const DWARFDebugAranges *DWARFContext::getDebugAranges() {
583 if (Aranges)
584 return Aranges.get();
585
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000586 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000587 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000588 return Aranges.get();
589}
590
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000591const DWARFDebugFrame *DWARFContext::getDebugFrame() {
592 if (DebugFrame)
593 return DebugFrame.get();
594
595 // There's a "bug" in the DWARFv3 standard with respect to the target address
596 // size within debug frame sections. While DWARF is supposed to be independent
597 // of its container, FDEs have fields with size being "target address size",
598 // which isn't specified in DWARF in general. It's only specified for CUs, but
599 // .eh_frame can appear without a .debug_info section. Follow the example of
600 // other tools (libdwarf) and extract this from the container (ObjectFile
601 // provides this information). This problem is fixed in DWARFv4
602 // See this dwarf-discuss discussion for more details:
603 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000604 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
605 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000606 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
607 DebugFrame->parse(debugFrameData);
608 return DebugFrame.get();
609}
610
611const DWARFDebugFrame *DWARFContext::getEHFrame() {
612 if (EHFrame)
613 return EHFrame.get();
614
Rafael Espindolac398e672017-07-19 22:27:28 +0000615 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
616 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000617 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000618 DebugFrame->parse(debugFrameData);
619 return DebugFrame.get();
620}
621
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000622const DWARFDebugMacro *DWARFContext::getDebugMacro() {
623 if (Macro)
624 return Macro.get();
625
Rafael Espindolac398e672017-07-19 22:27:28 +0000626 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000627 Macro.reset(new DWARFDebugMacro());
628 Macro->parse(MacinfoData);
629 return Macro.get();
630}
631
Eric Christopher494109b2012-10-16 23:46:25 +0000632const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000633DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000634 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000635 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000636
Greg Claytonc8c10322016-12-13 18:25:19 +0000637 auto UnitDIE = U->getUnitDIE();
638 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000639 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000640
Greg Clayton97d22182017-01-13 21:08:18 +0000641 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000642 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000643 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000644
Greg Clayton52fe1f62016-12-14 22:38:08 +0000645 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000646 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000647 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000648 return lt;
649
Greg Clayton48ff66a2017-05-04 18:29:44 +0000650 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000651 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000652 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000653
Benjamin Kramer679e1752011-09-15 20:43:18 +0000654 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000655 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000656 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000657 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000658}
659
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000660void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000661 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000662}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000663
David Blaikie03c089c2013-09-23 22:44:47 +0000664void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000665 if (!TUs.empty())
666 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000667 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000668 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000669 TUs.back().parse(*this, S);
670 });
David Blaikie03c089c2013-09-23 22:44:47 +0000671}
672
Eric Christopherda4b2192013-01-02 23:52:13 +0000673void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000674 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000675}
676
David Blaikie92d9d622014-01-09 05:08:24 +0000677void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000678 if (!DWOTUs.empty())
679 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000680 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000681 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000682 DWOTUs.back().parseDWO(*this, S);
683 });
David Blaikie92d9d622014-01-09 05:08:24 +0000684}
685
Alexey Samsonov45be7932012-08-30 07:49:50 +0000686DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000687 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000688 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000689}
690
Alexey Samsonov45be7932012-08-30 07:49:50 +0000691DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000692 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000693 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000694 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000695 return getCompileUnitForOffset(CUOffset);
696}
697
David Blaikieefc4eba2017-02-06 20:19:02 +0000698static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
699 uint64_t Address,
700 FunctionNameKind Kind,
701 std::string &FunctionName,
702 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000703 // The address may correspond to instruction in some inlined function,
704 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000705 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000706 SmallVector<DWARFDie, 4> InlinedChain;
707 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000708 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000709 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000710
711 const DWARFDie &DIE = InlinedChain[0];
712 bool FoundResult = false;
713 const char *Name = nullptr;
714 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000715 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000716 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000717 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000718 if (auto DeclLineResult = DIE.getDeclLine()) {
719 StartLine = DeclLineResult;
720 FoundResult = true;
721 }
722
723 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000724}
725
Alexey Samsonov45be7932012-08-30 07:49:50 +0000726DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000727 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000728 DILineInfo Result;
729
Alexey Samsonov45be7932012-08-30 07:49:50 +0000730 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
731 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000732 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000733 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
734 Result.FunctionName,
735 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000736 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000737 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
738 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
739 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000740 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000741 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000742}
David Blaikiea379b1812011-12-20 02:50:00 +0000743
Alexey Samsonovdce67342014-05-15 21:24:32 +0000744DILineInfoTable
745DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
746 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000747 DILineInfoTable Lines;
748 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
749 if (!CU)
750 return Lines;
751
752 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000753 uint32_t StartLine = 0;
754 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
755 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000756
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000757 // If the Specifier says we don't need FileLineInfo, just
758 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000759 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000760 DILineInfo Result;
761 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000762 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000763 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000764 return Lines;
765 }
766
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000767 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000768
769 // Get the index of row we're looking for in the line table.
770 std::vector<uint32_t> RowVector;
771 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
772 return Lines;
773
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000774 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000775 // Take file number and line/column from the row.
776 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000777 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000778 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
779 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000780 Result.FunctionName = FunctionName;
781 Result.Line = Row.Line;
782 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000783 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000784 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000785 }
786
787 return Lines;
788}
789
Alexey Samsonovdce67342014-05-15 21:24:32 +0000790DIInliningInfo
791DWARFContext::getInliningInfoForAddress(uint64_t Address,
792 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000793 DIInliningInfo InliningInfo;
794
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000795 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
796 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000797 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000798
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000799 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000800 SmallVector<DWARFDie, 4> InlinedChain;
801 CU->getInlinedChainForAddress(Address, InlinedChain);
802 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000803 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
804 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000805 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000806 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000807 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000808 if (LineTable &&
809 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
810 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000811 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000812 }
813 return InliningInfo;
814 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000815
Dehao Chenef700d52017-04-17 20:10:39 +0000816 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000817 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
818 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000819 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000820 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000821 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000822 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000823 if (auto DeclLineResult = FunctionDIE.getDeclLine())
824 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000825 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000826 if (i == 0) {
827 // For the topmost frame, initialize the line table of this
828 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000829 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000830 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000831 if (LineTable)
832 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
833 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000834 } else {
835 // Otherwise, use call file, call line and call column from
836 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000837 if (LineTable)
838 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
839 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000840 Frame.Line = CallLine;
841 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000842 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000843 }
844 // Get call file/line/column of a current DIE.
845 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000846 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
847 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000848 }
849 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000850 InliningInfo.addFrame(Frame);
851 }
852 return InliningInfo;
853}
854
David Blaikief9803fb2017-05-23 00:30:42 +0000855std::shared_ptr<DWARFContext>
856DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000857 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000858 DWARFContext *Ctxt = S->Context.get();
859 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
860 }
861
David Blaikie15d85fc2017-05-23 06:48:53 +0000862 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
863
864 if (auto S = Entry->lock()) {
865 DWARFContext *Ctxt = S->Context.get();
866 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
867 }
868
David Blaikie15d85fc2017-05-23 06:48:53 +0000869 Expected<OwningBinary<ObjectFile>> Obj = [&] {
870 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000871 SmallString<128> DWPName;
872 auto Obj = object::ObjectFile::createObjectFile(
873 this->DWPName.empty()
874 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
875 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000876 if (Obj) {
877 Entry = &DWP;
878 return Obj;
879 } else {
880 CheckedForDWP = true;
881 // TODO: Should this error be handled (maybe in a high verbosity mode)
882 // before falling back to .dwo files?
883 consumeError(Obj.takeError());
884 }
885 }
886
887 return object::ObjectFile::createObjectFile(AbsolutePath);
888 }();
889
David Blaikief9803fb2017-05-23 00:30:42 +0000890 if (!Obj) {
891 // TODO: Actually report errors helpfully.
892 consumeError(Obj.takeError());
893 return nullptr;
894 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000895
896 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000897 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000898 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000899 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000900 auto *Ctxt = S->Context.get();
901 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
902}
903
George Rimar702dac62017-04-12 08:59:15 +0000904static Error createError(const Twine &Reason, llvm::Error E) {
905 return make_error<StringError>(Reason + toString(std::move(E)),
906 inconvertibleErrorCode());
907}
908
George Rimara25d3292017-05-27 18:10:23 +0000909/// SymInfo contains information about symbol: it's address
910/// and section index which is -1LL for absolute symbols.
911struct SymInfo {
912 uint64_t Address;
913 uint64_t SectionIndex;
914};
915
916/// Returns the address of symbol relocation used against and a section index.
917/// Used for futher relocations computation. Symbol's section load address is
918static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
919 const RelocationRef &Reloc,
920 const LoadedObjectInfo *L,
921 std::map<SymbolRef, SymInfo> &Cache) {
922 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000923 object::section_iterator RSec = Obj.section_end();
924 object::symbol_iterator Sym = Reloc.getSymbol();
925
George Rimara25d3292017-05-27 18:10:23 +0000926 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000927 // First calculate the address of the symbol or section as it appears
928 // in the object file
929 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000930 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000931 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000932 if (!New)
933 return CacheIt->second;
934
George Rimar702dac62017-04-12 08:59:15 +0000935 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
936 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000937 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000938 SymAddrOrErr.takeError());
939
940 // Also remember what section this symbol is in for later
941 auto SectOrErr = Sym->getSection();
942 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000943 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000944 SectOrErr.takeError());
945
946 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000947 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000948 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
949 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000950 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000951 }
952
George Rimara25d3292017-05-27 18:10:23 +0000953 if (RSec != Obj.section_end())
954 Ret.SectionIndex = RSec->getIndex();
955
George Rimar702dac62017-04-12 08:59:15 +0000956 // If we are given load addresses for the sections, we need to adjust:
957 // SymAddr = (Address of Symbol Or Section in File) -
958 // (Address of Section in File) +
959 // (Load Address of Section)
960 // RSec is now either the section being targeted or the section
961 // containing the symbol being targeted. In either case,
962 // we need to perform the same computation.
963 if (L && RSec != Obj.section_end())
964 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000965 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000966
967 if (CacheIt != Cache.end())
968 CacheIt->second = Ret;
969
George Rimar702dac62017-04-12 08:59:15 +0000970 return Ret;
971}
972
973static bool isRelocScattered(const object::ObjectFile &Obj,
974 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000975 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
976 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000977 return false;
978 // MachO also has relocations that point to sections and
979 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000980 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
981 return MachObj->isRelocationScattered(RelocInfo);
982}
983
Rafael Espindolac398e672017-07-19 22:27:28 +0000984ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000985 errs() << "error: " + toString(std::move(E)) << '\n';
986 return ErrorPolicy::Continue;
987}
988
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000989namespace {
990struct DWARFSectionMap final : public DWARFSection {
991 RelocAddrMap Relocs;
992};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000993
Rafael Espindolac398e672017-07-19 22:27:28 +0000994class DWARFObjInMemory final : public DWARFObject {
995 bool IsLittleEndian;
996 uint8_t AddressSize;
997 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +0000998 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +0000999 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001000
Rafael Espindolac398e672017-07-19 22:27:28 +00001001 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1002 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001003
Rafael Espindolac398e672017-07-19 22:27:28 +00001004 TypeSectionMap TypesSections;
1005 TypeSectionMap TypesDWOSections;
1006
1007 DWARFSectionMap InfoSection;
1008 DWARFSectionMap LocSection;
1009 DWARFSectionMap LineSection;
1010 DWARFSectionMap RangeSection;
1011 DWARFSectionMap StringOffsetSection;
1012 DWARFSectionMap InfoDWOSection;
1013 DWARFSectionMap LineDWOSection;
1014 DWARFSectionMap LocDWOSection;
1015 DWARFSectionMap StringOffsetDWOSection;
1016 DWARFSectionMap RangeDWOSection;
1017 DWARFSectionMap AddrSection;
1018 DWARFSectionMap AppleNamesSection;
1019 DWARFSectionMap AppleTypesSection;
1020 DWARFSectionMap AppleNamespacesSection;
1021 DWARFSectionMap AppleObjCSection;
1022
1023 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1024 return StringSwitch<DWARFSectionMap *>(Name)
1025 .Case("debug_info", &InfoSection)
1026 .Case("debug_loc", &LocSection)
1027 .Case("debug_line", &LineSection)
1028 .Case("debug_str_offsets", &StringOffsetSection)
1029 .Case("debug_ranges", &RangeSection)
1030 .Case("debug_info.dwo", &InfoDWOSection)
1031 .Case("debug_loc.dwo", &LocDWOSection)
1032 .Case("debug_line.dwo", &LineDWOSection)
1033 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1034 .Case("debug_addr", &AddrSection)
1035 .Case("apple_names", &AppleNamesSection)
1036 .Case("apple_types", &AppleTypesSection)
1037 .Case("apple_namespaces", &AppleNamespacesSection)
1038 .Case("apple_namespac", &AppleNamespacesSection)
1039 .Case("apple_objc", &AppleObjCSection)
1040 .Default(nullptr);
1041 }
1042
1043 StringRef AbbrevSection;
1044 StringRef ARangeSection;
1045 StringRef DebugFrameSection;
1046 StringRef EHFrameSection;
1047 StringRef StringSection;
1048 StringRef MacinfoSection;
1049 StringRef PubNamesSection;
1050 StringRef PubTypesSection;
1051 StringRef GnuPubNamesSection;
1052 StringRef AbbrevDWOSection;
1053 StringRef StringDWOSection;
1054 StringRef GnuPubTypesSection;
1055 StringRef CUIndexSection;
1056 StringRef GdbIndexSection;
1057 StringRef TUIndexSection;
1058
1059 SmallVector<SmallString<32>, 4> UncompressedSections;
1060
1061 StringRef *mapSectionToMember(StringRef Name) {
1062 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1063 return &Sec->Data;
1064 return StringSwitch<StringRef *>(Name)
1065 .Case("debug_abbrev", &AbbrevSection)
1066 .Case("debug_aranges", &ARangeSection)
1067 .Case("debug_frame", &DebugFrameSection)
1068 .Case("eh_frame", &EHFrameSection)
1069 .Case("debug_str", &StringSection)
1070 .Case("debug_macinfo", &MacinfoSection)
1071 .Case("debug_pubnames", &PubNamesSection)
1072 .Case("debug_pubtypes", &PubTypesSection)
1073 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1074 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1075 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1076 .Case("debug_str.dwo", &StringDWOSection)
1077 .Case("debug_cu_index", &CUIndexSection)
1078 .Case("debug_tu_index", &TUIndexSection)
1079 .Case("gdb_index", &GdbIndexSection)
1080 // Any more debug info sections go here.
1081 .Default(nullptr);
1082 }
1083
1084 /// If Sec is compressed section, decompresses and updates its contents
1085 /// provided by Data. Otherwise leaves it unchanged.
1086 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1087 StringRef &Data) {
1088 if (!Decompressor::isCompressed(Sec))
1089 return Error::success();
1090
1091 Expected<Decompressor> Decompressor =
1092 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1093 if (!Decompressor)
1094 return Decompressor.takeError();
1095
1096 SmallString<32> Out;
1097 if (auto Err = Decompressor->resizeAndDecompress(Out))
1098 return Err;
1099
1100 UncompressedSections.emplace_back(std::move(Out));
1101 Data = UncompressedSections.back();
1102
1103 return Error::success();
1104 }
1105
1106public:
1107 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1108 uint8_t AddrSize, bool IsLittleEndian)
1109 : IsLittleEndian(IsLittleEndian) {
1110 for (const auto &SecIt : Sections) {
1111 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1112 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001113 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001114 }
1115 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1116 function_ref<ErrorPolicy(Error)> HandleError)
1117 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001118 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1119 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001120
George Rimare1c30f72017-08-15 15:54:43 +00001121 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001122 for (const SectionRef &Section : Obj.sections()) {
1123 StringRef Name;
1124 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001125 ++SectionAmountMap[Name];
1126 SectionNames.push_back({ Name, true });
1127
Rafael Espindolac398e672017-07-19 22:27:28 +00001128 // Skip BSS and Virtual sections, they aren't interesting.
1129 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001130 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001131
Rafael Espindolac398e672017-07-19 22:27:28 +00001132 StringRef Data;
1133 section_iterator RelocatedSection = Section.getRelocatedSection();
1134 // Try to obtain an already relocated version of this section.
1135 // Else use the unrelocated section from the object file. We'll have to
1136 // apply relocations ourselves later.
1137 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1138 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001139
Rafael Espindolac398e672017-07-19 22:27:28 +00001140 if (auto Err = maybeDecompress(Section, Name, Data)) {
1141 ErrorPolicy EP = HandleError(createError(
1142 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001143 if (EP == ErrorPolicy::Halt)
1144 return;
George Rimarfed9f092017-05-17 12:10:51 +00001145 continue;
1146 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001147
1148 // Compressed sections names in GNU style starts from ".z",
1149 // at this point section is decompressed and we drop compression prefix.
1150 Name = Name.substr(
1151 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1152
1153 // Map platform specific debug section names to DWARF standard section
1154 // names.
1155 Name = Obj.mapDebugSectionName(Name);
1156
1157 if (StringRef *SectionData = mapSectionToMember(Name)) {
1158 *SectionData = Data;
1159 if (Name == "debug_ranges") {
1160 // FIXME: Use the other dwo range section when we emit it.
1161 RangeDWOSection.Data = Data;
1162 }
1163 } else if (Name == "debug_types") {
1164 // Find debug_types data by section rather than name as there are
1165 // multiple, comdat grouped, debug_types sections.
1166 TypesSections[Section].Data = Data;
1167 } else if (Name == "debug_types.dwo") {
1168 TypesDWOSections[Section].Data = Data;
1169 }
1170
1171 if (RelocatedSection == Obj.section_end())
1172 continue;
1173
1174 StringRef RelSecName;
1175 StringRef RelSecData;
1176 RelocatedSection->getName(RelSecName);
1177
1178 // If the section we're relocating was relocated already by the JIT,
1179 // then we used the relocated version above, so we do not need to process
1180 // relocations for it now.
1181 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1182 continue;
1183
1184 // In Mach-o files, the relocations do not need to be applied if
1185 // there is no load offset to apply. The value read at the
1186 // relocation point already factors in the section address
1187 // (actually applying the relocations will produce wrong results
1188 // as the section address will be added twice).
1189 if (!L && isa<MachOObjectFile>(&Obj))
1190 continue;
1191
1192 RelSecName = RelSecName.substr(
1193 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1194
1195 // TODO: Add support for relocations in other sections as needed.
1196 // Record relocations for the debug_info and debug_line sections.
1197 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1198 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1199 if (!Map) {
1200 // Find debug_types relocs by section rather than name as there are
1201 // multiple, comdat grouped, debug_types sections.
1202 if (RelSecName == "debug_types")
1203 Map =
1204 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1205 .Relocs;
1206 else if (RelSecName == "debug_types.dwo")
1207 Map = &static_cast<DWARFSectionMap &>(
1208 TypesDWOSections[*RelocatedSection])
1209 .Relocs;
1210 else
1211 continue;
1212 }
1213
1214 if (Section.relocation_begin() == Section.relocation_end())
1215 continue;
1216
1217 // Symbol to [address, section index] cache mapping.
1218 std::map<SymbolRef, SymInfo> AddrCache;
1219 for (const RelocationRef &Reloc : Section.relocations()) {
1220 // FIXME: it's not clear how to correctly handle scattered
1221 // relocations.
1222 if (isRelocScattered(Obj, Reloc))
1223 continue;
1224
1225 Expected<SymInfo> SymInfoOrErr =
1226 getSymbolInfo(Obj, Reloc, L, AddrCache);
1227 if (!SymInfoOrErr) {
1228 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1229 return;
1230 continue;
1231 }
1232
1233 object::RelocVisitor V(Obj);
1234 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1235 if (V.error()) {
1236 SmallString<32> Type;
1237 Reloc.getTypeName(Type);
1238 ErrorPolicy EP = HandleError(
1239 createError("failed to compute relocation: " + Type + ", ",
1240 errorCodeToError(object_error::parse_failed)));
1241 if (EP == ErrorPolicy::Halt)
1242 return;
1243 continue;
1244 }
1245 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1246 Map->insert({Reloc.getOffset(), Rel});
1247 }
Eric Christopher7370b552012-11-12 21:40:38 +00001248 }
George Rimare1c30f72017-08-15 15:54:43 +00001249
1250 for (SectionName &S : SectionNames)
1251 if (SectionAmountMap[S.Name] > 1)
1252 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001253 }
Eric Christopher7370b552012-11-12 21:40:38 +00001254
Rafael Espindolac398e672017-07-19 22:27:28 +00001255 Optional<RelocAddrEntry> find(const DWARFSection &S,
1256 uint64_t Pos) const override {
1257 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1258 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1259 if (AI == Sec.Relocs.end())
1260 return None;
1261 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001262 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001263
George Rimar6957ab52017-08-15 12:32:54 +00001264 const object::ObjectFile *getFile() const override { return Obj; }
1265
George Rimare1c30f72017-08-15 15:54:43 +00001266 ArrayRef<SectionName> getSectionNames() const override {
1267 return SectionNames;
1268 }
1269
Rafael Espindolac398e672017-07-19 22:27:28 +00001270 bool isLittleEndian() const override { return IsLittleEndian; }
1271 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1272 const DWARFSection &getLineDWOSection() const override {
1273 return LineDWOSection;
1274 }
1275 const DWARFSection &getLocDWOSection() const override {
1276 return LocDWOSection;
1277 }
1278 StringRef getStringDWOSection() const override { return StringDWOSection; }
1279 const DWARFSection &getStringOffsetDWOSection() const override {
1280 return StringOffsetDWOSection;
1281 }
1282 const DWARFSection &getRangeDWOSection() const override {
1283 return RangeDWOSection;
1284 }
1285 const DWARFSection &getAddrSection() const override { return AddrSection; }
1286 StringRef getCUIndexSection() const override { return CUIndexSection; }
1287 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1288 StringRef getTUIndexSection() const override { return TUIndexSection; }
1289
1290 // DWARF v5
1291 const DWARFSection &getStringOffsetSection() const override {
1292 return StringOffsetSection;
1293 }
1294
1295 // Sections for DWARF5 split dwarf proposal.
1296 const DWARFSection &getInfoDWOSection() const override {
1297 return InfoDWOSection;
1298 }
1299 void forEachTypesDWOSections(
1300 function_ref<void(const DWARFSection &)> F) const override {
1301 for (auto &P : TypesDWOSections)
1302 F(P.second);
1303 }
1304
1305 StringRef getAbbrevSection() const override { return AbbrevSection; }
1306 const DWARFSection &getLocSection() const override { return LocSection; }
1307 StringRef getARangeSection() const override { return ARangeSection; }
1308 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1309 StringRef getEHFrameSection() const override { return EHFrameSection; }
1310 const DWARFSection &getLineSection() const override { return LineSection; }
1311 StringRef getStringSection() const override { return StringSection; }
1312 const DWARFSection &getRangeSection() const override { return RangeSection; }
1313 StringRef getMacinfoSection() const override { return MacinfoSection; }
1314 StringRef getPubNamesSection() const override { return PubNamesSection; }
1315 StringRef getPubTypesSection() const override { return PubTypesSection; }
1316 StringRef getGnuPubNamesSection() const override {
1317 return GnuPubNamesSection;
1318 }
1319 StringRef getGnuPubTypesSection() const override {
1320 return GnuPubTypesSection;
1321 }
1322 const DWARFSection &getAppleNamesSection() const override {
1323 return AppleNamesSection;
1324 }
1325 const DWARFSection &getAppleTypesSection() const override {
1326 return AppleTypesSection;
1327 }
1328 const DWARFSection &getAppleNamespacesSection() const override {
1329 return AppleNamespacesSection;
1330 }
1331 const DWARFSection &getAppleObjCSection() const override {
1332 return AppleObjCSection;
1333 }
1334
1335 StringRef getFileName() const override { return FileName; }
1336 uint8_t getAddressSize() const override { return AddressSize; }
1337 const DWARFSection &getInfoSection() const override { return InfoSection; }
1338 void forEachTypesSections(
1339 function_ref<void(const DWARFSection &)> F) const override {
1340 for (auto &P : TypesSections)
1341 F(P.second);
1342 }
1343};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001344} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001345
1346std::unique_ptr<DWARFContext>
1347DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001348 function_ref<ErrorPolicy(Error)> HandleError,
1349 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001350 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001351 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001352}
1353
Rafael Espindolac398e672017-07-19 22:27:28 +00001354std::unique_ptr<DWARFContext>
1355DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1356 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001357 auto DObj =
1358 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001359 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001360}
Reid Klecknera0587362017-08-29 21:41:21 +00001361
1362Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1363 // Detect the architecture from the object file. We usually don't need OS
1364 // info to lookup a target and create register info.
1365 Triple TT;
1366 TT.setArch(Triple::ArchType(Obj.getArch()));
1367 TT.setVendor(Triple::UnknownVendor);
1368 TT.setOS(Triple::UnknownOS);
1369 std::string TargetLookupError;
1370 const Target *TheTarget =
1371 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1372 if (!TargetLookupError.empty())
1373 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1374 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1375 return Error::success();
1376}