blob: 35c3f59b3f408fd9d8798c1399737a46915245b3 [file] [log] [blame]
Eugene Zelenko28db7e62017-03-01 01:14:23 +00001//===- DWARFContext.cpp ---------------------------------------------------===//
Benjamin Krameraa2f78f2011-09-13 19:42:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Greg Claytonb8c162b2017-05-03 16:02:29 +000010#include "llvm/DebugInfo/DWARF/DWARFContext.h"
11#include "llvm/ADT/STLExtras.h"
Alexey Samsonove16e16a2012-07-19 07:03:58 +000012#include "llvm/ADT/SmallString.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000013#include "llvm/ADT/SmallVector.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000014#include "llvm/ADT/StringRef.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000015#include "llvm/ADT/StringSwitch.h"
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000016#include "llvm/BinaryFormat/Dwarf.h"
Zachary Turner82af9432015-01-30 18:07:45 +000017#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000018#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000019#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
Victor Leschuk58d33992018-07-31 22:19:19 +000020#include "llvm/DebugInfo/DWARF/DWARFDebugAddr.h"
Zachary Turner82af9432015-01-30 18:07:45 +000021#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000022#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000023#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
24#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
25#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
26#include "llvm/DebugInfo/DWARF/DWARFDebugMacro.h"
George Rimare71e33f2016-12-17 09:10:32 +000027#include "llvm/DebugInfo/DWARF/DWARFDebugPubTable.h"
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +000028#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
James Henderson3fcc7452018-02-02 12:35:52 +000029#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000030#include "llvm/DebugInfo/DWARF/DWARFDie.h"
31#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
32#include "llvm/DebugInfo/DWARF/DWARFGdbIndex.h"
33#include "llvm/DebugInfo/DWARF/DWARFSection.h"
David Blaikie65a8efe2015-11-11 19:28:21 +000034#include "llvm/DebugInfo/DWARF/DWARFUnitIndex.h"
Greg Claytonb8c162b2017-05-03 16:02:29 +000035#include "llvm/DebugInfo/DWARF/DWARFVerifier.h"
Reid Klecknera0587362017-08-29 21:41:21 +000036#include "llvm/MC/MCRegisterInfo.h"
George Rimar4bf30832017-01-11 15:26:41 +000037#include "llvm/Object/Decompressor.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000038#include "llvm/Object/MachO.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000039#include "llvm/Object/ObjectFile.h"
Reid Klecknerdafc5d72016-07-06 16:56:42 +000040#include "llvm/Object/RelocVisitor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000041#include "llvm/Support/Casting.h"
42#include "llvm/Support/DataExtractor.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000043#include "llvm/Support/Error.h"
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +000044#include "llvm/Support/Format.h"
Eugene Zelenko28db7e62017-03-01 01:14:23 +000045#include "llvm/Support/MemoryBuffer.h"
Adrian Prantl3ae35eb2017-09-13 22:09:01 +000046#include "llvm/Support/Path.h"
Reid Klecknera0587362017-08-29 21:41:21 +000047#include "llvm/Support/TargetRegistry.h"
Jonas Devlieghere84e99262018-04-14 22:07:23 +000048#include "llvm/Support/WithColor.h"
Benjamin Kramera6002fd2011-09-14 01:09:52 +000049#include "llvm/Support/raw_ostream.h"
Benjamin Kramer2602ca62011-09-15 20:43:22 +000050#include <algorithm>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000051#include <cstdint>
Fangrui Song5bad9d82018-07-23 23:27:45 +000052#include <deque>
Greg Claytonc7695a82017-05-02 20:28:33 +000053#include <map>
Eugene Zelenko28db7e62017-03-01 01:14:23 +000054#include <string>
55#include <utility>
56#include <vector>
57
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000058using namespace llvm;
Benjamin Kramer6dda0322011-09-15 18:02:20 +000059using namespace dwarf;
Rafael Espindola4f60a382013-05-30 03:05:14 +000060using namespace object;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000061
Chandler Carruthe96dd892014-04-21 22:55:11 +000062#define DEBUG_TYPE "dwarf"
63
Eugene Zelenko2db0cfa2017-06-23 21:57:40 +000064using DWARFLineTable = DWARFDebugLine::LineTable;
65using FileLineInfoKind = DILineInfoSpecifier::FileLineInfoKind;
66using FunctionNameKind = DILineInfoSpecifier::FunctionNameKind;
Eric Christopher494109b2012-10-16 23:46:25 +000067
Reid Klecknera0587362017-08-29 21:41:21 +000068DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
69 std::string DWPName)
70 : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
71
72DWARFContext::~DWARFContext() = default;
73
Adrian Prantl3dcd1222017-09-13 18:22:59 +000074/// Dump the UUID load command.
75static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
76 auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
77 if (!MachO)
78 return;
79 for (auto LC : MachO->load_commands()) {
80 raw_ostream::uuid_t UUID;
81 if (LC.C.cmd == MachO::LC_UUID) {
82 if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
83 OS << "error: UUID load command is too short.\n";
84 return;
85 }
86 OS << "UUID: ";
87 memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
88 OS.write_uuid(UUID);
Adrian Prantl146ed402018-01-05 21:44:17 +000089 Triple T = MachO->getArchTriple();
90 OS << " (" << T.getArchName() << ')';
Adrian Prantl3dcd1222017-09-13 18:22:59 +000091 OS << ' ' << MachO->getFileName() << '\n';
92 }
93 }
94}
95
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +000096using ContributionCollection =
97 std::vector<Optional<StrOffsetsContributionDescriptor>>;
98
99// Collect all the contributions to the string offsets table from all units,
100// sort them by their starting offsets and remove duplicates.
101static ContributionCollection
Paul Robinson96545db2018-08-02 19:29:38 +0000102collectContributionData(DWARFContext::unit_iterator_range Units) {
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000103 ContributionCollection Contributions;
Paul Robinson96545db2018-08-02 19:29:38 +0000104 for (const auto &U : Units)
105 Contributions.push_back(U->getStringOffsetsTableContribution());
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000106 // Sort the contributions so that any invalid ones are placed at
107 // the start of the contributions vector. This way they are reported
108 // first.
Fangrui Song0cac7262018-09-27 02:13:45 +0000109 llvm::sort(Contributions,
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000110 [](const Optional<StrOffsetsContributionDescriptor> &L,
111 const Optional<StrOffsetsContributionDescriptor> &R) {
Fangrui Song0cac7262018-09-27 02:13:45 +0000112 if (L && R)
113 return L->Base < R->Base;
Mandeep Singh Grangfe1d28e2018-04-01 16:18:49 +0000114 return R.hasValue();
115 });
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000116
117 // Uniquify contributions, as it is possible that units (specifically
118 // type units in dwo or dwp files) share contributions. We don't want
119 // to report them more than once.
120 Contributions.erase(
121 std::unique(Contributions.begin(), Contributions.end(),
122 [](const Optional<StrOffsetsContributionDescriptor> &L,
123 const Optional<StrOffsetsContributionDescriptor> &R) {
124 if (L && R)
125 return L->Base == R->Base && L->Size == R->Size;
126 return false;
127 }),
128 Contributions.end());
129 return Contributions;
130}
131
132static void dumpDWARFv5StringOffsetsSection(
133 raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
134 const DWARFSection &StringOffsetsSection, StringRef StringSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000135 DWARFContext::unit_iterator_range Units, bool LittleEndian) {
136 auto Contributions = collectContributionData(Units);
Rafael Espindolac398e672017-07-19 22:27:28 +0000137 DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000138 DataExtractor StrData(StringSection, LittleEndian, 0);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000139 uint64_t SectionSize = StringOffsetsSection.Data.size();
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000140 uint32_t Offset = 0;
141 for (auto &Contribution : Contributions) {
142 // Report an ill-formed contribution.
143 if (!Contribution) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000144 OS << "error: invalid contribution to string offsets table in section ."
145 << SectionName << ".\n";
146 return;
147 }
148
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000149 dwarf::DwarfFormat Format = Contribution->getFormat();
150 uint16_t Version = Contribution->getVersion();
151 uint64_t ContributionHeader = Contribution->Base;
152 // In DWARF v5 there is a contribution header that immediately precedes
153 // the string offsets base (the location we have previously retrieved from
154 // the CU DIE's DW_AT_str_offsets attribute). The header is located either
155 // 8 or 16 bytes before the base, depending on the contribution's format.
156 if (Version >= 5)
157 ContributionHeader -= Format == DWARF32 ? 8 : 16;
158
159 // Detect overlapping contributions.
160 if (Offset > ContributionHeader) {
161 OS << "error: overlapping contributions to string offsets table in "
162 "section ."
163 << SectionName << ".\n";
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000164 return;
165 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000166 // Report a gap in the table.
167 if (Offset < ContributionHeader) {
168 OS << format("0x%8.8x: Gap, length = ", Offset);
169 OS << (ContributionHeader - Offset) << "\n";
170 }
Wolfgang Piebb4ba1aa2017-12-22 01:12:24 +0000171 OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
Wolfgang Piebf2b6915e2018-05-10 20:02:34 +0000172 // In DWARF v5 the contribution size in the descriptor does not equal
173 // the originally encoded length (it does not contain the length of the
174 // version field and the padding, a total of 4 bytes). Add them back in
175 // for reporting.
176 OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000177 << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000178 << ", Version = " << Version << "\n";
179
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000180 Offset = Contribution->Base;
181 unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
182 while (Offset - Contribution->Base < Contribution->Size) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000183 OS << format("0x%8.8x: ", Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000184 // FIXME: We can only extract strings if the offset fits in 32 bits.
Paul Robinson17536b92017-06-29 16:52:08 +0000185 uint64_t StringOffset =
186 StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000187 // Extract the string if we can and display it. Otherwise just report
188 // the offset.
189 if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000190 uint32_t StringOffset32 = (uint32_t)StringOffset;
Simon Dardisb1b52c02017-08-07 16:08:11 +0000191 OS << format("%8.8x ", StringOffset32);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000192 const char *S = StrData.getCStr(&StringOffset32);
193 if (S)
194 OS << format("\"%s\"", S);
195 } else
Simon Dardisec4ea992017-08-07 13:30:03 +0000196 OS << format("%16.16" PRIx64 " ", StringOffset);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000197 OS << "\n";
198 }
199 }
Wolfgang Pieb6ecd6a82017-12-21 19:38:13 +0000200 // Report a gap at the end of the table.
201 if (Offset < SectionSize) {
202 OS << format("0x%8.8x: Gap, length = ", Offset);
203 OS << (SectionSize - Offset) << "\n";
204 }
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000205}
206
207// Dump a DWARF string offsets section. This may be a DWARF v5 formatted
208// string offsets section, where each compile or type unit contributes a
209// number of entries (string offsets), with each contribution preceded by
210// a header containing size and version number. Alternatively, it may be a
211// monolithic series of string offsets, as generated by the pre-DWARF v5
212// implementation of split DWARF.
Paul Robinson7f330942018-08-01 20:46:46 +0000213static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName,
214 const DWARFObject &Obj,
215 const DWARFSection &StringOffsetsSection,
216 StringRef StringSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000217 DWARFContext::unit_iterator_range Units,
Paul Robinson7f330942018-08-01 20:46:46 +0000218 bool LittleEndian, unsigned MaxVersion) {
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000219 // If we have at least one (compile or type) unit with DWARF v5 or greater,
220 // we assume that the section is formatted like a DWARF v5 string offsets
221 // section.
222 if (MaxVersion >= 5)
Rafael Espindolac398e672017-07-19 22:27:28 +0000223 dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
Paul Robinson96545db2018-08-02 19:29:38 +0000224 StringSection, Units, LittleEndian);
Wolfgang Pieb77d3e932017-06-06 01:22:34 +0000225 else {
226 DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
227 uint32_t offset = 0;
228 uint64_t size = StringOffsetsSection.Data.size();
229 // Ensure that size is a multiple of the size of an entry.
230 if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
231 OS << "error: size of ." << SectionName << " is not a multiple of "
232 << sizeof(uint32_t) << ".\n";
233 size &= -(uint64_t)sizeof(uint32_t);
234 }
235 DataExtractor StrData(StringSection, LittleEndian, 0);
236 while (offset < size) {
237 OS << format("0x%8.8x: ", offset);
238 uint32_t StringOffset = strOffsetExt.getU32(&offset);
239 OS << format("%8.8x ", StringOffset);
240 const char *S = StrData.getCStr(&StringOffset);
241 if (S)
242 OS << format("\"%s\"", S);
243 OS << "\n";
244 }
245 }
246}
247
Victor Leschuk58d33992018-07-31 22:19:19 +0000248// Dump the .debug_addr section.
249static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
250 DIDumpOptions DumpOpts, uint16_t Version,
251 uint8_t AddrSize) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000252 uint32_t Offset = 0;
253 while (AddrData.isValidOffset(Offset)) {
254 DWARFDebugAddrTable AddrTable;
255 uint32_t TableOffset = Offset;
Victor Leschukcf1f7142018-08-23 12:43:33 +0000256 if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
257 DWARFContext::dumpWarning)) {
Victor Leschuk58d33992018-07-31 22:19:19 +0000258 WithColor::error() << toString(std::move(Err)) << '\n';
259 // Keep going after an error, if we can, assuming that the length field
260 // could be read. If it couldn't, stop reading the section.
261 if (!AddrTable.hasValidLength())
262 break;
263 uint64_t Length = AddrTable.getLength();
264 Offset = TableOffset + Length;
265 } else {
266 AddrTable.dump(OS, DumpOpts);
267 }
268 }
269}
270
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000271// Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
David Blaikie59ac2062018-10-20 06:16:25 +0000272static void
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000273dumpRnglistsSection(raw_ostream &OS, DWARFDataExtractor &rnglistData,
274 llvm::function_ref<Optional<SectionedAddress>(uint32_t)>
275 LookupPooledAddress,
276 DIDumpOptions DumpOpts) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000277 uint32_t Offset = 0;
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000278 while (rnglistData.isValidOffset(Offset)) {
279 llvm::DWARFDebugRnglistTable Rnglists;
280 uint32_t TableOffset = Offset;
281 if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000282 WithColor::error() << toString(std::move(Err)) << '\n';
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000283 uint64_t Length = Rnglists.length();
284 // Keep going after an error, if we can, assuming that the length field
285 // could be read. If it couldn't, stop reading the section.
286 if (Length == 0)
Wolfgang Piebad605592018-05-18 20:12:54 +0000287 break;
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000288 Offset = TableOffset + Length;
Wolfgang Piebad605592018-05-18 20:12:54 +0000289 } else {
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000290 Rnglists.dump(OS, LookupPooledAddress, DumpOpts);
Wolfgang Piebad605592018-05-18 20:12:54 +0000291 }
292 }
293}
294
George Rimar4c7dd9c2018-10-22 11:30:54 +0000295static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts,
296 DWARFDataExtractor Data,
297 const MCRegisterInfo *MRI,
298 Optional<uint64_t> DumpOffset) {
299 uint32_t Offset = 0;
300 DWARFDebugLoclists Loclists;
301
302 DWARFListTableHeader Header(".debug_loclists", "locations");
303 if (Error E = Header.extract(Data, &Offset)) {
304 WithColor::error() << toString(std::move(E)) << '\n';
305 return;
306 }
307
308 Header.dump(OS, DumpOpts);
309 DataExtractor LocData(Data.getData().drop_front(Offset),
310 Data.isLittleEndian(), Header.getAddrSize());
311
George Rimar581fc632018-10-25 10:56:44 +0000312 Loclists.parse(LocData, Header.getVersion());
George Rimar4c7dd9c2018-10-22 11:30:54 +0000313 Loclists.dump(OS, 0, MRI, DumpOffset);
314}
315
Adrian Prantl057d3362017-09-15 23:04:04 +0000316void DWARFContext::dump(
317 raw_ostream &OS, DIDumpOptions DumpOpts,
318 std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
319
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000320 uint64_t DumpType = DumpOpts.DumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +0000321
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000322 StringRef Extension = sys::path::extension(DObj->getFileName());
323 bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
324
325 // Print UUID header.
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000326 const auto *ObjFile = DObj->getFile();
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000327 if (DumpType & DIDT_UUID)
328 dumpUUID(OS, *ObjFile);
329
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000330 // Print a header for each explicitly-requested section.
331 // Otherwise just print one for non-empty sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000332 // Only print empty .dwo section headers when dumping a .dwo file.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000333 bool Explicit = DumpType != DIDT_All && !IsDWO;
Adrian Prantl057d3362017-09-15 23:04:04 +0000334 bool ExplicitDWO = Explicit && IsDWO;
335 auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
David Blaikie582a5eb2018-11-12 18:53:28 +0000336 StringRef Section) -> Optional<uint64_t> * {
Adrian Prantl057d3362017-09-15 23:04:04 +0000337 unsigned Mask = 1U << ID;
338 bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
David Blaikie582a5eb2018-11-12 18:53:28 +0000339 if (!Should)
340 return nullptr;
341 OS << "\n" << Name << " contents:\n";
342 return &DumpOffsets[ID];
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000343 };
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000344
345 // Dump individual sections.
Adrian Prantl057d3362017-09-15 23:04:04 +0000346 if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
347 DObj->getAbbrevSection()))
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000348 getDebugAbbrev()->dump(OS);
Adrian Prantl057d3362017-09-15 23:04:04 +0000349 if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
350 DObj->getAbbrevDWOSection()))
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000351 getDebugAbbrevDWO()->dump(OS);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000352
Paul Robinson746c22382018-11-07 21:39:09 +0000353 auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
354 OS << '\n' << Name << " contents:\n";
David Blaikie582a5eb2018-11-12 18:53:28 +0000355 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
Paul Robinson746c22382018-11-07 21:39:09 +0000356 for (const auto &U : Units)
357 U->getDIEForOffset(DumpOffset.getValue())
358 .dump(OS, 0, DumpOpts.noImplicitRecursion());
David Blaikiefdada092018-10-05 20:55:20 +0000359 else
360 for (const auto &U : Units)
361 U->dump(OS, DumpOpts);
Adrian Prantl057d3362017-09-15 23:04:04 +0000362 };
Paul Robinson746c22382018-11-07 21:39:09 +0000363 if ((DumpType & DIDT_DebugInfo)) {
364 if (Explicit || getNumCompileUnits())
365 dumpDebugInfo(".debug_info", info_section_units());
366 if (ExplicitDWO || getNumDWOCompileUnits())
367 dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
368 }
David Blaikie622dce42014-01-08 23:29:59 +0000369
Paul Robinson96545db2018-08-02 19:29:38 +0000370 auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
Adrian Prantl099d7e42017-09-16 16:58:18 +0000371 OS << '\n' << Name << " contents:\n";
Paul Robinson96545db2018-08-02 19:29:38 +0000372 for (const auto &U : Units)
David Blaikie582a5eb2018-11-12 18:53:28 +0000373 if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
Paul Robinson96545db2018-08-02 19:29:38 +0000374 U->getDIEForOffset(*DumpOffset)
Paul Robinson7f330942018-08-01 20:46:46 +0000375 .dump(OS, 0, DumpOpts.noImplicitRecursion());
376 else
Paul Robinson96545db2018-08-02 19:29:38 +0000377 U->dump(OS, DumpOpts);
Adrian Prantl099d7e42017-09-16 16:58:18 +0000378 };
379 if ((DumpType & DIDT_DebugTypes)) {
380 if (Explicit || getNumTypeUnits())
Paul Robinson2c25f342018-08-01 20:54:11 +0000381 dumpDebugType(".debug_types", types_section_units());
Adrian Prantl099d7e42017-09-16 16:58:18 +0000382 if (ExplicitDWO || getNumDWOTypeUnits())
Paul Robinson2c25f342018-08-01 20:54:11 +0000383 dumpDebugType(".debug_types.dwo", dwo_types_section_units());
David Blaikie03c089c2013-09-23 22:44:47 +0000384 }
385
David Blaikie582a5eb2018-11-12 18:53:28 +0000386 if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
387 DObj->getLocSection().Data)) {
388 getDebugLoc()->dump(OS, getRegisterInfo(), *Off);
David Blaikie18e73502013-06-19 21:37:13 +0000389 }
David Blaikie582a5eb2018-11-12 18:53:28 +0000390 if (const auto *Off =
391 shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
392 DObj->getLoclistsSection().Data)) {
George Rimar4c7dd9c2018-10-22 11:30:54 +0000393 DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
394 0);
David Blaikie582a5eb2018-11-12 18:53:28 +0000395 dumpLoclistsSection(OS, DumpOpts, Data, getRegisterInfo(), *Off);
George Rimar4c7dd9c2018-10-22 11:30:54 +0000396 }
David Blaikie582a5eb2018-11-12 18:53:28 +0000397 if (const auto *Off =
398 shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
399 DObj->getLocDWOSection().Data)) {
400 getDebugLocDWO()->dump(OS, 0, getRegisterInfo(), *Off);
David Blaikie9c550ac2014-03-25 01:44:02 +0000401 }
402
David Blaikie582a5eb2018-11-12 18:53:28 +0000403 if (const auto *Off = shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
404 DObj->getDebugFrameSection()))
405 getDebugFrame()->dump(OS, getRegisterInfo(), *Off);
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000406
David Blaikie582a5eb2018-11-12 18:53:28 +0000407 if (const auto *Off = shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
408 DObj->getEHFrameSection()))
409 getEHFrame()->dump(OS, getRegisterInfo(), *Off);
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000410
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000411 if (DumpType & DIDT_DebugMacro) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000412 if (Explicit || !getDebugMacro()->empty()) {
413 OS << "\n.debug_macinfo contents:\n";
414 getDebugMacro()->dump(OS);
415 }
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000416 }
417
Adrian Prantl057d3362017-09-15 23:04:04 +0000418 if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
Adrian Prantl84168022017-09-15 17:39:50 +0000419 DObj->getARangeSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000420 uint32_t offset = 0;
Rafael Espindolac398e672017-07-19 22:27:28 +0000421 DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000422 DWARFDebugArangeSet set;
423 while (set.extract(arangesData, &offset))
424 set.dump(OS);
425 }
Benjamin Kramer5acab502011-09-15 02:12:05 +0000426
James Hendersona3acf992018-05-10 10:51:33 +0000427 auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
David Blaikie582a5eb2018-11-12 18:53:28 +0000428 DIDumpOptions DumpOpts,
429 Optional<uint64_t> DumpOffset) {
James Hendersona3acf992018-05-10 10:51:33 +0000430 while (!Parser.done()) {
431 if (DumpOffset && Parser.getOffset() != *DumpOffset) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000432 Parser.skip(dumpWarning);
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000433 continue;
Paul Robinson63811a42017-11-22 15:33:17 +0000434 }
James Hendersona3acf992018-05-10 10:51:33 +0000435 OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n";
Paul Robinson63811a42017-11-22 15:33:17 +0000436 if (DumpOpts.Verbose) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000437 Parser.parseNext(dumpWarning, dumpWarning, &OS);
Paul Robinson63811a42017-11-22 15:33:17 +0000438 } else {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000439 DWARFDebugLine::LineTable LineTable =
440 Parser.parseNext(dumpWarning, dumpWarning);
James Hendersona3acf992018-05-10 10:51:33 +0000441 LineTable.dump(OS, DumpOpts);
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000442 }
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000443 }
James Hendersona3acf992018-05-10 10:51:33 +0000444 };
445
David Blaikie582a5eb2018-11-12 18:53:28 +0000446 if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
447 DObj->getLineSection().Data)) {
James Hendersona3acf992018-05-10 10:51:33 +0000448 DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
449 0);
450 DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
Paul Robinson7f330942018-08-01 20:46:46 +0000451 type_units());
David Blaikie582a5eb2018-11-12 18:53:28 +0000452 DumpLineSection(Parser, DumpOpts, *Off);
Benjamin Kramer6dda0322011-09-15 18:02:20 +0000453 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000454
David Blaikie582a5eb2018-11-12 18:53:28 +0000455 if (const auto *Off =
456 shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
457 DObj->getLineDWOSection().Data)) {
Paul Robinson63811a42017-11-22 15:33:17 +0000458 DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
459 isLittleEndian(), 0);
James Hendersona3acf992018-05-10 10:51:33 +0000460 DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
Paul Robinson7f330942018-08-01 20:46:46 +0000461 dwo_type_units());
David Blaikie582a5eb2018-11-12 18:53:28 +0000462 DumpLineSection(Parser, DumpOpts, *Off);
David Blaikie1d4736e2014-02-24 23:58:54 +0000463 }
464
Adrian Prantl057d3362017-09-15 23:04:04 +0000465 if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000466 DObj->getCUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000467 getCUIndex().dump(OS);
468 }
469
Adrian Prantl057d3362017-09-15 23:04:04 +0000470 if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000471 DObj->getTUIndexSection())) {
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000472 getTUIndex().dump(OS);
473 }
474
Adrian Prantl057d3362017-09-15 23:04:04 +0000475 if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000476 DObj->getStringSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000477 DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000478 uint32_t offset = 0;
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000479 uint32_t strOffset = 0;
480 while (const char *s = strData.getCStr(&offset)) {
481 OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
482 strOffset = offset;
483 }
Benjamin Kramer07d4b1c2011-09-15 16:57:13 +0000484 }
Adrian Prantl057d3362017-09-15 23:04:04 +0000485 if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
Adrian Prantl84168022017-09-15 17:39:50 +0000486 DObj->getStringDWOSection())) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000487 DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000488 uint32_t offset = 0;
David Blaikie66865d62014-01-09 00:13:35 +0000489 uint32_t strDWOOffset = 0;
490 while (const char *s = strDWOData.getCStr(&offset)) {
491 OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
492 strDWOOffset = offset;
David Blaikie622dce42014-01-08 23:29:59 +0000493 }
David Blaikie66865d62014-01-09 00:13:35 +0000494 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000495 if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
496 DObj->getLineStringSection())) {
497 DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0);
498 uint32_t offset = 0;
499 uint32_t strOffset = 0;
500 while (const char *s = strData.getCStr(&offset)) {
Scott Linder16c7bda2018-02-23 23:01:06 +0000501 OS << format("0x%8.8x: \"", strOffset);
502 OS.write_escaped(s);
503 OS << "\"\n";
Paul Robinsonb6aa01c2018-01-25 22:02:36 +0000504 strOffset = offset;
505 }
506 }
David Blaikie622dce42014-01-08 23:29:59 +0000507
Victor Leschuk58d33992018-07-31 22:19:19 +0000508 if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
509 DObj->getAddrSection().Data)) {
510 DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
511 isLittleEndian(), 0);
512 dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
513 }
514
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000515 if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
516 DObj->getRangeSection().Data)) {
517 uint8_t savedAddressByteSize = getCUAddrSize();
518 DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
519 isLittleEndian(), savedAddressByteSize);
520 uint32_t offset = 0;
521 DWARFDebugRangeList rangeList;
522 while (rangesData.isValidOffset(offset)) {
523 if (Error E = rangeList.extract(rangesData, &offset)) {
524 WithColor::error() << toString(std::move(E)) << '\n';
525 break;
526 }
527 rangeList.dump(OS);
528 }
529 }
530
David Blaikie59ac2062018-10-20 06:16:25 +0000531 auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
532 const auto &CUs = compile_units();
533 auto I = CUs.begin();
534 if (I == CUs.end())
535 return None;
536 return (*I)->getAddrOffsetSectionItem(Index);
537 };
538
James Henderson3fcc7452018-02-02 12:35:52 +0000539 if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
540 DObj->getRnglistsSection().Data)) {
Wolfgang Piebad605592018-05-18 20:12:54 +0000541 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000542 isLittleEndian(), 0);
543 dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
Wolfgang Piebad605592018-05-18 20:12:54 +0000544 }
545
546 if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
547 DObj->getRnglistsDWOSection().Data)) {
548 DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
Wolfgang Piebf39a9bb2018-10-31 01:12:58 +0000549 isLittleEndian(), 0);
550 dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
James Henderson3fcc7452018-02-02 12:35:52 +0000551 }
552
Adrian Prantl057d3362017-09-15 23:04:04 +0000553 if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
Fangrui Song158b2622018-11-11 18:57:28 +0000554 DObj->getPubNamesSection().Data))
555 DWARFDebugPubTable(*DObj, DObj->getPubNamesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000556 .dump(OS);
Krzysztof Parzyszek97438dc2013-02-12 16:20:28 +0000557
Adrian Prantl057d3362017-09-15 23:04:04 +0000558 if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
Fangrui Song158b2622018-11-11 18:57:28 +0000559 DObj->getPubTypesSection().Data))
560 DWARFDebugPubTable(*DObj, DObj->getPubTypesSection(), isLittleEndian(), false)
Adrian Prantl84168022017-09-15 17:39:50 +0000561 .dump(OS);
Eric Christopher4c7e6ba2013-09-25 23:02:41 +0000562
Adrian Prantl057d3362017-09-15 23:04:04 +0000563 if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
Fangrui Song158b2622018-11-11 18:57:28 +0000564 DObj->getGnuPubNamesSection().Data))
565 DWARFDebugPubTable(*DObj, DObj->getGnuPubNamesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000566 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000567 .dump(OS);
David Blaikieecd21ff2013-09-24 19:50:00 +0000568
Adrian Prantl057d3362017-09-15 23:04:04 +0000569 if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
Fangrui Song158b2622018-11-11 18:57:28 +0000570 DObj->getGnuPubTypesSection().Data))
571 DWARFDebugPubTable(*DObj, DObj->getGnuPubTypesSection(), isLittleEndian(),
George Rimare71e33f2016-12-17 09:10:32 +0000572 true /* GnuStyle */)
Adrian Prantl84168022017-09-15 17:39:50 +0000573 .dump(OS);
David Blaikie404d3042013-09-19 23:01:29 +0000574
Adrian Prantl057d3362017-09-15 23:04:04 +0000575 if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000576 DObj->getStringOffsetSection().Data))
Paul Robinson7f330942018-08-01 20:46:46 +0000577 dumpStringOffsetsSection(OS, "debug_str_offsets", *DObj,
578 DObj->getStringOffsetSection(),
Paul Robinson96545db2018-08-02 19:29:38 +0000579 DObj->getStringSection(), normal_units(),
580 isLittleEndian(), getMaxVersion());
Adrian Prantl057d3362017-09-15 23:04:04 +0000581 if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
Adrian Prantl84168022017-09-15 17:39:50 +0000582 DObj->getStringOffsetDWOSection().Data))
Paul Robinson96545db2018-08-02 19:29:38 +0000583 dumpStringOffsetsSection(OS, "debug_str_offsets.dwo", *DObj,
584 DObj->getStringOffsetDWOSection(),
585 DObj->getStringDWOSection(), dwo_units(),
David Blaikiefdada092018-10-05 20:55:20 +0000586 isLittleEndian(), getMaxDWOVersion());
Frederic Risse837ec22014-11-14 16:15:53 +0000587
Fangrui Song999570a2018-11-02 20:34:40 +0000588 if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
Adrian Prantl84168022017-09-15 17:39:50 +0000589 DObj->getGdbIndexSection())) {
George Rimar4f82df52016-09-23 11:01:53 +0000590 getGdbIndex().dump(OS);
591 }
592
Adrian Prantl057d3362017-09-15 23:04:04 +0000593 if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
Adrian Prantl84168022017-09-15 17:39:50 +0000594 DObj->getAppleNamesSection().Data))
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000595 getAppleNames().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000596
Adrian Prantl057d3362017-09-15 23:04:04 +0000597 if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
Adrian Prantl84168022017-09-15 17:39:50 +0000598 DObj->getAppleTypesSection().Data))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000599 getAppleTypes().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000600
Adrian Prantl057d3362017-09-15 23:04:04 +0000601 if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
Adrian Prantl84168022017-09-15 17:39:50 +0000602 DObj->getAppleNamespacesSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000603 getAppleNamespaces().dump(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000604
Adrian Prantl057d3362017-09-15 23:04:04 +0000605 if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
Adrian Prantl84168022017-09-15 17:39:50 +0000606 DObj->getAppleObjCSection().Data))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000607 getAppleObjC().dump(OS);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000608 if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
609 DObj->getDebugNamesSection().Data))
610 getDebugNames().dump(OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000611}
612
David Blaikie15d85fc2017-05-23 06:48:53 +0000613DWARFCompileUnit *DWARFContext::getDWOCompileUnitForHash(uint64_t Hash) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000614 parseDWOUnits(LazyParse);
David Blaikiea62f1cb2017-07-30 15:15:58 +0000615
David Blaikieebac0b92017-07-30 08:12:07 +0000616 if (const auto &CUI = getCUIndex()) {
617 if (const auto *R = CUI.getFromHash(Hash))
Paul Robinson2c25f342018-08-01 20:54:11 +0000618 return dyn_cast_or_null<DWARFCompileUnit>(
619 DWOUnits.getUnitForIndexEntry(*R));
David Blaikieebac0b92017-07-30 08:12:07 +0000620 return nullptr;
621 }
622
623 // If there's no index, just search through the CUs in the DWO - there's
624 // probably only one unless this is something like LTO - though an in-process
625 // built/cached lookup table could be used in that case to improve repeated
626 // lookups of different CUs in the DWO.
Paul Robinson543c0e12018-05-22 17:27:31 +0000627 for (const auto &DWOCU : dwo_compile_units()) {
628 // Might not have parsed DWO ID yet.
629 if (!DWOCU->getDWOId()) {
630 if (Optional<uint64_t> DWOId =
631 toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
632 DWOCU->setDWOId(*DWOId);
633 else
634 // No DWO ID?
635 continue;
636 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000637 if (DWOCU->getDWOId() == Hash)
Paul Robinson143eaea2018-08-01 20:43:47 +0000638 return dyn_cast<DWARFCompileUnit>(DWOCU.get());
Paul Robinson543c0e12018-05-22 17:27:31 +0000639 }
David Blaikie15d85fc2017-05-23 06:48:53 +0000640 return nullptr;
641}
642
Greg Claytonc7695a82017-05-02 20:28:33 +0000643DWARFDie DWARFContext::getDIEForOffset(uint32_t Offset) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000644 parseNormalUnits();
645 if (auto *CU = NormalUnits.getUnitForOffset(Offset))
Greg Claytonc7695a82017-05-02 20:28:33 +0000646 return CU->getDIEForOffset(Offset);
647 return DWARFDie();
648}
649
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000650bool DWARFContext::verify(raw_ostream &OS, DIDumpOptions DumpOpts) {
Greg Claytonc7695a82017-05-02 20:28:33 +0000651 bool Success = true;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000652 DWARFVerifier verifier(OS, *this, DumpOpts);
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000653
Spyridoula Gravani364b5352017-07-20 02:06:52 +0000654 Success &= verifier.handleDebugAbbrev();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000655 if (DumpOpts.DumpType & DIDT_DebugInfo)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000656 Success &= verifier.handleDebugInfo();
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000657 if (DumpOpts.DumpType & DIDT_DebugLine)
Spyridoula Gravani73e17962017-07-27 00:59:33 +0000658 Success &= verifier.handleDebugLine();
Spyridoula Gravanidc635f42017-07-26 00:52:31 +0000659 Success &= verifier.handleAccelTables();
Greg Clayton48432cf2017-05-01 22:07:02 +0000660 return Success;
661}
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000662
David Blaikie82641be2015-11-17 00:39:55 +0000663const DWARFUnitIndex &DWARFContext::getCUIndex() {
664 if (CUIndex)
665 return *CUIndex;
666
Rafael Espindolac398e672017-07-19 22:27:28 +0000667 DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000668
David Blaikieb073cb92015-12-02 06:21:34 +0000669 CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
David Blaikie82641be2015-11-17 00:39:55 +0000670 CUIndex->parse(CUIndexData);
671 return *CUIndex;
672}
673
674const DWARFUnitIndex &DWARFContext::getTUIndex() {
675 if (TUIndex)
676 return *TUIndex;
677
Rafael Espindolac398e672017-07-19 22:27:28 +0000678 DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
David Blaikie82641be2015-11-17 00:39:55 +0000679
David Blaikieb073cb92015-12-02 06:21:34 +0000680 TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
David Blaikie82641be2015-11-17 00:39:55 +0000681 TUIndex->parse(TUIndexData);
682 return *TUIndex;
683}
684
George Rimar4f82df52016-09-23 11:01:53 +0000685DWARFGdbIndex &DWARFContext::getGdbIndex() {
686 if (GdbIndex)
687 return *GdbIndex;
688
Rafael Espindolac398e672017-07-19 22:27:28 +0000689 DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
George Rimar4f82df52016-09-23 11:01:53 +0000690 GdbIndex = llvm::make_unique<DWARFGdbIndex>();
691 GdbIndex->parse(GdbIndexData);
692 return *GdbIndex;
693}
694
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000695const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
696 if (Abbrev)
697 return Abbrev.get();
698
Rafael Espindolac398e672017-07-19 22:27:28 +0000699 DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000700
701 Abbrev.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000702 Abbrev->extract(abbrData);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000703 return Abbrev.get();
704}
705
Eric Christopherda4b2192013-01-02 23:52:13 +0000706const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
707 if (AbbrevDWO)
708 return AbbrevDWO.get();
709
Rafael Espindolac398e672017-07-19 22:27:28 +0000710 DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
Eric Christopherda4b2192013-01-02 23:52:13 +0000711 AbbrevDWO.reset(new DWARFDebugAbbrev());
Alexey Samsonov4316df52014-04-25 21:10:56 +0000712 AbbrevDWO->extract(abbrData);
Eric Christopherda4b2192013-01-02 23:52:13 +0000713 return AbbrevDWO.get();
714}
715
David Blaikie18e73502013-06-19 21:37:13 +0000716const DWARFDebugLoc *DWARFContext::getDebugLoc() {
717 if (Loc)
718 return Loc.get();
719
Paul Robinson17536b92017-06-29 16:52:08 +0000720 Loc.reset(new DWARFDebugLoc);
Paul Robinson143eaea2018-08-01 20:43:47 +0000721 // Assume all units have the same address byte size.
Paul Robinson17536b92017-06-29 16:52:08 +0000722 if (getNumCompileUnits()) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000723 DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
Paul Robinson143eaea2018-08-01 20:43:47 +0000724 getUnitAtIndex(0)->getAddressByteSize());
Paul Robinson17536b92017-06-29 16:52:08 +0000725 Loc->parse(LocData);
726 }
David Blaikie18e73502013-06-19 21:37:13 +0000727 return Loc.get();
728}
729
George Rimar4c7dd9c2018-10-22 11:30:54 +0000730const DWARFDebugLoclists *DWARFContext::getDebugLocDWO() {
David Blaikie9c550ac2014-03-25 01:44:02 +0000731 if (LocDWO)
732 return LocDWO.get();
733
George Rimar4c7dd9c2018-10-22 11:30:54 +0000734 LocDWO.reset(new DWARFDebugLoclists());
Pavel Labath54ca2d62018-04-06 08:49:57 +0000735 // Assume all compile units have the same address byte size.
Wolfgang Pieba9ea9c52018-10-09 18:38:55 +0000736 // FIXME: We don't need AddressSize for split DWARF since relocatable
737 // addresses cannot appear there. At the moment DWARFExpression requires it.
738 DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 4);
George Rimar581fc632018-10-25 10:56:44 +0000739 // Use version 4. DWO does not support the DWARF v5 .debug_loclists yet and
740 // that means we are parsing the new style .debug_loc (pre-standatized version
741 // of the .debug_loclists).
742 LocDWO->parse(LocData, 4 /* Version */);
David Blaikie9c550ac2014-03-25 01:44:02 +0000743 return LocDWO.get();
744}
745
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000746const DWARFDebugAranges *DWARFContext::getDebugAranges() {
747 if (Aranges)
748 return Aranges.get();
749
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000750 Aranges.reset(new DWARFDebugAranges());
Alexey Samsonova1694c12012-11-16 08:36:25 +0000751 Aranges->generate(this);
Benjamin Kramera6002fd2011-09-14 01:09:52 +0000752 return Aranges.get();
753}
754
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000755const DWARFDebugFrame *DWARFContext::getDebugFrame() {
756 if (DebugFrame)
757 return DebugFrame.get();
758
759 // There's a "bug" in the DWARFv3 standard with respect to the target address
760 // size within debug frame sections. While DWARF is supposed to be independent
761 // of its container, FDEs have fields with size being "target address size",
762 // which isn't specified in DWARF in general. It's only specified for CUs, but
763 // .eh_frame can appear without a .debug_info section. Follow the example of
764 // other tools (libdwarf) and extract this from the container (ObjectFile
765 // provides this information). This problem is fixed in DWARFv4
766 // See this dwarf-discuss discussion for more details:
767 // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000768 DWARFDataExtractor debugFrameData(DObj->getDebugFrameSection(),
769 isLittleEndian(), DObj->getAddressSize());
Luke Cheesemand6dbd642018-11-23 11:01:47 +0000770 DebugFrame.reset(new DWARFDebugFrame(Arch, false /* IsEH */));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000771 DebugFrame->parse(debugFrameData);
772 return DebugFrame.get();
773}
774
775const DWARFDebugFrame *DWARFContext::getEHFrame() {
776 if (EHFrame)
777 return EHFrame.get();
778
Rafael Auler86fb7bf2018-03-08 00:46:53 +0000779 DWARFDataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
780 DObj->getAddressSize());
Luke Cheesemand6dbd642018-11-23 11:01:47 +0000781 DebugFrame.reset(new DWARFDebugFrame(Arch, true /* IsEH */));
Eli Benderskyfd08bc12013-02-05 23:30:58 +0000782 DebugFrame->parse(debugFrameData);
783 return DebugFrame.get();
784}
785
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000786const DWARFDebugMacro *DWARFContext::getDebugMacro() {
787 if (Macro)
788 return Macro.get();
789
Rafael Espindolac398e672017-07-19 22:27:28 +0000790 DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
Amjad Aboude59cc3e2015-11-12 09:38:54 +0000791 Macro.reset(new DWARFDebugMacro());
792 Macro->parse(MacinfoData);
793 return Macro.get();
794}
795
Pavel Labath3c9a9182018-01-29 11:08:32 +0000796template <typename T>
797static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
798 const DWARFSection &Section, StringRef StringSection,
799 bool IsLittleEndian) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000800 if (Cache)
801 return *Cache;
802 DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
803 DataExtractor StrData(StringSection, IsLittleEndian, 0);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000804 Cache.reset(new T(AccelSection, StrData));
Jonas Devlieghereba915892017-12-11 18:22:47 +0000805 if (Error E = Cache->extract())
806 llvm::consumeError(std::move(E));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000807 return *Cache;
808}
809
Pavel Labath3c9a9182018-01-29 11:08:32 +0000810const DWARFDebugNames &DWARFContext::getDebugNames() {
811 return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(),
812 DObj->getStringSection(), isLittleEndian());
813}
814
Pavel Labath9b36fd22018-01-22 13:17:23 +0000815const AppleAcceleratorTable &DWARFContext::getAppleNames() {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000816 return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
817 DObj->getStringSection(), isLittleEndian());
818}
819
Pavel Labath9b36fd22018-01-22 13:17:23 +0000820const AppleAcceleratorTable &DWARFContext::getAppleTypes() {
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000821 return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
822 DObj->getStringSection(), isLittleEndian());
823}
824
Pavel Labath9b36fd22018-01-22 13:17:23 +0000825const AppleAcceleratorTable &DWARFContext::getAppleNamespaces() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000826 return getAccelTable(AppleNamespaces, *DObj,
827 DObj->getAppleNamespacesSection(),
828 DObj->getStringSection(), isLittleEndian());
829}
830
Pavel Labath9b36fd22018-01-22 13:17:23 +0000831const AppleAcceleratorTable &DWARFContext::getAppleObjC() {
Adrian Prantlf51e7802017-09-29 00:52:33 +0000832 return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
833 DObj->getStringSection(), isLittleEndian());
834}
835
James Hendersona3acf992018-05-10 10:51:33 +0000836const DWARFDebugLine::LineTable *
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000837DWARFContext::getLineTableForUnit(DWARFUnit *U) {
James Hendersona3acf992018-05-10 10:51:33 +0000838 Expected<const DWARFDebugLine::LineTable *> ExpectedLineTable =
Victor Leschukcf1f7142018-08-23 12:43:33 +0000839 getLineTableForUnit(U, dumpWarning);
James Hendersona3acf992018-05-10 10:51:33 +0000840 if (!ExpectedLineTable) {
Victor Leschukcf1f7142018-08-23 12:43:33 +0000841 dumpWarning(ExpectedLineTable.takeError());
James Hendersona3acf992018-05-10 10:51:33 +0000842 return nullptr;
843 }
844 return *ExpectedLineTable;
845}
846
James Henderson004b7292018-05-21 15:30:54 +0000847Expected<const DWARFDebugLine::LineTable *> DWARFContext::getLineTableForUnit(
848 DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
Benjamin Kramer679e1752011-09-15 20:43:18 +0000849 if (!Line)
Paul Robinson17536b92017-06-29 16:52:08 +0000850 Line.reset(new DWARFDebugLine);
David Blaikiec4e2bed2015-11-17 21:08:05 +0000851
Greg Claytonc8c10322016-12-13 18:25:19 +0000852 auto UnitDIE = U->getUnitDIE();
853 if (!UnitDIE)
Alexey Samsonov7a18c062015-05-19 21:54:32 +0000854 return nullptr;
David Blaikiec4e2bed2015-11-17 21:08:05 +0000855
Greg Clayton97d22182017-01-13 21:08:18 +0000856 auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
Greg Clayton52fe1f62016-12-14 22:38:08 +0000857 if (!Offset)
Craig Topper2617dcc2014-04-15 06:32:26 +0000858 return nullptr; // No line table for this compile unit.
Benjamin Kramer5acab502011-09-15 02:12:05 +0000859
Greg Clayton52fe1f62016-12-14 22:38:08 +0000860 uint32_t stmtOffset = *Offset + U->getLineTableOffset();
Benjamin Kramer679e1752011-09-15 20:43:18 +0000861 // See if the line table is cached.
Eric Christopher494109b2012-10-16 23:46:25 +0000862 if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
Benjamin Kramer679e1752011-09-15 20:43:18 +0000863 return lt;
864
Greg Clayton48ff66a2017-05-04 18:29:44 +0000865 // Make sure the offset is good before we try to parse.
Paul Robinson17536b92017-06-29 16:52:08 +0000866 if (stmtOffset >= U->getLineSection().Data.size())
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000867 return nullptr;
Greg Clayton48ff66a2017-05-04 18:29:44 +0000868
Benjamin Kramer679e1752011-09-15 20:43:18 +0000869 // We have to parse it first.
Rafael Espindolac398e672017-07-19 22:27:28 +0000870 DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
Paul Robinson17536b92017-06-29 16:52:08 +0000871 U->getAddressByteSize());
James Hendersona3acf992018-05-10 10:51:33 +0000872 return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
James Henderson004b7292018-05-21 15:30:54 +0000873 RecoverableErrorCallback);
Benjamin Kramer5acab502011-09-15 02:12:05 +0000874}
875
Paul Robinson2c25f342018-08-01 20:54:11 +0000876void DWARFContext::parseNormalUnits() {
877 if (!NormalUnits.empty())
Paul Robinson7f330942018-08-01 20:46:46 +0000878 return;
Paul Robinson746c22382018-11-07 21:39:09 +0000879 DObj->forEachInfoSections([&](const DWARFSection &S) {
880 NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
881 });
Paul Robinson2c25f342018-08-01 20:54:11 +0000882 NormalUnits.finishedInfoUnits();
Rafael Espindolac398e672017-07-19 22:27:28 +0000883 DObj->forEachTypesSections([&](const DWARFSection &S) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000884 NormalUnits.addUnitsForSection(*this, S, DW_SECT_TYPES);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000885 });
David Blaikie03c089c2013-09-23 22:44:47 +0000886}
887
Paul Robinson2c25f342018-08-01 20:54:11 +0000888void DWARFContext::parseDWOUnits(bool Lazy) {
889 if (!DWOUnits.empty())
Paul Robinson7f330942018-08-01 20:46:46 +0000890 return;
Paul Robinson746c22382018-11-07 21:39:09 +0000891 DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
892 DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
893 });
Paul Robinson2c25f342018-08-01 20:54:11 +0000894 DWOUnits.finishedInfoUnits();
Rafael Espindolac398e672017-07-19 22:27:28 +0000895 DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000896 DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_TYPES, Lazy);
Rafael Espindola5e5dfa12017-07-12 21:08:24 +0000897 });
David Blaikie92d9d622014-01-09 05:08:24 +0000898}
899
Alexey Samsonov45be7932012-08-30 07:49:50 +0000900DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
Paul Robinson2c25f342018-08-01 20:54:11 +0000901 parseNormalUnits();
902 return dyn_cast_or_null<DWARFCompileUnit>(
903 NormalUnits.getUnitForOffset(Offset));
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000904}
905
Alexey Samsonov45be7932012-08-30 07:49:50 +0000906DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
Benjamin Kramer112ec172011-09-15 21:59:13 +0000907 // First, get the offset of the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000908 uint32_t CUOffset = getDebugAranges()->findAddress(Address);
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000909 // Retrieve the compile unit.
Alexey Samsonov45be7932012-08-30 07:49:50 +0000910 return getCompileUnitForOffset(CUOffset);
911}
912
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000913DWARFContext::DIEsForAddress DWARFContext::getDIEsForAddress(uint64_t Address) {
914 DIEsForAddress Result;
915
916 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
917 if (!CU)
918 return Result;
919
920 Result.CompileUnit = CU;
921 Result.FunctionDIE = CU->getSubroutineForAddress(Address);
922
923 std::vector<DWARFDie> Worklist;
924 Worklist.push_back(Result.FunctionDIE);
925 while (!Worklist.empty()) {
926 DWARFDie DIE = Worklist.back();
927 Worklist.pop_back();
928
929 if (DIE.getTag() == DW_TAG_lexical_block &&
930 DIE.addressRangeContainsAddress(Address)) {
931 Result.BlockDIE = DIE;
932 break;
933 }
934
935 for (auto Child : DIE)
936 Worklist.push_back(Child);
937 }
938
939 return Result;
940}
941
David Blaikieefc4eba2017-02-06 20:19:02 +0000942static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU,
943 uint64_t Address,
944 FunctionNameKind Kind,
945 std::string &FunctionName,
946 uint32_t &StartLine) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000947 // The address may correspond to instruction in some inlined function,
948 // so we have to build the chain of inlined functions and take the
David Blaikieefc4eba2017-02-06 20:19:02 +0000949 // name of the topmost function in it.
Greg Claytonc8c10322016-12-13 18:25:19 +0000950 SmallVector<DWARFDie, 4> InlinedChain;
951 CU->getInlinedChainForAddress(Address, InlinedChain);
David Blaikieefc4eba2017-02-06 20:19:02 +0000952 if (InlinedChain.empty())
Alexey Samsonovd0109992014-04-18 21:36:39 +0000953 return false;
David Blaikieefc4eba2017-02-06 20:19:02 +0000954
955 const DWARFDie &DIE = InlinedChain[0];
956 bool FoundResult = false;
957 const char *Name = nullptr;
958 if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000959 FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +0000960 FoundResult = true;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000961 }
David Blaikieefc4eba2017-02-06 20:19:02 +0000962 if (auto DeclLineResult = DIE.getDeclLine()) {
963 StartLine = DeclLineResult;
964 FoundResult = true;
965 }
966
967 return FoundResult;
Alexey Samsonovd0109992014-04-18 21:36:39 +0000968}
969
Alexey Samsonov45be7932012-08-30 07:49:50 +0000970DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
Alexey Samsonovdce67342014-05-15 21:24:32 +0000971 DILineInfoSpecifier Spec) {
Alexey Samsonovd0109992014-04-18 21:36:39 +0000972 DILineInfo Result;
973
Alexey Samsonov45be7932012-08-30 07:49:50 +0000974 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
975 if (!CU)
Alexey Samsonovd0109992014-04-18 21:36:39 +0000976 return Result;
David Blaikieefc4eba2017-02-06 20:19:02 +0000977 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind,
978 Result.FunctionName,
979 Result.StartLine);
Alexey Samsonovdce67342014-05-15 21:24:32 +0000980 if (Spec.FLIKind != FileLineInfoKind::None) {
Frederic Riss101b5e22014-09-19 15:11:51 +0000981 if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
982 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
983 Spec.FLIKind, Result);
Alexey Samsonovf4462fa2012-07-02 05:54:45 +0000984 }
Alexey Samsonovd0109992014-04-18 21:36:39 +0000985 return Result;
Benjamin Kramer2602ca62011-09-15 20:43:22 +0000986}
David Blaikiea379b1812011-12-20 02:50:00 +0000987
Alexey Samsonovdce67342014-05-15 21:24:32 +0000988DILineInfoTable
989DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
990 DILineInfoSpecifier Spec) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +0000991 DILineInfoTable Lines;
992 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
993 if (!CU)
994 return Lines;
995
996 std::string FunctionName = "<invalid>";
David Blaikieefc4eba2017-02-06 20:19:02 +0000997 uint32_t StartLine = 0;
998 getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
999 StartLine);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001000
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001001 // If the Specifier says we don't need FileLineInfo, just
1002 // return the top-most function at the starting address.
Alexey Samsonovdce67342014-05-15 21:24:32 +00001003 if (Spec.FLIKind == FileLineInfoKind::None) {
Alexey Samsonovd0109992014-04-18 21:36:39 +00001004 DILineInfo Result;
1005 Result.FunctionName = FunctionName;
David Blaikieefc4eba2017-02-06 20:19:02 +00001006 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +00001007 Lines.push_back(std::make_pair(Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001008 return Lines;
1009 }
1010
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001011 const DWARFLineTable *LineTable = getLineTableForUnit(CU);
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001012
1013 // Get the index of row we're looking for in the line table.
1014 std::vector<uint32_t> RowVector;
1015 if (!LineTable->lookupAddressRange(Address, Size, RowVector))
1016 return Lines;
1017
Alexey Samsonov1eabf982014-03-13 07:52:54 +00001018 for (uint32_t RowIndex : RowVector) {
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001019 // Take file number and line/column from the row.
1020 const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
Alexey Samsonovd0109992014-04-18 21:36:39 +00001021 DILineInfo Result;
Frederic Riss101b5e22014-09-19 15:11:51 +00001022 LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1023 Spec.FLIKind, Result.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +00001024 Result.FunctionName = FunctionName;
1025 Result.Line = Row.Line;
1026 Result.Column = Row.Column;
David Blaikieefc4eba2017-02-06 20:19:02 +00001027 Result.StartLine = StartLine;
Alexey Samsonovd0109992014-04-18 21:36:39 +00001028 Lines.push_back(std::make_pair(Row.Address, Result));
Andrew Kaylor9a8ff812013-01-26 00:28:05 +00001029 }
1030
1031 return Lines;
1032}
1033
Alexey Samsonovdce67342014-05-15 21:24:32 +00001034DIInliningInfo
1035DWARFContext::getInliningInfoForAddress(uint64_t Address,
1036 DILineInfoSpecifier Spec) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001037 DIInliningInfo InliningInfo;
1038
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001039 DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
1040 if (!CU)
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001041 return InliningInfo;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001042
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001043 const DWARFLineTable *LineTable = nullptr;
Greg Claytonc8c10322016-12-13 18:25:19 +00001044 SmallVector<DWARFDie, 4> InlinedChain;
1045 CU->getInlinedChainForAddress(Address, InlinedChain);
1046 if (InlinedChain.size() == 0) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001047 // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1048 // try to at least get file/line info from symbol table.
Alexey Samsonovdce67342014-05-15 21:24:32 +00001049 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001050 DILineInfo Frame;
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001051 LineTable = getLineTableForUnit(CU);
Frederic Riss101b5e22014-09-19 15:11:51 +00001052 if (LineTable &&
1053 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
1054 Spec.FLIKind, Frame))
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001055 InliningInfo.addFrame(Frame);
Alexey Samsonov5c39fdf2014-04-18 22:22:44 +00001056 }
1057 return InliningInfo;
1058 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001059
Dehao Chenef700d52017-04-17 20:10:39 +00001060 uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
Greg Claytonc8c10322016-12-13 18:25:19 +00001061 for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1062 DWARFDie &FunctionDIE = InlinedChain[i];
Alexey Samsonovd0109992014-04-18 21:36:39 +00001063 DILineInfo Frame;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001064 // Get function name if necessary.
Greg Claytonc8c10322016-12-13 18:25:19 +00001065 if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
Alexey Samsonovdce67342014-05-15 21:24:32 +00001066 Frame.FunctionName = Name;
David Blaikieefc4eba2017-02-06 20:19:02 +00001067 if (auto DeclLineResult = FunctionDIE.getDeclLine())
1068 Frame.StartLine = DeclLineResult;
Alexey Samsonovdce67342014-05-15 21:24:32 +00001069 if (Spec.FLIKind != FileLineInfoKind::None) {
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001070 if (i == 0) {
1071 // For the topmost frame, initialize the line table of this
1072 // compile unit and fetch file/line info from it.
Frederic Rissec8a5ba2014-09-04 06:14:40 +00001073 LineTable = getLineTableForUnit(CU);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001074 // For the topmost routine, get file/line info from line table.
Frederic Riss101b5e22014-09-19 15:11:51 +00001075 if (LineTable)
1076 LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
1077 Spec.FLIKind, Frame);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001078 } else {
1079 // Otherwise, use call file, call line and call column from
1080 // previous DIE in inlined chain.
Frederic Riss101b5e22014-09-19 15:11:51 +00001081 if (LineTable)
1082 LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1083 Spec.FLIKind, Frame.FileName);
Alexey Samsonovd0109992014-04-18 21:36:39 +00001084 Frame.Line = CallLine;
1085 Frame.Column = CallColumn;
Dehao Chenef700d52017-04-17 20:10:39 +00001086 Frame.Discriminator = CallDiscriminator;
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001087 }
1088 // Get call file/line/column of a current DIE.
1089 if (i + 1 < n) {
Dehao Chenef700d52017-04-17 20:10:39 +00001090 FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1091 CallDiscriminator);
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001092 }
1093 }
Alexey Samsonovc942e6b2012-09-04 08:12:33 +00001094 InliningInfo.addFrame(Frame);
1095 }
1096 return InliningInfo;
1097}
1098
David Blaikief9803fb2017-05-23 00:30:42 +00001099std::shared_ptr<DWARFContext>
1100DWARFContext::getDWOContext(StringRef AbsolutePath) {
David Blaikie15d85fc2017-05-23 06:48:53 +00001101 if (auto S = DWP.lock()) {
David Blaikief9803fb2017-05-23 00:30:42 +00001102 DWARFContext *Ctxt = S->Context.get();
1103 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1104 }
1105
David Blaikie15d85fc2017-05-23 06:48:53 +00001106 std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1107
1108 if (auto S = Entry->lock()) {
1109 DWARFContext *Ctxt = S->Context.get();
1110 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1111 }
1112
David Blaikie15d85fc2017-05-23 06:48:53 +00001113 Expected<OwningBinary<ObjectFile>> Obj = [&] {
1114 if (!CheckedForDWP) {
David Blaikiee5adb682017-07-30 01:34:08 +00001115 SmallString<128> DWPName;
1116 auto Obj = object::ObjectFile::createObjectFile(
1117 this->DWPName.empty()
1118 ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1119 : StringRef(this->DWPName));
David Blaikie15d85fc2017-05-23 06:48:53 +00001120 if (Obj) {
1121 Entry = &DWP;
1122 return Obj;
1123 } else {
1124 CheckedForDWP = true;
1125 // TODO: Should this error be handled (maybe in a high verbosity mode)
1126 // before falling back to .dwo files?
1127 consumeError(Obj.takeError());
1128 }
1129 }
1130
1131 return object::ObjectFile::createObjectFile(AbsolutePath);
1132 }();
1133
David Blaikief9803fb2017-05-23 00:30:42 +00001134 if (!Obj) {
1135 // TODO: Actually report errors helpfully.
1136 consumeError(Obj.takeError());
1137 return nullptr;
1138 }
David Blaikie15d85fc2017-05-23 06:48:53 +00001139
1140 auto S = std::make_shared<DWOFile>();
David Blaikief9803fb2017-05-23 00:30:42 +00001141 S->File = std::move(Obj.get());
Rafael Espindolac398e672017-07-19 22:27:28 +00001142 S->Context = DWARFContext::create(*S->File.getBinary());
David Blaikie15d85fc2017-05-23 06:48:53 +00001143 *Entry = S;
David Blaikief9803fb2017-05-23 00:30:42 +00001144 auto *Ctxt = S->Context.get();
1145 return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1146}
1147
George Rimar702dac62017-04-12 08:59:15 +00001148static Error createError(const Twine &Reason, llvm::Error E) {
1149 return make_error<StringError>(Reason + toString(std::move(E)),
1150 inconvertibleErrorCode());
1151}
1152
George Rimara25d3292017-05-27 18:10:23 +00001153/// SymInfo contains information about symbol: it's address
1154/// and section index which is -1LL for absolute symbols.
1155struct SymInfo {
1156 uint64_t Address;
1157 uint64_t SectionIndex;
1158};
1159
1160/// Returns the address of symbol relocation used against and a section index.
1161/// Used for futher relocations computation. Symbol's section load address is
1162static Expected<SymInfo> getSymbolInfo(const object::ObjectFile &Obj,
1163 const RelocationRef &Reloc,
1164 const LoadedObjectInfo *L,
1165 std::map<SymbolRef, SymInfo> &Cache) {
1166 SymInfo Ret = {0, (uint64_t)-1LL};
George Rimar702dac62017-04-12 08:59:15 +00001167 object::section_iterator RSec = Obj.section_end();
1168 object::symbol_iterator Sym = Reloc.getSymbol();
1169
George Rimara25d3292017-05-27 18:10:23 +00001170 std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
George Rimar702dac62017-04-12 08:59:15 +00001171 // First calculate the address of the symbol or section as it appears
1172 // in the object file
1173 if (Sym != Obj.symbol_end()) {
George Rimar958b01a2017-05-15 11:45:28 +00001174 bool New;
George Rimara25d3292017-05-27 18:10:23 +00001175 std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
George Rimar958b01a2017-05-15 11:45:28 +00001176 if (!New)
1177 return CacheIt->second;
1178
George Rimar702dac62017-04-12 08:59:15 +00001179 Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1180 if (!SymAddrOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001181 return createError("failed to compute symbol address: ",
George Rimar702dac62017-04-12 08:59:15 +00001182 SymAddrOrErr.takeError());
1183
1184 // Also remember what section this symbol is in for later
1185 auto SectOrErr = Sym->getSection();
1186 if (!SectOrErr)
George Rimar1af3cb22017-06-28 08:21:19 +00001187 return createError("failed to get symbol section: ",
George Rimar702dac62017-04-12 08:59:15 +00001188 SectOrErr.takeError());
1189
1190 RSec = *SectOrErr;
George Rimara25d3292017-05-27 18:10:23 +00001191 Ret.Address = *SymAddrOrErr;
George Rimar702dac62017-04-12 08:59:15 +00001192 } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1193 RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
George Rimara25d3292017-05-27 18:10:23 +00001194 Ret.Address = RSec->getAddress();
George Rimar702dac62017-04-12 08:59:15 +00001195 }
1196
George Rimara25d3292017-05-27 18:10:23 +00001197 if (RSec != Obj.section_end())
1198 Ret.SectionIndex = RSec->getIndex();
1199
George Rimar702dac62017-04-12 08:59:15 +00001200 // If we are given load addresses for the sections, we need to adjust:
1201 // SymAddr = (Address of Symbol Or Section in File) -
1202 // (Address of Section in File) +
1203 // (Load Address of Section)
1204 // RSec is now either the section being targeted or the section
1205 // containing the symbol being targeted. In either case,
1206 // we need to perform the same computation.
1207 if (L && RSec != Obj.section_end())
1208 if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
George Rimara25d3292017-05-27 18:10:23 +00001209 Ret.Address += SectionLoadAddress - RSec->getAddress();
George Rimar958b01a2017-05-15 11:45:28 +00001210
1211 if (CacheIt != Cache.end())
1212 CacheIt->second = Ret;
1213
George Rimar702dac62017-04-12 08:59:15 +00001214 return Ret;
1215}
1216
1217static bool isRelocScattered(const object::ObjectFile &Obj,
1218 const RelocationRef &Reloc) {
George Rimard4998b02017-04-13 09:52:50 +00001219 const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1220 if (!MachObj)
George Rimar702dac62017-04-12 08:59:15 +00001221 return false;
1222 // MachO also has relocations that point to sections and
1223 // scattered relocations.
George Rimar702dac62017-04-12 08:59:15 +00001224 auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1225 return MachObj->isRelocationScattered(RelocInfo);
1226}
1227
Rafael Espindolac398e672017-07-19 22:27:28 +00001228ErrorPolicy DWARFContext::defaultErrorHandler(Error E) {
Jonas Devlieghere84e99262018-04-14 22:07:23 +00001229 WithColor::error() << toString(std::move(E)) << '\n';
George Rimar1af3cb22017-06-28 08:21:19 +00001230 return ErrorPolicy::Continue;
1231}
1232
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001233namespace {
1234struct DWARFSectionMap final : public DWARFSection {
1235 RelocAddrMap Relocs;
1236};
Rafael Espindola87c3f4a92017-07-24 19:34:26 +00001237
Rafael Espindolac398e672017-07-19 22:27:28 +00001238class DWARFObjInMemory final : public DWARFObject {
1239 bool IsLittleEndian;
1240 uint8_t AddressSize;
1241 StringRef FileName;
George Rimar6957ab52017-08-15 12:32:54 +00001242 const object::ObjectFile *Obj = nullptr;
George Rimare1c30f72017-08-15 15:54:43 +00001243 std::vector<SectionName> SectionNames;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001244
Paul Robinson746c22382018-11-07 21:39:09 +00001245 using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
Rafael Espindolac398e672017-07-19 22:27:28 +00001246 std::map<object::SectionRef, unsigned>>;
Eric Christopher7370b552012-11-12 21:40:38 +00001247
Paul Robinson746c22382018-11-07 21:39:09 +00001248 InfoSectionMap InfoSections;
1249 InfoSectionMap TypesSections;
1250 InfoSectionMap InfoDWOSections;
1251 InfoSectionMap TypesDWOSections;
Rafael Espindolac398e672017-07-19 22:27:28 +00001252
Rafael Espindolac398e672017-07-19 22:27:28 +00001253 DWARFSectionMap LocSection;
George Rimar4c7dd9c2018-10-22 11:30:54 +00001254 DWARFSectionMap LocListsSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001255 DWARFSectionMap LineSection;
1256 DWARFSectionMap RangeSection;
James Henderson3fcc7452018-02-02 12:35:52 +00001257 DWARFSectionMap RnglistsSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001258 DWARFSectionMap StringOffsetSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001259 DWARFSectionMap LineDWOSection;
1260 DWARFSectionMap LocDWOSection;
1261 DWARFSectionMap StringOffsetDWOSection;
1262 DWARFSectionMap RangeDWOSection;
Wolfgang Piebad605592018-05-18 20:12:54 +00001263 DWARFSectionMap RnglistsDWOSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001264 DWARFSectionMap AddrSection;
1265 DWARFSectionMap AppleNamesSection;
1266 DWARFSectionMap AppleTypesSection;
1267 DWARFSectionMap AppleNamespacesSection;
1268 DWARFSectionMap AppleObjCSection;
Pavel Labath3c9a9182018-01-29 11:08:32 +00001269 DWARFSectionMap DebugNamesSection;
Fangrui Song158b2622018-11-11 18:57:28 +00001270 DWARFSectionMap PubNamesSection;
1271 DWARFSectionMap PubTypesSection;
1272 DWARFSectionMap GnuPubNamesSection;
1273 DWARFSectionMap GnuPubTypesSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001274
1275 DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1276 return StringSwitch<DWARFSectionMap *>(Name)
Rafael Espindolac398e672017-07-19 22:27:28 +00001277 .Case("debug_loc", &LocSection)
George Rimar4c7dd9c2018-10-22 11:30:54 +00001278 .Case("debug_loclists", &LocListsSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001279 .Case("debug_line", &LineSection)
1280 .Case("debug_str_offsets", &StringOffsetSection)
1281 .Case("debug_ranges", &RangeSection)
James Henderson3fcc7452018-02-02 12:35:52 +00001282 .Case("debug_rnglists", &RnglistsSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001283 .Case("debug_loc.dwo", &LocDWOSection)
1284 .Case("debug_line.dwo", &LineDWOSection)
Pavel Labath3c9a9182018-01-29 11:08:32 +00001285 .Case("debug_names", &DebugNamesSection)
Wolfgang Piebad605592018-05-18 20:12:54 +00001286 .Case("debug_rnglists.dwo", &RnglistsDWOSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001287 .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1288 .Case("debug_addr", &AddrSection)
1289 .Case("apple_names", &AppleNamesSection)
Fangrui Song158b2622018-11-11 18:57:28 +00001290 .Case("debug_pubnames", &PubNamesSection)
1291 .Case("debug_pubtypes", &PubTypesSection)
1292 .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1293 .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001294 .Case("apple_types", &AppleTypesSection)
1295 .Case("apple_namespaces", &AppleNamespacesSection)
1296 .Case("apple_namespac", &AppleNamespacesSection)
1297 .Case("apple_objc", &AppleObjCSection)
1298 .Default(nullptr);
1299 }
1300
1301 StringRef AbbrevSection;
1302 StringRef ARangeSection;
1303 StringRef DebugFrameSection;
1304 StringRef EHFrameSection;
1305 StringRef StringSection;
1306 StringRef MacinfoSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001307 StringRef AbbrevDWOSection;
1308 StringRef StringDWOSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001309 StringRef CUIndexSection;
1310 StringRef GdbIndexSection;
1311 StringRef TUIndexSection;
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001312 StringRef LineStringSection;
Rafael Espindolac398e672017-07-19 22:27:28 +00001313
Fangrui Song5bad9d82018-07-23 23:27:45 +00001314 // A deque holding section data whose iterators are not invalidated when
1315 // new decompressed sections are inserted at the end.
1316 std::deque<SmallString<0>> UncompressedSections;
Rafael Espindolac398e672017-07-19 22:27:28 +00001317
1318 StringRef *mapSectionToMember(StringRef Name) {
1319 if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1320 return &Sec->Data;
1321 return StringSwitch<StringRef *>(Name)
1322 .Case("debug_abbrev", &AbbrevSection)
1323 .Case("debug_aranges", &ARangeSection)
1324 .Case("debug_frame", &DebugFrameSection)
1325 .Case("eh_frame", &EHFrameSection)
1326 .Case("debug_str", &StringSection)
1327 .Case("debug_macinfo", &MacinfoSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001328 .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1329 .Case("debug_str.dwo", &StringDWOSection)
1330 .Case("debug_cu_index", &CUIndexSection)
1331 .Case("debug_tu_index", &TUIndexSection)
1332 .Case("gdb_index", &GdbIndexSection)
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001333 .Case("debug_line_str", &LineStringSection)
Rafael Espindolac398e672017-07-19 22:27:28 +00001334 // Any more debug info sections go here.
1335 .Default(nullptr);
1336 }
1337
1338 /// If Sec is compressed section, decompresses and updates its contents
1339 /// provided by Data. Otherwise leaves it unchanged.
1340 Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1341 StringRef &Data) {
1342 if (!Decompressor::isCompressed(Sec))
1343 return Error::success();
1344
1345 Expected<Decompressor> Decompressor =
1346 Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1347 if (!Decompressor)
1348 return Decompressor.takeError();
1349
Fangrui Song5bad9d82018-07-23 23:27:45 +00001350 SmallString<0> Out;
Rafael Espindolac398e672017-07-19 22:27:28 +00001351 if (auto Err = Decompressor->resizeAndDecompress(Out))
1352 return Err;
1353
Fangrui Song5bad9d82018-07-23 23:27:45 +00001354 UncompressedSections.push_back(std::move(Out));
Rafael Espindolac398e672017-07-19 22:27:28 +00001355 Data = UncompressedSections.back();
1356
1357 return Error::success();
1358 }
1359
1360public:
1361 DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1362 uint8_t AddrSize, bool IsLittleEndian)
1363 : IsLittleEndian(IsLittleEndian) {
1364 for (const auto &SecIt : Sections) {
1365 if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1366 *SectionData = SecIt.second->getBuffer();
Paul Robinson746c22382018-11-07 21:39:09 +00001367 else if (SecIt.first() == "debug_info")
1368 // Find debug_info and debug_types data by section rather than name as
1369 // there are multiple, comdat grouped, of these sections.
1370 InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1371 else if (SecIt.first() == "debug_info.dwo")
1372 InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1373 else if (SecIt.first() == "debug_types")
1374 TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1375 else if (SecIt.first() == "debug_types.dwo")
1376 TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001377 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001378 }
1379 DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1380 function_ref<ErrorPolicy(Error)> HandleError)
1381 : IsLittleEndian(Obj.isLittleEndian()),
George Rimar6957ab52017-08-15 12:32:54 +00001382 AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1383 Obj(&Obj) {
Alexey Samsonov068fc8a2013-04-23 10:17:34 +00001384
George Rimare1c30f72017-08-15 15:54:43 +00001385 StringMap<unsigned> SectionAmountMap;
Rafael Espindolac398e672017-07-19 22:27:28 +00001386 for (const SectionRef &Section : Obj.sections()) {
1387 StringRef Name;
1388 Section.getName(Name);
George Rimare1c30f72017-08-15 15:54:43 +00001389 ++SectionAmountMap[Name];
1390 SectionNames.push_back({ Name, true });
1391
Rafael Espindolac398e672017-07-19 22:27:28 +00001392 // Skip BSS and Virtual sections, they aren't interesting.
1393 if (Section.isBSS() || Section.isVirtual())
George Rimarfed9f092017-05-17 12:10:51 +00001394 continue;
Keno Fischerc780e8e2015-05-21 21:24:32 +00001395
Jonas Devlieghere8af23872017-09-26 14:22:35 +00001396 // Skip sections stripped by dsymutil.
1397 if (Section.isStripped())
1398 continue;
1399
Rafael Espindolac398e672017-07-19 22:27:28 +00001400 StringRef Data;
1401 section_iterator RelocatedSection = Section.getRelocatedSection();
1402 // Try to obtain an already relocated version of this section.
1403 // Else use the unrelocated section from the object file. We'll have to
1404 // apply relocations ourselves later.
1405 if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1406 Section.getContents(Data);
George Rimarfed9f092017-05-17 12:10:51 +00001407
Rafael Espindolac398e672017-07-19 22:27:28 +00001408 if (auto Err = maybeDecompress(Section, Name, Data)) {
1409 ErrorPolicy EP = HandleError(createError(
1410 "failed to decompress '" + Name + "', ", std::move(Err)));
George Rimar1af3cb22017-06-28 08:21:19 +00001411 if (EP == ErrorPolicy::Halt)
1412 return;
George Rimarfed9f092017-05-17 12:10:51 +00001413 continue;
1414 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001415
1416 // Compressed sections names in GNU style starts from ".z",
1417 // at this point section is decompressed and we drop compression prefix.
1418 Name = Name.substr(
1419 Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1420
1421 // Map platform specific debug section names to DWARF standard section
1422 // names.
1423 Name = Obj.mapDebugSectionName(Name);
1424
1425 if (StringRef *SectionData = mapSectionToMember(Name)) {
1426 *SectionData = Data;
1427 if (Name == "debug_ranges") {
1428 // FIXME: Use the other dwo range section when we emit it.
1429 RangeDWOSection.Data = Data;
1430 }
Paul Robinson746c22382018-11-07 21:39:09 +00001431 } else if (Name == "debug_info") {
1432 // Find debug_info and debug_types data by section rather than name as
1433 // there are multiple, comdat grouped, of these sections.
1434 InfoSections[Section].Data = Data;
1435 } else if (Name == "debug_info.dwo") {
1436 InfoDWOSections[Section].Data = Data;
Rafael Espindolac398e672017-07-19 22:27:28 +00001437 } else if (Name == "debug_types") {
Rafael Espindolac398e672017-07-19 22:27:28 +00001438 TypesSections[Section].Data = Data;
1439 } else if (Name == "debug_types.dwo") {
1440 TypesDWOSections[Section].Data = Data;
1441 }
1442
1443 if (RelocatedSection == Obj.section_end())
1444 continue;
1445
1446 StringRef RelSecName;
1447 StringRef RelSecData;
1448 RelocatedSection->getName(RelSecName);
1449
1450 // If the section we're relocating was relocated already by the JIT,
1451 // then we used the relocated version above, so we do not need to process
1452 // relocations for it now.
1453 if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1454 continue;
1455
1456 // In Mach-o files, the relocations do not need to be applied if
1457 // there is no load offset to apply. The value read at the
1458 // relocation point already factors in the section address
1459 // (actually applying the relocations will produce wrong results
1460 // as the section address will be added twice).
1461 if (!L && isa<MachOObjectFile>(&Obj))
1462 continue;
1463
1464 RelSecName = RelSecName.substr(
1465 RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1466
1467 // TODO: Add support for relocations in other sections as needed.
1468 // Record relocations for the debug_info and debug_line sections.
1469 DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1470 RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1471 if (!Map) {
Paul Robinson746c22382018-11-07 21:39:09 +00001472 // Find debug_info and debug_types relocs by section rather than name
1473 // as there are multiple, comdat grouped, of these sections.
1474 if (RelSecName == "debug_info")
1475 Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1476 .Relocs;
1477 else if (RelSecName == "debug_info.dwo")
1478 Map = &static_cast<DWARFSectionMap &>(
1479 InfoDWOSections[*RelocatedSection])
1480 .Relocs;
1481 else if (RelSecName == "debug_types")
Rafael Espindolac398e672017-07-19 22:27:28 +00001482 Map =
1483 &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1484 .Relocs;
1485 else if (RelSecName == "debug_types.dwo")
1486 Map = &static_cast<DWARFSectionMap &>(
1487 TypesDWOSections[*RelocatedSection])
1488 .Relocs;
1489 else
1490 continue;
1491 }
1492
1493 if (Section.relocation_begin() == Section.relocation_end())
1494 continue;
1495
1496 // Symbol to [address, section index] cache mapping.
1497 std::map<SymbolRef, SymInfo> AddrCache;
1498 for (const RelocationRef &Reloc : Section.relocations()) {
1499 // FIXME: it's not clear how to correctly handle scattered
1500 // relocations.
1501 if (isRelocScattered(Obj, Reloc))
1502 continue;
1503
1504 Expected<SymInfo> SymInfoOrErr =
1505 getSymbolInfo(Obj, Reloc, L, AddrCache);
1506 if (!SymInfoOrErr) {
1507 if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1508 return;
1509 continue;
1510 }
1511
1512 object::RelocVisitor V(Obj);
1513 uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1514 if (V.error()) {
1515 SmallString<32> Type;
1516 Reloc.getTypeName(Type);
1517 ErrorPolicy EP = HandleError(
1518 createError("failed to compute relocation: " + Type + ", ",
1519 errorCodeToError(object_error::parse_failed)));
1520 if (EP == ErrorPolicy::Halt)
1521 return;
1522 continue;
1523 }
1524 RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1525 Map->insert({Reloc.getOffset(), Rel});
1526 }
Eric Christopher7370b552012-11-12 21:40:38 +00001527 }
George Rimare1c30f72017-08-15 15:54:43 +00001528
1529 for (SectionName &S : SectionNames)
1530 if (SectionAmountMap[S.Name] > 1)
1531 S.IsNameUnique = false;
Eric Christopher7370b552012-11-12 21:40:38 +00001532 }
Eric Christopher7370b552012-11-12 21:40:38 +00001533
Rafael Espindolac398e672017-07-19 22:27:28 +00001534 Optional<RelocAddrEntry> find(const DWARFSection &S,
1535 uint64_t Pos) const override {
1536 auto &Sec = static_cast<const DWARFSectionMap &>(S);
1537 RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1538 if (AI == Sec.Relocs.end())
1539 return None;
1540 return AI->second;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001541 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001542
George Rimar6957ab52017-08-15 12:32:54 +00001543 const object::ObjectFile *getFile() const override { return Obj; }
1544
George Rimare1c30f72017-08-15 15:54:43 +00001545 ArrayRef<SectionName> getSectionNames() const override {
1546 return SectionNames;
1547 }
1548
Rafael Espindolac398e672017-07-19 22:27:28 +00001549 bool isLittleEndian() const override { return IsLittleEndian; }
1550 StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1551 const DWARFSection &getLineDWOSection() const override {
1552 return LineDWOSection;
1553 }
1554 const DWARFSection &getLocDWOSection() const override {
1555 return LocDWOSection;
1556 }
1557 StringRef getStringDWOSection() const override { return StringDWOSection; }
1558 const DWARFSection &getStringOffsetDWOSection() const override {
1559 return StringOffsetDWOSection;
1560 }
1561 const DWARFSection &getRangeDWOSection() const override {
1562 return RangeDWOSection;
1563 }
Wolfgang Piebad605592018-05-18 20:12:54 +00001564 const DWARFSection &getRnglistsDWOSection() const override {
1565 return RnglistsDWOSection;
1566 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001567 const DWARFSection &getAddrSection() const override { return AddrSection; }
1568 StringRef getCUIndexSection() const override { return CUIndexSection; }
1569 StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1570 StringRef getTUIndexSection() const override { return TUIndexSection; }
1571
1572 // DWARF v5
1573 const DWARFSection &getStringOffsetSection() const override {
1574 return StringOffsetSection;
1575 }
Paul Robinsonb6aa01c2018-01-25 22:02:36 +00001576 StringRef getLineStringSection() const override { return LineStringSection; }
Rafael Espindolac398e672017-07-19 22:27:28 +00001577
1578 // Sections for DWARF5 split dwarf proposal.
Paul Robinson746c22382018-11-07 21:39:09 +00001579 void forEachInfoDWOSections(
1580 function_ref<void(const DWARFSection &)> F) const override {
1581 for (auto &P : InfoDWOSections)
1582 F(P.second);
Rafael Espindolac398e672017-07-19 22:27:28 +00001583 }
1584 void forEachTypesDWOSections(
1585 function_ref<void(const DWARFSection &)> F) const override {
1586 for (auto &P : TypesDWOSections)
1587 F(P.second);
1588 }
1589
1590 StringRef getAbbrevSection() const override { return AbbrevSection; }
1591 const DWARFSection &getLocSection() const override { return LocSection; }
George Rimar4c7dd9c2018-10-22 11:30:54 +00001592 const DWARFSection &getLoclistsSection() const override { return LocListsSection; }
Rafael Espindolac398e672017-07-19 22:27:28 +00001593 StringRef getARangeSection() const override { return ARangeSection; }
1594 StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1595 StringRef getEHFrameSection() const override { return EHFrameSection; }
1596 const DWARFSection &getLineSection() const override { return LineSection; }
1597 StringRef getStringSection() const override { return StringSection; }
1598 const DWARFSection &getRangeSection() const override { return RangeSection; }
James Henderson3fcc7452018-02-02 12:35:52 +00001599 const DWARFSection &getRnglistsSection() const override {
1600 return RnglistsSection;
1601 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001602 StringRef getMacinfoSection() const override { return MacinfoSection; }
Fangrui Song158b2622018-11-11 18:57:28 +00001603 const DWARFSection &getPubNamesSection() const override { return PubNamesSection; }
1604 const DWARFSection &getPubTypesSection() const override { return PubTypesSection; }
1605 const DWARFSection &getGnuPubNamesSection() const override {
Rafael Espindolac398e672017-07-19 22:27:28 +00001606 return GnuPubNamesSection;
1607 }
Fangrui Song158b2622018-11-11 18:57:28 +00001608 const DWARFSection &getGnuPubTypesSection() const override {
Rafael Espindolac398e672017-07-19 22:27:28 +00001609 return GnuPubTypesSection;
1610 }
1611 const DWARFSection &getAppleNamesSection() const override {
1612 return AppleNamesSection;
1613 }
1614 const DWARFSection &getAppleTypesSection() const override {
1615 return AppleTypesSection;
1616 }
1617 const DWARFSection &getAppleNamespacesSection() const override {
1618 return AppleNamespacesSection;
1619 }
1620 const DWARFSection &getAppleObjCSection() const override {
1621 return AppleObjCSection;
1622 }
Pavel Labath3c9a9182018-01-29 11:08:32 +00001623 const DWARFSection &getDebugNamesSection() const override {
1624 return DebugNamesSection;
1625 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001626
1627 StringRef getFileName() const override { return FileName; }
1628 uint8_t getAddressSize() const override { return AddressSize; }
Paul Robinson746c22382018-11-07 21:39:09 +00001629 void forEachInfoSections(
1630 function_ref<void(const DWARFSection &)> F) const override {
1631 for (auto &P : InfoSections)
1632 F(P.second);
1633 }
Rafael Espindolac398e672017-07-19 22:27:28 +00001634 void forEachTypesSections(
1635 function_ref<void(const DWARFSection &)> F) const override {
1636 for (auto &P : TypesSections)
1637 F(P.second);
1638 }
1639};
Benjamin Kramer49a49fe2017-08-20 13:03:48 +00001640} // namespace
Rafael Espindolac398e672017-07-19 22:27:28 +00001641
1642std::unique_ptr<DWARFContext>
1643DWARFContext::create(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
David Blaikiee5adb682017-07-30 01:34:08 +00001644 function_ref<ErrorPolicy(Error)> HandleError,
1645 std::string DWPName) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001646 auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
Luke Cheesemand6dbd642018-11-23 11:01:47 +00001647 std::unique_ptr<DWARFContext> Ctx =
1648 llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
1649 logAllUnhandledErrors(Ctx->loadArchitectureInfo(Obj), errs(),
1650 Obj.getFileName() + ": ");
1651 return Ctx;
Chris Bieneman2e752db2017-01-20 19:03:14 +00001652}
1653
Rafael Espindolac398e672017-07-19 22:27:28 +00001654std::unique_ptr<DWARFContext>
1655DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1656 uint8_t AddrSize, bool isLittleEndian) {
Reid Kleckner388f8802017-07-19 23:42:53 +00001657 auto DObj =
1658 llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
David Blaikiee5adb682017-07-30 01:34:08 +00001659 return llvm::make_unique<DWARFContext>(std::move(DObj), "");
Rafael Espindola77e87b32017-07-07 05:36:53 +00001660}
Reid Klecknera0587362017-08-29 21:41:21 +00001661
Luke Cheesemand6dbd642018-11-23 11:01:47 +00001662Error DWARFContext::loadArchitectureInfo(const object::ObjectFile &Obj) {
Reid Klecknera0587362017-08-29 21:41:21 +00001663 // Detect the architecture from the object file. We usually don't need OS
1664 // info to lookup a target and create register info.
Luke Cheesemand6dbd642018-11-23 11:01:47 +00001665 Arch = Triple::ArchType(Obj.getArch());
1666
Reid Klecknera0587362017-08-29 21:41:21 +00001667 Triple TT;
1668 TT.setArch(Triple::ArchType(Obj.getArch()));
1669 TT.setVendor(Triple::UnknownVendor);
1670 TT.setOS(Triple::UnknownOS);
1671 std::string TargetLookupError;
1672 const Target *TheTarget =
1673 TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1674 if (!TargetLookupError.empty())
Victor Leschukcba595d2018-08-20 09:59:08 +00001675 return createStringError(errc::invalid_argument,
1676 TargetLookupError.c_str());
Reid Klecknera0587362017-08-29 21:41:21 +00001677 RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1678 return Error::success();
1679}
Victor Leschuk58d33992018-07-31 22:19:19 +00001680
1681uint8_t DWARFContext::getCUAddrSize() {
1682 // In theory, different compile units may have different address byte
1683 // sizes, but for simplicity we just use the address byte size of the
1684 // last compile unit. In practice the address size field is repeated across
1685 // various DWARF headers (at least in version 5) to make it easier to dump
1686 // them independently, not to enable varying the address size.
1687 uint8_t Addr = 0;
1688 for (const auto &CU : compile_units()) {
1689 Addr = CU->getAddressByteSize();
1690 break;
1691 }
1692 return Addr;
1693}
Victor Leschukcf1f7142018-08-23 12:43:33 +00001694
1695void DWARFContext::dumpWarning(Error Warning) {
1696 handleAllErrors(std::move(Warning), [](ErrorInfoBase &Info) {
1697 WithColor::warning() << Info.message() << '\n';
1698 });
1699}