blob: 353a5bad997d36f3d74b429acc1a7335bc702e1a [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 Prantl597aa482017-09-16 17:28:00 +0000225 unsigned RecDepth =
226 DumpOpts.ShowChildren ? std::numeric_limits<unsigned>::max() : 0;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000227
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000228 StringRef Extension = sys::path::extension(DObj->getFileName());
229 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
230
231 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000232 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000233 if (DumpType & DIDT_UUID)
234 dumpUUID(OS, *ObjFile);
235
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000236 // Print a header for each explicitly-requested section.
237 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000238 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000239 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000240 bool ExplicitDWO = Explicit && IsDWO;
241 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
242 StringRef Section) {
243 DumpOffset = DumpOffsets[ID];
244 unsigned Mask = 1U << ID;
245 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
Adrian Prantl84168022017-09-15 17:39:50 +0000246 if (Should)
Adrian Prantl057d3362017-09-15 23:04:04 +0000247 OS << "\n" << Name << " contents:\n";
Adrian Prantl84168022017-09-15 17:39:50 +0000248 return Should;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000249 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000250
251 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000252 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
253 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000254 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000255 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
256 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000257 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000258
Adrian Prantl057d3362017-09-15 23:04:04 +0000259 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
260 DWARFSection Section, cu_iterator_range CUs) {
261 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
262 for (const auto &CU : CUs)
263 if (DumpOffset)
Adrian Prantl597aa482017-09-16 17:28:00 +0000264 CU->getDIEForOffset(DumpOffset.getValue()).dump(OS, RecDepth);
Adrian Prantl057d3362017-09-15 23:04:04 +0000265 else
266 CU->dump(OS, DumpOpts);
267 }
268 };
269 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
270 compile_units());
271 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
272 dwo_compile_units());
David Blaikie622dce42014-01-08 23:29:59 +0000273
Adrian Prantl099d7e42017-09-16 16:58:18 +0000274 auto dumpDebugType = [&](const char *Name,
275 tu_section_iterator_range TUSections) {
276 OS << '\n' << Name << " contents:\n";
277 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
278 for (const auto &TUS : TUSections)
279 for (const auto &TU : TUS)
280 if (DumpOffset)
Adrian Prantl597aa482017-09-16 17:28:00 +0000281 TU->getDIEForOffset(*DumpOffset).dump(OS, RecDepth);
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)) {
Reid Klecknera0587362017-08-29 21:41:21 +0000294 getDebugLoc()->dump(OS, getRegisterInfo());
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)) {
Reid Klecknera0587362017-08-29 21:41:21 +0000298 getDebugLocDWO()->dump(OS, getRegisterInfo());
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 Prantl84168022017-09-15 17:39:50 +0000302 DObj->getDebugFrameSection())) {
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000303 getDebugFrame()->dump(OS);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000304 }
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000305
306 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
307 DObj->getEHFrameSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000308 getEHFrame()->dump(OS);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000309 }
310
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000311 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000312 if (Explicit || !getDebugMacro()->empty()) {
313 OS << "\n.debug_macinfo contents:\n";
314 getDebugMacro()->dump(OS);
315 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000316 }
317
Adrian Prantl057d3362017-09-15 23:04:04 +0000318 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000319 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000320 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000321 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000322 DWARFDebugArangeSet set;
323 while (set.extract(arangesData, &offset))
324 set.dump(OS);
325 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000326
Alexey Samsonov034e57a2012-08-27 07:17:47 +0000327 uint8_t savedAddressByteSize = 0;
Adrian Prantl057d3362017-09-15 23:04:04 +0000328 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000329 DObj->getLineSection().Data)) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000330 for (const auto &CU : compile_units()) {
331 savedAddressByteSize = CU->getAddressByteSize();
Greg Claytonc8c10322016-12-13 18:25:19 +0000332 auto CUDIE = CU->getUnitDIE();
333 if (!CUDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000334 continue;
Greg Clayton97d22182017-01-13 21:08:18 +0000335 if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list))) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000336 DWARFDataExtractor lineData(*DObj, DObj->getLineSection(),
337 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000338 DWARFDebugLine::LineTable LineTable;
Greg Clayton52fe1f62016-12-14 22:38:08 +0000339 uint32_t Offset = *StmtOffset;
Paul Robinson17536b92017-06-29 16:52:08 +0000340 LineTable.parse(lineData, &Offset);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000341 LineTable.dump(OS);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000342 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000343 }
344 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000345
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000346 // FIXME: This seems sketchy.
347 for (const auto &CU : compile_units()) {
348 savedAddressByteSize = CU->getAddressByteSize();
349 break;
David Blaikie65a8efe2015-11-11 19:28:21 +0000350 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000351 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000352 DObj->getLineDWOSection().Data)) {
David Blaikie1d4736e2014-02-24 23:58:54 +0000353 unsigned stmtOffset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000354 DWARFDataExtractor lineData(*DObj, DObj->getLineDWOSection(),
355 isLittleEndian(), savedAddressByteSize);
Alexey Samsonov110d5952014-04-30 00:09:19 +0000356 DWARFDebugLine::LineTable LineTable;
357 while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
358 LineTable.dump(OS);
359 LineTable.clear();
360 }
David Blaikie1d4736e2014-02-24 23:58:54 +0000361 }
362
Adrian Prantl057d3362017-09-15 23:04:04 +0000363 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000364 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000365 getCUIndex().dump(OS);
366 }
367
Adrian Prantl057d3362017-09-15 23:04:04 +0000368 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000369 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000370 getTUIndex().dump(OS);
371 }
372
Adrian Prantl057d3362017-09-15 23:04:04 +0000373 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000374 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000375 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000376 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000377 uint32_t strOffset = 0;
378 while (const char *s = strData.getCStr(&offset)) {
379 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
380 strOffset = offset;
381 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000382 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000383 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000384 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000385 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000386 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000387 uint32_t strDWOOffset = 0;
388 while (const char *s = strDWOData.getCStr(&offset)) {
389 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
390 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000391 }
David Blaikie66865d62014-01-09 00:13:35 +0000392 }
David Blaikie622dce42014-01-08 23:29:59 +0000393
Adrian Prantl057d3362017-09-15 23:04:04 +0000394 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000395 DObj->getRangeSection().Data)) {
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000396 // In fact, different compile units may have different address byte
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000397 // sizes, but for simplicity we just use the address byte size of the
398 // last compile unit (there is no easy and fast way to associate address
399 // range list and the compile unit it describes).
400 // FIXME: savedAddressByteSize seems sketchy.
Rafael Espindolac398e672017-07-19 22:27:28 +0000401 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
402 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000403 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000404 DWARFDebugRangeList rangeList;
Paul Robinson17536b92017-06-29 16:52:08 +0000405 while (rangeList.extract(rangesData, &offset))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000406 rangeList.dump(OS);
Eric Christopherda4b2192013-01-02 23:52:13 +0000407 }
Eric Christopher962c9082013-01-15 23:56:56 +0000408
Adrian Prantl057d3362017-09-15 23:04:04 +0000409 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000410 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000411 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000412 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000413
Adrian Prantl057d3362017-09-15 23:04:04 +0000414 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000415 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000416 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000417 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000418
Adrian Prantl057d3362017-09-15 23:04:04 +0000419 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000420 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000421 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000422 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000423 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000424
Adrian Prantl057d3362017-09-15 23:04:04 +0000425 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000426 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000427 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000428 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000429 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000430
Adrian Prantl057d3362017-09-15 23:04:04 +0000431 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000432 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000433 dumpStringOffsetsSection(
434 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
435 DObj->getStringSection(), isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000436 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000437 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000438 dumpStringOffsetsSection(
439 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
440 DObj->getStringDWOSection(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000441
Adrian Prantl057d3362017-09-15 23:04:04 +0000442 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000443 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000444 getGdbIndex().dump(OS);
445 }
446
Adrian Prantl057d3362017-09-15 23:04:04 +0000447 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000448 DObj->getAppleNamesSection().Data))
449 dumpAccelSection(OS, *DObj, DObj->getAppleNamesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000450 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000451
Adrian Prantl057d3362017-09-15 23:04:04 +0000452 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000453 DObj->getAppleTypesSection().Data))
454 dumpAccelSection(OS, *DObj, DObj->getAppleTypesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000455 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000456
Adrian Prantl057d3362017-09-15 23:04:04 +0000457 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000458 DObj->getAppleNamespacesSection().Data))
459 dumpAccelSection(OS, *DObj, DObj->getAppleNamespacesSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000460 DObj->getStringSection(), isLittleEndian());
Frederic Risse837ec22014-11-14 16:15:53 +0000461
Adrian Prantl057d3362017-09-15 23:04:04 +0000462 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000463 DObj->getAppleObjCSection().Data))
464 dumpAccelSection(OS, *DObj, DObj->getAppleObjCSection(),
Rafael Espindolac398e672017-07-19 22:27:28 +0000465 DObj->getStringSection(), isLittleEndian());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000466}
467
David Blaikie15d85fc2017-05-23 06:48:53 +0000468DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
David Blaikiea62f1cb2017-07-30 15:15:58 +0000469 parseDWOCompileUnits();
470
David Blaikieebac0b92017-07-30 08:12:07 +0000471 if (const auto &CUI = getCUIndex()) {
472 if (const auto *R = CUI.getFromHash(Hash))
473 if (auto CUOff = R->getOffset(DW_SECT_INFO))
David Blaikiea62f1cb2017-07-30 15:15:58 +0000474 return DWOCUs.getUnitForOffset(CUOff->Offset);
David Blaikieebac0b92017-07-30 08:12:07 +0000475 return nullptr;
476 }
477
478 // If there's no index, just search through the CUs in the DWO - there's
479 // probably only one unless this is something like LTO - though an in-process
480 // built/cached lookup table could be used in that case to improve repeated
481 // lookups of different CUs in the DWO.
David Blaikie15d85fc2017-05-23 06:48:53 +0000482 for (const auto &DWOCU : dwo_compile_units())
483 if (DWOCU->getDWOId() == Hash)
484 return DWOCU.get();
485 return nullptr;
486}
487
Greg Claytonc7695a82017-05-02 20:28:33 +0000488DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
489 parseCompileUnits();
490 if (auto *CU = CUs.getUnitForOffset(Offset))
491 return CU->getDIEForOffset(Offset);
492 return DWARFDie();
493}
494
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000495bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000496 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000497 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000498
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000499 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000500 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000501 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000502 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000503 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000504 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000505 return Success;
506}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000507
David Blaikie82641be2015-11-17 00:39:55 +0000508const DWARFUnitIndex &DWARFContext::getCUIndex() {
509 if (CUIndex)
510 return *CUIndex;
511
Rafael Espindolac398e672017-07-19 22:27:28 +0000512 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000513
David Blaikieb073cb92015-12-02 06:21:34 +0000514 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000515 CUIndex->parse(CUIndexData);
516 return *CUIndex;
517}
518
519const DWARFUnitIndex &DWARFContext::getTUIndex() {
520 if (TUIndex)
521 return *TUIndex;
522
Rafael Espindolac398e672017-07-19 22:27:28 +0000523 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000524
David Blaikieb073cb92015-12-02 06:21:34 +0000525 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000526 TUIndex->parse(TUIndexData);
527 return *TUIndex;
528}
529
George Rimar4f82df52016-09-23 11:01:53 +0000530DWARFGdbIndex &DWARFContext::getGdbIndex() {
531 if (GdbIndex)
532 return *GdbIndex;
533
Rafael Espindolac398e672017-07-19 22:27:28 +0000534 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000535 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
536 GdbIndex->parse(GdbIndexData);
537 return *GdbIndex;
538}
539
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000540const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
541 if (Abbrev)
542 return Abbrev.get();
543
Rafael Espindolac398e672017-07-19 22:27:28 +0000544 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000545
546 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000547 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000548 return Abbrev.get();
549}
550
Eric Christopherda4b2192013-01-02 23:52:13 +0000551const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
552 if (AbbrevDWO)
553 return AbbrevDWO.get();
554
Rafael Espindolac398e672017-07-19 22:27:28 +0000555 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000556 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000557 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000558 return AbbrevDWO.get();
559}
560
David Blaikie18e73502013-06-19 21:37:13 +0000561const DWARFDebugLoc *DWARFContext::getDebugLoc() {
562 if (Loc)
563 return Loc.get();
564
Paul Robinson17536b92017-06-29 16:52:08 +0000565 Loc.reset(new DWARFDebugLoc);
David Blaikie18e73502013-06-19 21:37:13 +0000566 // assume all compile units have the same address byte size
Paul Robinson17536b92017-06-29 16:52:08 +0000567 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000568 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000569 getCompileUnitAtIndex(0)->getAddressByteSize());
570 Loc->parse(LocData);
571 }
David Blaikie18e73502013-06-19 21:37:13 +0000572 return Loc.get();
573}
574
David Blaikie9c550ac2014-03-25 01:44:02 +0000575const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
576 if (LocDWO)
577 return LocDWO.get();
578
Rafael Espindolac398e672017-07-19 22:27:28 +0000579 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
David Blaikie9c550ac2014-03-25 01:44:02 +0000580 LocDWO.reset(new DWARFDebugLocDWO());
581 LocDWO->parse(LocData);
582 return LocDWO.get();
583}
584
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000585const DWARFDebugAranges *DWARFContext::getDebugAranges() {
586 if (Aranges)
587 return Aranges.get();
588
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000589 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000590 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000591 return Aranges.get();
592}
593
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000594const DWARFDebugFrame *DWARFContext::getDebugFrame() {
595 if (DebugFrame)
596 return DebugFrame.get();
597
598 // There's a "bug" in the DWARFv3 standard with respect to the target address
599 // size within debug frame sections. While DWARF is supposed to be independent
600 // of its container, FDEs have fields with size being "target address size",
601 // which isn't specified in DWARF in general. It's only specified for CUs, but
602 // .eh_frame can appear without a .debug_info section. Follow the example of
603 // other tools (libdwarf) and extract this from the container (ObjectFile
604 // provides this information). This problem is fixed in DWARFv4
605 // See this dwarf-discuss discussion for more details:
606 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Espindolac398e672017-07-19 22:27:28 +0000607 DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
608 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000609 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
610 DebugFrame->parse(debugFrameData);
611 return DebugFrame.get();
612}
613
614const DWARFDebugFrame *DWARFContext::getEHFrame() {
615 if (EHFrame)
616 return EHFrame.get();
617
Rafael Espindolac398e672017-07-19 22:27:28 +0000618 DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
619 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000620 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000621 DebugFrame->parse(debugFrameData);
622 return DebugFrame.get();
623}
624
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000625const DWARFDebugMacro *DWARFContext::getDebugMacro() {
626 if (Macro)
627 return Macro.get();
628
Rafael Espindolac398e672017-07-19 22:27:28 +0000629 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000630 Macro.reset(new DWARFDebugMacro());
631 Macro->parse(MacinfoData);
632 return Macro.get();
633}
634
Eric Christopher494109b2012-10-16 23:46:25 +0000635const DWARFLineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000636DWARFContext::getLineTableForUnit(DWARFUnit *U) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000637 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000638 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000639
Greg Claytonc8c10322016-12-13 18:25:19 +0000640 auto UnitDIE = U->getUnitDIE();
641 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000642 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000643
Greg Clayton97d22182017-01-13 21:08:18 +0000644 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000645 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000646 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000647
Greg Clayton52fe1f62016-12-14 22:38:08 +0000648 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000649 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000650 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000651 return lt;
652
Greg Clayton48ff66a2017-05-04 18:29:44 +0000653 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000654 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000655 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000656
Benjamin Kramer679e1752011-09-15 20:43:18 +0000657 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000658 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000659 U->getAddressByteSize());
Benjamin Kramer679e1752011-09-15 20:43:18 +0000660 return Line->getOrParseLineTable(lineData, stmtOffset);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000661}
662
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000663void DWARFContext::parseCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000664 CUs.parse(*this, DObj->getInfoSection());
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000665}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000666
David Blaikie03c089c2013-09-23 22:44:47 +0000667void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000668 if (!TUs.empty())
669 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000670 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000671 TUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000672 TUs.back().parse(*this, S);
673 });
David Blaikie03c089c2013-09-23 22:44:47 +0000674}
675
Eric Christopherda4b2192013-01-02 23:52:13 +0000676void DWARFContext::parseDWOCompileUnits() {
Rafael Espindolac398e672017-07-19 22:27:28 +0000677 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
Eric Christopherda4b2192013-01-02 23:52:13 +0000678}
679
David Blaikie92d9d622014-01-09 05:08:24 +0000680void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000681 if (!DWOTUs.empty())
682 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000683 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000684 DWOTUs.emplace_back();
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000685 DWOTUs.back().parseDWO(*this, S);
686 });
David Blaikie92d9d622014-01-09 05:08:24 +0000687}
688
Alexey Samsonov45be7932012-08-30 07:49:50 +0000689DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000690 parseCompileUnits();
Frederic Riss4e126a02014-09-15 07:50:27 +0000691 return CUs.getUnitForOffset(Offset);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000692}
693
Alexey Samsonov45be7932012-08-30 07:49:50 +0000694DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000695 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000696 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000697 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000698 return getCompileUnitForOffset(CUOffset);
699}
700
David Blaikieefc4eba2017-02-06 20:19:02 +0000701static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
702 uint64_t Address,
703 FunctionNameKind Kind,
704 std::string &FunctionName,
705 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000706 // The address may correspond to instruction in some inlined function,
707 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000708 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000709 SmallVector<DWARFDie, 4> InlinedChain;
710 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000711 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000712 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000713
714 const DWARFDie &DIE = InlinedChain[0];
715 bool FoundResult = false;
716 const char *Name = nullptr;
717 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000718 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000719 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000720 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000721 if (auto DeclLineResult = DIE.getDeclLine()) {
722 StartLine = DeclLineResult;
723 FoundResult = true;
724 }
725
726 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000727}
728
Alexey Samsonov45be7932012-08-30 07:49:50 +0000729DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000730 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000731 DILineInfo Result;
732
Alexey Samsonov45be7932012-08-30 07:49:50 +0000733 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
734 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000735 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000736 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
737 Result.FunctionName,
738 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000739 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000740 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
741 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
742 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000743 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000744 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000745}
David Blaikiea379b1812011-12-20 02:50:00 +0000746
Alexey Samsonovdce67342014-05-15 21:24:32 +0000747DILineInfoTable
748DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
749 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000750 DILineInfoTable Lines;
751 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
752 if (!CU)
753 return Lines;
754
755 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000756 uint32_t StartLine = 0;
757 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
758 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000759
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000760 // If the Specifier says we don't need FileLineInfo, just
761 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000762 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000763 DILineInfo Result;
764 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000765 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000766 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000767 return Lines;
768 }
769
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000770 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000771
772 // Get the index of row we're looking for in the line table.
773 std::vector<uint32_t> RowVector;
774 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
775 return Lines;
776
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000777 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000778 // Take file number and line/column from the row.
779 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000780 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000781 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
782 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000783 Result.FunctionName = FunctionName;
784 Result.Line = Row.Line;
785 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000786 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000787 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000788 }
789
790 return Lines;
791}
792
Alexey Samsonovdce67342014-05-15 21:24:32 +0000793DIInliningInfo
794DWARFContext::getInliningInfoForAddress(uint64_t Address,
795 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000796 DIInliningInfo InliningInfo;
797
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000798 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
799 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000800 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000801
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000802 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000803 SmallVector<DWARFDie, 4> InlinedChain;
804 CU->getInlinedChainForAddress(Address, InlinedChain);
805 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000806 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
807 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000808 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000809 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000810 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +0000811 if (LineTable &&
812 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
813 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000814 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000815 }
816 return InliningInfo;
817 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000818
Dehao Chenef700d52017-04-17 20:10:39 +0000819 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +0000820 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
821 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000822 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000823 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +0000824 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +0000825 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000826 if (auto DeclLineResult = FunctionDIE.getDeclLine())
827 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +0000828 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000829 if (i == 0) {
830 // For the topmost frame, initialize the line table of this
831 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000832 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000833 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +0000834 if (LineTable)
835 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
836 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000837 } else {
838 // Otherwise, use call file, call line and call column from
839 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +0000840 if (LineTable)
841 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
842 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000843 Frame.Line = CallLine;
844 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +0000845 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000846 }
847 // Get call file/line/column of a current DIE.
848 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +0000849 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
850 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000851 }
852 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000853 InliningInfo.addFrame(Frame);
854 }
855 return InliningInfo;
856}
857
David Blaikief9803fb2017-05-23 00:30:42 +0000858std::shared_ptr<DWARFContext>
859DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +0000860 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +0000861 DWARFContext *Ctxt = S->Context.get();
862 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
863 }
864
David Blaikie15d85fc2017-05-23 06:48:53 +0000865 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
866
867 if (auto S = Entry->lock()) {
868 DWARFContext *Ctxt = S->Context.get();
869 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
870 }
871
David Blaikie15d85fc2017-05-23 06:48:53 +0000872 Expected<OwningBinary<ObjectFile>> Obj = [&] {
873 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +0000874 SmallString<128> DWPName;
875 auto Obj = object::ObjectFile::createObjectFile(
876 this->DWPName.empty()
877 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
878 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +0000879 if (Obj) {
880 Entry = &DWP;
881 return Obj;
882 } else {
883 CheckedForDWP = true;
884 // TODO: Should this error be handled (maybe in a high verbosity mode)
885 // before falling back to .dwo files?
886 consumeError(Obj.takeError());
887 }
888 }
889
890 return object::ObjectFile::createObjectFile(AbsolutePath);
891 }();
892
David Blaikief9803fb2017-05-23 00:30:42 +0000893 if (!Obj) {
894 // TODO: Actually report errors helpfully.
895 consumeError(Obj.takeError());
896 return nullptr;
897 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000898
899 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +0000900 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +0000901 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +0000902 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +0000903 auto *Ctxt = S->Context.get();
904 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
905}
906
George Rimar702dac62017-04-12 08:59:15 +0000907static Error createError(const Twine &Reason, llvm::Error E) {
908 return make_error<StringError>(Reason + toString(std::move(E)),
909 inconvertibleErrorCode());
910}
911
George Rimara25d3292017-05-27 18:10:23 +0000912/// SymInfo contains information about symbol: it's address
913/// and section index which is -1LL for absolute symbols.
914struct SymInfo {
915 uint64_t Address;
916 uint64_t SectionIndex;
917};
918
919/// Returns the address of symbol relocation used against and a section index.
920/// Used for futher relocations computation. Symbol's section load address is
921static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
922 const RelocationRef &Reloc,
923 const LoadedObjectInfo *L,
924 std::map<SymbolRef, SymInfo> &Cache) {
925 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +0000926 object::section_iterator RSec = Obj.section_end();
927 object::symbol_iterator Sym = Reloc.getSymbol();
928
George Rimara25d3292017-05-27 18:10:23 +0000929 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +0000930 // First calculate the address of the symbol or section as it appears
931 // in the object file
932 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +0000933 bool New;
George Rimara25d3292017-05-27 18:10:23 +0000934 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +0000935 if (!New)
936 return CacheIt->second;
937
George Rimar702dac62017-04-12 08:59:15 +0000938 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
939 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000940 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +0000941 SymAddrOrErr.takeError());
942
943 // Also remember what section this symbol is in for later
944 auto SectOrErr = Sym->getSection();
945 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +0000946 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +0000947 SectOrErr.takeError());
948
949 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +0000950 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +0000951 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
952 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +0000953 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +0000954 }
955
George Rimara25d3292017-05-27 18:10:23 +0000956 if (RSec != Obj.section_end())
957 Ret.SectionIndex = RSec->getIndex();
958
George Rimar702dac62017-04-12 08:59:15 +0000959 // If we are given load addresses for the sections, we need to adjust:
960 // SymAddr = (Address of Symbol Or Section in File) -
961 // (Address of Section in File) +
962 // (Load Address of Section)
963 // RSec is now either the section being targeted or the section
964 // containing the symbol being targeted. In either case,
965 // we need to perform the same computation.
966 if (L && RSec != Obj.section_end())
967 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +0000968 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +0000969
970 if (CacheIt != Cache.end())
971 CacheIt->second = Ret;
972
George Rimar702dac62017-04-12 08:59:15 +0000973 return Ret;
974}
975
976static bool isRelocScattered(const object::ObjectFile &Obj,
977 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +0000978 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
979 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +0000980 return false;
981 // MachO also has relocations that point to sections and
982 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +0000983 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
984 return MachObj->isRelocationScattered(RelocInfo);
985}
986
Rafael Espindolac398e672017-07-19 22:27:28 +0000987ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
George Rimar1af3cb22017-06-28 08:21:19 +0000988 errs() << "error: " + toString(std::move(E)) << '\n';
989 return ErrorPolicy::Continue;
990}
991
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000992namespace {
993struct DWARFSectionMap final : public DWARFSection {
994 RelocAddrMap Relocs;
995};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +0000996
Rafael Espindolac398e672017-07-19 22:27:28 +0000997class DWARFObjInMemory final : public DWARFObject {
998 bool IsLittleEndian;
999 uint8_t AddressSize;
1000 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001001 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001002 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001003
Rafael Espindolac398e672017-07-19 22:27:28 +00001004 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1005 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001006
Rafael Espindolac398e672017-07-19 22:27:28 +00001007 TypeSectionMap TypesSections;
1008 TypeSectionMap TypesDWOSections;
1009
1010 DWARFSectionMap InfoSection;
1011 DWARFSectionMap LocSection;
1012 DWARFSectionMap LineSection;
1013 DWARFSectionMap RangeSection;
1014 DWARFSectionMap StringOffsetSection;
1015 DWARFSectionMap InfoDWOSection;
1016 DWARFSectionMap LineDWOSection;
1017 DWARFSectionMap LocDWOSection;
1018 DWARFSectionMap StringOffsetDWOSection;
1019 DWARFSectionMap RangeDWOSection;
1020 DWARFSectionMap AddrSection;
1021 DWARFSectionMap AppleNamesSection;
1022 DWARFSectionMap AppleTypesSection;
1023 DWARFSectionMap AppleNamespacesSection;
1024 DWARFSectionMap AppleObjCSection;
1025
1026 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1027 return StringSwitch<DWARFSectionMap *>(Name)
1028 .Case("debug_info", &InfoSection)
1029 .Case("debug_loc", &LocSection)
1030 .Case("debug_line", &LineSection)
1031 .Case("debug_str_offsets", &StringOffsetSection)
1032 .Case("debug_ranges", &RangeSection)
1033 .Case("debug_info.dwo", &InfoDWOSection)
1034 .Case("debug_loc.dwo", &LocDWOSection)
1035 .Case("debug_line.dwo", &LineDWOSection)
1036 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1037 .Case("debug_addr", &AddrSection)
1038 .Case("apple_names", &AppleNamesSection)
1039 .Case("apple_types", &AppleTypesSection)
1040 .Case("apple_namespaces", &AppleNamespacesSection)
1041 .Case("apple_namespac", &AppleNamespacesSection)
1042 .Case("apple_objc", &AppleObjCSection)
1043 .Default(nullptr);
1044 }
1045
1046 StringRef AbbrevSection;
1047 StringRef ARangeSection;
1048 StringRef DebugFrameSection;
1049 StringRef EHFrameSection;
1050 StringRef StringSection;
1051 StringRef MacinfoSection;
1052 StringRef PubNamesSection;
1053 StringRef PubTypesSection;
1054 StringRef GnuPubNamesSection;
1055 StringRef AbbrevDWOSection;
1056 StringRef StringDWOSection;
1057 StringRef GnuPubTypesSection;
1058 StringRef CUIndexSection;
1059 StringRef GdbIndexSection;
1060 StringRef TUIndexSection;
1061
1062 SmallVector<SmallString<32>, 4> UncompressedSections;
1063
1064 StringRef *mapSectionToMember(StringRef Name) {
1065 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1066 return &Sec->Data;
1067 return StringSwitch<StringRef *>(Name)
1068 .Case("debug_abbrev", &AbbrevSection)
1069 .Case("debug_aranges", &ARangeSection)
1070 .Case("debug_frame", &DebugFrameSection)
1071 .Case("eh_frame", &EHFrameSection)
1072 .Case("debug_str", &StringSection)
1073 .Case("debug_macinfo", &MacinfoSection)
1074 .Case("debug_pubnames", &PubNamesSection)
1075 .Case("debug_pubtypes", &PubTypesSection)
1076 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1077 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1078 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1079 .Case("debug_str.dwo", &StringDWOSection)
1080 .Case("debug_cu_index", &CUIndexSection)
1081 .Case("debug_tu_index", &TUIndexSection)
1082 .Case("gdb_index", &GdbIndexSection)
1083 // Any more debug info sections go here.
1084 .Default(nullptr);
1085 }
1086
1087 /// If Sec is compressed section, decompresses and updates its contents
1088 /// provided by Data. Otherwise leaves it unchanged.
1089 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1090 StringRef &Data) {
1091 if (!Decompressor::isCompressed(Sec))
1092 return Error::success();
1093
1094 Expected<Decompressor> Decompressor =
1095 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1096 if (!Decompressor)
1097 return Decompressor.takeError();
1098
1099 SmallString<32> Out;
1100 if (auto Err = Decompressor->resizeAndDecompress(Out))
1101 return Err;
1102
1103 UncompressedSections.emplace_back(std::move(Out));
1104 Data = UncompressedSections.back();
1105
1106 return Error::success();
1107 }
1108
1109public:
1110 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1111 uint8_t AddrSize, bool IsLittleEndian)
1112 : IsLittleEndian(IsLittleEndian) {
1113 for (const auto &SecIt : Sections) {
1114 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1115 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001116 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001117 }
1118 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1119 function_ref<ErrorPolicy(Error)> HandleError)
1120 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001121 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1122 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001123
George Rimare1c30f72017-08-15 15:54:43 +00001124 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001125 for (const SectionRef &Section : Obj.sections()) {
1126 StringRef Name;
1127 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001128 ++SectionAmountMap[Name];
1129 SectionNames.push_back({ Name, true });
1130
Rafael Espindolac398e672017-07-19 22:27:28 +00001131 // Skip BSS and Virtual sections, they aren't interesting.
1132 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001133 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001134
Rafael Espindolac398e672017-07-19 22:27:28 +00001135 StringRef Data;
1136 section_iterator RelocatedSection = Section.getRelocatedSection();
1137 // Try to obtain an already relocated version of this section.
1138 // Else use the unrelocated section from the object file. We'll have to
1139 // apply relocations ourselves later.
1140 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1141 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001142
Rafael Espindolac398e672017-07-19 22:27:28 +00001143 if (auto Err = maybeDecompress(Section, Name, Data)) {
1144 ErrorPolicy EP = HandleError(createError(
1145 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001146 if (EP == ErrorPolicy::Halt)
1147 return;
George Rimarfed9f092017-05-17 12:10:51 +00001148 continue;
1149 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001150
1151 // Compressed sections names in GNU style starts from ".z",
1152 // at this point section is decompressed and we drop compression prefix.
1153 Name = Name.substr(
1154 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1155
1156 // Map platform specific debug section names to DWARF standard section
1157 // names.
1158 Name = Obj.mapDebugSectionName(Name);
1159
1160 if (StringRef *SectionData = mapSectionToMember(Name)) {
1161 *SectionData = Data;
1162 if (Name == "debug_ranges") {
1163 // FIXME: Use the other dwo range section when we emit it.
1164 RangeDWOSection.Data = Data;
1165 }
1166 } else if (Name == "debug_types") {
1167 // Find debug_types data by section rather than name as there are
1168 // multiple, comdat grouped, debug_types sections.
1169 TypesSections[Section].Data = Data;
1170 } else if (Name == "debug_types.dwo") {
1171 TypesDWOSections[Section].Data = Data;
1172 }
1173
1174 if (RelocatedSection == Obj.section_end())
1175 continue;
1176
1177 StringRef RelSecName;
1178 StringRef RelSecData;
1179 RelocatedSection->getName(RelSecName);
1180
1181 // If the section we're relocating was relocated already by the JIT,
1182 // then we used the relocated version above, so we do not need to process
1183 // relocations for it now.
1184 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1185 continue;
1186
1187 // In Mach-o files, the relocations do not need to be applied if
1188 // there is no load offset to apply. The value read at the
1189 // relocation point already factors in the section address
1190 // (actually applying the relocations will produce wrong results
1191 // as the section address will be added twice).
1192 if (!L && isa<MachOObjectFile>(&Obj))
1193 continue;
1194
1195 RelSecName = RelSecName.substr(
1196 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1197
1198 // TODO: Add support for relocations in other sections as needed.
1199 // Record relocations for the debug_info and debug_line sections.
1200 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1201 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1202 if (!Map) {
1203 // Find debug_types relocs by section rather than name as there are
1204 // multiple, comdat grouped, debug_types sections.
1205 if (RelSecName == "debug_types")
1206 Map =
1207 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1208 .Relocs;
1209 else if (RelSecName == "debug_types.dwo")
1210 Map = &static_cast<DWARFSectionMap &>(
1211 TypesDWOSections[*RelocatedSection])
1212 .Relocs;
1213 else
1214 continue;
1215 }
1216
1217 if (Section.relocation_begin() == Section.relocation_end())
1218 continue;
1219
1220 // Symbol to [address, section index] cache mapping.
1221 std::map<SymbolRef, SymInfo> AddrCache;
1222 for (const RelocationRef &Reloc : Section.relocations()) {
1223 // FIXME: it's not clear how to correctly handle scattered
1224 // relocations.
1225 if (isRelocScattered(Obj, Reloc))
1226 continue;
1227
1228 Expected<SymInfo> SymInfoOrErr =
1229 getSymbolInfo(Obj, Reloc, L, AddrCache);
1230 if (!SymInfoOrErr) {
1231 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1232 return;
1233 continue;
1234 }
1235
1236 object::RelocVisitor V(Obj);
1237 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1238 if (V.error()) {
1239 SmallString<32> Type;
1240 Reloc.getTypeName(Type);
1241 ErrorPolicy EP = HandleError(
1242 createError("failed to compute relocation: " + Type + ", ",
1243 errorCodeToError(object_error::parse_failed)));
1244 if (EP == ErrorPolicy::Halt)
1245 return;
1246 continue;
1247 }
1248 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1249 Map->insert({Reloc.getOffset(), Rel});
1250 }
Eric Christopher7370b552012-11-12 21:40:38 +00001251 }
George Rimare1c30f72017-08-15 15:54:43 +00001252
1253 for (SectionName &S : SectionNames)
1254 if (SectionAmountMap[S.Name] > 1)
1255 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001256 }
Eric Christopher7370b552012-11-12 21:40:38 +00001257
Rafael Espindolac398e672017-07-19 22:27:28 +00001258 Optional<RelocAddrEntry> find(const DWARFSection &S,
1259 uint64_t Pos) const override {
1260 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1261 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1262 if (AI == Sec.Relocs.end())
1263 return None;
1264 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001265 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001266
George Rimar6957ab52017-08-15 12:32:54 +00001267 const object::ObjectFile *getFile() const override { return Obj; }
1268
George Rimare1c30f72017-08-15 15:54:43 +00001269 ArrayRef<SectionName> getSectionNames() const override {
1270 return SectionNames;
1271 }
1272
Rafael Espindolac398e672017-07-19 22:27:28 +00001273 bool isLittleEndian() const override { return IsLittleEndian; }
1274 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1275 const DWARFSection &getLineDWOSection() const override {
1276 return LineDWOSection;
1277 }
1278 const DWARFSection &getLocDWOSection() const override {
1279 return LocDWOSection;
1280 }
1281 StringRef getStringDWOSection() const override { return StringDWOSection; }
1282 const DWARFSection &getStringOffsetDWOSection() const override {
1283 return StringOffsetDWOSection;
1284 }
1285 const DWARFSection &getRangeDWOSection() const override {
1286 return RangeDWOSection;
1287 }
1288 const DWARFSection &getAddrSection() const override { return AddrSection; }
1289 StringRef getCUIndexSection() const override { return CUIndexSection; }
1290 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1291 StringRef getTUIndexSection() const override { return TUIndexSection; }
1292
1293 // DWARF v5
1294 const DWARFSection &getStringOffsetSection() const override {
1295 return StringOffsetSection;
1296 }
1297
1298 // Sections for DWARF5 split dwarf proposal.
1299 const DWARFSection &getInfoDWOSection() const override {
1300 return InfoDWOSection;
1301 }
1302 void forEachTypesDWOSections(
1303 function_ref<void(const DWARFSection &)> F) const override {
1304 for (auto &P : TypesDWOSections)
1305 F(P.second);
1306 }
1307
1308 StringRef getAbbrevSection() const override { return AbbrevSection; }
1309 const DWARFSection &getLocSection() const override { return LocSection; }
1310 StringRef getARangeSection() const override { return ARangeSection; }
1311 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1312 StringRef getEHFrameSection() const override { return EHFrameSection; }
1313 const DWARFSection &getLineSection() const override { return LineSection; }
1314 StringRef getStringSection() const override { return StringSection; }
1315 const DWARFSection &getRangeSection() const override { return RangeSection; }
1316 StringRef getMacinfoSection() const override { return MacinfoSection; }
1317 StringRef getPubNamesSection() const override { return PubNamesSection; }
1318 StringRef getPubTypesSection() const override { return PubTypesSection; }
1319 StringRef getGnuPubNamesSection() const override {
1320 return GnuPubNamesSection;
1321 }
1322 StringRef getGnuPubTypesSection() const override {
1323 return GnuPubTypesSection;
1324 }
1325 const DWARFSection &getAppleNamesSection() const override {
1326 return AppleNamesSection;
1327 }
1328 const DWARFSection &getAppleTypesSection() const override {
1329 return AppleTypesSection;
1330 }
1331 const DWARFSection &getAppleNamespacesSection() const override {
1332 return AppleNamespacesSection;
1333 }
1334 const DWARFSection &getAppleObjCSection() const override {
1335 return AppleObjCSection;
1336 }
1337
1338 StringRef getFileName() const override { return FileName; }
1339 uint8_t getAddressSize() const override { return AddressSize; }
1340 const DWARFSection &getInfoSection() const override { return InfoSection; }
1341 void forEachTypesSections(
1342 function_ref<void(const DWARFSection &)> F) const override {
1343 for (auto &P : TypesSections)
1344 F(P.second);
1345 }
1346};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001347} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001348
1349std::unique_ptr<DWARFContext>
1350DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001351 function_ref<ErrorPolicy(Error)> HandleError,
1352 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001353 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001354 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001355}
1356
Rafael Espindolac398e672017-07-19 22:27:28 +00001357std::unique_ptr<DWARFContext>
1358DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1359 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001360 auto DObj =
1361 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001362 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001363}
Reid Klecknera0587362017-08-29 21:41:21 +00001364
1365Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1366 // Detect the architecture from the object file. We usually don't need OS
1367 // info to lookup a target and create register info.
1368 Triple TT;
1369 TT.setArch(Triple::ArchType(Obj.getArch()));
1370 TT.setVendor(Triple::UnknownVendor);
1371 TT.setOS(Triple::UnknownOS);
1372 std::string TargetLookupError;
1373 const Target *TheTarget =
1374 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1375 if (!TargetLookupError.empty())
1376 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1377 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1378 return Error::success();
1379}