blob: 5d9f5a328ae2372e61316b18d2d19a11c859793a [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"
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +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
Paul Robinson96545db2018-08-02 19:29:38 +0000102collectContributionData(DWARFContext::unit_iterator_range Units) {
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000103 ContributionCollection Contributions;
Paul Robinson96545db2018-08-02 19:29:38 +0000104 for (const auto &U : Units)
105 Contributions.push_back(U->getStringOffsetsTableContribution());
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000106 // Sort the contributions so that any invalid ones are placed at
107 // the start of the contributions vector. This way they are reported
108 // first.
Fangrui Song0cac7262018-09-27 02:13:45 +0000109 llvm::sort(Contributions,
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000110 [](const Optional<StrOffsetsContributionDescriptor> &L,
111 const Optional<StrOffsetsContributionDescriptor> &R) {
Fangrui Song0cac7262018-09-27 02:13:45 +0000112 if (L && R)
113 return L->Base < R->Base;
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000114 return R.hasValue();
115 });
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000116
117 // Uniquify contributions, as it is possible that units (specifically
118 // type units in dwo or dwp files) share contributions. We don't want
119 // to report them more than once.
120 Contributions.erase(
121 std::unique(Contributions.begin(), Contributions.end(),
122 [](const Optional<StrOffsetsContributionDescriptor> &L,
123 const Optional<StrOffsetsContributionDescriptor> &R) {
124 if (L && R)
125 return L->Base == R->Base && L->Size == R->Size;
126 return false;
127 }),
128 Contributions.end());
129 return Contributions;
130}
131
132static void dumpDWARFv5StringOffsetsSection(
133 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
134 const DWARFSection &StringOffsetsSection, StringRef StringSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000135 DWARFContext::unit_iterator_range Units, bool LittleEndian) {
136 auto Contributions = collectContributionData(Units);
Rafael Espindolac398e672017-07-19 22:27:28 +0000137 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000138 DataExtractor StrData(StringSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000139 uint64_t SectionSize = StringOffsetsSection.Data.size();
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000140 uint32_t Offset = 0;
141 for (auto &Contribution : Contributions) {
142 // Report an ill-formed contribution.
143 if (!Contribution) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000144 OS << "error: invalid contribution to string offsets table in section ."
145 << SectionName << ".\n";
146 return;
147 }
148
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000149 dwarf::DwarfFormat Format = Contribution->getFormat();
150 uint16_t Version = Contribution->getVersion();
151 uint64_t ContributionHeader = Contribution->Base;
152 // In DWARF v5 there is a contribution header that immediately precedes
153 // the string offsets base (the location we have previously retrieved from
154 // the CU DIE's DW_AT_str_offsets attribute). The header is located either
155 // 8 or 16 bytes before the base, depending on the contribution's format.
156 if (Version >= 5)
157 ContributionHeader -= Format == DWARF32 ? 8 : 16;
158
159 // Detect overlapping contributions.
160 if (Offset > ContributionHeader) {
161 OS << "error: overlapping contributions to string offsets table in "
162 "section ."
163 << SectionName << ".\n";
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000164 return;
165 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000166 // Report a gap in the table.
167 if (Offset < ContributionHeader) {
168 OS << format("0x%8.8x: Gap, length = ", Offset);
169 OS << (ContributionHeader - Offset) << "\n";
170 }
Wolfgang Piebb4ba1aa2017-12-22 01:12:24 +0000171 OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
Wolfgang Piebf2b6915e2018-05-10 20:02:34 +0000172 // In DWARF v5 the contribution size in the descriptor does not equal
173 // the originally encoded length (it does not contain the length of the
174 // version field and the padding, a total of 4 bytes). Add them back in
175 // for reporting.
176 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000177 << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000178 << ", Version = " << Version << "\n";
179
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000180 Offset = Contribution->Base;
181 unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
182 while (Offset - Contribution->Base < Contribution->Size) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000183 OS << format("0x%8.8x: ", Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000184 // FIXME: We can only extract strings if the offset fits in 32 bits.
Paul Robinson17536b92017-06-29 16:52:08 +0000185 uint64_t StringOffset =
186 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000187 // Extract the string if we can and display it. Otherwise just report
188 // the offset.
189 if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000190 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000191 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000192 const char *S = StrData.getCStr(&StringOffset32);
193 if (S)
194 OS << format("\"%s\"", S);
195 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000196 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000197 OS << "\n";
198 }
199 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000200 // Report a gap at the end of the table.
201 if (Offset < SectionSize) {
202 OS << format("0x%8.8x: Gap, length = ", Offset);
203 OS << (SectionSize - Offset) << "\n";
204 }
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000205}
206
207// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
208// string offsets section, where each compile or type unit contributes a
209// number of entries (string offsets), with each contribution preceded by
210// a header containing size and version number. Alternatively, it may be a
211// monolithic series of string offsets, as generated by the pre-DWARF v5
212// implementation of split DWARF.
Paul Robinson7f330942018-08-01 20:46:46 +0000213static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
214 const DWARFObject &Obj,
215 const DWARFSection &StringOffsetsSection,
216 StringRef StringSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000217 DWARFContext::unit_iterator_range Units,
Paul Robinson7f330942018-08-01 20:46:46 +0000218 bool LittleEndian, unsigned MaxVersion) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000219 // If we have at least one (compile or type) unit with DWARF v5 or greater,
220 // we assume that the section is formatted like a DWARF v5 string offsets
221 // section.
222 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000223 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000224 StringSection, Units, LittleEndian);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000225 else {
226 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
227 uint32_t offset = 0;
228 uint64_t size = StringOffsetsSection.Data.size();
229 // Ensure that size is a multiple of the size of an entry.
230 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
231 OS << "error: size of ." << SectionName << " is not a multiple of "
232 << sizeof(uint32_t) << ".\n";
233 size &= -(uint64_t)sizeof(uint32_t);
234 }
235 DataExtractor StrData(StringSection, LittleEndian, 0);
236 while (offset < size) {
237 OS << format("0x%8.8x: ", offset);
238 uint32_t StringOffset = strOffsetExt.getU32(&offset);
239 OS << format("%8.8x ", StringOffset);
240 const char *S = StrData.getCStr(&StringOffset);
241 if (S)
242 OS << format("\"%s\"", S);
243 OS << "\n";
244 }
245 }
246}
247
Victor Leschuk58d33992018-07-31 22:19:19 +0000248// Dump the .debug_addr section.
249static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
250 DIDumpOptions DumpOpts, uint16_t Version,
251 uint8_t AddrSize) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000252 uint32_t Offset = 0;
253 while (AddrData.isValidOffset(Offset)) {
254 DWARFDebugAddrTable AddrTable;
255 uint32_t TableOffset = Offset;
Victor Leschukcf1f7142018-08-23 12:43:33 +0000256 if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
257 DWARFContext::dumpWarning)) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000258 WithColor::error() << toString(std::move(Err)) << '\n';
259 // Keep going after an error, if we can, assuming that the length field
260 // could be read. If it couldn't, stop reading the section.
261 if (!AddrTable.hasValidLength())
262 break;
263 uint64_t Length = AddrTable.getLength();
264 Offset = TableOffset + Length;
265 } else {
266 AddrTable.dump(OS, DumpOpts);
267 }
268 }
269}
270
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000271// Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
272static void dumpRnglistsSection(raw_ostream &OS,
273 DWARFDataExtractor &rnglistData,
274 DIDumpOptions DumpOpts) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000275 uint32_t Offset = 0;
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000276 while (rnglistData.isValidOffset(Offset)) {
277 llvm::DWARFDebugRnglistTable Rnglists;
278 uint32_t TableOffset = Offset;
279 if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000280 WithColor::error() << toString(std::move(Err)) << '\n';
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000281 uint64_t Length = Rnglists.length();
282 // Keep going after an error, if we can, assuming that the length field
283 // could be read. If it couldn't, stop reading the section.
284 if (Length == 0)
Wolfgang Piebad605592018-05-18 20:12:54 +0000285 break;
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000286 Offset = TableOffset + Length;
Wolfgang Piebad605592018-05-18 20:12:54 +0000287 } else {
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000288 Rnglists.dump(OS, DumpOpts);
Wolfgang Piebad605592018-05-18 20:12:54 +0000289 }
290 }
291}
292
Adrian Prantl057d3362017-09-15 23:04:04 +0000293void DWARFContext::dump(
294 raw_ostream &OS, DIDumpOptions DumpOpts,
295 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
296
297 Optional<uint64_t> DumpOffset;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000298 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000299
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000300 StringRef Extension = sys::path::extension(DObj->getFileName());
301 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
302
303 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000304 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000305 if (DumpType & DIDT_UUID)
306 dumpUUID(OS, *ObjFile);
307
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000308 // Print a header for each explicitly-requested section.
309 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000310 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000311 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000312 bool ExplicitDWO = Explicit && IsDWO;
313 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
314 StringRef Section) {
315 DumpOffset = DumpOffsets[ID];
316 unsigned Mask = 1U << ID;
317 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
Adrian Prantl84168022017-09-15 17:39:50 +0000318 if (Should)
Adrian Prantl057d3362017-09-15 23:04:04 +0000319 OS << "\n" << Name << " contents:\n";
Adrian Prantl84168022017-09-15 17:39:50 +0000320 return Should;
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000321 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000322
323 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000324 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
325 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000326 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000327 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
328 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000329 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000330
Adrian Prantl057d3362017-09-15 23:04:04 +0000331 auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
Paul Robinson96545db2018-08-02 19:29:38 +0000332 DWARFSection Section, unit_iterator_range Units) {
Adrian Prantl057d3362017-09-15 23:04:04 +0000333 if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
Adrian Prantlc8d86532017-09-18 21:44:40 +0000334 if (DumpOffset)
Adrian Prantld3f9f212017-09-20 17:44:00 +0000335 getDIEForOffset(DumpOffset.getValue())
336 .dump(OS, 0, DumpOpts.noImplicitRecursion());
Adrian Prantlc8d86532017-09-18 21:44:40 +0000337 else
Paul Robinson96545db2018-08-02 19:29:38 +0000338 for (const auto &U : Units)
339 U->dump(OS, DumpOpts);
Adrian Prantl057d3362017-09-15 23:04:04 +0000340 }
341 };
342 dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
Paul Robinson2c25f342018-08-01 20:54:11 +0000343 info_section_units());
Adrian Prantl057d3362017-09-15 23:04:04 +0000344 dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
Paul Robinson2c25f342018-08-01 20:54:11 +0000345 dwo_info_section_units());
David Blaikie622dce42014-01-08 23:29:59 +0000346
Paul Robinson96545db2018-08-02 19:29:38 +0000347 auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
Adrian Prantl099d7e42017-09-16 16:58:18 +0000348 OS << '\n' << Name << " contents:\n";
349 DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
Paul Robinson96545db2018-08-02 19:29:38 +0000350 for (const auto &U : Units)
Paul Robinson7f330942018-08-01 20:46:46 +0000351 if (DumpOffset)
Paul Robinson96545db2018-08-02 19:29:38 +0000352 U->getDIEForOffset(*DumpOffset)
Paul Robinson7f330942018-08-01 20:46:46 +0000353 .dump(OS, 0, DumpOpts.noImplicitRecursion());
354 else
Paul Robinson96545db2018-08-02 19:29:38 +0000355 U->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000356 };
357 if ((DumpType & DIDT_DebugTypes)) {
358 if (Explicit || getNumTypeUnits())
Paul Robinson2c25f342018-08-01 20:54:11 +0000359 dumpDebugType(".debug_types", types_section_units());
Adrian Prantl099d7e42017-09-16 16:58:18 +0000360 if (ExplicitDWO || getNumDWOTypeUnits())
Paul Robinson2c25f342018-08-01 20:54:11 +0000361 dumpDebugType(".debug_types.dwo", dwo_types_section_units());
David Blaikie03c089c2013-09-23 22:44:47 +0000362 }
363
Adrian Prantl057d3362017-09-15 23:04:04 +0000364 if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000365 DObj->getLocSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000366 getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie18e73502013-06-19 21:37:13 +0000367 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000368 if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
Adrian Prantl84168022017-09-15 17:39:50 +0000369 DObj->getLocDWOSection().Data)) {
Jonas Devlieghere622c5632017-09-27 09:33:36 +0000370 getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset);
David Blaikie9c550ac2014-03-25 01:44:02 +0000371 }
372
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000373 if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000374 DObj->getDebugFrameSection()))
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000375 getDebugFrame()->dump(OS, getRegisterInfo(), DumpOffset);
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000376
377 if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
Adrian Prantl62528e62017-09-21 18:52:03 +0000378 DObj->getEHFrameSection()))
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000379 getEHFrame()->dump(OS, getRegisterInfo(), DumpOffset);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000380
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000381 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000382 if (Explicit || !getDebugMacro()->empty()) {
383 OS << "\n.debug_macinfo contents:\n";
384 getDebugMacro()->dump(OS);
385 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000386 }
387
Adrian Prantl057d3362017-09-15 23:04:04 +0000388 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000389 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000390 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000391 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000392 DWARFDebugArangeSet set;
393 while (set.extract(arangesData, &offset))
394 set.dump(OS);
395 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000396
James Hendersona3acf992018-05-10 10:51:33 +0000397 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
398 DIDumpOptions DumpOpts) {
399 while (!Parser.done()) {
400 if (DumpOffset && Parser.getOffset() != *DumpOffset) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000401 Parser.skip(dumpWarning);
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000402 continue;
Paul Robinson63811a42017-11-22 15:33:17 +0000403 }
James Hendersona3acf992018-05-10 10:51:33 +0000404 OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n";
Paul Robinson63811a42017-11-22 15:33:17 +0000405 if (DumpOpts.Verbose) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000406 Parser.parseNext(dumpWarning, dumpWarning, &OS);
Paul Robinson63811a42017-11-22 15:33:17 +0000407 } else {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000408 DWARFDebugLine::LineTable LineTable =
409 Parser.parseNext(dumpWarning, dumpWarning);
James Hendersona3acf992018-05-10 10:51:33 +0000410 LineTable.dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000411 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000412 }
James Hendersona3acf992018-05-10 10:51:33 +0000413 };
414
415 if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
416 DObj->getLineSection().Data)) {
417 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
418 0);
419 DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
Paul Robinson7f330942018-08-01 20:46:46 +0000420 type_units());
James Hendersona3acf992018-05-10 10:51:33 +0000421 DumpLineSection(Parser, DumpOpts);
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000422 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000423
Adrian Prantl057d3362017-09-15 23:04:04 +0000424 if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
Adrian Prantl84168022017-09-15 17:39:50 +0000425 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000426 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
427 isLittleEndian(), 0);
James Hendersona3acf992018-05-10 10:51:33 +0000428 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
Paul Robinson7f330942018-08-01 20:46:46 +0000429 dwo_type_units());
James Hendersona3acf992018-05-10 10:51:33 +0000430 DumpLineSection(Parser, DumpOpts);
David Blaikie1d4736e2014-02-24 23:58:54 +0000431 }
432
Adrian Prantl057d3362017-09-15 23:04:04 +0000433 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000434 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000435 getCUIndex().dump(OS);
436 }
437
Adrian Prantl057d3362017-09-15 23:04:04 +0000438 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000439 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000440 getTUIndex().dump(OS);
441 }
442
Adrian Prantl057d3362017-09-15 23:04:04 +0000443 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000444 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000445 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000446 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000447 uint32_t strOffset = 0;
448 while (const char *s = strData.getCStr(&offset)) {
449 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
450 strOffset = offset;
451 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000452 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000453 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000454 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000455 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000456 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000457 uint32_t strDWOOffset = 0;
458 while (const char *s = strDWOData.getCStr(&offset)) {
459 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
460 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000461 }
David Blaikie66865d62014-01-09 00:13:35 +0000462 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000463 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
464 DObj->getLineStringSection())) {
465 DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0);
466 uint32_t offset = 0;
467 uint32_t strOffset = 0;
468 while (const char *s = strData.getCStr(&offset)) {
Scott Linder16c7bda2018-02-23 23:01:06 +0000469 OS << format("0x%8.8x: \"", strOffset);
470 OS.write_escaped(s);
471 OS << "\"\n";
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000472 strOffset = offset;
473 }
474 }
David Blaikie622dce42014-01-08 23:29:59 +0000475
Victor Leschuk58d33992018-07-31 22:19:19 +0000476 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
477 DObj->getAddrSection().Data)) {
478 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
479 isLittleEndian(), 0);
480 dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
481 }
482
Adrian Prantl057d3362017-09-15 23:04:04 +0000483 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
Adrian Prantl84168022017-09-15 17:39:50 +0000484 DObj->getRangeSection().Data)) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000485 uint8_t savedAddressByteSize = getCUAddrSize();
Rafael Espindolac398e672017-07-19 22:27:28 +0000486 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
487 isLittleEndian(), savedAddressByteSize);
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000488 uint32_t offset = 0;
489 DWARFDebugRangeList rangeList;
490 while (rangesData.isValidOffset(offset)) {
491 if (Error E = rangeList.extract(rangesData, &offset)) {
492 WithColor::error() << toString(std::move(E)) << '\n';
493 break;
494 }
495 rangeList.dump(OS);
496 }
Eric Christopherda4b2192013-01-02 23:52:13 +0000497 }
Eric Christopher962c9082013-01-15 23:56:56 +0000498
James Henderson3fcc7452018-02-02 12:35:52 +0000499 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
500 DObj->getRnglistsSection().Data)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000501 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000502 isLittleEndian(), 0);
503 dumpRnglistsSection(OS, RnglistData, DumpOpts);
Wolfgang Piebad605592018-05-18 20:12:54 +0000504 }
505
506 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
507 DObj->getRnglistsDWOSection().Data)) {
508 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
Alexander Kornienkoe74e0f12018-09-17 15:40:01 +0000509 isLittleEndian(), 0);
510 dumpRnglistsSection(OS, RnglistData, DumpOpts);
James Henderson3fcc7452018-02-02 12:35:52 +0000511 }
512
Adrian Prantl057d3362017-09-15 23:04:04 +0000513 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000514 DObj->getPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000515 DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000516 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000517
Adrian Prantl057d3362017-09-15 23:04:04 +0000518 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000519 DObj->getPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000520 DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000521 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000522
Adrian Prantl057d3362017-09-15 23:04:04 +0000523 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Adrian Prantl84168022017-09-15 17:39:50 +0000524 DObj->getGnuPubNamesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000525 DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000526 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000527 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000528
Adrian Prantl057d3362017-09-15 23:04:04 +0000529 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000530 DObj->getGnuPubTypesSection()))
Rafael Espindolac398e672017-07-19 22:27:28 +0000531 DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000532 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000533 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000534
Adrian Prantl057d3362017-09-15 23:04:04 +0000535 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000536 DObj->getStringOffsetSection().Data))
Paul Robinson7f330942018-08-01 20:46:46 +0000537 dumpStringOffsetsSection(OS, "debug_str_offsets", *DObj,
538 DObj->getStringOffsetSection(),
Paul Robinson96545db2018-08-02 19:29:38 +0000539 DObj->getStringSection(), normal_units(),
540 isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000541 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000542 DObj->getStringOffsetDWOSection().Data))
Paul Robinson96545db2018-08-02 19:29:38 +0000543 dumpStringOffsetsSection(OS, "debug_str_offsets.dwo", *DObj,
544 DObj->getStringOffsetDWOSection(),
545 DObj->getStringDWOSection(), dwo_units(),
546 isLittleEndian(), getMaxVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000547
Adrian Prantl057d3362017-09-15 23:04:04 +0000548 if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000549 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000550 getGdbIndex().dump(OS);
551 }
552
Adrian Prantl057d3362017-09-15 23:04:04 +0000553 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000554 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000555 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000556
Adrian Prantl057d3362017-09-15 23:04:04 +0000557 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000558 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000559 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000560
Adrian Prantl057d3362017-09-15 23:04:04 +0000561 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000562 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000563 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000564
Adrian Prantl057d3362017-09-15 23:04:04 +0000565 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000566 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000567 getAppleObjC().dump(OS);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000568 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
569 DObj->getDebugNamesSection().Data))
570 getDebugNames().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000571}
572
David Blaikie15d85fc2017-05-23 06:48:53 +0000573DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000574 parseDWOUnits(LazyParse);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000575
David Blaikieebac0b92017-07-30 08:12:07 +0000576 if (const auto &CUI = getCUIndex()) {
577 if (const auto *R = CUI.getFromHash(Hash))
Paul Robinson2c25f342018-08-01 20:54:11 +0000578 return dyn_cast_or_null<DWARFCompileUnit>(
579 DWOUnits.getUnitForIndexEntry(*R));
David Blaikieebac0b92017-07-30 08:12:07 +0000580 return nullptr;
581 }
582
583 // If there's no index, just search through the CUs in the DWO - there's
584 // probably only one unless this is something like LTO - though an in-process
585 // built/cached lookup table could be used in that case to improve repeated
586 // lookups of different CUs in the DWO.
Paul Robinson543c0e12018-05-22 17:27:31 +0000587 for (const auto &DWOCU : dwo_compile_units()) {
588 // Might not have parsed DWO ID yet.
589 if (!DWOCU->getDWOId()) {
590 if (Optional<uint64_t> DWOId =
591 toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
592 DWOCU->setDWOId(*DWOId);
593 else
594 // No DWO ID?
595 continue;
596 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000597 if (DWOCU->getDWOId() == Hash)
Paul Robinson143eaea2018-08-01 20:43:47 +0000598 return dyn_cast<DWARFCompileUnit>(DWOCU.get());
Paul Robinson543c0e12018-05-22 17:27:31 +0000599 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000600 return nullptr;
601}
602
Greg Claytonc7695a82017-05-02 20:28:33 +0000603DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000604 parseNormalUnits();
605 if (auto *CU = NormalUnits.getUnitForOffset(Offset))
Greg Claytonc7695a82017-05-02 20:28:33 +0000606 return CU->getDIEForOffset(Offset);
607 return DWARFDie();
608}
609
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000610bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000611 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000612 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000613
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000614 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000615 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000616 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000617 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000618 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000619 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000620 return Success;
621}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000622
David Blaikie82641be2015-11-17 00:39:55 +0000623const DWARFUnitIndex &DWARFContext::getCUIndex() {
624 if (CUIndex)
625 return *CUIndex;
626
Rafael Espindolac398e672017-07-19 22:27:28 +0000627 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000628
David Blaikieb073cb92015-12-02 06:21:34 +0000629 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000630 CUIndex->parse(CUIndexData);
631 return *CUIndex;
632}
633
634const DWARFUnitIndex &DWARFContext::getTUIndex() {
635 if (TUIndex)
636 return *TUIndex;
637
Rafael Espindolac398e672017-07-19 22:27:28 +0000638 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000639
David Blaikieb073cb92015-12-02 06:21:34 +0000640 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000641 TUIndex->parse(TUIndexData);
642 return *TUIndex;
643}
644
George Rimar4f82df52016-09-23 11:01:53 +0000645DWARFGdbIndex &DWARFContext::getGdbIndex() {
646 if (GdbIndex)
647 return *GdbIndex;
648
Rafael Espindolac398e672017-07-19 22:27:28 +0000649 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000650 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
651 GdbIndex->parse(GdbIndexData);
652 return *GdbIndex;
653}
654
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000655const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
656 if (Abbrev)
657 return Abbrev.get();
658
Rafael Espindolac398e672017-07-19 22:27:28 +0000659 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000660
661 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000662 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000663 return Abbrev.get();
664}
665
Eric Christopherda4b2192013-01-02 23:52:13 +0000666const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
667 if (AbbrevDWO)
668 return AbbrevDWO.get();
669
Rafael Espindolac398e672017-07-19 22:27:28 +0000670 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000671 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000672 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000673 return AbbrevDWO.get();
674}
675
David Blaikie18e73502013-06-19 21:37:13 +0000676const DWARFDebugLoc *DWARFContext::getDebugLoc() {
677 if (Loc)
678 return Loc.get();
679
Paul Robinson17536b92017-06-29 16:52:08 +0000680 Loc.reset(new DWARFDebugLoc);
Paul Robinson143eaea2018-08-01 20:43:47 +0000681 // Assume all units have the same address byte size.
Paul Robinson17536b92017-06-29 16:52:08 +0000682 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000683 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson143eaea2018-08-01 20:43:47 +0000684 getUnitAtIndex(0)->getAddressByteSize());
Paul Robinson17536b92017-06-29 16:52:08 +0000685 Loc->parse(LocData);
686 }
David Blaikie18e73502013-06-19 21:37:13 +0000687 return Loc.get();
688}
689
David Blaikie9c550ac2014-03-25 01:44:02 +0000690const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
691 if (LocDWO)
692 return LocDWO.get();
693
David Blaikie9c550ac2014-03-25 01:44:02 +0000694 LocDWO.reset(new DWARFDebugLocDWO());
Pavel Labath54ca2d62018-04-06 08:49:57 +0000695 // Assume all compile units have the same address byte size.
696 if (getNumCompileUnits()) {
697 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(),
Paul Robinson143eaea2018-08-01 20:43:47 +0000698 getUnitAtIndex(0)->getAddressByteSize());
Pavel Labath54ca2d62018-04-06 08:49:57 +0000699 LocDWO->parse(LocData);
700 }
David Blaikie9c550ac2014-03-25 01:44:02 +0000701 return LocDWO.get();
702}
703
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000704const DWARFDebugAranges *DWARFContext::getDebugAranges() {
705 if (Aranges)
706 return Aranges.get();
707
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000708 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000709 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000710 return Aranges.get();
711}
712
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000713const DWARFDebugFrame *DWARFContext::getDebugFrame() {
714 if (DebugFrame)
715 return DebugFrame.get();
716
717 // There's a "bug" in the DWARFv3 standard with respect to the target address
718 // size within debug frame sections. While DWARF is supposed to be independent
719 // of its container, FDEs have fields with size being "target address size",
720 // which isn't specified in DWARF in general. It's only specified for CUs, but
721 // .eh_frame can appear without a .debug_info section. Follow the example of
722 // other tools (libdwarf) and extract this from the container (ObjectFile
723 // provides this information). This problem is fixed in DWARFv4
724 // See this dwarf-discuss discussion for more details:
725 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000726 DWARFDataExtractor debugFrameData(DObj->getDebugFrameSection(),
727 isLittleEndian(), DObj->getAddressSize());
Luke Cheeseman77aaa222018-09-26 14:48:03 +0000728 DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000729 DebugFrame->parse(debugFrameData);
730 return DebugFrame.get();
731}
732
733const DWARFDebugFrame *DWARFContext::getEHFrame() {
734 if (EHFrame)
735 return EHFrame.get();
736
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000737 DWARFDataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
738 DObj->getAddressSize());
Luke Cheeseman77aaa222018-09-26 14:48:03 +0000739 DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000740 DebugFrame->parse(debugFrameData);
741 return DebugFrame.get();
742}
743
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000744const DWARFDebugMacro *DWARFContext::getDebugMacro() {
745 if (Macro)
746 return Macro.get();
747
Rafael Espindolac398e672017-07-19 22:27:28 +0000748 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000749 Macro.reset(new DWARFDebugMacro());
750 Macro->parse(MacinfoData);
751 return Macro.get();
752}
753
Pavel Labath3c9a9182018-01-29 11:08:32 +0000754template <typename T>
755static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
756 const DWARFSection &Section, StringRef StringSection,
757 bool IsLittleEndian) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000758 if (Cache)
759 return *Cache;
760 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
761 DataExtractor StrData(StringSection, IsLittleEndian, 0);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000762 Cache.reset(new T(AccelSection, StrData));
Jonas Devlieghereba915892017-12-11 18:22:47 +0000763 if (Error E = Cache->extract())
764 llvm::consumeError(std::move(E));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000765 return *Cache;
766}
767
Pavel Labath3c9a9182018-01-29 11:08:32 +0000768const DWARFDebugNames &DWARFContext::getDebugNames() {
769 return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(),
770 DObj->getStringSection(), isLittleEndian());
771}
772
Pavel Labath9b36fd22018-01-22 13:17:23 +0000773const AppleAcceleratorTable &DWARFContext::getAppleNames() {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000774 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
775 DObj->getStringSection(), isLittleEndian());
776}
777
Pavel Labath9b36fd22018-01-22 13:17:23 +0000778const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000779 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
780 DObj->getStringSection(), isLittleEndian());
781}
782
Pavel Labath9b36fd22018-01-22 13:17:23 +0000783const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000784 return getAccelTable(AppleNamespaces, *DObj,
785 DObj->getAppleNamespacesSection(),
786 DObj->getStringSection(), isLittleEndian());
787}
788
Pavel Labath9b36fd22018-01-22 13:17:23 +0000789const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000790 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
791 DObj->getStringSection(), isLittleEndian());
792}
793
James Hendersona3acf992018-05-10 10:51:33 +0000794const DWARFDebugLine::LineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000795DWARFContext::getLineTableForUnit(DWARFUnit *U) {
James Hendersona3acf992018-05-10 10:51:33 +0000796 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
Victor Leschukcf1f7142018-08-23 12:43:33 +0000797 getLineTableForUnit(U, dumpWarning);
James Hendersona3acf992018-05-10 10:51:33 +0000798 if (!ExpectedLineTable) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000799 dumpWarning(ExpectedLineTable.takeError());
James Hendersona3acf992018-05-10 10:51:33 +0000800 return nullptr;
801 }
802 return *ExpectedLineTable;
803}
804
James Henderson004b7292018-05-21 15:30:54 +0000805Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
806 DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000807 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000808 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000809
Greg Claytonc8c10322016-12-13 18:25:19 +0000810 auto UnitDIE = U->getUnitDIE();
811 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000812 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000813
Greg Clayton97d22182017-01-13 21:08:18 +0000814 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000815 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000816 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000817
Greg Clayton52fe1f62016-12-14 22:38:08 +0000818 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000819 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000820 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000821 return lt;
822
Greg Clayton48ff66a2017-05-04 18:29:44 +0000823 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000824 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000825 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000826
Benjamin Kramer679e1752011-09-15 20:43:18 +0000827 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000828 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000829 U->getAddressByteSize());
James Hendersona3acf992018-05-10 10:51:33 +0000830 return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
James Henderson004b7292018-05-21 15:30:54 +0000831 RecoverableErrorCallback);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000832}
833
Paul Robinson2c25f342018-08-01 20:54:11 +0000834void DWARFContext::parseNormalUnits() {
835 if (!NormalUnits.empty())
Paul Robinson7f330942018-08-01 20:46:46 +0000836 return;
Paul Robinson2c25f342018-08-01 20:54:11 +0000837 NormalUnits.addUnitsForSection(*this, DObj->getInfoSection(), DW_SECT_INFO);
838 NormalUnits.finishedInfoUnits();
Rafael Espindolac398e672017-07-19 22:27:28 +0000839 DObj->forEachTypesSections([&](const DWARFSection &S) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000840 NormalUnits.addUnitsForSection(*this, S, DW_SECT_TYPES);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000841 });
David Blaikie03c089c2013-09-23 22:44:47 +0000842}
843
Paul Robinson2c25f342018-08-01 20:54:11 +0000844void DWARFContext::parseDWOUnits(bool Lazy) {
845 if (!DWOUnits.empty())
Paul Robinson7f330942018-08-01 20:46:46 +0000846 return;
Paul Robinson2c25f342018-08-01 20:54:11 +0000847 DWOUnits.addUnitsForDWOSection(*this, DObj->getInfoDWOSection(), DW_SECT_INFO,
848 Lazy);
849 DWOUnits.finishedInfoUnits();
Rafael Espindolac398e672017-07-19 22:27:28 +0000850 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000851 DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_TYPES, Lazy);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000852 });
David Blaikie92d9d622014-01-09 05:08:24 +0000853}
854
Alexey Samsonov45be7932012-08-30 07:49:50 +0000855DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000856 parseNormalUnits();
857 return dyn_cast_or_null<DWARFCompileUnit>(
858 NormalUnits.getUnitForOffset(Offset));
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000859}
860
Alexey Samsonov45be7932012-08-30 07:49:50 +0000861DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000862 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000863 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000864 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000865 return getCompileUnitForOffset(CUOffset);
866}
867
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000868DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
869 DIEsForAddress Result;
870
871 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
872 if (!CU)
873 return Result;
874
875 Result.CompileUnit = CU;
876 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
877
878 std::vector<DWARFDie> Worklist;
879 Worklist.push_back(Result.FunctionDIE);
880 while (!Worklist.empty()) {
881 DWARFDie DIE = Worklist.back();
882 Worklist.pop_back();
883
884 if (DIE.getTag() == DW_TAG_lexical_block &&
885 DIE.addressRangeContainsAddress(Address)) {
886 Result.BlockDIE = DIE;
887 break;
888 }
889
890 for (auto Child : DIE)
891 Worklist.push_back(Child);
892 }
893
894 return Result;
895}
896
David Blaikieefc4eba2017-02-06 20:19:02 +0000897static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
898 uint64_t Address,
899 FunctionNameKind Kind,
900 std::string &FunctionName,
901 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000902 // The address may correspond to instruction in some inlined function,
903 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000904 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000905 SmallVector<DWARFDie, 4> InlinedChain;
906 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000907 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000908 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000909
910 const DWARFDie &DIE = InlinedChain[0];
911 bool FoundResult = false;
912 const char *Name = nullptr;
913 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000914 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000915 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000916 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000917 if (auto DeclLineResult = DIE.getDeclLine()) {
918 StartLine = DeclLineResult;
919 FoundResult = true;
920 }
921
922 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000923}
924
Alexey Samsonov45be7932012-08-30 07:49:50 +0000925DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000926 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000927 DILineInfo Result;
928
Alexey Samsonov45be7932012-08-30 07:49:50 +0000929 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
930 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000931 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000932 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
933 Result.FunctionName,
934 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000935 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000936 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
937 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
938 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000939 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000940 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000941}
David Blaikiea379b1812011-12-20 02:50:00 +0000942
Alexey Samsonovdce67342014-05-15 21:24:32 +0000943DILineInfoTable
944DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
945 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000946 DILineInfoTable Lines;
947 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
948 if (!CU)
949 return Lines;
950
951 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000952 uint32_t StartLine = 0;
953 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
954 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000955
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000956 // If the Specifier says we don't need FileLineInfo, just
957 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +0000958 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000959 DILineInfo Result;
960 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +0000961 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000962 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000963 return Lines;
964 }
965
Frederic Rissec8a5ba2014-09-04 06:14:40 +0000966 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000967
968 // Get the index of row we're looking for in the line table.
969 std::vector<uint32_t> RowVector;
970 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
971 return Lines;
972
Alexey Samsonov1eabf982014-03-13 07:52:54 +0000973 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000974 // Take file number and line/column from the row.
975 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +0000976 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +0000977 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
978 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +0000979 Result.FunctionName = FunctionName;
980 Result.Line = Row.Line;
981 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +0000982 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000983 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000984 }
985
986 return Lines;
987}
988
Alexey Samsonovdce67342014-05-15 21:24:32 +0000989DIInliningInfo
990DWARFContext::getInliningInfoForAddress(uint64_t Address,
991 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000992 DIInliningInfo InliningInfo;
993
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000994 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
995 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000996 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +0000997
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +0000998 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +0000999 SmallVector<DWARFDie, 4> InlinedChain;
1000 CU->getInlinedChainForAddress(Address, InlinedChain);
1001 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001002 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1003 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +00001004 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001005 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001006 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +00001007 if (LineTable &&
1008 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
1009 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001010 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001011 }
1012 return InliningInfo;
1013 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001014
Dehao Chenef700d52017-04-17 20:10:39 +00001015 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00001016 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1017 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +00001018 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001019 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +00001020 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +00001021 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +00001022 if (auto DeclLineResult = FunctionDIE.getDeclLine())
1023 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +00001024 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001025 if (i == 0) {
1026 // For the topmost frame, initialize the line table of this
1027 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001028 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001029 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +00001030 if (LineTable)
1031 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
1032 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001033 } else {
1034 // Otherwise, use call file, call line and call column from
1035 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +00001036 if (LineTable)
1037 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1038 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +00001039 Frame.Line = CallLine;
1040 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +00001041 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001042 }
1043 // Get call file/line/column of a current DIE.
1044 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +00001045 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1046 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001047 }
1048 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001049 InliningInfo.addFrame(Frame);
1050 }
1051 return InliningInfo;
1052}
1053
David Blaikief9803fb2017-05-23 00:30:42 +00001054std::shared_ptr<DWARFContext>
1055DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +00001056 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +00001057 DWARFContext *Ctxt = S->Context.get();
1058 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1059 }
1060
David Blaikie15d85fc2017-05-23 06:48:53 +00001061 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1062
1063 if (auto S = Entry->lock()) {
1064 DWARFContext *Ctxt = S->Context.get();
1065 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1066 }
1067
David Blaikie15d85fc2017-05-23 06:48:53 +00001068 Expected<OwningBinary<ObjectFile>> Obj = [&] {
1069 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +00001070 SmallString<128> DWPName;
1071 auto Obj = object::ObjectFile::createObjectFile(
1072 this->DWPName.empty()
1073 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1074 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +00001075 if (Obj) {
1076 Entry = &DWP;
1077 return Obj;
1078 } else {
1079 CheckedForDWP = true;
1080 // TODO: Should this error be handled (maybe in a high verbosity mode)
1081 // before falling back to .dwo files?
1082 consumeError(Obj.takeError());
1083 }
1084 }
1085
1086 return object::ObjectFile::createObjectFile(AbsolutePath);
1087 }();
1088
David Blaikief9803fb2017-05-23 00:30:42 +00001089 if (!Obj) {
1090 // TODO: Actually report errors helpfully.
1091 consumeError(Obj.takeError());
1092 return nullptr;
1093 }
David Blaikie15d85fc2017-05-23 06:48:53 +00001094
1095 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +00001096 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +00001097 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +00001098 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +00001099 auto *Ctxt = S->Context.get();
1100 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1101}
1102
George Rimar702dac62017-04-12 08:59:15 +00001103static Error createError(const Twine &Reason, llvm::Error E) {
1104 return make_error<StringError>(Reason + toString(std::move(E)),
1105 inconvertibleErrorCode());
1106}
1107
George Rimara25d3292017-05-27 18:10:23 +00001108/// SymInfo contains information about symbol: it's address
1109/// and section index which is -1LL for absolute symbols.
1110struct SymInfo {
1111 uint64_t Address;
1112 uint64_t SectionIndex;
1113};
1114
1115/// Returns the address of symbol relocation used against and a section index.
1116/// Used for futher relocations computation. Symbol's section load address is
1117static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1118 const RelocationRef &Reloc,
1119 const LoadedObjectInfo *L,
1120 std::map<SymbolRef, SymInfo> &Cache) {
1121 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001122 object::section_iterator RSec = Obj.section_end();
1123 object::symbol_iterator Sym = Reloc.getSymbol();
1124
George Rimara25d3292017-05-27 18:10:23 +00001125 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001126 // First calculate the address of the symbol or section as it appears
1127 // in the object file
1128 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001129 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001130 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001131 if (!New)
1132 return CacheIt->second;
1133
George Rimar702dac62017-04-12 08:59:15 +00001134 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1135 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001136 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001137 SymAddrOrErr.takeError());
1138
1139 // Also remember what section this symbol is in for later
1140 auto SectOrErr = Sym->getSection();
1141 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001142 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001143 SectOrErr.takeError());
1144
1145 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001146 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001147 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1148 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001149 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001150 }
1151
George Rimara25d3292017-05-27 18:10:23 +00001152 if (RSec != Obj.section_end())
1153 Ret.SectionIndex = RSec->getIndex();
1154
George Rimar702dac62017-04-12 08:59:15 +00001155 // If we are given load addresses for the sections, we need to adjust:
1156 // SymAddr = (Address of Symbol Or Section in File) -
1157 // (Address of Section in File) +
1158 // (Load Address of Section)
1159 // RSec is now either the section being targeted or the section
1160 // containing the symbol being targeted. In either case,
1161 // we need to perform the same computation.
1162 if (L && RSec != Obj.section_end())
1163 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001164 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001165
1166 if (CacheIt != Cache.end())
1167 CacheIt->second = Ret;
1168
George Rimar702dac62017-04-12 08:59:15 +00001169 return Ret;
1170}
1171
1172static bool isRelocScattered(const object::ObjectFile &Obj,
1173 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001174 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1175 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001176 return false;
1177 // MachO also has relocations that point to sections and
1178 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001179 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1180 return MachObj->isRelocationScattered(RelocInfo);
1181}
1182
Rafael Espindolac398e672017-07-19 22:27:28 +00001183ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
Jonas Devlieghere84e99262018-04-14 22:07:23 +00001184 WithColor::error() << toString(std::move(E)) << '\n';
George Rimar1af3cb22017-06-28 08:21:19 +00001185 return ErrorPolicy::Continue;
1186}
1187
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001188namespace {
1189struct DWARFSectionMap final : public DWARFSection {
1190 RelocAddrMap Relocs;
1191};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001192
Rafael Espindolac398e672017-07-19 22:27:28 +00001193class DWARFObjInMemory final : public DWARFObject {
1194 bool IsLittleEndian;
1195 uint8_t AddressSize;
1196 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001197 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001198 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001199
Rafael Espindolac398e672017-07-19 22:27:28 +00001200 using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1201 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001202
Rafael Espindolac398e672017-07-19 22:27:28 +00001203 TypeSectionMap TypesSections;
1204 TypeSectionMap TypesDWOSections;
1205
1206 DWARFSectionMap InfoSection;
1207 DWARFSectionMap LocSection;
1208 DWARFSectionMap LineSection;
1209 DWARFSectionMap RangeSection;
James Henderson3fcc7452018-02-02 12:35:52 +00001210 DWARFSectionMap RnglistsSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001211 DWARFSectionMap StringOffsetSection;
1212 DWARFSectionMap InfoDWOSection;
1213 DWARFSectionMap LineDWOSection;
1214 DWARFSectionMap LocDWOSection;
1215 DWARFSectionMap StringOffsetDWOSection;
1216 DWARFSectionMap RangeDWOSection;
Wolfgang Piebad605592018-05-18 20:12:54 +00001217 DWARFSectionMap RnglistsDWOSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001218 DWARFSectionMap AddrSection;
1219 DWARFSectionMap AppleNamesSection;
1220 DWARFSectionMap AppleTypesSection;
1221 DWARFSectionMap AppleNamespacesSection;
1222 DWARFSectionMap AppleObjCSection;
Pavel Labath3c9a9182018-01-29 11:08:32 +00001223 DWARFSectionMap DebugNamesSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001224
1225 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1226 return StringSwitch<DWARFSectionMap *>(Name)
1227 .Case("debug_info", &InfoSection)
1228 .Case("debug_loc", &LocSection)
1229 .Case("debug_line", &LineSection)
1230 .Case("debug_str_offsets", &StringOffsetSection)
1231 .Case("debug_ranges", &RangeSection)
James Henderson3fcc7452018-02-02 12:35:52 +00001232 .Case("debug_rnglists", &RnglistsSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001233 .Case("debug_info.dwo", &InfoDWOSection)
1234 .Case("debug_loc.dwo", &LocDWOSection)
1235 .Case("debug_line.dwo", &LineDWOSection)
Pavel Labath3c9a9182018-01-29 11:08:32 +00001236 .Case("debug_names", &DebugNamesSection)
Wolfgang Piebad605592018-05-18 20:12:54 +00001237 .Case("debug_rnglists.dwo", &RnglistsDWOSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001238 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1239 .Case("debug_addr", &AddrSection)
1240 .Case("apple_names", &AppleNamesSection)
1241 .Case("apple_types", &AppleTypesSection)
1242 .Case("apple_namespaces", &AppleNamespacesSection)
1243 .Case("apple_namespac", &AppleNamespacesSection)
1244 .Case("apple_objc", &AppleObjCSection)
1245 .Default(nullptr);
1246 }
1247
1248 StringRef AbbrevSection;
1249 StringRef ARangeSection;
1250 StringRef DebugFrameSection;
1251 StringRef EHFrameSection;
1252 StringRef StringSection;
1253 StringRef MacinfoSection;
1254 StringRef PubNamesSection;
1255 StringRef PubTypesSection;
1256 StringRef GnuPubNamesSection;
1257 StringRef AbbrevDWOSection;
1258 StringRef StringDWOSection;
1259 StringRef GnuPubTypesSection;
1260 StringRef CUIndexSection;
1261 StringRef GdbIndexSection;
1262 StringRef TUIndexSection;
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001263 StringRef LineStringSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001264
Fangrui Song5bad9d82018-07-23 23:27:45 +00001265 // A deque holding section data whose iterators are not invalidated when
1266 // new decompressed sections are inserted at the end.
1267 std::deque<SmallString<0>> UncompressedSections;
Rafael Espindolac398e672017-07-19 22:27:28 +00001268
1269 StringRef *mapSectionToMember(StringRef Name) {
1270 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1271 return &Sec->Data;
1272 return StringSwitch<StringRef *>(Name)
1273 .Case("debug_abbrev", &AbbrevSection)
1274 .Case("debug_aranges", &ARangeSection)
1275 .Case("debug_frame", &DebugFrameSection)
1276 .Case("eh_frame", &EHFrameSection)
1277 .Case("debug_str", &StringSection)
1278 .Case("debug_macinfo", &MacinfoSection)
1279 .Case("debug_pubnames", &PubNamesSection)
1280 .Case("debug_pubtypes", &PubTypesSection)
1281 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1282 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1283 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1284 .Case("debug_str.dwo", &StringDWOSection)
1285 .Case("debug_cu_index", &CUIndexSection)
1286 .Case("debug_tu_index", &TUIndexSection)
1287 .Case("gdb_index", &GdbIndexSection)
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001288 .Case("debug_line_str", &LineStringSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001289 // Any more debug info sections go here.
1290 .Default(nullptr);
1291 }
1292
1293 /// If Sec is compressed section, decompresses and updates its contents
1294 /// provided by Data. Otherwise leaves it unchanged.
1295 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1296 StringRef &Data) {
1297 if (!Decompressor::isCompressed(Sec))
1298 return Error::success();
1299
1300 Expected<Decompressor> Decompressor =
1301 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1302 if (!Decompressor)
1303 return Decompressor.takeError();
1304
Fangrui Song5bad9d82018-07-23 23:27:45 +00001305 SmallString<0> Out;
Rafael Espindolac398e672017-07-19 22:27:28 +00001306 if (auto Err = Decompressor->resizeAndDecompress(Out))
1307 return Err;
1308
Fangrui Song5bad9d82018-07-23 23:27:45 +00001309 UncompressedSections.push_back(std::move(Out));
Rafael Espindolac398e672017-07-19 22:27:28 +00001310 Data = UncompressedSections.back();
1311
1312 return Error::success();
1313 }
1314
1315public:
1316 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1317 uint8_t AddrSize, bool IsLittleEndian)
1318 : IsLittleEndian(IsLittleEndian) {
1319 for (const auto &SecIt : Sections) {
1320 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1321 *SectionData = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001322 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001323 }
1324 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1325 function_ref<ErrorPolicy(Error)> HandleError)
1326 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001327 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1328 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001329
George Rimare1c30f72017-08-15 15:54:43 +00001330 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001331 for (const SectionRef &Section : Obj.sections()) {
1332 StringRef Name;
1333 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001334 ++SectionAmountMap[Name];
1335 SectionNames.push_back({ Name, true });
1336
Rafael Espindolac398e672017-07-19 22:27:28 +00001337 // Skip BSS and Virtual sections, they aren't interesting.
1338 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001339 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001340
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001341 // Skip sections stripped by dsymutil.
1342 if (Section.isStripped())
1343 continue;
1344
Rafael Espindolac398e672017-07-19 22:27:28 +00001345 StringRef Data;
1346 section_iterator RelocatedSection = Section.getRelocatedSection();
1347 // Try to obtain an already relocated version of this section.
1348 // Else use the unrelocated section from the object file. We'll have to
1349 // apply relocations ourselves later.
1350 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1351 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001352
Rafael Espindolac398e672017-07-19 22:27:28 +00001353 if (auto Err = maybeDecompress(Section, Name, Data)) {
1354 ErrorPolicy EP = HandleError(createError(
1355 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001356 if (EP == ErrorPolicy::Halt)
1357 return;
George Rimarfed9f092017-05-17 12:10:51 +00001358 continue;
1359 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001360
1361 // Compressed sections names in GNU style starts from ".z",
1362 // at this point section is decompressed and we drop compression prefix.
1363 Name = Name.substr(
1364 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1365
1366 // Map platform specific debug section names to DWARF standard section
1367 // names.
1368 Name = Obj.mapDebugSectionName(Name);
1369
1370 if (StringRef *SectionData = mapSectionToMember(Name)) {
1371 *SectionData = Data;
1372 if (Name == "debug_ranges") {
1373 // FIXME: Use the other dwo range section when we emit it.
1374 RangeDWOSection.Data = Data;
1375 }
1376 } else if (Name == "debug_types") {
1377 // Find debug_types data by section rather than name as there are
1378 // multiple, comdat grouped, debug_types sections.
1379 TypesSections[Section].Data = Data;
1380 } else if (Name == "debug_types.dwo") {
1381 TypesDWOSections[Section].Data = Data;
1382 }
1383
1384 if (RelocatedSection == Obj.section_end())
1385 continue;
1386
1387 StringRef RelSecName;
1388 StringRef RelSecData;
1389 RelocatedSection->getName(RelSecName);
1390
1391 // If the section we're relocating was relocated already by the JIT,
1392 // then we used the relocated version above, so we do not need to process
1393 // relocations for it now.
1394 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1395 continue;
1396
1397 // In Mach-o files, the relocations do not need to be applied if
1398 // there is no load offset to apply. The value read at the
1399 // relocation point already factors in the section address
1400 // (actually applying the relocations will produce wrong results
1401 // as the section address will be added twice).
1402 if (!L && isa<MachOObjectFile>(&Obj))
1403 continue;
1404
1405 RelSecName = RelSecName.substr(
1406 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1407
1408 // TODO: Add support for relocations in other sections as needed.
1409 // Record relocations for the debug_info and debug_line sections.
1410 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1411 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1412 if (!Map) {
1413 // Find debug_types relocs by section rather than name as there are
1414 // multiple, comdat grouped, debug_types sections.
1415 if (RelSecName == "debug_types")
1416 Map =
1417 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1418 .Relocs;
1419 else if (RelSecName == "debug_types.dwo")
1420 Map = &static_cast<DWARFSectionMap &>(
1421 TypesDWOSections[*RelocatedSection])
1422 .Relocs;
1423 else
1424 continue;
1425 }
1426
1427 if (Section.relocation_begin() == Section.relocation_end())
1428 continue;
1429
1430 // Symbol to [address, section index] cache mapping.
1431 std::map<SymbolRef, SymInfo> AddrCache;
1432 for (const RelocationRef &Reloc : Section.relocations()) {
1433 // FIXME: it's not clear how to correctly handle scattered
1434 // relocations.
1435 if (isRelocScattered(Obj, Reloc))
1436 continue;
1437
1438 Expected<SymInfo> SymInfoOrErr =
1439 getSymbolInfo(Obj, Reloc, L, AddrCache);
1440 if (!SymInfoOrErr) {
1441 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1442 return;
1443 continue;
1444 }
1445
1446 object::RelocVisitor V(Obj);
1447 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1448 if (V.error()) {
1449 SmallString<32> Type;
1450 Reloc.getTypeName(Type);
1451 ErrorPolicy EP = HandleError(
1452 createError("failed to compute relocation: " + Type + ", ",
1453 errorCodeToError(object_error::parse_failed)));
1454 if (EP == ErrorPolicy::Halt)
1455 return;
1456 continue;
1457 }
1458 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1459 Map->insert({Reloc.getOffset(), Rel});
1460 }
Eric Christopher7370b552012-11-12 21:40:38 +00001461 }
George Rimare1c30f72017-08-15 15:54:43 +00001462
1463 for (SectionName &S : SectionNames)
1464 if (SectionAmountMap[S.Name] > 1)
1465 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001466 }
Eric Christopher7370b552012-11-12 21:40:38 +00001467
Rafael Espindolac398e672017-07-19 22:27:28 +00001468 Optional<RelocAddrEntry> find(const DWARFSection &S,
1469 uint64_t Pos) const override {
1470 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1471 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1472 if (AI == Sec.Relocs.end())
1473 return None;
1474 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001475 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001476
George Rimar6957ab52017-08-15 12:32:54 +00001477 const object::ObjectFile *getFile() const override { return Obj; }
1478
George Rimare1c30f72017-08-15 15:54:43 +00001479 ArrayRef<SectionName> getSectionNames() const override {
1480 return SectionNames;
1481 }
1482
Rafael Espindolac398e672017-07-19 22:27:28 +00001483 bool isLittleEndian() const override { return IsLittleEndian; }
1484 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1485 const DWARFSection &getLineDWOSection() const override {
1486 return LineDWOSection;
1487 }
1488 const DWARFSection &getLocDWOSection() const override {
1489 return LocDWOSection;
1490 }
1491 StringRef getStringDWOSection() const override { return StringDWOSection; }
1492 const DWARFSection &getStringOffsetDWOSection() const override {
1493 return StringOffsetDWOSection;
1494 }
1495 const DWARFSection &getRangeDWOSection() const override {
1496 return RangeDWOSection;
1497 }
Wolfgang Piebad605592018-05-18 20:12:54 +00001498 const DWARFSection &getRnglistsDWOSection() const override {
1499 return RnglistsDWOSection;
1500 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001501 const DWARFSection &getAddrSection() const override { return AddrSection; }
1502 StringRef getCUIndexSection() const override { return CUIndexSection; }
1503 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1504 StringRef getTUIndexSection() const override { return TUIndexSection; }
1505
1506 // DWARF v5
1507 const DWARFSection &getStringOffsetSection() const override {
1508 return StringOffsetSection;
1509 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001510 StringRef getLineStringSection() const override { return LineStringSection; }
Rafael Espindolac398e672017-07-19 22:27:28 +00001511
1512 // Sections for DWARF5 split dwarf proposal.
1513 const DWARFSection &getInfoDWOSection() const override {
1514 return InfoDWOSection;
1515 }
1516 void forEachTypesDWOSections(
1517 function_ref<void(const DWARFSection &)> F) const override {
1518 for (auto &P : TypesDWOSections)
1519 F(P.second);
1520 }
1521
1522 StringRef getAbbrevSection() const override { return AbbrevSection; }
1523 const DWARFSection &getLocSection() const override { return LocSection; }
1524 StringRef getARangeSection() const override { return ARangeSection; }
1525 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1526 StringRef getEHFrameSection() const override { return EHFrameSection; }
1527 const DWARFSection &getLineSection() const override { return LineSection; }
1528 StringRef getStringSection() const override { return StringSection; }
1529 const DWARFSection &getRangeSection() const override { return RangeSection; }
James Henderson3fcc7452018-02-02 12:35:52 +00001530 const DWARFSection &getRnglistsSection() const override {
1531 return RnglistsSection;
1532 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001533 StringRef getMacinfoSection() const override { return MacinfoSection; }
1534 StringRef getPubNamesSection() const override { return PubNamesSection; }
1535 StringRef getPubTypesSection() const override { return PubTypesSection; }
1536 StringRef getGnuPubNamesSection() const override {
1537 return GnuPubNamesSection;
1538 }
1539 StringRef getGnuPubTypesSection() const override {
1540 return GnuPubTypesSection;
1541 }
1542 const DWARFSection &getAppleNamesSection() const override {
1543 return AppleNamesSection;
1544 }
1545 const DWARFSection &getAppleTypesSection() const override {
1546 return AppleTypesSection;
1547 }
1548 const DWARFSection &getAppleNamespacesSection() const override {
1549 return AppleNamespacesSection;
1550 }
1551 const DWARFSection &getAppleObjCSection() const override {
1552 return AppleObjCSection;
1553 }
Pavel Labath3c9a9182018-01-29 11:08:32 +00001554 const DWARFSection &getDebugNamesSection() const override {
1555 return DebugNamesSection;
1556 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001557
1558 StringRef getFileName() const override { return FileName; }
1559 uint8_t getAddressSize() const override { return AddressSize; }
1560 const DWARFSection &getInfoSection() const override { return InfoSection; }
1561 void forEachTypesSections(
1562 function_ref<void(const DWARFSection &)> F) const override {
1563 for (auto &P : TypesSections)
1564 F(P.second);
1565 }
1566};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001567} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001568
1569std::unique_ptr<DWARFContext>
1570DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001571 function_ref<ErrorPolicy(Error)> HandleError,
1572 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001573 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
David Blaikiee5adb682017-07-30 01:34:08 +00001574 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001575}
1576
Rafael Espindolac398e672017-07-19 22:27:28 +00001577std::unique_ptr<DWARFContext>
1578DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1579 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001580 auto DObj =
1581 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001582 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001583}
Reid Klecknera0587362017-08-29 21:41:21 +00001584
Luke Cheeseman77aaa222018-09-26 14:48:03 +00001585Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
Reid Klecknera0587362017-08-29 21:41:21 +00001586 // Detect the architecture from the object file. We usually don't need OS
1587 // info to lookup a target and create register info.
1588 Triple TT;
1589 TT.setArch(Triple::ArchType(Obj.getArch()));
1590 TT.setVendor(Triple::UnknownVendor);
1591 TT.setOS(Triple::UnknownOS);
1592 std::string TargetLookupError;
1593 const Target *TheTarget =
1594 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1595 if (!TargetLookupError.empty())
Victor Leschukcba595d2018-08-20 09:59:08 +00001596 return createStringError(errc::invalid_argument,
1597 TargetLookupError.c_str());
Reid Klecknera0587362017-08-29 21:41:21 +00001598 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1599 return Error::success();
1600}
Victor Leschuk58d33992018-07-31 22:19:19 +00001601
1602uint8_t DWARFContext::getCUAddrSize() {
1603 // In theory, different compile units may have different address byte
1604 // sizes, but for simplicity we just use the address byte size of the
1605 // last compile unit. In practice the address size field is repeated across
1606 // various DWARF headers (at least in version 5) to make it easier to dump
1607 // them independently, not to enable varying the address size.
1608 uint8_t Addr = 0;
1609 for (const auto &CU : compile_units()) {
1610 Addr = CU->getAddressByteSize();
1611 break;
1612 }
1613 return Addr;
1614}
Victor Leschukcf1f7142018-08-23 12:43:33 +00001615
1616void DWARFContext::dumpWarning(Error Warning) {
1617 handleAllErrors(std::move(Warning), [](ErrorInfoBase &Info) {
1618 WithColor::warning() << Info.message() << '\n';
1619 });
1620}