blob: a26ebba0a219a4fcb4644df1264b5cbff1e37a87 [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"
Victor Leschuk58d33992018-07-31 22:19:19 +000020#include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000022#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000023#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
24#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
25#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
26#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
George Rimare71e33f2016-12-17 09:10:32 +000027#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000028#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
James Henderson3fcc7452018-02-02 12:35:52 +000029#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000030#include "llvm/DebugInfo/DWARF/DWARFDie.h"
31#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
32#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
33#include "llvm/DebugInfo/DWARF/DWARFSection.h"
David Blaikie65a8efe2015-11-11 19:28:21 +000034#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000035#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Reid Klecknera0587362017-08-29 21:41:21 +000036#include "llvm/MC/MCRegisterInfo.h"
George Rimar4bf30832017-01-11 15:26:41 +000037#include "llvm/Object/Decompressor.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000038#include "llvm/Object/MachO.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000039#include "llvm/Object/ObjectFile.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000040#include "llvm/Object/RelocVisitor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000041#include "llvm/Support/Casting.h"
42#include "llvm/Support/DataExtractor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000043#include "llvm/Support/Error.h"
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +000044#include "llvm/Support/Format.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000045#include "llvm/Support/MemoryBuffer.h"
Adrian Prantl3ae35eb2017-09-13 22:09:01 +000046#include "llvm/Support/Path.h"
Reid Klecknera0587362017-08-29 21:41:21 +000047#include "llvm/Support/TargetRegistry.h"
Jonas Devlieghere84e99262018-04-14 22:07:23 +000048#include "llvm/Support/WithColor.h"
Benjamin Kramera6002fd2011-09-14 01:09:52 +000049#include "llvm/Support/raw_ostream.h"
Benjamin Kramer2602ca62011-09-15 20:43:22 +000050#include <algorithm>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000051#include <cstdint>
Fangrui Song5bad9d82018-07-23 23:27:45 +000052#include <deque>
Greg Claytonc7695a82017-05-02 20:28:33 +000053#include <map>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000054#include <string>
55#include <utility>
56#include <vector>
57
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000058using namespace llvm;
Benjamin Kramer6dda0322011-09-15 18:02:20 +000059using namespace dwarf;
Rafael Espindola4f60a382013-05-30 03:05:14 +000060using namespace object;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000061
Chandler Carruthe96dd892014-04-21 22:55:11 +000062#define DEBUG_TYPE "dwarf"
63
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000064using DWARFLineTable = DWARFDebugLine::LineTable;
65using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
66using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
Eric Christopher494109b2012-10-16 23:46:25 +000067
Reid Klecknera0587362017-08-29 21:41:21 +000068DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
69 std::string DWPName)
70 : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
71
72DWARFContext::~DWARFContext() = default;
73
Adrian Prantl3dcd1222017-09-13 18:22:59 +000074/// Dump the UUID load command.
75static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
76 auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
77 if (!MachO)
78 return;
79 for (auto LC : MachO->load_commands()) {
80 raw_ostream::uuid_t UUID;
81 if (LC.C.cmd == MachO::LC_UUID) {
82 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
83 OS << "error: UUID load command is too short.\n";
84 return;
85 }
86 OS << "UUID: ";
87 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
88 OS.write_uuid(UUID);
Adrian Prantl146ed402018-01-05 21:44:17 +000089 Triple T = MachO->getArchTriple();
90 OS << " (" << T.getArchName() << ')';
Adrian Prantl3dcd1222017-09-13 18:22:59 +000091 OS << ' ' << MachO->getFileName() << '\n';
92 }
93 }
94}
95
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +000096using ContributionCollection =
97 std::vector<Optional<StrOffsetsContributionDescriptor>>;
98
99// Collect all the contributions to the string offsets table from all units,
100// sort them by their starting offsets and remove duplicates.
101static ContributionCollection
102collectContributionData(DWARFContext::cu_iterator_range CUs,
103 DWARFContext::tu_section_iterator_range TUSs) {
104 ContributionCollection Contributions;
105 for (const auto &CU : CUs)
106 Contributions.push_back(CU->getStringOffsetsTableContribution());
107 for (const auto &TUS : TUSs)
108 for (const auto &TU : TUS)
109 Contributions.push_back(TU->getStringOffsetsTableContribution());
110
111 // Sort the contributions so that any invalid ones are placed at
112 // the start of the contributions vector. This way they are reported
113 // first.
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000114 llvm::sort(Contributions.begin(), Contributions.end(),
115 [](const Optional<StrOffsetsContributionDescriptor> &L,
116 const Optional<StrOffsetsContributionDescriptor> &R) {
117 if (L && R) return L->Base < R->Base;
118 return R.hasValue();
119 });
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000120
121 // Uniquify contributions, as it is possible that units (specifically
122 // type units in dwo or dwp files) share contributions. We don't want
123 // to report them more than once.
124 Contributions.erase(
125 std::unique(Contributions.begin(), Contributions.end(),
126 [](const Optional<StrOffsetsContributionDescriptor> &L,
127 const Optional<StrOffsetsContributionDescriptor> &R) {
128 if (L && R)
129 return L->Base == R->Base && L->Size == R->Size;
130 return false;
131 }),
132 Contributions.end());
133 return Contributions;
134}
135
136static void dumpDWARFv5StringOffsetsSection(
137 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
138 const DWARFSection &StringOffsetsSection, StringRef StringSection,
139 DWARFContext::cu_iterator_range CUs,
140 DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian) {
141 auto Contributions = collectContributionData(CUs, TUSs);
Rafael Espindolac398e672017-07-19 22:27:28 +0000142 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000143 DataExtractor StrData(StringSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000144 uint64_t SectionSize = StringOffsetsSection.Data.size();
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000145 uint32_t Offset = 0;
146 for (auto &Contribution : Contributions) {
147 // Report an ill-formed contribution.
148 if (!Contribution) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000149 OS << "error: invalid contribution to string offsets table in section ."
150 << SectionName << ".\n";
151 return;
152 }
153
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000154 dwarf::DwarfFormat Format = Contribution->getFormat();
155 uint16_t Version = Contribution->getVersion();
156 uint64_t ContributionHeader = Contribution->Base;
157 // In DWARF v5 there is a contribution header that immediately precedes
158 // the string offsets base (the location we have previously retrieved from
159 // the CU DIE's DW_AT_str_offsets attribute). The header is located either
160 // 8 or 16 bytes before the base, depending on the contribution's format.
161 if (Version >= 5)
162 ContributionHeader -= Format == DWARF32 ? 8 : 16;
163
164 // Detect overlapping contributions.
165 if (Offset > ContributionHeader) {
166 OS << "error: overlapping contributions to string offsets table in "
167 "section ."
168 << SectionName << ".\n";
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000169 return;
170 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000171 // Report a gap in the table.
172 if (Offset < ContributionHeader) {
173 OS << format("0x%8.8x: Gap, length = ", Offset);
174 OS << (ContributionHeader - Offset) << "\n";
175 }
Wolfgang Piebb4ba1aa2017-12-22 01:12:24 +0000176 OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
Wolfgang Piebf2b6915e2018-05-10 20:02:34 +0000177 // In DWARF v5 the contribution size in the descriptor does not equal
178 // the originally encoded length (it does not contain the length of the
179 // version field and the padding, a total of 4 bytes). Add them back in
180 // for reporting.
181 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000182 << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000183 << ", Version = " << Version << "\n";
184
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000185 Offset = Contribution->Base;
186 unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
187 while (Offset - Contribution->Base < Contribution->Size) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000188 OS << format("0x%8.8x: ", Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000189 // FIXME: We can only extract strings if the offset fits in 32 bits.
Paul Robinson17536b92017-06-29 16:52:08 +0000190 uint64_t StringOffset =
191 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000192 // Extract the string if we can and display it. Otherwise just report
193 // the offset.
194 if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000195 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000196 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000197 const char *S = StrData.getCStr(&StringOffset32);
198 if (S)
199 OS << format("\"%s\"", S);
200 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000201 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000202 OS << "\n";
203 }
204 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000205 // Report a gap at the end of the table.
206 if (Offset < SectionSize) {
207 OS << format("0x%8.8x: Gap, length = ", Offset);
208 OS << (SectionSize - Offset) << "\n";
209 }
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000210}
211
212// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
213// string offsets section, where each compile or type unit contributes a
214// number of entries (string offsets), with each contribution preceded by
215// a header containing size and version number. Alternatively, it may be a
216// monolithic series of string offsets, as generated by the pre-DWARF v5
217// implementation of split DWARF.
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000218static void dumpStringOffsetsSection(
219 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
220 const DWARFSection &StringOffsetsSection, StringRef StringSection,
221 DWARFContext::cu_iterator_range CUs,
222 DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian,
223 unsigned MaxVersion) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000224 // If we have at least one (compile or type) unit with DWARF v5 or greater,
225 // we assume that the section is formatted like a DWARF v5 string offsets
226 // section.
227 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000228 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000229 StringSection, CUs, TUSs, LittleEndian);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000230 else {
231 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
232 uint32_t offset = 0;
233 uint64_t size = StringOffsetsSection.Data.size();
234 // Ensure that size is a multiple of the size of an entry.
235 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
236 OS << "error: size of ." << SectionName << " is not a multiple of "
237 << sizeof(uint32_t) << ".\n";
238 size &= -(uint64_t)sizeof(uint32_t);
239 }
240 DataExtractor StrData(StringSection, LittleEndian, 0);
241 while (offset < size) {
242 OS << format("0x%8.8x: ", offset);
243 uint32_t StringOffset = strOffsetExt.getU32(&offset);
244 OS << format("%8.8x ", StringOffset);
245 const char *S = StrData.getCStr(&StringOffset);
246 if (S)
247 OS << format("\"%s\"", S);
248 OS << "\n";
249 }
250 }
251}
252
Victor Leschuk58d33992018-07-31 22:19:19 +0000253// Dump the .debug_addr section.
254static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
255 DIDumpOptions DumpOpts, uint16_t Version,
256 uint8_t AddrSize) {
257 // TODO: Make this more general: add callback types to Error.h, create
258 // implementation and make all DWARF classes use them.
259 static auto WarnCallback = [](Error Warn) {
260 handleAllErrors(std::move(Warn), [](ErrorInfoBase &Info) {
261 WithColor::warning() << Info.message() << '\n';
262 });
263 };
264 uint32_t Offset = 0;
265 while (AddrData.isValidOffset(Offset)) {
266 DWARFDebugAddrTable AddrTable;
267 uint32_t TableOffset = Offset;
268 if (Error Err = AddrTable.extract(AddrData, &Offset, Version,
269 AddrSize, WarnCallback)) {
270 WithColor::error() << toString(std::move(Err)) << '\n';
271 // Keep going after an error, if we can, assuming that the length field
272 // could be read. If it couldn't, stop reading the section.
273 if (!AddrTable.hasValidLength())
274 break;
275 uint64_t Length = AddrTable.getLength();
276 Offset = TableOffset + Length;
277 } else {
278 AddrTable.dump(OS, DumpOpts);
279 }
280 }
281}
282
Wolfgang Piebad605592018-05-18 20:12:54 +0000283// Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
284static void dumpRnglistsSection(raw_ostream &OS,
285 DWARFDataExtractor &rnglistData,
286 DIDumpOptions DumpOpts) {
287 uint32_t Offset = 0;
288 while (rnglistData.isValidOffset(Offset)) {
289 llvm::DWARFDebugRnglistTable Rnglists;
290 uint32_t TableOffset = Offset;
291 if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
292 WithColor::error() << toString(std::move(Err)) << '\n';
293 uint64_t Length = Rnglists.length();
294 // Keep going after an error, if we can, assuming that the length field
295 // could be read. If it couldn't, stop reading the section.
296 if (Length == 0)
297 break;
298 Offset = TableOffset + Length;
299 } else {
300 Rnglists.dump(OS, DumpOpts);
301 }
302 }
303}
304
Adrian Prantl057d3362017-09-15 23:04:04 +0000305void DWARFContext::dump(
306 raw_ostream &OS, DIDumpOptions DumpOpts,
307 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
308
309 Optional<uint64_t> DumpOffset;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000310 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000311
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000312 StringRef Extension = sys::path::extension(DObj->getFileName());
313 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
314
315 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000316 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000317 if (DumpType & DIDT_UUID)
318 dumpUUID(OS, *ObjFile);
319
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000320 // Print a header for each explicitly-requested section.
321 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000322 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000323 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000324 bool ExplicitDWO = Explicit && IsDWO;
325 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
326 StringRef Section) {
327 DumpOffset = DumpOffsets[ID];
328 unsigned Mask = 1U << ID;
329 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
Adrian Prantl84168022017-09-15 17:39:50 +0000330 if (Should)
Adrian Prantl057d3362017-09-15 23:04:04 +0000331 OS << "\n" << Name << " contents:\n";
Adrian Prantl84168022017-09-15 17:39:50 +0000332 return Should;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000333 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000334
335 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000336 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
337 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000338 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000339 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
340 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000341 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000342
Adrian Prantl057d3362017-09-15 23:04:04 +0000343 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
344 DWARFSection Section, cu_iterator_range CUs) {
345 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
Adrian Prantlc8d86532017-09-18 21:44:40 +0000346 if (DumpOffset)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000347 getDIEForOffset(DumpOffset.getValue())
348 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantlc8d86532017-09-18 21:44:40 +0000349 else
350 for (const auto &CU : CUs)
Adrian Prantl057d3362017-09-15 23:04:04 +0000351 CU->dump(OS, DumpOpts);
352 }
353 };
354 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
355 compile_units());
356 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
357 dwo_compile_units());
David Blaikie622dce42014-01-08 23:29:59 +0000358
Adrian Prantl099d7e42017-09-16 16:58:18 +0000359 auto dumpDebugType = [&](const char *Name,
360 tu_section_iterator_range TUSections) {
361 OS << '\n' << Name << " contents:\n";
362 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
363 for (const auto &TUS : TUSections)
364 for (const auto &TU : TUS)
365 if (DumpOffset)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000366 TU->getDIEForOffset(*DumpOffset)
367 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantl099d7e42017-09-16 16:58:18 +0000368 else
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000369 TU->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000370 };
371 if ((DumpType & DIDT_DebugTypes)) {
372 if (Explicit || getNumTypeUnits())
373 dumpDebugType(".debug_types", type_unit_sections());
374 if (ExplicitDWO || getNumDWOTypeUnits())
375 dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
David Blaikie03c089c2013-09-23 22:44:47 +0000376 }
377
Adrian Prantl057d3362017-09-15 23:04:04 +0000378 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000379 DObj->getLocSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000380 getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie18e73502013-06-19 21:37:13 +0000381 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000382 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000383 DObj->getLocDWOSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000384 getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie9c550ac2014-03-25 01:44:02 +0000385 }
386
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000387 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000388 DObj->getDebugFrameSection()))
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000389 getDebugFrame()->dump(OS, getRegisterInfo(), DumpOffset);
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000390
391 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000392 DObj->getEHFrameSection()))
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000393 getEHFrame()->dump(OS, getRegisterInfo(), DumpOffset);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000394
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000395 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000396 if (Explicit || !getDebugMacro()->empty()) {
397 OS << "\n.debug_macinfo contents:\n";
398 getDebugMacro()->dump(OS);
399 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000400 }
401
Adrian Prantl057d3362017-09-15 23:04:04 +0000402 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000403 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000404 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000405 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000406 DWARFDebugArangeSet set;
407 while (set.extract(arangesData, &offset))
408 set.dump(OS);
409 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000410
James Hendersona3acf992018-05-10 10:51:33 +0000411 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
412 DIDumpOptions DumpOpts) {
413 while (!Parser.done()) {
414 if (DumpOffset && Parser.getOffset() != *DumpOffset) {
415 Parser.skip();
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000416 continue;
Paul Robinson63811a42017-11-22 15:33:17 +0000417 }
James Hendersona3acf992018-05-10 10:51:33 +0000418 OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n";
Paul Robinson63811a42017-11-22 15:33:17 +0000419 if (DumpOpts.Verbose) {
James Henderson004b7292018-05-21 15:30:54 +0000420 Parser.parseNext(DWARFDebugLine::warn, DWARFDebugLine::warn, &OS);
Paul Robinson63811a42017-11-22 15:33:17 +0000421 } else {
James Hendersona3acf992018-05-10 10:51:33 +0000422 DWARFDebugLine::LineTable LineTable = Parser.parseNext();
423 LineTable.dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000424 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000425 }
James Hendersona3acf992018-05-10 10:51:33 +0000426 };
427
428 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
429 DObj->getLineSection().Data)) {
430 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
431 0);
432 DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
433 type_unit_sections());
434 DumpLineSection(Parser, DumpOpts);
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000435 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000436
Adrian Prantl057d3362017-09-15 23:04:04 +0000437 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000438 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000439 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
440 isLittleEndian(), 0);
James Hendersona3acf992018-05-10 10:51:33 +0000441 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
442 dwo_type_unit_sections());
443 DumpLineSection(Parser, DumpOpts);
David Blaikie1d4736e2014-02-24 23:58:54 +0000444 }
445
Adrian Prantl057d3362017-09-15 23:04:04 +0000446 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000447 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000448 getCUIndex().dump(OS);
449 }
450
Adrian Prantl057d3362017-09-15 23:04:04 +0000451 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000452 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000453 getTUIndex().dump(OS);
454 }
455
Adrian Prantl057d3362017-09-15 23:04:04 +0000456 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000457 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000458 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000459 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000460 uint32_t strOffset = 0;
461 while (const char *s = strData.getCStr(&offset)) {
462 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
463 strOffset = offset;
464 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000465 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000466 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000467 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000468 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000469 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000470 uint32_t strDWOOffset = 0;
471 while (const char *s = strDWOData.getCStr(&offset)) {
472 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
473 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000474 }
David Blaikie66865d62014-01-09 00:13:35 +0000475 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000476 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
477 DObj->getLineStringSection())) {
478 DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0);
479 uint32_t offset = 0;
480 uint32_t strOffset = 0;
481 while (const char *s = strData.getCStr(&offset)) {
Scott Linder16c7bda2018-02-23 23:01:06 +0000482 OS << format("0x%8.8x: \"", strOffset);
483 OS.write_escaped(s);
484 OS << "\"\n";
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000485 strOffset = offset;
486 }
487 }
David Blaikie622dce42014-01-08 23:29:59 +0000488
Victor Leschuk58d33992018-07-31 22:19:19 +0000489 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
490 DObj->getAddrSection().Data)) {
491 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
492 isLittleEndian(), 0);
493 dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
494 }
495
Adrian Prantl057d3362017-09-15 23:04:04 +0000496 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000497 DObj->getRangeSection().Data)) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000498 uint8_t savedAddressByteSize = getCUAddrSize();
Rafael Espindolac398e672017-07-19 22:27:28 +0000499 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
500 isLittleEndian(), savedAddressByteSize);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000501 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000502 DWARFDebugRangeList rangeList;
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000503 while (rangesData.isValidOffset(offset)) {
504 if (Error E = rangeList.extract(rangesData, &offset)) {
505 WithColor::error() << toString(std::move(E)) << '\n';
Fangrui Songf78650a2018-07-30 19:41:25 +0000506 break;
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000507 }
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000508 rangeList.dump(OS);
Wolfgang Pieb61d8c8d2018-06-20 22:56:37 +0000509 }
Eric Christopherda4b2192013-01-02 23:52:13 +0000510 }
Eric Christopher962c9082013-01-15 23:56:56 +0000511
James Henderson3fcc7452018-02-02 12:35:52 +0000512 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
513 DObj->getRnglistsSection().Data)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000514 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
James Henderson3fcc7452018-02-02 12:35:52 +0000515 isLittleEndian(), 0);
Wolfgang Piebad605592018-05-18 20:12:54 +0000516 dumpRnglistsSection(OS, RnglistData, DumpOpts);
517 }
518
519 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
520 DObj->getRnglistsDWOSection().Data)) {
521 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
522 isLittleEndian(), 0);
523 dumpRnglistsSection(OS, RnglistData, DumpOpts);
James Henderson3fcc7452018-02-02 12:35:52 +0000524 }
525
Adrian Prantl057d3362017-09-15 23:04:04 +0000526 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000527 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000528 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000529 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000530
Adrian Prantl057d3362017-09-15 23:04:04 +0000531 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000532 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000533 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000534 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000535
Adrian Prantl057d3362017-09-15 23:04:04 +0000536 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000537 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000538 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000539 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000540 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000541
Adrian Prantl057d3362017-09-15 23:04:04 +0000542 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000543 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000544 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000545 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000546 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000547
Adrian Prantl057d3362017-09-15 23:04:04 +0000548 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000549 DObj->getStringOffsetSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000550 dumpStringOffsetsSection(
551 OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000552 DObj->getStringSection(), compile_units(), type_unit_sections(),
553 isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000554 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000555 DObj->getStringOffsetDWOSection().Data))
Rafael Espindolac398e672017-07-19 22:27:28 +0000556 dumpStringOffsetsSection(
557 OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000558 DObj->getStringDWOSection(), dwo_compile_units(),
559 dwo_type_unit_sections(), isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000560
Adrian Prantl057d3362017-09-15 23:04:04 +0000561 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000562 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000563 getGdbIndex().dump(OS);
564 }
565
Adrian Prantl057d3362017-09-15 23:04:04 +0000566 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000567 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000568 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000569
Adrian Prantl057d3362017-09-15 23:04:04 +0000570 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000571 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000572 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000573
Adrian Prantl057d3362017-09-15 23:04:04 +0000574 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000575 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000576 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000577
Adrian Prantl057d3362017-09-15 23:04:04 +0000578 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000579 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000580 getAppleObjC().dump(OS);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000581 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
582 DObj->getDebugNamesSection().Data))
583 getDebugNames().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000584}
585
David Blaikie15d85fc2017-05-23 06:48:53 +0000586DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
Paul Robinson143eaea2018-08-01 20:43:47 +0000587 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), DW_SECT_INFO, true);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000588
David Blaikieebac0b92017-07-30 08:12:07 +0000589 if (const auto &CUI = getCUIndex()) {
590 if (const auto *R = CUI.getFromHash(Hash))
Paul Robinson143eaea2018-08-01 20:43:47 +0000591 return dyn_cast_or_null<DWARFCompileUnit>(DWOCUs.getUnitForIndexEntry(*R));
David Blaikieebac0b92017-07-30 08:12:07 +0000592 return nullptr;
593 }
594
595 // If there's no index, just search through the CUs in the DWO - there's
596 // probably only one unless this is something like LTO - though an in-process
597 // built/cached lookup table could be used in that case to improve repeated
598 // lookups of different CUs in the DWO.
Paul Robinson543c0e12018-05-22 17:27:31 +0000599 for (const auto &DWOCU : dwo_compile_units()) {
600 // Might not have parsed DWO ID yet.
601 if (!DWOCU->getDWOId()) {
602 if (Optional<uint64_t> DWOId =
603 toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
604 DWOCU->setDWOId(*DWOId);
605 else
606 // No DWO ID?
607 continue;
608 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000609 if (DWOCU->getDWOId() == Hash)
Paul Robinson143eaea2018-08-01 20:43:47 +0000610 return dyn_cast<DWARFCompileUnit>(DWOCU.get());
Paul Robinson543c0e12018-05-22 17:27:31 +0000611 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000612 return nullptr;
613}
614
Greg Claytonc7695a82017-05-02 20:28:33 +0000615DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
616 parseCompileUnits();
617 if (auto *CU = CUs.getUnitForOffset(Offset))
618 return CU->getDIEForOffset(Offset);
619 return DWARFDie();
620}
621
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000622bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000623 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000624 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000625
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000626 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000627 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000628 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000629 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000630 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000631 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000632 return Success;
633}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000634
David Blaikie82641be2015-11-17 00:39:55 +0000635const DWARFUnitIndex &DWARFContext::getCUIndex() {
636 if (CUIndex)
637 return *CUIndex;
638
Rafael Espindolac398e672017-07-19 22:27:28 +0000639 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000640
David Blaikieb073cb92015-12-02 06:21:34 +0000641 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000642 CUIndex->parse(CUIndexData);
643 return *CUIndex;
644}
645
646const DWARFUnitIndex &DWARFContext::getTUIndex() {
647 if (TUIndex)
648 return *TUIndex;
649
Rafael Espindolac398e672017-07-19 22:27:28 +0000650 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000651
David Blaikieb073cb92015-12-02 06:21:34 +0000652 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000653 TUIndex->parse(TUIndexData);
654 return *TUIndex;
655}
656
George Rimar4f82df52016-09-23 11:01:53 +0000657DWARFGdbIndex &DWARFContext::getGdbIndex() {
658 if (GdbIndex)
659 return *GdbIndex;
660
Rafael Espindolac398e672017-07-19 22:27:28 +0000661 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000662 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
663 GdbIndex->parse(GdbIndexData);
664 return *GdbIndex;
665}
666
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000667const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
668 if (Abbrev)
669 return Abbrev.get();
670
Rafael Espindolac398e672017-07-19 22:27:28 +0000671 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000672
673 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000674 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000675 return Abbrev.get();
676}
677
Eric Christopherda4b2192013-01-02 23:52:13 +0000678const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
679 if (AbbrevDWO)
680 return AbbrevDWO.get();
681
Rafael Espindolac398e672017-07-19 22:27:28 +0000682 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000683 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000684 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000685 return AbbrevDWO.get();
686}
687
David Blaikie18e73502013-06-19 21:37:13 +0000688const DWARFDebugLoc *DWARFContext::getDebugLoc() {
689 if (Loc)
690 return Loc.get();
691
Paul Robinson17536b92017-06-29 16:52:08 +0000692 Loc.reset(new DWARFDebugLoc);
Paul Robinson143eaea2018-08-01 20:43:47 +0000693 // Assume all units have the same address byte size.
Paul Robinson17536b92017-06-29 16:52:08 +0000694 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000695 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson143eaea2018-08-01 20:43:47 +0000696 getUnitAtIndex(0)->getAddressByteSize());
Paul Robinson17536b92017-06-29 16:52:08 +0000697 Loc->parse(LocData);
698 }
David Blaikie18e73502013-06-19 21:37:13 +0000699 return Loc.get();
700}
701
David Blaikie9c550ac2014-03-25 01:44:02 +0000702const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
703 if (LocDWO)
704 return LocDWO.get();
705
David Blaikie9c550ac2014-03-25 01:44:02 +0000706 LocDWO.reset(new DWARFDebugLocDWO());
Pavel Labath54ca2d62018-04-06 08:49:57 +0000707 // Assume all compile units have the same address byte size.
708 if (getNumCompileUnits()) {
709 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(),
Paul Robinson143eaea2018-08-01 20:43:47 +0000710 getUnitAtIndex(0)->getAddressByteSize());
Pavel Labath54ca2d62018-04-06 08:49:57 +0000711 LocDWO->parse(LocData);
712 }
David Blaikie9c550ac2014-03-25 01:44:02 +0000713 return LocDWO.get();
714}
715
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000716const DWARFDebugAranges *DWARFContext::getDebugAranges() {
717 if (Aranges)
718 return Aranges.get();
719
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000720 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000721 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000722 return Aranges.get();
723}
724
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000725const DWARFDebugFrame *DWARFContext::getDebugFrame() {
726 if (DebugFrame)
727 return DebugFrame.get();
728
729 // There's a "bug" in the DWARFv3 standard with respect to the target address
730 // size within debug frame sections. While DWARF is supposed to be independent
731 // of its container, FDEs have fields with size being "target address size",
732 // which isn't specified in DWARF in general. It's only specified for CUs, but
733 // .eh_frame can appear without a .debug_info section. Follow the example of
734 // other tools (libdwarf) and extract this from the container (ObjectFile
735 // provides this information). This problem is fixed in DWARFv4
736 // See this dwarf-discuss discussion for more details:
737 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000738 DWARFDataExtractor debugFrameData(DObj->getDebugFrameSection(),
739 isLittleEndian(), DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000740 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
741 DebugFrame->parse(debugFrameData);
742 return DebugFrame.get();
743}
744
745const DWARFDebugFrame *DWARFContext::getEHFrame() {
746 if (EHFrame)
747 return EHFrame.get();
748
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000749 DWARFDataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
750 DObj->getAddressSize());
Igor Laevsky03a670c2016-01-26 15:09:42 +0000751 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000752 DebugFrame->parse(debugFrameData);
753 return DebugFrame.get();
754}
755
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000756const DWARFDebugMacro *DWARFContext::getDebugMacro() {
757 if (Macro)
758 return Macro.get();
759
Rafael Espindolac398e672017-07-19 22:27:28 +0000760 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000761 Macro.reset(new DWARFDebugMacro());
762 Macro->parse(MacinfoData);
763 return Macro.get();
764}
765
Pavel Labath3c9a9182018-01-29 11:08:32 +0000766template <typename T>
767static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
768 const DWARFSection &Section, StringRef StringSection,
769 bool IsLittleEndian) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000770 if (Cache)
771 return *Cache;
772 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
773 DataExtractor StrData(StringSection, IsLittleEndian, 0);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000774 Cache.reset(new T(AccelSection, StrData));
Jonas Devlieghereba915892017-12-11 18:22:47 +0000775 if (Error E = Cache->extract())
776 llvm::consumeError(std::move(E));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000777 return *Cache;
778}
779
Pavel Labath3c9a9182018-01-29 11:08:32 +0000780const DWARFDebugNames &DWARFContext::getDebugNames() {
781 return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(),
782 DObj->getStringSection(), isLittleEndian());
783}
784
Pavel Labath9b36fd22018-01-22 13:17:23 +0000785const AppleAcceleratorTable &DWARFContext::getAppleNames() {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000786 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
787 DObj->getStringSection(), isLittleEndian());
788}
789
Pavel Labath9b36fd22018-01-22 13:17:23 +0000790const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000791 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
792 DObj->getStringSection(), isLittleEndian());
793}
794
Pavel Labath9b36fd22018-01-22 13:17:23 +0000795const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000796 return getAccelTable(AppleNamespaces, *DObj,
797 DObj->getAppleNamespacesSection(),
798 DObj->getStringSection(), isLittleEndian());
799}
800
Pavel Labath9b36fd22018-01-22 13:17:23 +0000801const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000802 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
803 DObj->getStringSection(), isLittleEndian());
804}
805
James Hendersona3acf992018-05-10 10:51:33 +0000806const DWARFDebugLine::LineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000807DWARFContext::getLineTableForUnit(DWARFUnit *U) {
James Hendersona3acf992018-05-10 10:51:33 +0000808 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
809 getLineTableForUnit(U, DWARFDebugLine::warn);
810 if (!ExpectedLineTable) {
James Henderson004b7292018-05-21 15:30:54 +0000811 DWARFDebugLine::warn(ExpectedLineTable.takeError());
James Hendersona3acf992018-05-10 10:51:33 +0000812 return nullptr;
813 }
814 return *ExpectedLineTable;
815}
816
James Henderson004b7292018-05-21 15:30:54 +0000817Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
818 DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000819 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000820 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000821
Greg Claytonc8c10322016-12-13 18:25:19 +0000822 auto UnitDIE = U->getUnitDIE();
823 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000824 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000825
Greg Clayton97d22182017-01-13 21:08:18 +0000826 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000827 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000828 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000829
Greg Clayton52fe1f62016-12-14 22:38:08 +0000830 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000831 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000832 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000833 return lt;
834
Greg Clayton48ff66a2017-05-04 18:29:44 +0000835 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000836 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000837 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000838
Benjamin Kramer679e1752011-09-15 20:43:18 +0000839 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000840 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000841 U->getAddressByteSize());
James Hendersona3acf992018-05-10 10:51:33 +0000842 return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
James Henderson004b7292018-05-21 15:30:54 +0000843 RecoverableErrorCallback);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000844}
845
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000846void DWARFContext::parseCompileUnits() {
Paul Robinson143eaea2018-08-01 20:43:47 +0000847 CUs.parse(*this, DObj->getInfoSection(), DW_SECT_INFO);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000848}
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000849
David Blaikie03c089c2013-09-23 22:44:47 +0000850void DWARFContext::parseTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000851 if (!TUs.empty())
852 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000853 DObj->forEachTypesSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000854 TUs.emplace_back();
Paul Robinson143eaea2018-08-01 20:43:47 +0000855 TUs.back().parse(*this, S, DW_SECT_TYPES);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000856 });
David Blaikie03c089c2013-09-23 22:44:47 +0000857}
858
Eric Christopherda4b2192013-01-02 23:52:13 +0000859void DWARFContext::parseDWOCompileUnits() {
Paul Robinson143eaea2018-08-01 20:43:47 +0000860 DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), DW_SECT_INFO);
Eric Christopherda4b2192013-01-02 23:52:13 +0000861}
862
David Blaikie92d9d622014-01-09 05:08:24 +0000863void DWARFContext::parseDWOTypeUnits() {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000864 if (!DWOTUs.empty())
865 return;
Rafael Espindolac398e672017-07-19 22:27:28 +0000866 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000867 DWOTUs.emplace_back();
Paul Robinson143eaea2018-08-01 20:43:47 +0000868 DWOTUs.back().parseDWO(*this, S, DW_SECT_TYPES);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000869 });
David Blaikie92d9d622014-01-09 05:08:24 +0000870}
871
Alexey Samsonov45be7932012-08-30 07:49:50 +0000872DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000873 parseCompileUnits();
Paul Robinson143eaea2018-08-01 20:43:47 +0000874 return dyn_cast_or_null<DWARFCompileUnit>(CUs.getUnitForOffset(Offset));
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000875}
876
Alexey Samsonov45be7932012-08-30 07:49:50 +0000877DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000878 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000879 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000880 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000881 return getCompileUnitForOffset(CUOffset);
882}
883
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000884DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
885 DIEsForAddress Result;
886
887 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
888 if (!CU)
889 return Result;
890
891 Result.CompileUnit = CU;
892 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
893
894 std::vector<DWARFDie> Worklist;
895 Worklist.push_back(Result.FunctionDIE);
896 while (!Worklist.empty()) {
897 DWARFDie DIE = Worklist.back();
898 Worklist.pop_back();
899
900 if (DIE.getTag() == DW_TAG_lexical_block &&
901 DIE.addressRangeContainsAddress(Address)) {
902 Result.BlockDIE = DIE;
903 break;
904 }
905
906 for (auto Child : DIE)
907 Worklist.push_back(Child);
908 }
909
910 return Result;
911}
912
David Blaikieefc4eba2017-02-06 20:19:02 +0000913static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
914 uint64_t Address,
915 FunctionNameKind Kind,
916 std::string &FunctionName,
917 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000918 // The address may correspond to instruction in some inlined function,
919 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000920 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000921 SmallVector<DWARFDie, 4> InlinedChain;
922 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000923 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000924 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000925
926 const DWARFDie &DIE = InlinedChain[0];
927 bool FoundResult = false;
928 const char *Name = nullptr;
929 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000930 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000931 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000932 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000933 if (auto DeclLineResult = DIE.getDeclLine()) {
934 StartLine = DeclLineResult;
935 FoundResult = true;
936 }
937
938 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000939}
940
Alexey Samsonov45be7932012-08-30 07:49:50 +0000941DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000942 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000943 DILineInfo Result;
944
Alexey Samsonov45be7932012-08-30 07:49:50 +0000945 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
946 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000947 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000948 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
949 Result.FunctionName,
950 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000951 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000952 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
953 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
954 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000955 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000956 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000957}
David Blaikiea379b1812011-12-20 02:50:00 +0000958
Alexey Samsonovdce67342014-05-15 21:24:32 +0000959DILineInfoTable
960DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
961 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000962 DILineInfoTable Lines;
963 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
964 if (!CU)
965 return Lines;
966
967 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000968 uint32_t StartLine = 0;
969 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
970 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000971
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000972 // If the Specifier says we don't need FileLineInfo, just
973 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000974 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000975 DILineInfo Result;
976 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000977 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000978 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000979 return Lines;
980 }
981
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000982 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000983
984 // Get the index of row we're looking for in the line table.
985 std::vector<uint32_t> RowVector;
986 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
987 return Lines;
988
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000989 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000990 // Take file number and line/column from the row.
991 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000992 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000993 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
994 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000995 Result.FunctionName = FunctionName;
996 Result.Line = Row.Line;
997 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000998 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000999 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001000 }
1001
1002 return Lines;
1003}
1004
Alexey Samsonovdce67342014-05-15 21:24:32 +00001005DIInliningInfo
1006DWARFContext::getInliningInfoForAddress(uint64_t Address,
1007 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001008 DIInliningInfo InliningInfo;
1009
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001010 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
1011 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001012 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001013
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001014 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +00001015 SmallVector<DWARFDie, 4> InlinedChain;
1016 CU->getInlinedChainForAddress(Address, InlinedChain);
1017 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001018 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1019 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +00001020 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001021 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001022 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +00001023 if (LineTable &&
1024 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
1025 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001026 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001027 }
1028 return InliningInfo;
1029 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001030
Dehao Chenef700d52017-04-17 20:10:39 +00001031 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00001032 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1033 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +00001034 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001035 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +00001036 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +00001037 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +00001038 if (auto DeclLineResult = FunctionDIE.getDeclLine())
1039 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +00001040 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001041 if (i == 0) {
1042 // For the topmost frame, initialize the line table of this
1043 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001044 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001045 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +00001046 if (LineTable)
1047 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
1048 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001049 } else {
1050 // Otherwise, use call file, call line and call column from
1051 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +00001052 if (LineTable)
1053 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1054 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +00001055 Frame.Line = CallLine;
1056 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +00001057 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001058 }
1059 // Get call file/line/column of a current DIE.
1060 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +00001061 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1062 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001063 }
1064 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001065 InliningInfo.addFrame(Frame);
1066 }
1067 return InliningInfo;
1068}
1069
David Blaikief9803fb2017-05-23 00:30:42 +00001070std::shared_ptr<DWARFContext>
1071DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +00001072 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +00001073 DWARFContext *Ctxt = S->Context.get();
1074 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1075 }
1076
David Blaikie15d85fc2017-05-23 06:48:53 +00001077 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1078
1079 if (auto S = Entry->lock()) {
1080 DWARFContext *Ctxt = S->Context.get();
1081 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1082 }
1083
David Blaikie15d85fc2017-05-23 06:48:53 +00001084 Expected<OwningBinary<ObjectFile>> Obj = [&] {
1085 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +00001086 SmallString<128> DWPName;
1087 auto Obj = object::ObjectFile::createObjectFile(
1088 this->DWPName.empty()
1089 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1090 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +00001091 if (Obj) {
1092 Entry = &DWP;
1093 return Obj;
1094 } else {
1095 CheckedForDWP = true;
1096 // TODO: Should this error be handled (maybe in a high verbosity mode)
1097 // before falling back to .dwo files?
1098 consumeError(Obj.takeError());
1099 }
1100 }
1101
1102 return object::ObjectFile::createObjectFile(AbsolutePath);
1103 }();
1104
David Blaikief9803fb2017-05-23 00:30:42 +00001105 if (!Obj) {
1106 // TODO: Actually report errors helpfully.
1107 consumeError(Obj.takeError());
1108 return nullptr;
1109 }
David Blaikie15d85fc2017-05-23 06:48:53 +00001110
1111 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +00001112 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +00001113 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +00001114 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +00001115 auto *Ctxt = S->Context.get();
1116 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1117}
1118
George Rimar702dac62017-04-12 08:59:15 +00001119static Error createError(const Twine &Reason, llvm::Error E) {
1120 return make_error<StringError>(Reason + toString(std::move(E)),
1121 inconvertibleErrorCode());
1122}
1123
George Rimara25d3292017-05-27 18:10:23 +00001124/// SymInfo contains information about symbol: it's address
1125/// and section index which is -1LL for absolute symbols.
1126struct SymInfo {
1127 uint64_t Address;
1128 uint64_t SectionIndex;
1129};
1130
1131/// Returns the address of symbol relocation used against and a section index.
1132/// Used for futher relocations computation. Symbol's section load address is
1133static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1134 const RelocationRef &Reloc,
1135 const LoadedObjectInfo *L,
1136 std::map<SymbolRef, SymInfo> &Cache) {
1137 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001138 object::section_iterator RSec = Obj.section_end();
1139 object::symbol_iterator Sym = Reloc.getSymbol();
1140
George Rimara25d3292017-05-27 18:10:23 +00001141 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001142 // First calculate the address of the symbol or section as it appears
1143 // in the object file
1144 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001145 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001146 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001147 if (!New)
1148 return CacheIt->second;
1149
George Rimar702dac62017-04-12 08:59:15 +00001150 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1151 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001152 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001153 SymAddrOrErr.takeError());
1154
1155 // Also remember what section this symbol is in for later
1156 auto SectOrErr = Sym->getSection();
1157 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001158 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001159 SectOrErr.takeError());
1160
1161 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001162 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001163 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1164 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001165 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001166 }
1167
George Rimara25d3292017-05-27 18:10:23 +00001168 if (RSec != Obj.section_end())
1169 Ret.SectionIndex = RSec->getIndex();
1170
George Rimar702dac62017-04-12 08:59:15 +00001171 // If we are given load addresses for the sections, we need to adjust:
1172 // SymAddr = (Address of Symbol Or Section in File) -
1173 // (Address of Section in File) +
1174 // (Load Address of Section)
1175 // RSec is now either the section being targeted or the section
1176 // containing the symbol being targeted. In either case,
1177 // we need to perform the same computation.
1178 if (L && RSec != Obj.section_end())
1179 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001180 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001181
1182 if (CacheIt != Cache.end())
1183 CacheIt->second = Ret;
1184
George Rimar702dac62017-04-12 08:59:15 +00001185 return Ret;
1186}
1187
1188static bool isRelocScattered(const object::ObjectFile &Obj,
1189 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001190 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1191 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001192 return false;
1193 // MachO also has relocations that point to sections and
1194 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001195 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1196 return MachObj->isRelocationScattered(RelocInfo);
1197}
1198
Rafael Espindolac398e672017-07-19 22:27:28 +00001199ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
Jonas Devlieghere84e99262018-04-14 22:07:23 +00001200 WithColor::error() << toString(std::move(E)) << '\n';
George Rimar1af3cb22017-06-28 08:21:19 +00001201 return ErrorPolicy::Continue;
1202}
1203
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001204namespace {
1205struct DWARFSectionMap final : public DWARFSection {
1206 RelocAddrMap Relocs;
1207};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001208
Rafael Espindolac398e672017-07-19 22:27:28 +00001209class DWARFObjInMemory final : public DWARFObject {
1210 bool IsLittleEndian;
1211 uint8_t AddressSize;
1212 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001213 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001214 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001215
Rafael Espindolac398e672017-07-19 22:27:28 +00001216 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1217 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001218
Rafael Espindolac398e672017-07-19 22:27:28 +00001219 TypeSectionMap TypesSections;
1220 TypeSectionMap TypesDWOSections;
1221
1222 DWARFSectionMap InfoSection;
1223 DWARFSectionMap LocSection;
1224 DWARFSectionMap LineSection;
1225 DWARFSectionMap RangeSection;
James Henderson3fcc7452018-02-02 12:35:52 +00001226 DWARFSectionMap RnglistsSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001227 DWARFSectionMap StringOffsetSection;
1228 DWARFSectionMap InfoDWOSection;
1229 DWARFSectionMap LineDWOSection;
1230 DWARFSectionMap LocDWOSection;
1231 DWARFSectionMap StringOffsetDWOSection;
1232 DWARFSectionMap RangeDWOSection;
Wolfgang Piebad605592018-05-18 20:12:54 +00001233 DWARFSectionMap RnglistsDWOSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001234 DWARFSectionMap AddrSection;
1235 DWARFSectionMap AppleNamesSection;
1236 DWARFSectionMap AppleTypesSection;
1237 DWARFSectionMap AppleNamespacesSection;
1238 DWARFSectionMap AppleObjCSection;
Pavel Labath3c9a9182018-01-29 11:08:32 +00001239 DWARFSectionMap DebugNamesSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001240
1241 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1242 return StringSwitch<DWARFSectionMap *>(Name)
1243 .Case("debug_info", &InfoSection)
1244 .Case("debug_loc", &LocSection)
1245 .Case("debug_line", &LineSection)
1246 .Case("debug_str_offsets", &StringOffsetSection)
1247 .Case("debug_ranges", &RangeSection)
James Henderson3fcc7452018-02-02 12:35:52 +00001248 .Case("debug_rnglists", &RnglistsSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001249 .Case("debug_info.dwo", &InfoDWOSection)
1250 .Case("debug_loc.dwo", &LocDWOSection)
1251 .Case("debug_line.dwo", &LineDWOSection)
Pavel Labath3c9a9182018-01-29 11:08:32 +00001252 .Case("debug_names", &DebugNamesSection)
Wolfgang Piebad605592018-05-18 20:12:54 +00001253 .Case("debug_rnglists.dwo", &RnglistsDWOSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001254 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1255 .Case("debug_addr", &AddrSection)
1256 .Case("apple_names", &AppleNamesSection)
1257 .Case("apple_types", &AppleTypesSection)
1258 .Case("apple_namespaces", &AppleNamespacesSection)
1259 .Case("apple_namespac", &AppleNamespacesSection)
1260 .Case("apple_objc", &AppleObjCSection)
1261 .Default(nullptr);
1262 }
1263
1264 StringRef AbbrevSection;
1265 StringRef ARangeSection;
1266 StringRef DebugFrameSection;
1267 StringRef EHFrameSection;
1268 StringRef StringSection;
1269 StringRef MacinfoSection;
1270 StringRef PubNamesSection;
1271 StringRef PubTypesSection;
1272 StringRef GnuPubNamesSection;
1273 StringRef AbbrevDWOSection;
1274 StringRef StringDWOSection;
1275 StringRef GnuPubTypesSection;
1276 StringRef CUIndexSection;
1277 StringRef GdbIndexSection;
1278 StringRef TUIndexSection;
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001279 StringRef LineStringSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001280
Fangrui Song5bad9d82018-07-23 23:27:45 +00001281 // A deque holding section data whose iterators are not invalidated when
1282 // new decompressed sections are inserted at the end.
1283 std::deque<SmallString<0>> UncompressedSections;
Rafael Espindolac398e672017-07-19 22:27:28 +00001284
1285 StringRef *mapSectionToMember(StringRef Name) {
1286 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1287 return &Sec->Data;
1288 return StringSwitch<StringRef *>(Name)
1289 .Case("debug_abbrev", &AbbrevSection)
1290 .Case("debug_aranges", &ARangeSection)
1291 .Case("debug_frame", &DebugFrameSection)
1292 .Case("eh_frame", &EHFrameSection)
1293 .Case("debug_str", &StringSection)
1294 .Case("debug_macinfo", &MacinfoSection)
1295 .Case("debug_pubnames", &PubNamesSection)
1296 .Case("debug_pubtypes", &PubTypesSection)
1297 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1298 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1299 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1300 .Case("debug_str.dwo", &StringDWOSection)
1301 .Case("debug_cu_index", &CUIndexSection)
1302 .Case("debug_tu_index", &TUIndexSection)
1303 .Case("gdb_index", &GdbIndexSection)
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001304 .Case("debug_line_str", &LineStringSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001305 // Any more debug info sections go here.
1306 .Default(nullptr);
1307 }
1308
1309 /// If Sec is compressed section, decompresses and updates its contents
1310 /// provided by Data. Otherwise leaves it unchanged.
1311 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1312 StringRef &Data) {
1313 if (!Decompressor::isCompressed(Sec))
1314 return Error::success();
1315
1316 Expected<Decompressor> Decompressor =
1317 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1318 if (!Decompressor)
1319 return Decompressor.takeError();
1320
Fangrui Song5bad9d82018-07-23 23:27:45 +00001321 SmallString<0> Out;
Rafael Espindolac398e672017-07-19 22:27:28 +00001322 if (auto Err = Decompressor->resizeAndDecompress(Out))
1323 return Err;
1324
Fangrui Song5bad9d82018-07-23 23:27:45 +00001325 UncompressedSections.push_back(std::move(Out));
Rafael Espindolac398e672017-07-19 22:27:28 +00001326 Data = UncompressedSections.back();
1327
1328 return Error::success();
1329 }
1330
1331public:
1332 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1333 uint8_t AddrSize, bool IsLittleEndian)
1334 : IsLittleEndian(IsLittleEndian) {
1335 for (const auto &SecIt : Sections) {
1336 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1337 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001338 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001339 }
1340 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1341 function_ref<ErrorPolicy(Error)> HandleError)
1342 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001343 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1344 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001345
George Rimare1c30f72017-08-15 15:54:43 +00001346 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001347 for (const SectionRef &Section : Obj.sections()) {
1348 StringRef Name;
1349 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001350 ++SectionAmountMap[Name];
1351 SectionNames.push_back({ Name, true });
1352
Rafael Espindolac398e672017-07-19 22:27:28 +00001353 // Skip BSS and Virtual sections, they aren't interesting.
1354 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001355 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001356
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001357 // Skip sections stripped by dsymutil.
1358 if (Section.isStripped())
1359 continue;
1360
Rafael Espindolac398e672017-07-19 22:27:28 +00001361 StringRef Data;
1362 section_iterator RelocatedSection = Section.getRelocatedSection();
1363 // Try to obtain an already relocated version of this section.
1364 // Else use the unrelocated section from the object file. We'll have to
1365 // apply relocations ourselves later.
1366 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1367 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001368
Rafael Espindolac398e672017-07-19 22:27:28 +00001369 if (auto Err = maybeDecompress(Section, Name, Data)) {
1370 ErrorPolicy EP = HandleError(createError(
1371 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001372 if (EP == ErrorPolicy::Halt)
1373 return;
George Rimarfed9f092017-05-17 12:10:51 +00001374 continue;
1375 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001376
1377 // Compressed sections names in GNU style starts from ".z",
1378 // at this point section is decompressed and we drop compression prefix.
1379 Name = Name.substr(
1380 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1381
1382 // Map platform specific debug section names to DWARF standard section
1383 // names.
1384 Name = Obj.mapDebugSectionName(Name);
1385
1386 if (StringRef *SectionData = mapSectionToMember(Name)) {
1387 *SectionData = Data;
1388 if (Name == "debug_ranges") {
1389 // FIXME: Use the other dwo range section when we emit it.
1390 RangeDWOSection.Data = Data;
1391 }
1392 } else if (Name == "debug_types") {
1393 // Find debug_types data by section rather than name as there are
1394 // multiple, comdat grouped, debug_types sections.
1395 TypesSections[Section].Data = Data;
1396 } else if (Name == "debug_types.dwo") {
1397 TypesDWOSections[Section].Data = Data;
1398 }
1399
1400 if (RelocatedSection == Obj.section_end())
1401 continue;
1402
1403 StringRef RelSecName;
1404 StringRef RelSecData;
1405 RelocatedSection->getName(RelSecName);
1406
1407 // If the section we're relocating was relocated already by the JIT,
1408 // then we used the relocated version above, so we do not need to process
1409 // relocations for it now.
1410 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1411 continue;
1412
1413 // In Mach-o files, the relocations do not need to be applied if
1414 // there is no load offset to apply. The value read at the
1415 // relocation point already factors in the section address
1416 // (actually applying the relocations will produce wrong results
1417 // as the section address will be added twice).
1418 if (!L && isa<MachOObjectFile>(&Obj))
1419 continue;
1420
1421 RelSecName = RelSecName.substr(
1422 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1423
1424 // TODO: Add support for relocations in other sections as needed.
1425 // Record relocations for the debug_info and debug_line sections.
1426 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1427 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1428 if (!Map) {
1429 // Find debug_types relocs by section rather than name as there are
1430 // multiple, comdat grouped, debug_types sections.
1431 if (RelSecName == "debug_types")
1432 Map =
1433 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1434 .Relocs;
1435 else if (RelSecName == "debug_types.dwo")
1436 Map = &static_cast<DWARFSectionMap &>(
1437 TypesDWOSections[*RelocatedSection])
1438 .Relocs;
1439 else
1440 continue;
1441 }
1442
1443 if (Section.relocation_begin() == Section.relocation_end())
1444 continue;
1445
1446 // Symbol to [address, section index] cache mapping.
1447 std::map<SymbolRef, SymInfo> AddrCache;
1448 for (const RelocationRef &Reloc : Section.relocations()) {
1449 // FIXME: it's not clear how to correctly handle scattered
1450 // relocations.
1451 if (isRelocScattered(Obj, Reloc))
1452 continue;
1453
1454 Expected<SymInfo> SymInfoOrErr =
1455 getSymbolInfo(Obj, Reloc, L, AddrCache);
1456 if (!SymInfoOrErr) {
1457 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1458 return;
1459 continue;
1460 }
1461
1462 object::RelocVisitor V(Obj);
1463 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1464 if (V.error()) {
1465 SmallString<32> Type;
1466 Reloc.getTypeName(Type);
1467 ErrorPolicy EP = HandleError(
1468 createError("failed to compute relocation: " + Type + ", ",
1469 errorCodeToError(object_error::parse_failed)));
1470 if (EP == ErrorPolicy::Halt)
1471 return;
1472 continue;
1473 }
1474 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1475 Map->insert({Reloc.getOffset(), Rel});
1476 }
Eric Christopher7370b552012-11-12 21:40:38 +00001477 }
George Rimare1c30f72017-08-15 15:54:43 +00001478
1479 for (SectionName &S : SectionNames)
1480 if (SectionAmountMap[S.Name] > 1)
1481 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001482 }
Eric Christopher7370b552012-11-12 21:40:38 +00001483
Rafael Espindolac398e672017-07-19 22:27:28 +00001484 Optional<RelocAddrEntry> find(const DWARFSection &S,
1485 uint64_t Pos) const override {
1486 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1487 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1488 if (AI == Sec.Relocs.end())
1489 return None;
1490 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001491 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001492
George Rimar6957ab52017-08-15 12:32:54 +00001493 const object::ObjectFile *getFile() const override { return Obj; }
1494
George Rimare1c30f72017-08-15 15:54:43 +00001495 ArrayRef<SectionName> getSectionNames() const override {
1496 return SectionNames;
1497 }
1498
Rafael Espindolac398e672017-07-19 22:27:28 +00001499 bool isLittleEndian() const override { return IsLittleEndian; }
1500 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1501 const DWARFSection &getLineDWOSection() const override {
1502 return LineDWOSection;
1503 }
1504 const DWARFSection &getLocDWOSection() const override {
1505 return LocDWOSection;
1506 }
1507 StringRef getStringDWOSection() const override { return StringDWOSection; }
1508 const DWARFSection &getStringOffsetDWOSection() const override {
1509 return StringOffsetDWOSection;
1510 }
1511 const DWARFSection &getRangeDWOSection() const override {
1512 return RangeDWOSection;
1513 }
Wolfgang Piebad605592018-05-18 20:12:54 +00001514 const DWARFSection &getRnglistsDWOSection() const override {
1515 return RnglistsDWOSection;
1516 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001517 const DWARFSection &getAddrSection() const override { return AddrSection; }
1518 StringRef getCUIndexSection() const override { return CUIndexSection; }
1519 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1520 StringRef getTUIndexSection() const override { return TUIndexSection; }
1521
1522 // DWARF v5
1523 const DWARFSection &getStringOffsetSection() const override {
1524 return StringOffsetSection;
1525 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001526 StringRef getLineStringSection() const override { return LineStringSection; }
Rafael Espindolac398e672017-07-19 22:27:28 +00001527
1528 // Sections for DWARF5 split dwarf proposal.
1529 const DWARFSection &getInfoDWOSection() const override {
1530 return InfoDWOSection;
1531 }
1532 void forEachTypesDWOSections(
1533 function_ref<void(const DWARFSection &)> F) const override {
1534 for (auto &P : TypesDWOSections)
1535 F(P.second);
1536 }
1537
1538 StringRef getAbbrevSection() const override { return AbbrevSection; }
1539 const DWARFSection &getLocSection() const override { return LocSection; }
1540 StringRef getARangeSection() const override { return ARangeSection; }
1541 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1542 StringRef getEHFrameSection() const override { return EHFrameSection; }
1543 const DWARFSection &getLineSection() const override { return LineSection; }
1544 StringRef getStringSection() const override { return StringSection; }
1545 const DWARFSection &getRangeSection() const override { return RangeSection; }
James Henderson3fcc7452018-02-02 12:35:52 +00001546 const DWARFSection &getRnglistsSection() const override {
1547 return RnglistsSection;
1548 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001549 StringRef getMacinfoSection() const override { return MacinfoSection; }
1550 StringRef getPubNamesSection() const override { return PubNamesSection; }
1551 StringRef getPubTypesSection() const override { return PubTypesSection; }
1552 StringRef getGnuPubNamesSection() const override {
1553 return GnuPubNamesSection;
1554 }
1555 StringRef getGnuPubTypesSection() const override {
1556 return GnuPubTypesSection;
1557 }
1558 const DWARFSection &getAppleNamesSection() const override {
1559 return AppleNamesSection;
1560 }
1561 const DWARFSection &getAppleTypesSection() const override {
1562 return AppleTypesSection;
1563 }
1564 const DWARFSection &getAppleNamespacesSection() const override {
1565 return AppleNamespacesSection;
1566 }
1567 const DWARFSection &getAppleObjCSection() const override {
1568 return AppleObjCSection;
1569 }
Pavel Labath3c9a9182018-01-29 11:08:32 +00001570 const DWARFSection &getDebugNamesSection() const override {
1571 return DebugNamesSection;
1572 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001573
1574 StringRef getFileName() const override { return FileName; }
1575 uint8_t getAddressSize() const override { return AddressSize; }
1576 const DWARFSection &getInfoSection() const override { return InfoSection; }
1577 void forEachTypesSections(
1578 function_ref<void(const DWARFSection &)> F) const override {
1579 for (auto &P : TypesSections)
1580 F(P.second);
1581 }
1582};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001583} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001584
1585std::unique_ptr<DWARFContext>
1586DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001587 function_ref<ErrorPolicy(Error)> HandleError,
1588 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001589 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001590 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001591}
1592
Rafael Espindolac398e672017-07-19 22:27:28 +00001593std::unique_ptr<DWARFContext>
1594DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1595 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001596 auto DObj =
1597 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001598 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001599}
Reid Klecknera0587362017-08-29 21:41:21 +00001600
1601Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
1602 // Detect the architecture from the object file. We usually don't need OS
1603 // info to lookup a target and create register info.
1604 Triple TT;
1605 TT.setArch(Triple::ArchType(Obj.getArch()));
1606 TT.setVendor(Triple::UnknownVendor);
1607 TT.setOS(Triple::UnknownOS);
1608 std::string TargetLookupError;
1609 const Target *TheTarget =
1610 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1611 if (!TargetLookupError.empty())
1612 return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1613 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1614 return Error::success();
1615}
Victor Leschuk58d33992018-07-31 22:19:19 +00001616
1617uint8_t DWARFContext::getCUAddrSize() {
1618 // In theory, different compile units may have different address byte
1619 // sizes, but for simplicity we just use the address byte size of the
1620 // last compile unit. In practice the address size field is repeated across
1621 // various DWARF headers (at least in version 5) to make it easier to dump
1622 // them independently, not to enable varying the address size.
1623 uint8_t Addr = 0;
1624 for (const auto &CU : compile_units()) {
1625 Addr = CU->getAddressByteSize();
1626 break;
1627 }
1628 return Addr;
1629}