blob: b7bb9c2347a1ea181abc28c379470d8ace7a1d98 [file] [log] [blame]
Eugene Zelenko28db7e62017-03-01 01:14:23 +00001//===- DWARFContext.cpp ---------------------------------------------------===//
Benjamin Krameraa2f78f2011-09-13 19:42:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Benjamin Krameraa2f78f2011-09-13 19:42:23 +00006//
7//===----------------------------------------------------------------------===//
8
Greg Claytonb8c162b2017-05-03 16:02:29 +00009#include "llvm/DebugInfo/DWARF/DWARFContext.h"
10#include "llvm/ADT/STLExtras.h"
Alexey Samsonove16e16a2012-07-19 07:03:58 +000011#include "llvm/ADT/SmallString.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000012#include "llvm/ADT/SmallVector.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000013#include "llvm/ADT/StringRef.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000014#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000015#include "llvm/BinaryFormat/Dwarf.h"
Zachary Turner82af9432015-01-30 18:07:45 +000016#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000017#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000018#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
Victor Leschuk58d33992018-07-31 22:19:19 +000019#include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
Zachary Turner82af9432015-01-30 18:07:45 +000020#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000021#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000022#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
23#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
24#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
25#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
George Rimare71e33f2016-12-17 09:10:32 +000026#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +000027#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
James Henderson3fcc7452018-02-02 12:35:52 +000028#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000029#include "llvm/DebugInfo/DWARF/DWARFDie.h"
30#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
31#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
32#include "llvm/DebugInfo/DWARF/DWARFSection.h"
David Blaikie65a8efe2015-11-11 19:28:21 +000033#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000034#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Reid Klecknera0587362017-08-29 21:41:21 +000035#include "llvm/MC/MCRegisterInfo.h"
George Rimar4bf30832017-01-11 15:26:41 +000036#include "llvm/Object/Decompressor.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000037#include "llvm/Object/MachO.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000038#include "llvm/Object/ObjectFile.h"
Fangrui Song4597dce2019-03-22 02:43:11 +000039#include "llvm/Object/RelocationResolver.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000040#include "llvm/Support/Casting.h"
41#include "llvm/Support/DataExtractor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000042#include "llvm/Support/Error.h"
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +000043#include "llvm/Support/Format.h"
Peter Collingbourne9c8282a2019-06-24 20:03:23 +000044#include "llvm/Support/LEB128.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)
David Blaikiea17564c2019-05-25 00:07:22 +0000105 if (const auto &C = U->getStringOffsetsTableContribution())
106 Contributions.push_back(C);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000107 // Sort the contributions so that any invalid ones are placed at
108 // the start of the contributions vector. This way they are reported
109 // first.
Fangrui Song0cac7262018-09-27 02:13:45 +0000110 llvm::sort(Contributions,
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000111 [](const Optional<StrOffsetsContributionDescriptor> &L,
112 const Optional<StrOffsetsContributionDescriptor> &R) {
Fangrui Song0cac7262018-09-27 02:13:45 +0000113 if (L && R)
114 return L->Base < R->Base;
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000115 return R.hasValue();
116 });
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000117
118 // Uniquify contributions, as it is possible that units (specifically
119 // type units in dwo or dwp files) share contributions. We don't want
120 // to report them more than once.
121 Contributions.erase(
122 std::unique(Contributions.begin(), Contributions.end(),
123 [](const Optional<StrOffsetsContributionDescriptor> &L,
124 const Optional<StrOffsetsContributionDescriptor> &R) {
125 if (L && R)
126 return L->Base == R->Base && L->Size == R->Size;
127 return false;
128 }),
129 Contributions.end());
130 return Contributions;
131}
132
133static void dumpDWARFv5StringOffsetsSection(
134 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
135 const DWARFSection &StringOffsetsSection, StringRef StringSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000136 DWARFContext::unit_iterator_range Units, bool LittleEndian) {
137 auto Contributions = collectContributionData(Units);
Rafael Espindolac398e672017-07-19 22:27:28 +0000138 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000139 DataExtractor StrData(StringSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000140 uint64_t SectionSize = StringOffsetsSection.Data.size();
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000141 uint32_t Offset = 0;
142 for (auto &Contribution : Contributions) {
143 // Report an ill-formed contribution.
144 if (!Contribution) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000145 OS << "error: invalid contribution to string offsets table in section ."
146 << SectionName << ".\n";
147 return;
148 }
149
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000150 dwarf::DwarfFormat Format = Contribution->getFormat();
151 uint16_t Version = Contribution->getVersion();
152 uint64_t ContributionHeader = Contribution->Base;
153 // In DWARF v5 there is a contribution header that immediately precedes
154 // the string offsets base (the location we have previously retrieved from
155 // the CU DIE's DW_AT_str_offsets attribute). The header is located either
156 // 8 or 16 bytes before the base, depending on the contribution's format.
157 if (Version >= 5)
158 ContributionHeader -= Format == DWARF32 ? 8 : 16;
159
160 // Detect overlapping contributions.
161 if (Offset > ContributionHeader) {
David Blaikiea17564c2019-05-25 00:07:22 +0000162 WithColor::error()
163 << "overlapping contributions to string offsets table in section ."
164 << SectionName << ".\n";
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000165 return;
166 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000167 // Report a gap in the table.
168 if (Offset < ContributionHeader) {
169 OS << format("0x%8.8x: Gap, length = ", Offset);
170 OS << (ContributionHeader - Offset) << "\n";
171 }
Wolfgang Piebb4ba1aa2017-12-22 01:12:24 +0000172 OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
Wolfgang Piebf2b6915e2018-05-10 20:02:34 +0000173 // In DWARF v5 the contribution size in the descriptor does not equal
174 // the originally encoded length (it does not contain the length of the
175 // version field and the padding, a total of 4 bytes). Add them back in
176 // for reporting.
177 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000178 << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000179 << ", Version = " << Version << "\n";
180
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000181 Offset = Contribution->Base;
182 unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
183 while (Offset - Contribution->Base < Contribution->Size) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000184 OS << format("0x%8.8x: ", Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000185 // FIXME: We can only extract strings if the offset fits in 32 bits.
Paul Robinson17536b92017-06-29 16:52:08 +0000186 uint64_t StringOffset =
187 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000188 // Extract the string if we can and display it. Otherwise just report
189 // the offset.
190 if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000191 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000192 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000193 const char *S = StrData.getCStr(&StringOffset32);
194 if (S)
195 OS << format("\"%s\"", S);
196 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000197 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000198 OS << "\n";
199 }
200 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000201 // Report a gap at the end of the table.
202 if (Offset < SectionSize) {
203 OS << format("0x%8.8x: Gap, length = ", Offset);
204 OS << (SectionSize - Offset) << "\n";
205 }
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000206}
207
208// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
209// string offsets section, where each compile or type unit contributes a
210// number of entries (string offsets), with each contribution preceded by
211// a header containing size and version number. Alternatively, it may be a
212// monolithic series of string offsets, as generated by the pre-DWARF v5
213// implementation of split DWARF.
Paul Robinson7f330942018-08-01 20:46:46 +0000214static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
215 const DWARFObject &Obj,
216 const DWARFSection &StringOffsetsSection,
217 StringRef StringSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000218 DWARFContext::unit_iterator_range Units,
Paul Robinson7f330942018-08-01 20:46:46 +0000219 bool LittleEndian, unsigned MaxVersion) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000220 // If we have at least one (compile or type) unit with DWARF v5 or greater,
221 // we assume that the section is formatted like a DWARF v5 string offsets
222 // section.
223 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000224 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000225 StringSection, Units, LittleEndian);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000226 else {
227 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
228 uint32_t offset = 0;
229 uint64_t size = StringOffsetsSection.Data.size();
230 // Ensure that size is a multiple of the size of an entry.
231 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
232 OS << "error: size of ." << SectionName << " is not a multiple of "
233 << sizeof(uint32_t) << ".\n";
234 size &= -(uint64_t)sizeof(uint32_t);
235 }
236 DataExtractor StrData(StringSection, LittleEndian, 0);
237 while (offset < size) {
238 OS << format("0x%8.8x: ", offset);
239 uint32_t StringOffset = strOffsetExt.getU32(&offset);
240 OS << format("%8.8x ", StringOffset);
241 const char *S = StrData.getCStr(&StringOffset);
242 if (S)
243 OS << format("\"%s\"", S);
244 OS << "\n";
245 }
246 }
247}
248
Victor Leschuk58d33992018-07-31 22:19:19 +0000249// Dump the .debug_addr section.
250static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
251 DIDumpOptions DumpOpts, uint16_t Version,
252 uint8_t AddrSize) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000253 uint32_t Offset = 0;
254 while (AddrData.isValidOffset(Offset)) {
255 DWARFDebugAddrTable AddrTable;
256 uint32_t TableOffset = Offset;
Victor Leschukcf1f7142018-08-23 12:43:33 +0000257 if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
258 DWARFContext::dumpWarning)) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000259 WithColor::error() << toString(std::move(Err)) << '\n';
260 // Keep going after an error, if we can, assuming that the length field
261 // could be read. If it couldn't, stop reading the section.
262 if (!AddrTable.hasValidLength())
263 break;
264 uint64_t Length = AddrTable.getLength();
265 Offset = TableOffset + Length;
266 } else {
267 AddrTable.dump(OS, DumpOpts);
268 }
269 }
270}
271
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000272// Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000273static void dumpRnglistsSection(
274 raw_ostream &OS, DWARFDataExtractor &rnglistData,
275 llvm::function_ref<Optional<object::SectionedAddress>(uint32_t)>
276 LookupPooledAddress,
277 DIDumpOptions DumpOpts) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000278 uint32_t Offset = 0;
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000279 while (rnglistData.isValidOffset(Offset)) {
280 llvm::DWARFDebugRnglistTable Rnglists;
281 uint32_t TableOffset = Offset;
282 if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000283 WithColor::error() << toString(std::move(Err)) << '\n';
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000284 uint64_t Length = Rnglists.length();
285 // Keep going after an error, if we can, assuming that the length field
286 // could be read. If it couldn't, stop reading the section.
287 if (Length == 0)
Wolfgang Piebad605592018-05-18 20:12:54 +0000288 break;
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000289 Offset = TableOffset + Length;
Wolfgang Piebad605592018-05-18 20:12:54 +0000290 } else {
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000291 Rnglists.dump(OS, LookupPooledAddress, DumpOpts);
Wolfgang Piebad605592018-05-18 20:12:54 +0000292 }
293 }
294}
295
George Rimar4c7dd9c2018-10-22 11:30:54 +0000296static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
297 DWARFDataExtractor Data,
298 const MCRegisterInfo *MRI,
299 Optional<uint64_t> DumpOffset) {
300 uint32_t Offset = 0;
301 DWARFDebugLoclists Loclists;
302
303 DWARFListTableHeader Header(".debug_loclists", "locations");
304 if (Error E = Header.extract(Data, &Offset)) {
305 WithColor::error() << toString(std::move(E)) << '\n';
306 return;
307 }
308
309 Header.dump(OS, DumpOpts);
310 DataExtractor LocData(Data.getData().drop_front(Offset),
311 Data.isLittleEndian(), Header.getAddrSize());
312
George Rimar581fc632018-10-25 10:56:44 +0000313 Loclists.parse(LocData, Header.getVersion());
George Rimar4c7dd9c2018-10-22 11:30:54 +0000314 Loclists.dump(OS, 0, MRI, DumpOffset);
315}
316
Adrian Prantl057d3362017-09-15 23:04:04 +0000317void DWARFContext::dump(
318 raw_ostream &OS, DIDumpOptions DumpOpts,
319 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
320
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000321 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000322
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000323 StringRef Extension = sys::path::extension(DObj->getFileName());
324 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
325
326 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000327 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000328 if (DumpType & DIDT_UUID)
329 dumpUUID(OS, *ObjFile);
330
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000331 // Print a header for each explicitly-requested section.
332 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000333 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000334 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000335 bool ExplicitDWO = Explicit && IsDWO;
336 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
David Blaikie582a5eb2018-11-12 18:53:28 +0000337 StringRef Section) -> Optional<uint64_t> * {
Adrian Prantl057d3362017-09-15 23:04:04 +0000338 unsigned Mask = 1U << ID;
339 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
David Blaikie582a5eb2018-11-12 18:53:28 +0000340 if (!Should)
341 return nullptr;
342 OS << "\n" << Name << " contents:\n";
343 return &DumpOffsets[ID];
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000344 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000345
346 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000347 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
348 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000349 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000350 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
351 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000352 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000353
Paul Robinson746c22382018-11-07 21:39:09 +0000354 auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
355 OS << '\n' << Name << " contents:\n";
David Blaikie582a5eb2018-11-12 18:53:28 +0000356 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
Paul Robinson746c22382018-11-07 21:39:09 +0000357 for (const auto &U : Units)
358 U->getDIEForOffset(DumpOffset.getValue())
359 .dump(OS, 0, DumpOpts.noImplicitRecursion());
David Blaikiefdada092018-10-05 20:55:20 +0000360 else
361 for (const auto &U : Units)
362 U->dump(OS, DumpOpts);
Adrian Prantl057d3362017-09-15 23:04:04 +0000363 };
Paul Robinson746c22382018-11-07 21:39:09 +0000364 if ((DumpType & DIDT_DebugInfo)) {
365 if (Explicit || getNumCompileUnits())
366 dumpDebugInfo(".debug_info", info_section_units());
367 if (ExplicitDWO || getNumDWOCompileUnits())
368 dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
369 }
David Blaikie622dce42014-01-08 23:29:59 +0000370
Paul Robinson96545db2018-08-02 19:29:38 +0000371 auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
Adrian Prantl099d7e42017-09-16 16:58:18 +0000372 OS << '\n' << Name << " contents:\n";
Paul Robinson96545db2018-08-02 19:29:38 +0000373 for (const auto &U : Units)
David Blaikie582a5eb2018-11-12 18:53:28 +0000374 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
Paul Robinson96545db2018-08-02 19:29:38 +0000375 U->getDIEForOffset(*DumpOffset)
Paul Robinson7f330942018-08-01 20:46:46 +0000376 .dump(OS, 0, DumpOpts.noImplicitRecursion());
377 else
Paul Robinson96545db2018-08-02 19:29:38 +0000378 U->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000379 };
380 if ((DumpType & DIDT_DebugTypes)) {
381 if (Explicit || getNumTypeUnits())
Paul Robinson2c25f342018-08-01 20:54:11 +0000382 dumpDebugType(".debug_types", types_section_units());
Adrian Prantl099d7e42017-09-16 16:58:18 +0000383 if (ExplicitDWO || getNumDWOTypeUnits())
Paul Robinson2c25f342018-08-01 20:54:11 +0000384 dumpDebugType(".debug_types.dwo", dwo_types_section_units());
David Blaikie03c089c2013-09-23 22:44:47 +0000385 }
386
David Blaikie582a5eb2018-11-12 18:53:28 +0000387 if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
388 DObj->getLocSection().Data)) {
389 getDebugLoc()->dump(OS, getRegisterInfo(), *Off);
David Blaikie18e73502013-06-19 21:37:13 +0000390 }
David Blaikie582a5eb2018-11-12 18:53:28 +0000391 if (const auto *Off =
392 shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
393 DObj->getLoclistsSection().Data)) {
George Rimar4c7dd9c2018-10-22 11:30:54 +0000394 DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
395 0);
David Blaikie582a5eb2018-11-12 18:53:28 +0000396 dumpLoclistsSection(OS, DumpOpts, Data, getRegisterInfo(), *Off);
George Rimar4c7dd9c2018-10-22 11:30:54 +0000397 }
David Blaikie582a5eb2018-11-12 18:53:28 +0000398 if (const auto *Off =
399 shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
400 DObj->getLocDWOSection().Data)) {
401 getDebugLocDWO()->dump(OS, 0, getRegisterInfo(), *Off);
David Blaikie9c550ac2014-03-25 01:44:02 +0000402 }
403
David Blaikie582a5eb2018-11-12 18:53:28 +0000404 if (const auto *Off = shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000405 DObj->getDebugFrameSection().Data))
David Blaikie582a5eb2018-11-12 18:53:28 +0000406 getDebugFrame()->dump(OS, getRegisterInfo(), *Off);
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000407
David Blaikie582a5eb2018-11-12 18:53:28 +0000408 if (const auto *Off = shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000409 DObj->getEHFrameSection().Data))
David Blaikie582a5eb2018-11-12 18:53:28 +0000410 getEHFrame()->dump(OS, getRegisterInfo(), *Off);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000411
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000412 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000413 if (Explicit || !getDebugMacro()->empty()) {
414 OS << "\n.debug_macinfo contents:\n";
415 getDebugMacro()->dump(OS);
416 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000417 }
418
Adrian Prantl057d3362017-09-15 23:04:04 +0000419 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000420 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000421 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000422 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000423 DWARFDebugArangeSet set;
424 while (set.extract(arangesData, &offset))
425 set.dump(OS);
426 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000427
James Hendersona3acf992018-05-10 10:51:33 +0000428 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
David Blaikie582a5eb2018-11-12 18:53:28 +0000429 DIDumpOptions DumpOpts,
430 Optional<uint64_t> DumpOffset) {
James Hendersona3acf992018-05-10 10:51:33 +0000431 while (!Parser.done()) {
432 if (DumpOffset && Parser.getOffset() != *DumpOffset) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000433 Parser.skip(dumpWarning);
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000434 continue;
Paul Robinson63811a42017-11-22 15:33:17 +0000435 }
James Hendersona3acf992018-05-10 10:51:33 +0000436 OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n";
Paul Robinson63811a42017-11-22 15:33:17 +0000437 if (DumpOpts.Verbose) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000438 Parser.parseNext(dumpWarning, dumpWarning, &OS);
Paul Robinson63811a42017-11-22 15:33:17 +0000439 } else {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000440 DWARFDebugLine::LineTable LineTable =
441 Parser.parseNext(dumpWarning, dumpWarning);
James Hendersona3acf992018-05-10 10:51:33 +0000442 LineTable.dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000443 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000444 }
James Hendersona3acf992018-05-10 10:51:33 +0000445 };
446
David Blaikie582a5eb2018-11-12 18:53:28 +0000447 if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
448 DObj->getLineSection().Data)) {
James Hendersona3acf992018-05-10 10:51:33 +0000449 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
450 0);
451 DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
Paul Robinson7f330942018-08-01 20:46:46 +0000452 type_units());
David Blaikie582a5eb2018-11-12 18:53:28 +0000453 DumpLineSection(Parser, DumpOpts, *Off);
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000454 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000455
David Blaikie582a5eb2018-11-12 18:53:28 +0000456 if (const auto *Off =
457 shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
458 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000459 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
460 isLittleEndian(), 0);
James Hendersona3acf992018-05-10 10:51:33 +0000461 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
Paul Robinson7f330942018-08-01 20:46:46 +0000462 dwo_type_units());
David Blaikie582a5eb2018-11-12 18:53:28 +0000463 DumpLineSection(Parser, DumpOpts, *Off);
David Blaikie1d4736e2014-02-24 23:58:54 +0000464 }
465
Adrian Prantl057d3362017-09-15 23:04:04 +0000466 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000467 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000468 getCUIndex().dump(OS);
469 }
470
Adrian Prantl057d3362017-09-15 23:04:04 +0000471 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000472 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000473 getTUIndex().dump(OS);
474 }
475
Adrian Prantl057d3362017-09-15 23:04:04 +0000476 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000477 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000478 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000479 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000480 uint32_t strOffset = 0;
481 while (const char *s = strData.getCStr(&offset)) {
482 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
483 strOffset = offset;
484 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000485 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000486 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000487 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000488 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000489 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000490 uint32_t strDWOOffset = 0;
491 while (const char *s = strDWOData.getCStr(&offset)) {
492 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
493 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000494 }
David Blaikie66865d62014-01-09 00:13:35 +0000495 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000496 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
497 DObj->getLineStringSection())) {
498 DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0);
499 uint32_t offset = 0;
500 uint32_t strOffset = 0;
501 while (const char *s = strData.getCStr(&offset)) {
Scott Linder16c7bda2018-02-23 23:01:06 +0000502 OS << format("0x%8.8x: \"", strOffset);
503 OS.write_escaped(s);
504 OS << "\"\n";
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000505 strOffset = offset;
506 }
507 }
David Blaikie622dce42014-01-08 23:29:59 +0000508
Victor Leschuk58d33992018-07-31 22:19:19 +0000509 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
510 DObj->getAddrSection().Data)) {
511 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
512 isLittleEndian(), 0);
513 dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
514 }
515
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000516 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
517 DObj->getRangeSection().Data)) {
518 uint8_t savedAddressByteSize = getCUAddrSize();
519 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
520 isLittleEndian(), savedAddressByteSize);
521 uint32_t offset = 0;
522 DWARFDebugRangeList rangeList;
523 while (rangesData.isValidOffset(offset)) {
524 if (Error E = rangeList.extract(rangesData, &offset)) {
525 WithColor::error() << toString(std::move(E)) << '\n';
526 break;
527 }
528 rangeList.dump(OS);
529 }
530 }
531
David Blaikie59ac2062018-10-20 06:16:25 +0000532 auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
533 const auto &CUs = compile_units();
534 auto I = CUs.begin();
535 if (I == CUs.end())
536 return None;
537 return (*I)->getAddrOffsetSectionItem(Index);
538 };
539
James Henderson3fcc7452018-02-02 12:35:52 +0000540 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
541 DObj->getRnglistsSection().Data)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000542 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000543 isLittleEndian(), 0);
544 dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
Wolfgang Piebad605592018-05-18 20:12:54 +0000545 }
546
547 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
548 DObj->getRnglistsDWOSection().Data)) {
549 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000550 isLittleEndian(), 0);
551 dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
James Henderson3fcc7452018-02-02 12:35:52 +0000552 }
553
Adrian Prantl057d3362017-09-15 23:04:04 +0000554 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Fangrui Song158b2622018-11-11 18:57:28 +0000555 DObj->getPubNamesSection().Data))
556 DWARFDebugPubTable(*DObj, DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000557 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000558
Adrian Prantl057d3362017-09-15 23:04:04 +0000559 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Fangrui Song158b2622018-11-11 18:57:28 +0000560 DObj->getPubTypesSection().Data))
561 DWARFDebugPubTable(*DObj, DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000562 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000563
Adrian Prantl057d3362017-09-15 23:04:04 +0000564 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Fangrui Song158b2622018-11-11 18:57:28 +0000565 DObj->getGnuPubNamesSection().Data))
566 DWARFDebugPubTable(*DObj, DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000567 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000568 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000569
Adrian Prantl057d3362017-09-15 23:04:04 +0000570 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Fangrui Song158b2622018-11-11 18:57:28 +0000571 DObj->getGnuPubTypesSection().Data))
572 DWARFDebugPubTable(*DObj, DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000573 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000574 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000575
Adrian Prantl057d3362017-09-15 23:04:04 +0000576 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000577 DObj->getStringOffsetSection().Data))
Paul Robinson7f330942018-08-01 20:46:46 +0000578 dumpStringOffsetsSection(OS, "debug_str_offsets", *DObj,
579 DObj->getStringOffsetSection(),
Paul Robinson96545db2018-08-02 19:29:38 +0000580 DObj->getStringSection(), normal_units(),
581 isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000582 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000583 DObj->getStringOffsetDWOSection().Data))
Paul Robinson96545db2018-08-02 19:29:38 +0000584 dumpStringOffsetsSection(OS, "debug_str_offsets.dwo", *DObj,
585 DObj->getStringOffsetDWOSection(),
586 DObj->getStringDWOSection(), dwo_units(),
David Blaikiefdada092018-10-05 20:55:20 +0000587 isLittleEndian(), getMaxDWOVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000588
Fangrui Song999570a2018-11-02 20:34:40 +0000589 if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000590 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000591 getGdbIndex().dump(OS);
592 }
593
Adrian Prantl057d3362017-09-15 23:04:04 +0000594 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000595 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000596 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000597
Adrian Prantl057d3362017-09-15 23:04:04 +0000598 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000599 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000600 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000601
Adrian Prantl057d3362017-09-15 23:04:04 +0000602 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000603 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000604 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000605
Adrian Prantl057d3362017-09-15 23:04:04 +0000606 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000607 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000608 getAppleObjC().dump(OS);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000609 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
610 DObj->getDebugNamesSection().Data))
611 getDebugNames().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000612}
613
David Blaikie15d85fc2017-05-23 06:48:53 +0000614DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000615 parseDWOUnits(LazyParse);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000616
David Blaikieebac0b92017-07-30 08:12:07 +0000617 if (const auto &CUI = getCUIndex()) {
618 if (const auto *R = CUI.getFromHash(Hash))
Paul Robinson2c25f342018-08-01 20:54:11 +0000619 return dyn_cast_or_null<DWARFCompileUnit>(
620 DWOUnits.getUnitForIndexEntry(*R));
David Blaikieebac0b92017-07-30 08:12:07 +0000621 return nullptr;
622 }
623
624 // If there's no index, just search through the CUs in the DWO - there's
625 // probably only one unless this is something like LTO - though an in-process
626 // built/cached lookup table could be used in that case to improve repeated
627 // lookups of different CUs in the DWO.
Paul Robinson543c0e12018-05-22 17:27:31 +0000628 for (const auto &DWOCU : dwo_compile_units()) {
629 // Might not have parsed DWO ID yet.
630 if (!DWOCU->getDWOId()) {
631 if (Optional<uint64_t> DWOId =
632 toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
633 DWOCU->setDWOId(*DWOId);
634 else
635 // No DWO ID?
636 continue;
637 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000638 if (DWOCU->getDWOId() == Hash)
Paul Robinson143eaea2018-08-01 20:43:47 +0000639 return dyn_cast<DWARFCompileUnit>(DWOCU.get());
Paul Robinson543c0e12018-05-22 17:27:31 +0000640 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000641 return nullptr;
642}
643
Greg Claytonc7695a82017-05-02 20:28:33 +0000644DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000645 parseNormalUnits();
646 if (auto *CU = NormalUnits.getUnitForOffset(Offset))
Greg Claytonc7695a82017-05-02 20:28:33 +0000647 return CU->getDIEForOffset(Offset);
648 return DWARFDie();
649}
650
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000651bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000652 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000653 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000654
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000655 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000656 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000657 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000658 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000659 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000660 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000661 return Success;
662}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000663
David Blaikie82641be2015-11-17 00:39:55 +0000664const DWARFUnitIndex &DWARFContext::getCUIndex() {
665 if (CUIndex)
666 return *CUIndex;
667
Rafael Espindolac398e672017-07-19 22:27:28 +0000668 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000669
David Blaikieb073cb92015-12-02 06:21:34 +0000670 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000671 CUIndex->parse(CUIndexData);
672 return *CUIndex;
673}
674
675const DWARFUnitIndex &DWARFContext::getTUIndex() {
676 if (TUIndex)
677 return *TUIndex;
678
Rafael Espindolac398e672017-07-19 22:27:28 +0000679 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000680
David Blaikieb073cb92015-12-02 06:21:34 +0000681 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000682 TUIndex->parse(TUIndexData);
683 return *TUIndex;
684}
685
George Rimar4f82df52016-09-23 11:01:53 +0000686DWARFGdbIndex &DWARFContext::getGdbIndex() {
687 if (GdbIndex)
688 return *GdbIndex;
689
Rafael Espindolac398e672017-07-19 22:27:28 +0000690 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000691 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
692 GdbIndex->parse(GdbIndexData);
693 return *GdbIndex;
694}
695
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000696const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
697 if (Abbrev)
698 return Abbrev.get();
699
Rafael Espindolac398e672017-07-19 22:27:28 +0000700 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000701
702 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000703 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000704 return Abbrev.get();
705}
706
Eric Christopherda4b2192013-01-02 23:52:13 +0000707const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
708 if (AbbrevDWO)
709 return AbbrevDWO.get();
710
Rafael Espindolac398e672017-07-19 22:27:28 +0000711 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000712 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000713 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000714 return AbbrevDWO.get();
715}
716
David Blaikie18e73502013-06-19 21:37:13 +0000717const DWARFDebugLoc *DWARFContext::getDebugLoc() {
718 if (Loc)
719 return Loc.get();
720
Paul Robinson17536b92017-06-29 16:52:08 +0000721 Loc.reset(new DWARFDebugLoc);
Paul Robinson143eaea2018-08-01 20:43:47 +0000722 // Assume all units have the same address byte size.
Paul Robinson17536b92017-06-29 16:52:08 +0000723 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000724 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson143eaea2018-08-01 20:43:47 +0000725 getUnitAtIndex(0)->getAddressByteSize());
Paul Robinson17536b92017-06-29 16:52:08 +0000726 Loc->parse(LocData);
727 }
David Blaikie18e73502013-06-19 21:37:13 +0000728 return Loc.get();
729}
730
George Rimar4c7dd9c2018-10-22 11:30:54 +0000731const DWARFDebugLoclists *DWARFContext::getDebugLocDWO() {
David Blaikie9c550ac2014-03-25 01:44:02 +0000732 if (LocDWO)
733 return LocDWO.get();
734
George Rimar4c7dd9c2018-10-22 11:30:54 +0000735 LocDWO.reset(new DWARFDebugLoclists());
Pavel Labath54ca2d62018-04-06 08:49:57 +0000736 // Assume all compile units have the same address byte size.
Wolfgang Pieba9ea9c52018-10-09 18:38:55 +0000737 // FIXME: We don't need AddressSize for split DWARF since relocatable
738 // addresses cannot appear there. At the moment DWARFExpression requires it.
739 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 4);
George Rimar581fc632018-10-25 10:56:44 +0000740 // Use version 4. DWO does not support the DWARF v5 .debug_loclists yet and
741 // that means we are parsing the new style .debug_loc (pre-standatized version
742 // of the .debug_loclists).
743 LocDWO->parse(LocData, 4 /* Version */);
David Blaikie9c550ac2014-03-25 01:44:02 +0000744 return LocDWO.get();
745}
746
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000747const DWARFDebugAranges *DWARFContext::getDebugAranges() {
748 if (Aranges)
749 return Aranges.get();
750
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000751 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000752 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000753 return Aranges.get();
754}
755
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000756const DWARFDebugFrame *DWARFContext::getDebugFrame() {
757 if (DebugFrame)
758 return DebugFrame.get();
759
760 // There's a "bug" in the DWARFv3 standard with respect to the target address
761 // size within debug frame sections. While DWARF is supposed to be independent
762 // of its container, FDEs have fields with size being "target address size",
763 // which isn't specified in DWARF in general. It's only specified for CUs, but
764 // .eh_frame can appear without a .debug_info section. Follow the example of
765 // other tools (libdwarf) and extract this from the container (ObjectFile
766 // provides this information). This problem is fixed in DWARFv4
767 // See this dwarf-discuss discussion for more details:
768 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000769 DWARFDataExtractor debugFrameData(*DObj, DObj->getDebugFrameSection(),
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000770 isLittleEndian(), DObj->getAddressSize());
Luke Cheesemanf57d7d82018-12-18 10:37:42 +0000771 DebugFrame.reset(new DWARFDebugFrame(getArch(), false /* IsEH */));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000772 DebugFrame->parse(debugFrameData);
773 return DebugFrame.get();
774}
775
776const DWARFDebugFrame *DWARFContext::getEHFrame() {
777 if (EHFrame)
778 return EHFrame.get();
779
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +0000780 DWARFDataExtractor debugFrameData(*DObj, DObj->getEHFrameSection(),
781 isLittleEndian(), DObj->getAddressSize());
Luke Cheesemanf57d7d82018-12-18 10:37:42 +0000782 DebugFrame.reset(new DWARFDebugFrame(getArch(), true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000783 DebugFrame->parse(debugFrameData);
784 return DebugFrame.get();
785}
786
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000787const DWARFDebugMacro *DWARFContext::getDebugMacro() {
788 if (Macro)
789 return Macro.get();
790
Rafael Espindolac398e672017-07-19 22:27:28 +0000791 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000792 Macro.reset(new DWARFDebugMacro());
793 Macro->parse(MacinfoData);
794 return Macro.get();
795}
796
Pavel Labath3c9a9182018-01-29 11:08:32 +0000797template <typename T>
798static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
799 const DWARFSection &Section, StringRef StringSection,
800 bool IsLittleEndian) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000801 if (Cache)
802 return *Cache;
803 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
804 DataExtractor StrData(StringSection, IsLittleEndian, 0);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000805 Cache.reset(new T(AccelSection, StrData));
Jonas Devlieghereba915892017-12-11 18:22:47 +0000806 if (Error E = Cache->extract())
807 llvm::consumeError(std::move(E));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000808 return *Cache;
809}
810
Pavel Labath3c9a9182018-01-29 11:08:32 +0000811const DWARFDebugNames &DWARFContext::getDebugNames() {
812 return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(),
813 DObj->getStringSection(), isLittleEndian());
814}
815
Pavel Labath9b36fd22018-01-22 13:17:23 +0000816const AppleAcceleratorTable &DWARFContext::getAppleNames() {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000817 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
818 DObj->getStringSection(), isLittleEndian());
819}
820
Pavel Labath9b36fd22018-01-22 13:17:23 +0000821const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000822 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
823 DObj->getStringSection(), isLittleEndian());
824}
825
Pavel Labath9b36fd22018-01-22 13:17:23 +0000826const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000827 return getAccelTable(AppleNamespaces, *DObj,
828 DObj->getAppleNamespacesSection(),
829 DObj->getStringSection(), isLittleEndian());
830}
831
Pavel Labath9b36fd22018-01-22 13:17:23 +0000832const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000833 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
834 DObj->getStringSection(), isLittleEndian());
835}
836
James Hendersona3acf992018-05-10 10:51:33 +0000837const DWARFDebugLine::LineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000838DWARFContext::getLineTableForUnit(DWARFUnit *U) {
James Hendersona3acf992018-05-10 10:51:33 +0000839 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
Victor Leschukcf1f7142018-08-23 12:43:33 +0000840 getLineTableForUnit(U, dumpWarning);
James Hendersona3acf992018-05-10 10:51:33 +0000841 if (!ExpectedLineTable) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000842 dumpWarning(ExpectedLineTable.takeError());
James Hendersona3acf992018-05-10 10:51:33 +0000843 return nullptr;
844 }
845 return *ExpectedLineTable;
846}
847
James Henderson004b7292018-05-21 15:30:54 +0000848Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
849 DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000850 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000851 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000852
Greg Claytonc8c10322016-12-13 18:25:19 +0000853 auto UnitDIE = U->getUnitDIE();
854 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000855 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000856
Greg Clayton97d22182017-01-13 21:08:18 +0000857 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000858 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000859 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000860
Greg Clayton52fe1f62016-12-14 22:38:08 +0000861 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000862 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000863 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000864 return lt;
865
Greg Clayton48ff66a2017-05-04 18:29:44 +0000866 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000867 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000868 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000869
Benjamin Kramer679e1752011-09-15 20:43:18 +0000870 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000871 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000872 U->getAddressByteSize());
James Hendersona3acf992018-05-10 10:51:33 +0000873 return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
James Henderson004b7292018-05-21 15:30:54 +0000874 RecoverableErrorCallback);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000875}
876
Paul Robinson2c25f342018-08-01 20:54:11 +0000877void DWARFContext::parseNormalUnits() {
878 if (!NormalUnits.empty())
Paul Robinson7f330942018-08-01 20:46:46 +0000879 return;
Paul Robinson746c22382018-11-07 21:39:09 +0000880 DObj->forEachInfoSections([&](const DWARFSection &S) {
881 NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
882 });
Paul Robinson2c25f342018-08-01 20:54:11 +0000883 NormalUnits.finishedInfoUnits();
Rafael Espindolac398e672017-07-19 22:27:28 +0000884 DObj->forEachTypesSections([&](const DWARFSection &S) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000885 NormalUnits.addUnitsForSection(*this, S, DW_SECT_TYPES);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000886 });
David Blaikie03c089c2013-09-23 22:44:47 +0000887}
888
Paul Robinson2c25f342018-08-01 20:54:11 +0000889void DWARFContext::parseDWOUnits(bool Lazy) {
890 if (!DWOUnits.empty())
Paul Robinson7f330942018-08-01 20:46:46 +0000891 return;
Paul Robinson746c22382018-11-07 21:39:09 +0000892 DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
893 DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
894 });
Paul Robinson2c25f342018-08-01 20:54:11 +0000895 DWOUnits.finishedInfoUnits();
Rafael Espindolac398e672017-07-19 22:27:28 +0000896 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000897 DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_TYPES, Lazy);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000898 });
David Blaikie92d9d622014-01-09 05:08:24 +0000899}
900
Alexey Samsonov45be7932012-08-30 07:49:50 +0000901DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000902 parseNormalUnits();
903 return dyn_cast_or_null<DWARFCompileUnit>(
904 NormalUnits.getUnitForOffset(Offset));
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000905}
906
Alexey Samsonov45be7932012-08-30 07:49:50 +0000907DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000908 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000909 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000910 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000911 return getCompileUnitForOffset(CUOffset);
912}
913
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000914DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
915 DIEsForAddress Result;
916
917 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
918 if (!CU)
919 return Result;
920
921 Result.CompileUnit = CU;
922 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
923
924 std::vector<DWARFDie> Worklist;
925 Worklist.push_back(Result.FunctionDIE);
926 while (!Worklist.empty()) {
927 DWARFDie DIE = Worklist.back();
928 Worklist.pop_back();
929
Paul Semel0c27bc22019-04-03 17:13:45 +0000930 if (!DIE.isValid())
931 continue;
932
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000933 if (DIE.getTag() == DW_TAG_lexical_block &&
934 DIE.addressRangeContainsAddress(Address)) {
935 Result.BlockDIE = DIE;
936 break;
937 }
938
939 for (auto Child : DIE)
940 Worklist.push_back(Child);
941 }
942
943 return Result;
944}
945
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000946/// TODO: change input parameter from "uint64_t Address"
947/// into "SectionedAddress Address"
David Blaikieefc4eba2017-02-06 20:19:02 +0000948static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
949 uint64_t Address,
950 FunctionNameKind Kind,
951 std::string &FunctionName,
952 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000953 // The address may correspond to instruction in some inlined function,
954 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000955 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000956 SmallVector<DWARFDie, 4> InlinedChain;
957 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000958 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000959 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000960
961 const DWARFDie &DIE = InlinedChain[0];
962 bool FoundResult = false;
963 const char *Name = nullptr;
964 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000965 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000966 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000967 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000968 if (auto DeclLineResult = DIE.getDeclLine()) {
969 StartLine = DeclLineResult;
970 FoundResult = true;
971 }
972
973 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000974}
975
Peter Collingbourne9c8282a2019-06-24 20:03:23 +0000976static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
977 if (auto SizeAttr = Type.find(DW_AT_byte_size))
978 if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
979 return Size;
980
981 switch (Type.getTag()) {
982 case DW_TAG_pointer_type:
983 case DW_TAG_reference_type:
984 case DW_TAG_rvalue_reference_type:
985 return PointerSize;
986 case DW_TAG_ptr_to_member_type: {
987 if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
988 if (BaseType.getTag() == DW_TAG_subroutine_type)
989 return 2 * PointerSize;
990 return PointerSize;
991 }
992 case DW_TAG_const_type:
993 case DW_TAG_volatile_type:
994 case DW_TAG_restrict_type:
995 case DW_TAG_typedef: {
996 if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
997 return getTypeSize(BaseType, PointerSize);
998 break;
999 }
1000 case DW_TAG_array_type: {
1001 DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type);
1002 if (!BaseType)
1003 return Optional<uint64_t>();
1004 Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
1005 if (!BaseSize)
1006 return Optional<uint64_t>();
1007 uint64_t Size = *BaseSize;
1008 for (DWARFDie Child : Type) {
1009 if (Child.getTag() != DW_TAG_subrange_type)
1010 continue;
1011
1012 if (auto ElemCountAttr = Child.find(DW_AT_count))
1013 if (Optional<uint64_t> ElemCount =
1014 ElemCountAttr->getAsUnsignedConstant())
1015 Size *= *ElemCount;
1016 if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
1017 if (Optional<int64_t> UpperBound =
1018 UpperBoundAttr->getAsSignedConstant()) {
1019 int64_t LowerBound = 0;
1020 if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
1021 LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
1022 Size *= *UpperBound - LowerBound + 1;
1023 }
1024 }
1025 return Size;
1026 }
1027 default:
1028 break;
1029 }
1030 return Optional<uint64_t>();
1031}
1032
1033void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1034 DWARFDie Die, std::vector<DILocal> &Result) {
1035 if (Die.getTag() == DW_TAG_variable ||
1036 Die.getTag() == DW_TAG_formal_parameter) {
1037 DILocal Local;
1038 if (auto NameAttr = Subprogram.find(DW_AT_name))
1039 if (Optional<const char *> Name = NameAttr->getAsCString())
1040 Local.FunctionName = *Name;
1041 if (auto LocationAttr = Die.find(DW_AT_location))
1042 if (Optional<ArrayRef<uint8_t>> Location = LocationAttr->getAsBlock())
1043 if (!Location->empty() && (*Location)[0] == DW_OP_fbreg)
1044 Local.FrameOffset =
1045 decodeSLEB128(Location->data() + 1, nullptr, Location->end());
1046 if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
1047 Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1048
1049 if (auto Origin =
1050 Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1051 Die = Origin;
1052 if (auto NameAttr = Die.find(DW_AT_name))
1053 if (Optional<const char *> Name = NameAttr->getAsCString())
1054 Local.Name = *Name;
1055 if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
1056 Local.Size = getTypeSize(Type, getCUAddrSize());
1057 if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
1058 if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
1059 LT->getFileNameByIndex(
1060 DeclFileAttr->getAsUnsignedConstant().getValue(),
1061 CU->getCompilationDir(),
1062 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1063 Local.DeclFile);
1064 }
1065 if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
1066 Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
1067
1068 Result.push_back(Local);
1069 return;
1070 }
1071
1072 if (Die.getTag() == DW_TAG_inlined_subroutine)
1073 if (auto Origin =
1074 Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1075 Subprogram = Origin;
1076
1077 for (auto Child : Die)
1078 addLocalsForDie(CU, Subprogram, Child, Result);
1079}
1080
1081std::vector<DILocal>
1082DWARFContext::getLocalsForAddress(object::SectionedAddress Address) {
1083 std::vector<DILocal> Result;
1084 DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1085 if (!CU)
1086 return Result;
1087
1088 DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
1089 if (Subprogram.isValid())
1090 addLocalsForDie(CU, Subprogram, Subprogram, Result);
1091 return Result;
1092}
1093
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001094DILineInfo DWARFContext::getLineInfoForAddress(object::SectionedAddress Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +00001095 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +00001096 DILineInfo Result;
1097
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001098 DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
Alexey Samsonov45be7932012-08-30 07:49:50 +00001099 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +00001100 return Result;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001101
1102 getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1103 Result.FunctionName, Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +00001104 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001105 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
1106 LineTable->getFileLineInfoForAddress(
1107 {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1108 Spec.FLIKind, Result);
1109 }
Alexey Samsonovf4462fa2012-07-02 05:54:45 +00001110 }
Alexey Samsonovd0109992014-04-18 21:36:39 +00001111 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +00001112}
David Blaikiea379b1812011-12-20 02:50:00 +00001113
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001114DILineInfoTable DWARFContext::getLineInfoForAddressRange(
1115 object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001116 DILineInfoTable Lines;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001117 DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001118 if (!CU)
1119 return Lines;
1120
1121 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +00001122 uint32_t StartLine = 0;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001123 getFunctionNameAndStartLineForAddress(CU, Address.Address, Spec.FNKind,
1124 FunctionName, StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001125
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001126 // If the Specifier says we don't need FileLineInfo, just
1127 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +00001128 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +00001129 DILineInfo Result;
1130 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +00001131 Result.StartLine = StartLine;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001132 Lines.push_back(std::make_pair(Address.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001133 return Lines;
1134 }
1135
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001136 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001137
1138 // Get the index of row we're looking for in the line table.
1139 std::vector<uint32_t> RowVector;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001140 if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
1141 Size, RowVector)) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001142 return Lines;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001143 }
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001144
Alexey Samsonov1eabf982014-03-13 07:52:54 +00001145 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001146 // Take file number and line/column from the row.
1147 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +00001148 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +00001149 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1150 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +00001151 Result.FunctionName = FunctionName;
1152 Result.Line = Row.Line;
1153 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +00001154 Result.StartLine = StartLine;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001155 Lines.push_back(std::make_pair(Row.Address.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001156 }
1157
1158 return Lines;
1159}
1160
Alexey Samsonovdce67342014-05-15 21:24:32 +00001161DIInliningInfo
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001162DWARFContext::getInliningInfoForAddress(object::SectionedAddress Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +00001163 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001164 DIInliningInfo InliningInfo;
1165
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001166 DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001167 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001168 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001169
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001170 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +00001171 SmallVector<DWARFDie, 4> InlinedChain;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001172 CU->getInlinedChainForAddress(Address.Address, InlinedChain);
Greg Claytonc8c10322016-12-13 18:25:19 +00001173 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001174 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1175 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +00001176 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001177 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001178 LineTable = getLineTableForUnit(CU);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001179 if (LineTable && LineTable->getFileLineInfoForAddress(
1180 {Address.Address, Address.SectionIndex},
1181 CU->getCompilationDir(), Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001182 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001183 }
1184 return InliningInfo;
1185 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001186
Dehao Chenef700d52017-04-17 20:10:39 +00001187 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00001188 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1189 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +00001190 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001191 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +00001192 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +00001193 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +00001194 if (auto DeclLineResult = FunctionDIE.getDeclLine())
1195 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +00001196 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001197 if (i == 0) {
1198 // For the topmost frame, initialize the line table of this
1199 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001200 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001201 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +00001202 if (LineTable)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00001203 LineTable->getFileLineInfoForAddress(
1204 {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1205 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001206 } else {
1207 // Otherwise, use call file, call line and call column from
1208 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +00001209 if (LineTable)
1210 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1211 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +00001212 Frame.Line = CallLine;
1213 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +00001214 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001215 }
1216 // Get call file/line/column of a current DIE.
1217 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +00001218 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1219 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001220 }
1221 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001222 InliningInfo.addFrame(Frame);
1223 }
1224 return InliningInfo;
1225}
1226
David Blaikief9803fb2017-05-23 00:30:42 +00001227std::shared_ptr<DWARFContext>
1228DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +00001229 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +00001230 DWARFContext *Ctxt = S->Context.get();
1231 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1232 }
1233
David Blaikie15d85fc2017-05-23 06:48:53 +00001234 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1235
1236 if (auto S = Entry->lock()) {
1237 DWARFContext *Ctxt = S->Context.get();
1238 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1239 }
1240
David Blaikie15d85fc2017-05-23 06:48:53 +00001241 Expected<OwningBinary<ObjectFile>> Obj = [&] {
1242 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +00001243 SmallString<128> DWPName;
1244 auto Obj = object::ObjectFile::createObjectFile(
1245 this->DWPName.empty()
1246 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1247 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +00001248 if (Obj) {
1249 Entry = &DWP;
1250 return Obj;
1251 } else {
1252 CheckedForDWP = true;
1253 // TODO: Should this error be handled (maybe in a high verbosity mode)
1254 // before falling back to .dwo files?
1255 consumeError(Obj.takeError());
1256 }
1257 }
1258
1259 return object::ObjectFile::createObjectFile(AbsolutePath);
1260 }();
1261
David Blaikief9803fb2017-05-23 00:30:42 +00001262 if (!Obj) {
1263 // TODO: Actually report errors helpfully.
1264 consumeError(Obj.takeError());
1265 return nullptr;
1266 }
David Blaikie15d85fc2017-05-23 06:48:53 +00001267
1268 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +00001269 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +00001270 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +00001271 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +00001272 auto *Ctxt = S->Context.get();
1273 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1274}
1275
George Rimar702dac62017-04-12 08:59:15 +00001276static Error createError(const Twine &Reason, llvm::Error E) {
1277 return make_error<StringError>(Reason + toString(std::move(E)),
1278 inconvertibleErrorCode());
1279}
1280
George Rimara25d3292017-05-27 18:10:23 +00001281/// SymInfo contains information about symbol: it's address
1282/// and section index which is -1LL for absolute symbols.
1283struct SymInfo {
1284 uint64_t Address;
1285 uint64_t SectionIndex;
1286};
1287
1288/// Returns the address of symbol relocation used against and a section index.
1289/// Used for futher relocations computation. Symbol's section load address is
1290static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1291 const RelocationRef &Reloc,
1292 const LoadedObjectInfo *L,
1293 std::map<SymbolRef, SymInfo> &Cache) {
1294 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001295 object::section_iterator RSec = Obj.section_end();
1296 object::symbol_iterator Sym = Reloc.getSymbol();
1297
George Rimara25d3292017-05-27 18:10:23 +00001298 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001299 // First calculate the address of the symbol or section as it appears
1300 // in the object file
1301 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001302 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001303 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001304 if (!New)
1305 return CacheIt->second;
1306
George Rimar702dac62017-04-12 08:59:15 +00001307 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1308 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001309 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001310 SymAddrOrErr.takeError());
1311
1312 // Also remember what section this symbol is in for later
1313 auto SectOrErr = Sym->getSection();
1314 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001315 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001316 SectOrErr.takeError());
1317
1318 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001319 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001320 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1321 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001322 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001323 }
1324
George Rimara25d3292017-05-27 18:10:23 +00001325 if (RSec != Obj.section_end())
1326 Ret.SectionIndex = RSec->getIndex();
1327
George Rimar702dac62017-04-12 08:59:15 +00001328 // If we are given load addresses for the sections, we need to adjust:
1329 // SymAddr = (Address of Symbol Or Section in File) -
1330 // (Address of Section in File) +
1331 // (Load Address of Section)
1332 // RSec is now either the section being targeted or the section
1333 // containing the symbol being targeted. In either case,
1334 // we need to perform the same computation.
1335 if (L && RSec != Obj.section_end())
1336 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001337 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001338
1339 if (CacheIt != Cache.end())
1340 CacheIt->second = Ret;
1341
George Rimar702dac62017-04-12 08:59:15 +00001342 return Ret;
1343}
1344
1345static bool isRelocScattered(const object::ObjectFile &Obj,
1346 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001347 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1348 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001349 return false;
1350 // MachO also has relocations that point to sections and
1351 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001352 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1353 return MachObj->isRelocationScattered(RelocInfo);
1354}
1355
Rafael Espindolac398e672017-07-19 22:27:28 +00001356ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
Jonas Devlieghere84e99262018-04-14 22:07:23 +00001357 WithColor::error() << toString(std::move(E)) << '\n';
George Rimar1af3cb22017-06-28 08:21:19 +00001358 return ErrorPolicy::Continue;
1359}
1360
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001361namespace {
1362struct DWARFSectionMap final : public DWARFSection {
1363 RelocAddrMap Relocs;
1364};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001365
Rafael Espindolac398e672017-07-19 22:27:28 +00001366class DWARFObjInMemory final : public DWARFObject {
1367 bool IsLittleEndian;
1368 uint8_t AddressSize;
1369 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001370 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001371 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001372
Paul Robinson746c22382018-11-07 21:39:09 +00001373 using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
Rafael Espindolac398e672017-07-19 22:27:28 +00001374 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001375
Paul Robinson746c22382018-11-07 21:39:09 +00001376 InfoSectionMap InfoSections;
1377 InfoSectionMap TypesSections;
1378 InfoSectionMap InfoDWOSections;
1379 InfoSectionMap TypesDWOSections;
Rafael Espindolac398e672017-07-19 22:27:28 +00001380
Rafael Espindolac398e672017-07-19 22:27:28 +00001381 DWARFSectionMap LocSection;
George Rimar4c7dd9c2018-10-22 11:30:54 +00001382 DWARFSectionMap LocListsSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001383 DWARFSectionMap LineSection;
1384 DWARFSectionMap RangeSection;
James Henderson3fcc7452018-02-02 12:35:52 +00001385 DWARFSectionMap RnglistsSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001386 DWARFSectionMap StringOffsetSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001387 DWARFSectionMap LineDWOSection;
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +00001388 DWARFSectionMap DebugFrameSection;
1389 DWARFSectionMap EHFrameSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001390 DWARFSectionMap LocDWOSection;
1391 DWARFSectionMap StringOffsetDWOSection;
1392 DWARFSectionMap RangeDWOSection;
Wolfgang Piebad605592018-05-18 20:12:54 +00001393 DWARFSectionMap RnglistsDWOSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001394 DWARFSectionMap AddrSection;
1395 DWARFSectionMap AppleNamesSection;
1396 DWARFSectionMap AppleTypesSection;
1397 DWARFSectionMap AppleNamespacesSection;
1398 DWARFSectionMap AppleObjCSection;
Pavel Labath3c9a9182018-01-29 11:08:32 +00001399 DWARFSectionMap DebugNamesSection;
Fangrui Song158b2622018-11-11 18:57:28 +00001400 DWARFSectionMap PubNamesSection;
1401 DWARFSectionMap PubTypesSection;
1402 DWARFSectionMap GnuPubNamesSection;
1403 DWARFSectionMap GnuPubTypesSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001404
1405 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1406 return StringSwitch<DWARFSectionMap *>(Name)
Rafael Espindolac398e672017-07-19 22:27:28 +00001407 .Case("debug_loc", &LocSection)
George Rimar4c7dd9c2018-10-22 11:30:54 +00001408 .Case("debug_loclists", &LocListsSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001409 .Case("debug_line", &LineSection)
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +00001410 .Case("debug_frame", &DebugFrameSection)
1411 .Case("eh_frame", &EHFrameSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001412 .Case("debug_str_offsets", &StringOffsetSection)
1413 .Case("debug_ranges", &RangeSection)
James Henderson3fcc7452018-02-02 12:35:52 +00001414 .Case("debug_rnglists", &RnglistsSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001415 .Case("debug_loc.dwo", &LocDWOSection)
1416 .Case("debug_line.dwo", &LineDWOSection)
Pavel Labath3c9a9182018-01-29 11:08:32 +00001417 .Case("debug_names", &DebugNamesSection)
Wolfgang Piebad605592018-05-18 20:12:54 +00001418 .Case("debug_rnglists.dwo", &RnglistsDWOSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001419 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1420 .Case("debug_addr", &AddrSection)
1421 .Case("apple_names", &AppleNamesSection)
Fangrui Song158b2622018-11-11 18:57:28 +00001422 .Case("debug_pubnames", &PubNamesSection)
1423 .Case("debug_pubtypes", &PubTypesSection)
1424 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1425 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001426 .Case("apple_types", &AppleTypesSection)
1427 .Case("apple_namespaces", &AppleNamespacesSection)
1428 .Case("apple_namespac", &AppleNamespacesSection)
1429 .Case("apple_objc", &AppleObjCSection)
1430 .Default(nullptr);
1431 }
1432
1433 StringRef AbbrevSection;
1434 StringRef ARangeSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001435 StringRef StringSection;
1436 StringRef MacinfoSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001437 StringRef AbbrevDWOSection;
1438 StringRef StringDWOSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001439 StringRef CUIndexSection;
1440 StringRef GdbIndexSection;
1441 StringRef TUIndexSection;
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001442 StringRef LineStringSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001443
Fangrui Song5bad9d82018-07-23 23:27:45 +00001444 // A deque holding section data whose iterators are not invalidated when
1445 // new decompressed sections are inserted at the end.
1446 std::deque<SmallString<0>> UncompressedSections;
Rafael Espindolac398e672017-07-19 22:27:28 +00001447
1448 StringRef *mapSectionToMember(StringRef Name) {
1449 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1450 return &Sec->Data;
1451 return StringSwitch<StringRef *>(Name)
1452 .Case("debug_abbrev", &AbbrevSection)
1453 .Case("debug_aranges", &ARangeSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001454 .Case("debug_str", &StringSection)
1455 .Case("debug_macinfo", &MacinfoSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001456 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1457 .Case("debug_str.dwo", &StringDWOSection)
1458 .Case("debug_cu_index", &CUIndexSection)
1459 .Case("debug_tu_index", &TUIndexSection)
1460 .Case("gdb_index", &GdbIndexSection)
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001461 .Case("debug_line_str", &LineStringSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001462 // Any more debug info sections go here.
1463 .Default(nullptr);
1464 }
1465
1466 /// If Sec is compressed section, decompresses and updates its contents
1467 /// provided by Data. Otherwise leaves it unchanged.
1468 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1469 StringRef &Data) {
1470 if (!Decompressor::isCompressed(Sec))
1471 return Error::success();
1472
1473 Expected<Decompressor> Decompressor =
1474 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1475 if (!Decompressor)
1476 return Decompressor.takeError();
1477
Fangrui Song5bad9d82018-07-23 23:27:45 +00001478 SmallString<0> Out;
Rafael Espindolac398e672017-07-19 22:27:28 +00001479 if (auto Err = Decompressor->resizeAndDecompress(Out))
1480 return Err;
1481
Fangrui Song5bad9d82018-07-23 23:27:45 +00001482 UncompressedSections.push_back(std::move(Out));
Rafael Espindolac398e672017-07-19 22:27:28 +00001483 Data = UncompressedSections.back();
1484
1485 return Error::success();
1486 }
1487
1488public:
1489 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1490 uint8_t AddrSize, bool IsLittleEndian)
1491 : IsLittleEndian(IsLittleEndian) {
1492 for (const auto &SecIt : Sections) {
1493 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1494 *SectionData = SecIt.second->getBuffer();
Paul Robinson746c22382018-11-07 21:39:09 +00001495 else if (SecIt.first() == "debug_info")
1496 // Find debug_info and debug_types data by section rather than name as
1497 // there are multiple, comdat grouped, of these sections.
1498 InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1499 else if (SecIt.first() == "debug_info.dwo")
1500 InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1501 else if (SecIt.first() == "debug_types")
1502 TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1503 else if (SecIt.first() == "debug_types.dwo")
1504 TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001505 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001506 }
1507 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1508 function_ref<ErrorPolicy(Error)> HandleError)
1509 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001510 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1511 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001512
George Rimare1c30f72017-08-15 15:54:43 +00001513 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001514 for (const SectionRef &Section : Obj.sections()) {
1515 StringRef Name;
1516 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001517 ++SectionAmountMap[Name];
1518 SectionNames.push_back({ Name, true });
1519
Rafael Espindolac398e672017-07-19 22:27:28 +00001520 // Skip BSS and Virtual sections, they aren't interesting.
1521 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001522 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001523
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001524 // Skip sections stripped by dsymutil.
1525 if (Section.isStripped())
1526 continue;
1527
Rafael Espindolac398e672017-07-19 22:27:28 +00001528 StringRef Data;
1529 section_iterator RelocatedSection = Section.getRelocatedSection();
1530 // Try to obtain an already relocated version of this section.
1531 // Else use the unrelocated section from the object file. We'll have to
1532 // apply relocations ourselves later.
Fangrui Songe1833402019-05-16 13:24:04 +00001533 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) {
1534 Expected<StringRef> E = Section.getContents();
1535 if (E)
1536 Data = *E;
1537 else
1538 // maybeDecompress below will error.
1539 consumeError(E.takeError());
1540 }
George Rimarfed9f092017-05-17 12:10:51 +00001541
Rafael Espindolac398e672017-07-19 22:27:28 +00001542 if (auto Err = maybeDecompress(Section, Name, Data)) {
1543 ErrorPolicy EP = HandleError(createError(
1544 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001545 if (EP == ErrorPolicy::Halt)
1546 return;
George Rimarfed9f092017-05-17 12:10:51 +00001547 continue;
1548 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001549
1550 // Compressed sections names in GNU style starts from ".z",
1551 // at this point section is decompressed and we drop compression prefix.
1552 Name = Name.substr(
1553 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1554
1555 // Map platform specific debug section names to DWARF standard section
1556 // names.
1557 Name = Obj.mapDebugSectionName(Name);
1558
1559 if (StringRef *SectionData = mapSectionToMember(Name)) {
1560 *SectionData = Data;
1561 if (Name == "debug_ranges") {
1562 // FIXME: Use the other dwo range section when we emit it.
1563 RangeDWOSection.Data = Data;
1564 }
Paul Robinson746c22382018-11-07 21:39:09 +00001565 } else if (Name == "debug_info") {
1566 // Find debug_info and debug_types data by section rather than name as
1567 // there are multiple, comdat grouped, of these sections.
1568 InfoSections[Section].Data = Data;
1569 } else if (Name == "debug_info.dwo") {
1570 InfoDWOSections[Section].Data = Data;
Rafael Espindolac398e672017-07-19 22:27:28 +00001571 } else if (Name == "debug_types") {
Rafael Espindolac398e672017-07-19 22:27:28 +00001572 TypesSections[Section].Data = Data;
1573 } else if (Name == "debug_types.dwo") {
1574 TypesDWOSections[Section].Data = Data;
1575 }
1576
1577 if (RelocatedSection == Obj.section_end())
1578 continue;
1579
1580 StringRef RelSecName;
1581 StringRef RelSecData;
1582 RelocatedSection->getName(RelSecName);
1583
1584 // If the section we're relocating was relocated already by the JIT,
1585 // then we used the relocated version above, so we do not need to process
1586 // relocations for it now.
1587 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1588 continue;
1589
1590 // In Mach-o files, the relocations do not need to be applied if
1591 // there is no load offset to apply. The value read at the
1592 // relocation point already factors in the section address
1593 // (actually applying the relocations will produce wrong results
1594 // as the section address will be added twice).
1595 if (!L && isa<MachOObjectFile>(&Obj))
1596 continue;
1597
1598 RelSecName = RelSecName.substr(
1599 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1600
1601 // TODO: Add support for relocations in other sections as needed.
1602 // Record relocations for the debug_info and debug_line sections.
1603 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1604 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1605 if (!Map) {
Paul Robinson746c22382018-11-07 21:39:09 +00001606 // Find debug_info and debug_types relocs by section rather than name
1607 // as there are multiple, comdat grouped, of these sections.
1608 if (RelSecName == "debug_info")
1609 Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1610 .Relocs;
1611 else if (RelSecName == "debug_info.dwo")
1612 Map = &static_cast<DWARFSectionMap &>(
1613 InfoDWOSections[*RelocatedSection])
1614 .Relocs;
1615 else if (RelSecName == "debug_types")
Rafael Espindolac398e672017-07-19 22:27:28 +00001616 Map =
1617 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1618 .Relocs;
1619 else if (RelSecName == "debug_types.dwo")
1620 Map = &static_cast<DWARFSectionMap &>(
1621 TypesDWOSections[*RelocatedSection])
1622 .Relocs;
1623 else
1624 continue;
1625 }
1626
1627 if (Section.relocation_begin() == Section.relocation_end())
1628 continue;
1629
1630 // Symbol to [address, section index] cache mapping.
1631 std::map<SymbolRef, SymInfo> AddrCache;
Fangrui Song4597dce2019-03-22 02:43:11 +00001632 bool (*Supports)(uint64_t);
1633 RelocationResolver Resolver;
1634 std::tie(Supports, Resolver) = getRelocationResolver(Obj);
Rafael Espindolac398e672017-07-19 22:27:28 +00001635 for (const RelocationRef &Reloc : Section.relocations()) {
1636 // FIXME: it's not clear how to correctly handle scattered
1637 // relocations.
1638 if (isRelocScattered(Obj, Reloc))
1639 continue;
1640
1641 Expected<SymInfo> SymInfoOrErr =
1642 getSymbolInfo(Obj, Reloc, L, AddrCache);
1643 if (!SymInfoOrErr) {
1644 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1645 return;
1646 continue;
1647 }
1648
Fangrui Song4597dce2019-03-22 02:43:11 +00001649 // Check if Resolver can handle this relocation type early so as not to
1650 // handle invalid cases in DWARFDataExtractor.
1651 //
1652 // TODO Don't store Resolver in every RelocAddrEntry.
1653 if (Supports && Supports(Reloc.getType())) {
Alex Bradbury44deaf72019-07-18 05:22:55 +00001654 auto I = Map->try_emplace(
1655 Reloc.getOffset(),
1656 RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
1657 SymInfoOrErr->Address,
1658 Optional<object::RelocationRef>(), 0, Resolver});
1659 // If we didn't successfully insert that's because we already had a
1660 // relocation for that offset. Store it as a second relocation in the
1661 // same RelocAddrEntry instead.
1662 if (!I.second) {
1663 RelocAddrEntry &entry = I.first->getSecond();
1664 if (entry.Reloc2) {
1665 ErrorPolicy EP = HandleError(createError(
1666 "At most two relocations per offset are supported"));
1667 if (EP == ErrorPolicy::Halt)
1668 return;
1669 }
1670 entry.Reloc2 = Reloc;
1671 entry.SymbolValue2 = SymInfoOrErr->Address;
1672 }
Fangrui Song4597dce2019-03-22 02:43:11 +00001673 } else {
Rafael Espindolac398e672017-07-19 22:27:28 +00001674 SmallString<32> Type;
1675 Reloc.getTypeName(Type);
1676 ErrorPolicy EP = HandleError(
1677 createError("failed to compute relocation: " + Type + ", ",
1678 errorCodeToError(object_error::parse_failed)));
1679 if (EP == ErrorPolicy::Halt)
1680 return;
Rafael Espindolac398e672017-07-19 22:27:28 +00001681 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001682 }
Eric Christopher7370b552012-11-12 21:40:38 +00001683 }
George Rimare1c30f72017-08-15 15:54:43 +00001684
1685 for (SectionName &S : SectionNames)
1686 if (SectionAmountMap[S.Name] > 1)
1687 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001688 }
Eric Christopher7370b552012-11-12 21:40:38 +00001689
Rafael Espindolac398e672017-07-19 22:27:28 +00001690 Optional<RelocAddrEntry> find(const DWARFSection &S,
1691 uint64_t Pos) const override {
1692 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1693 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1694 if (AI == Sec.Relocs.end())
1695 return None;
1696 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001697 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001698
George Rimar6957ab52017-08-15 12:32:54 +00001699 const object::ObjectFile *getFile() const override { return Obj; }
1700
George Rimare1c30f72017-08-15 15:54:43 +00001701 ArrayRef<SectionName> getSectionNames() const override {
1702 return SectionNames;
1703 }
1704
Rafael Espindolac398e672017-07-19 22:27:28 +00001705 bool isLittleEndian() const override { return IsLittleEndian; }
1706 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1707 const DWARFSection &getLineDWOSection() const override {
1708 return LineDWOSection;
1709 }
1710 const DWARFSection &getLocDWOSection() const override {
1711 return LocDWOSection;
1712 }
1713 StringRef getStringDWOSection() const override { return StringDWOSection; }
1714 const DWARFSection &getStringOffsetDWOSection() const override {
1715 return StringOffsetDWOSection;
1716 }
1717 const DWARFSection &getRangeDWOSection() const override {
1718 return RangeDWOSection;
1719 }
Wolfgang Piebad605592018-05-18 20:12:54 +00001720 const DWARFSection &getRnglistsDWOSection() const override {
1721 return RnglistsDWOSection;
1722 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001723 const DWARFSection &getAddrSection() const override { return AddrSection; }
1724 StringRef getCUIndexSection() const override { return CUIndexSection; }
1725 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1726 StringRef getTUIndexSection() const override { return TUIndexSection; }
1727
1728 // DWARF v5
1729 const DWARFSection &getStringOffsetSection() const override {
1730 return StringOffsetSection;
1731 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001732 StringRef getLineStringSection() const override { return LineStringSection; }
Rafael Espindolac398e672017-07-19 22:27:28 +00001733
1734 // Sections for DWARF5 split dwarf proposal.
Paul Robinson746c22382018-11-07 21:39:09 +00001735 void forEachInfoDWOSections(
1736 function_ref<void(const DWARFSection &)> F) const override {
1737 for (auto &P : InfoDWOSections)
1738 F(P.second);
Rafael Espindolac398e672017-07-19 22:27:28 +00001739 }
1740 void forEachTypesDWOSections(
1741 function_ref<void(const DWARFSection &)> F) const override {
1742 for (auto &P : TypesDWOSections)
1743 F(P.second);
1744 }
1745
1746 StringRef getAbbrevSection() const override { return AbbrevSection; }
1747 const DWARFSection &getLocSection() const override { return LocSection; }
George Rimar4c7dd9c2018-10-22 11:30:54 +00001748 const DWARFSection &getLoclistsSection() const override { return LocListsSection; }
Rafael Espindolac398e672017-07-19 22:27:28 +00001749 StringRef getARangeSection() const override { return ARangeSection; }
Hsiangkai Wang18ccfad2019-07-19 02:03:34 +00001750 const DWARFSection &getDebugFrameSection() const override {
1751 return DebugFrameSection;
1752 }
1753 const DWARFSection &getEHFrameSection() const override {
1754 return EHFrameSection;
1755 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001756 const DWARFSection &getLineSection() const override { return LineSection; }
1757 StringRef getStringSection() const override { return StringSection; }
1758 const DWARFSection &getRangeSection() const override { return RangeSection; }
James Henderson3fcc7452018-02-02 12:35:52 +00001759 const DWARFSection &getRnglistsSection() const override {
1760 return RnglistsSection;
1761 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001762 StringRef getMacinfoSection() const override { return MacinfoSection; }
Fangrui Song158b2622018-11-11 18:57:28 +00001763 const DWARFSection &getPubNamesSection() const override { return PubNamesSection; }
1764 const DWARFSection &getPubTypesSection() const override { return PubTypesSection; }
1765 const DWARFSection &getGnuPubNamesSection() const override {
Rafael Espindolac398e672017-07-19 22:27:28 +00001766 return GnuPubNamesSection;
1767 }
Fangrui Song158b2622018-11-11 18:57:28 +00001768 const DWARFSection &getGnuPubTypesSection() const override {
Rafael Espindolac398e672017-07-19 22:27:28 +00001769 return GnuPubTypesSection;
1770 }
1771 const DWARFSection &getAppleNamesSection() const override {
1772 return AppleNamesSection;
1773 }
1774 const DWARFSection &getAppleTypesSection() const override {
1775 return AppleTypesSection;
1776 }
1777 const DWARFSection &getAppleNamespacesSection() const override {
1778 return AppleNamespacesSection;
1779 }
1780 const DWARFSection &getAppleObjCSection() const override {
1781 return AppleObjCSection;
1782 }
Pavel Labath3c9a9182018-01-29 11:08:32 +00001783 const DWARFSection &getDebugNamesSection() const override {
1784 return DebugNamesSection;
1785 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001786
1787 StringRef getFileName() const override { return FileName; }
1788 uint8_t getAddressSize() const override { return AddressSize; }
Paul Robinson746c22382018-11-07 21:39:09 +00001789 void forEachInfoSections(
1790 function_ref<void(const DWARFSection &)> F) const override {
1791 for (auto &P : InfoSections)
1792 F(P.second);
1793 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001794 void forEachTypesSections(
1795 function_ref<void(const DWARFSection &)> F) const override {
1796 for (auto &P : TypesSections)
1797 F(P.second);
1798 }
1799};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001800} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001801
1802std::unique_ptr<DWARFContext>
1803DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001804 function_ref<ErrorPolicy(Error)> HandleError,
1805 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001806 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
Luke Cheeseman6db3a6a2018-11-23 17:13:06 +00001807 return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
Chris Bieneman2e752db2017-01-20 19:03:14 +00001808}
1809
Rafael Espindolac398e672017-07-19 22:27:28 +00001810std::unique_ptr<DWARFContext>
1811DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1812 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001813 auto DObj =
1814 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001815 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001816}
Reid Klecknera0587362017-08-29 21:41:21 +00001817
Luke Cheeseman6db3a6a2018-11-23 17:13:06 +00001818Error DWARFContext::loadRegisterInfo(const object::ObjectFile &Obj) {
Reid Klecknera0587362017-08-29 21:41:21 +00001819 // Detect the architecture from the object file. We usually don't need OS
1820 // info to lookup a target and create register info.
1821 Triple TT;
1822 TT.setArch(Triple::ArchType(Obj.getArch()));
1823 TT.setVendor(Triple::UnknownVendor);
1824 TT.setOS(Triple::UnknownOS);
1825 std::string TargetLookupError;
1826 const Target *TheTarget =
1827 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1828 if (!TargetLookupError.empty())
Victor Leschukcba595d2018-08-20 09:59:08 +00001829 return createStringError(errc::invalid_argument,
1830 TargetLookupError.c_str());
Reid Klecknera0587362017-08-29 21:41:21 +00001831 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1832 return Error::success();
1833}
Victor Leschuk58d33992018-07-31 22:19:19 +00001834
1835uint8_t DWARFContext::getCUAddrSize() {
1836 // In theory, different compile units may have different address byte
1837 // sizes, but for simplicity we just use the address byte size of the
1838 // last compile unit. In practice the address size field is repeated across
1839 // various DWARF headers (at least in version 5) to make it easier to dump
1840 // them independently, not to enable varying the address size.
1841 uint8_t Addr = 0;
1842 for (const auto &CU : compile_units()) {
1843 Addr = CU->getAddressByteSize();
1844 break;
1845 }
1846 return Addr;
1847}
Victor Leschukcf1f7142018-08-23 12:43:33 +00001848
1849void DWARFContext::dumpWarning(Error Warning) {
1850 handleAllErrors(std::move(Warning), [](ErrorInfoBase &Info) {
1851 WithColor::warning() << Info.message() << '\n';
1852 });
1853}