blob: e3fa5c3d74132ee2cf7b8abfaaf4b195ec2ee96b [file] [log] [blame]
Eric Christopher3680f882012-10-16 23:46:21 +00001//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===//
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//
10// This program is a utility that works like "dwarfdump".
11//
12//===----------------------------------------------------------------------===//
13
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000014#include "llvm/ADT/STLExtras.h"
Adrian Prantl61913a12017-09-30 00:22:25 +000015#include "llvm/ADT/StringSet.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000016#include "llvm/ADT/Triple.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000017#include "llvm/DebugInfo/DIContext.h"
18#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Adrian Prantl5fd3d492017-09-14 17:01:53 +000019#include "llvm/Object/Archive.h"
Frederic Riss4c5d3572015-08-03 00:10:31 +000020#include "llvm/Object/MachOUniversal.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000021#include "llvm/Object/ObjectFile.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000022#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
24#include "llvm/Support/Format.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000025#include "llvm/Support/InitLLVM.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000026#include "llvm/Support/MemoryBuffer.h"
Adrian Prantl8e7d3b92015-12-23 21:51:13 +000027#include "llvm/Support/Path.h"
Adrian Prantle5b93f22017-10-03 22:08:22 +000028#include "llvm/Support/Regex.h"
Reid Klecknera0587362017-08-29 21:41:21 +000029#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +000030#include "llvm/Support/ToolOutputFile.h"
Jonas Devlieghere27126f52018-05-24 11:36:57 +000031#include "llvm/Support/WithColor.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000032#include "llvm/Support/raw_ostream.h"
Eric Christopher7c678de2012-11-07 23:22:07 +000033
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000034using namespace llvm;
35using namespace object;
36
Adrian Prantl057d3362017-09-15 23:04:04 +000037/// Parser for options that take an optional offest argument.
38/// @{
39struct OffsetOption {
40 uint64_t Val = 0;
41 bool HasValue = false;
42 bool IsRequested = false;
43};
44
45namespace llvm {
46namespace cl {
47template <>
48class parser<OffsetOption> final : public basic_parser<OffsetOption> {
49public:
50 parser(Option &O) : basic_parser(O) {}
51
52 /// Return true on error.
53 bool parse(Option &O, StringRef ArgName, StringRef Arg, OffsetOption &Val) {
54 if (Arg == "") {
55 Val.Val = 0;
56 Val.HasValue = false;
57 Val.IsRequested = true;
58 return false;
59 }
60 if (Arg.getAsInteger(0, Val.Val))
61 return O.error("'" + Arg + "' value invalid for integer argument!");
62 Val.HasValue = true;
63 Val.IsRequested = true;
64 return false;
65 }
66
67 enum ValueExpected getValueExpectedFlagDefault() const {
68 return ValueOptional;
69 }
70
71 void printOptionInfo(const Option &O, size_t GlobalWidth) const {
72 outs() << " -" << O.ArgStr;
73 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
74 }
75
76 void printOptionDiff(const Option &O, OffsetOption V, OptVal Default,
77 size_t GlobalWidth) const {
78 printOptionName(O, GlobalWidth);
79 outs() << "[=offset]";
80 }
81
82 // An out-of-line virtual method to provide a 'home' for this class.
83 void anchor() override {};
84};
85} // cl
86} // llvm
87
88/// @}
89/// Command line options.
90/// @{
91
Adrian Prantl7c5b45d2017-09-12 22:32:53 +000092namespace {
Adrian Prantl057d3362017-09-15 23:04:04 +000093using namespace cl;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000094
Adrian Prantl7c5b45d2017-09-12 22:32:53 +000095OptionCategory DwarfDumpCategory("Specific Options");
96static opt<bool> Help("h", desc("Alias for -help"), Hidden,
97 cat(DwarfDumpCategory));
98static list<std::string>
99 InputFilenames(Positional, desc("<input object files or .dSYM bundles>"),
100 ZeroOrMore, cat(DwarfDumpCategory));
101
Adrian Prantl057d3362017-09-15 23:04:04 +0000102cl::OptionCategory SectionCategory("Section-specific Dump Options",
103 "These control which sections are dumped. "
104 "Where applicable these parameters take an "
105 "optional =<offset> argument to dump only "
106 "the entry at the specified offset.");
107
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000108static opt<bool> DumpAll("all", desc("Dump all debug info sections"),
109 cat(SectionCategory));
110static alias DumpAllAlias("a", desc("Alias for -all"), aliasopt(DumpAll));
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000111
Adrian Prantl057d3362017-09-15 23:04:04 +0000112// Options for dumping specific sections.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000113static unsigned DumpType = DIDT_Null;
Adrian Prantlccc21c42017-09-19 20:58:57 +0000114static std::array<llvm::Optional<uint64_t>, (unsigned)DIDT_ID_Count>
115 DumpOffsets;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000116#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \
Adrian Prantl057d3362017-09-15 23:04:04 +0000117 static opt<OffsetOption> Dump##ENUM_NAME( \
118 CMDLINE_NAME, desc("Dump the " ELF_NAME " section"), \
119 cat(SectionCategory));
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000120#include "llvm/BinaryFormat/Dwarf.def"
121#undef HANDLE_DWARF_SECTION
Adrian Prantl057d3362017-09-15 23:04:04 +0000122
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000123static alias DumpDebugFrameAlias("eh-frame", desc("Alias for -debug-frame"),
Adrian Prantl31819b32017-09-20 23:29:31 +0000124 NotHidden, cat(SectionCategory),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000125 aliasopt(DumpDebugFrame));
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000126static list<std::string>
127 ArchFilters("arch",
128 desc("Dump debug information for the specified CPU "
129 "architecture only. Architectures may be specified by "
130 "name or by number. This option can be specified "
131 "multiple times, once for each desired architecture."),
132 cat(DwarfDumpCategory));
Adrian Prantl01fb31c2017-12-08 23:32:47 +0000133static opt<bool>
134 Diff("diff",
135 desc("Emit diff-friendly output by omitting offsets and addresses."),
136 cat(DwarfDumpCategory));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000137static list<std::string>
138 Find("find",
139 desc("Search for the exact match for <name> in the accelerator tables "
Adrian Prantl17d0bb92017-09-30 00:31:15 +0000140 "and print the matching debug information entries. When no "
141 "accelerator tables are available, the slower but more complete "
142 "-name option can be used instead."),
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000143 value_desc("name"), cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000144static alias FindAlias("f", desc("Alias for -find."), aliasopt(Find));
Adrian Prantl46e006c2017-10-02 21:21:09 +0000145static opt<bool>
146 IgnoreCase("ignore-case",
147 desc("Ignore case distinctions in when searching by name."),
148 value_desc("i"), cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000149static alias IgnoreCaseAlias("i", desc("Alias for -ignore-case."),
Adrian Prantl46e006c2017-10-02 21:21:09 +0000150 aliasopt(IgnoreCase));
Adrian Prantle5b93f22017-10-03 22:08:22 +0000151static list<std::string> Name(
152 "name",
153 desc("Find and print all debug info entries whose name (DW_AT_name "
154 "attribute) matches the exact text in <pattern>. When used with the "
155 "the -regex option <pattern> is interpreted as a regular expression."),
156 value_desc("pattern"), cat(DwarfDumpCategory));
Adrian Prantl61913a12017-09-30 00:22:25 +0000157static alias NameAlias("n", desc("Alias for -name"), aliasopt(Name));
Jonas Devlieghereefb06382017-12-19 09:45:26 +0000158static opt<unsigned long long> Lookup("lookup",
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000159 desc("Lookup <address> in the debug information and print out any"
160 "available file, function, block and line table details."),
161 value_desc("address"), cat(DwarfDumpCategory));
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000162static opt<std::string>
163 OutputFilename("out-file", cl::init(""),
Adrian Prantl214babe2017-10-06 20:24:35 +0000164 cl::desc("Redirect output to the specified file."),
Hans Wennborgab2177e2017-10-03 18:39:13 +0000165 cl::value_desc("filename"));
Adrian Prantl214babe2017-10-06 20:24:35 +0000166static alias OutputFilenameAlias("o", desc("Alias for -out-file."),
Hans Wennborgab2177e2017-10-03 18:39:13 +0000167 aliasopt(OutputFilename),
168 cat(DwarfDumpCategory));
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000169static opt<bool>
Adrian Prantle5b93f22017-10-03 22:08:22 +0000170 UseRegex("regex",
171 desc("Treat any <pattern> strings as regular expressions when "
172 "searching instead of just as an exact string match."),
173 cat(DwarfDumpCategory));
174static alias RegexAlias("x", desc("Alias for -regex"), aliasopt(UseRegex));
175static opt<bool>
Adrian Prantl597aa482017-09-16 17:28:00 +0000176 ShowChildren("show-children",
177 desc("Show a debug info entry's children when selectively "
Adrian Prantl214babe2017-10-06 20:24:35 +0000178 "printing with the =<offset> option."),
Adrian Prantlccc21c42017-09-19 20:58:57 +0000179 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000180static alias ShowChildrenAlias("c", desc("Alias for -show-children."),
Adrian Prantl597aa482017-09-16 17:28:00 +0000181 aliasopt(ShowChildren));
182static opt<bool>
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000183 ShowParents("show-parents",
184 desc("Show a debug info entry's parents when selectively "
Adrian Prantl214babe2017-10-06 20:24:35 +0000185 "printing with the =<offset> option."),
Adrian Prantlccc21c42017-09-19 20:58:57 +0000186 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000187static alias ShowParentsAlias("p", desc("Alias for -show-parents."),
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000188 aliasopt(ShowParents));
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000189static opt<bool>
190 ShowForm("show-form",
191 desc("Show DWARF form types after the DWARF attribute types."),
192 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000193static alias ShowFormAlias("F", desc("Alias for -show-form."),
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000194 aliasopt(ShowForm), cat(DwarfDumpCategory));
Adrian Prantld3f9f212017-09-20 17:44:00 +0000195static opt<unsigned> RecurseDepth(
196 "recurse-depth",
197 desc("Only recurse to a depth of N when displaying debug info entries."),
198 cat(DwarfDumpCategory), init(-1U), value_desc("N"));
Adrian Prantl214babe2017-10-06 20:24:35 +0000199static alias RecurseDepthAlias("r", desc("Alias for -recurse-depth."),
Adrian Prantld3f9f212017-09-20 17:44:00 +0000200 aliasopt(RecurseDepth));
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000201
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000202static opt<bool>
David Blaikie50cc27e2016-10-18 21:09:48 +0000203 SummarizeTypes("summarize-types",
Adrian Prantl214babe2017-10-06 20:24:35 +0000204 desc("Abbreviate the description of type unit entries."),
Adrian Prantlccc21c42017-09-19 20:58:57 +0000205 cat(DwarfDumpCategory));
Adrian Prantl59f30b82017-10-06 20:24:34 +0000206static cl::opt<bool>
207 Statistics("statistics",
208 cl::desc("Emit JSON-formatted debug info quality metrics."),
209 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000210static opt<bool> Verify("verify", desc("Verify the DWARF debug info."),
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000211 cat(DwarfDumpCategory));
212static opt<bool> Quiet("quiet", desc("Use with -verify to not emit to STDOUT."),
213 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000214static opt<bool> DumpUUID("uuid", desc("Show the UUID for each architecture."),
Adrian Prantl61913a12017-09-30 00:22:25 +0000215 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000216static alias DumpUUIDAlias("u", desc("Alias for -uuid."), aliasopt(DumpUUID));
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000217static opt<bool> Verbose("verbose",
Adrian Prantl214babe2017-10-06 20:24:35 +0000218 desc("Print more low-level encoding details."),
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000219 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000220static alias VerboseAlias("v", desc("Alias for -verbose."), aliasopt(Verbose),
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000221 cat(DwarfDumpCategory));
222} // namespace
Adrian Prantl057d3362017-09-15 23:04:04 +0000223/// @}
224//===----------------------------------------------------------------------===//
225
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000226static void error(StringRef Prefix, std::error_code EC) {
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000227 if (!EC)
Davide Italiano4376ddb2015-07-26 05:35:59 +0000228 return;
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000229 errs() << Prefix << ": " << EC.message() << "\n";
Davide Italiano4376ddb2015-07-26 05:35:59 +0000230 exit(1);
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000231}
232
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000233static DIDumpOptions getDumpOpts() {
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000234 DIDumpOptions DumpOpts;
235 DumpOpts.DumpType = DumpType;
Adrian Prantld3f9f212017-09-20 17:44:00 +0000236 DumpOpts.RecurseDepth = RecurseDepth;
Adrian Prantl01fb31c2017-12-08 23:32:47 +0000237 DumpOpts.ShowAddresses = !Diff;
Adrian Prantl597aa482017-09-16 17:28:00 +0000238 DumpOpts.ShowChildren = ShowChildren;
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000239 DumpOpts.ShowParents = ShowParents;
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000240 DumpOpts.ShowForm = ShowForm;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000241 DumpOpts.SummarizeTypes = SummarizeTypes;
242 DumpOpts.Verbose = Verbose;
Adrian Prantld3f9f212017-09-20 17:44:00 +0000243 // In -verify mode, print DIEs without children in error messages.
244 if (Verify)
245 return DumpOpts.noImplicitRecursion();
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000246 return DumpOpts;
247}
248
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000249static uint32_t getCPUType(MachOObjectFile &MachO) {
250 if (MachO.is64Bit())
251 return MachO.getHeader64().cputype;
252 else
253 return MachO.getHeader().cputype;
254}
255
256/// Return true if the object file has not been filtered by an --arch option.
257static bool filterArch(ObjectFile &Obj) {
258 if (ArchFilters.empty())
259 return true;
Adrian Prantlfa163612017-09-30 00:22:21 +0000260
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000261 if (auto *MachO = dyn_cast<MachOObjectFile>(&Obj)) {
262 std::string ObjArch =
263 Triple::getArchTypeName(MachO->getArchTriple().getArch());
Adrian Prantlfa163612017-09-30 00:22:21 +0000264
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000265 for (auto Arch : ArchFilters) {
Adrian Prantlfa163612017-09-30 00:22:21 +0000266 // Match name.
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000267 if (Arch == ObjArch)
268 return true;
Adrian Prantlfa163612017-09-30 00:22:21 +0000269
270 // Match architecture number.
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000271 unsigned Value;
272 if (!StringRef(Arch).getAsInteger(0, Value))
273 if (Value == getCPUType(*MachO))
274 return true;
275 }
276 }
277 return false;
278}
279
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000280using HandlerFn = std::function<bool(ObjectFile &, DWARFContext &DICtx, Twine,
281 raw_ostream &)>;
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000282
Adrian Prantl61913a12017-09-30 00:22:25 +0000283/// Print only DIEs that have a certain name.
284static void filterByName(const StringSet<> &Names,
Paul Robinson96545db2018-08-02 19:29:38 +0000285 DWARFContext::unit_iterator_range CUs,
286 raw_ostream &OS) {
Adrian Prantl61913a12017-09-30 00:22:25 +0000287 for (const auto &CU : CUs)
288 for (const auto &Entry : CU->dies()) {
289 DWARFDie Die = {CU.get(), &Entry};
Adrian Prantl46e006c2017-10-02 21:21:09 +0000290 if (const char *NamePtr = Die.getName(DINameKind::ShortName)) {
Adrian Prantle5b93f22017-10-03 22:08:22 +0000291 std::string Name =
292 (IgnoreCase && !UseRegex) ? StringRef(NamePtr).lower() : NamePtr;
293 // Match regular expression.
294 if (UseRegex)
295 for (auto Pattern : Names.keys()) {
296 Regex RE(Pattern, IgnoreCase ? Regex::IgnoreCase : Regex::NoFlags);
297 std::string Error;
298 if (!RE.isValid(Error)) {
299 errs() << "error in regular expression: " << Error << "\n";
300 exit(1);
301 }
302 if (RE.match(Name))
303 Die.dump(OS, 0, getDumpOpts());
304 }
305 // Match full text.
306 else if (Names.count(Name))
Adrian Prantl46e006c2017-10-02 21:21:09 +0000307 Die.dump(OS, 0, getDumpOpts());
308 }
Adrian Prantl61913a12017-09-30 00:22:25 +0000309 }
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000310}
311
Pavel Labath4adc88e2018-06-13 08:14:27 +0000312static void getDies(DWARFContext &DICtx, const AppleAcceleratorTable &Accel,
313 StringRef Name, SmallVectorImpl<DWARFDie> &Dies) {
314 for (const auto &Entry : Accel.equal_range(Name)) {
315 if (llvm::Optional<uint64_t> Off = Entry.getDIESectionOffset()) {
316 if (DWARFDie Die = DICtx.getDIEForOffset(*Off))
317 Dies.push_back(Die);
318 }
319 }
320}
321
322static DWARFDie toDie(const DWARFDebugNames::Entry &Entry,
323 DWARFContext &DICtx) {
324 llvm::Optional<uint64_t> CUOff = Entry.getCUOffset();
325 llvm::Optional<uint64_t> Off = Entry.getDIEUnitOffset();
326 if (!CUOff || !Off)
327 return DWARFDie();
328
329 DWARFCompileUnit *CU = DICtx.getCompileUnitForOffset(*CUOff);
330 if (!CU)
331 return DWARFDie();
332
Pavel Labath4b896eb2018-06-13 08:29:19 +0000333 if (llvm::Optional<uint64_t> DWOId = CU->getDWOId()) {
Pavel Labath4adc88e2018-06-13 08:14:27 +0000334 // This is a skeleton unit. Look up the DIE in the DWO unit.
335 CU = DICtx.getDWOCompileUnitForHash(*DWOId);
336 if (!CU)
337 return DWARFDie();
338 }
339
340 return CU->getDIEForOffset(CU->getOffset() + *Off);
341}
342
343static void getDies(DWARFContext &DICtx, const DWARFDebugNames &Accel,
344 StringRef Name, SmallVectorImpl<DWARFDie> &Dies) {
345 for (const auto &Entry : Accel.equal_range(Name)) {
346 if (DWARFDie Die = toDie(Entry, DICtx))
347 Dies.push_back(Die);
348 }
Pavel Labath59870af2018-05-31 08:47:00 +0000349}
350
351/// Print only DIEs that have a certain name.
352static void filterByAccelName(ArrayRef<std::string> Names, DWARFContext &DICtx,
353 raw_ostream &OS) {
Pavel Labath4adc88e2018-06-13 08:14:27 +0000354 SmallVector<DWARFDie, 4> Dies;
Pavel Labath59870af2018-05-31 08:47:00 +0000355 for (const auto &Name : Names) {
Pavel Labath4adc88e2018-06-13 08:14:27 +0000356 getDies(DICtx, DICtx.getAppleNames(), Name, Dies);
357 getDies(DICtx, DICtx.getAppleTypes(), Name, Dies);
358 getDies(DICtx, DICtx.getAppleNamespaces(), Name, Dies);
359 getDies(DICtx, DICtx.getDebugNames(), Name, Dies);
Pavel Labath59870af2018-05-31 08:47:00 +0000360 }
Pavel Labath4adc88e2018-06-13 08:14:27 +0000361 llvm::sort(Dies.begin(), Dies.end());
362 Dies.erase(std::unique(Dies.begin(), Dies.end()), Dies.end());
Pavel Labath59870af2018-05-31 08:47:00 +0000363
Pavel Labath4adc88e2018-06-13 08:14:27 +0000364 for (DWARFDie Die : Dies)
Pavel Labath59870af2018-05-31 08:47:00 +0000365 Die.dump(OS, 0, getDumpOpts());
Pavel Labath59870af2018-05-31 08:47:00 +0000366}
367
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000368/// Handle the --lookup option and dump the DIEs and line info for the given
369/// address.
370static bool lookup(DWARFContext &DICtx, uint64_t Address, raw_ostream &OS) {
371 auto DIEsForAddr = DICtx.getDIEsForAddress(Lookup);
372
373 if (!DIEsForAddr)
374 return false;
375
376 DIDumpOptions DumpOpts = getDumpOpts();
377 DumpOpts.RecurseDepth = 0;
378 DIEsForAddr.CompileUnit->dump(OS, DumpOpts);
379 if (DIEsForAddr.FunctionDIE) {
380 DIEsForAddr.FunctionDIE.dump(OS, 2, DumpOpts);
381 if (DIEsForAddr.BlockDIE)
382 DIEsForAddr.BlockDIE.dump(OS, 4, DumpOpts);
383 }
384
385 if (DILineInfo LineInfo = DICtx.getLineInfoForAddress(Lookup))
386 LineInfo.dump(OS);
387
388 return true;
Adrian Prantl61913a12017-09-30 00:22:25 +0000389}
390
Adrian Prantl59f30b82017-10-06 20:24:34 +0000391bool collectStatsForObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
392 Twine Filename, raw_ostream &OS);
393
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000394static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx, Twine Filename,
395 raw_ostream &OS) {
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000396 logAllUnhandledErrors(DICtx.loadRegisterInfo(Obj), errs(),
Reid Klecknera0587362017-08-29 21:41:21 +0000397 Filename.str() + ": ");
Adrian Prantl61913a12017-09-30 00:22:25 +0000398 // The UUID dump already contains all the same information.
399 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All)
400 OS << Filename << ":\tfile format " << Obj.getFileFormatName() << '\n';
401
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000402 // Handle the --lookup option.
403 if (Lookup)
404 return lookup(DICtx, Lookup, OS);
405
Adrian Prantl61913a12017-09-30 00:22:25 +0000406 // Handle the --name option.
407 if (!Name.empty()) {
408 StringSet<> Names;
409 for (auto name : Name)
Adrian Prantle5b93f22017-10-03 22:08:22 +0000410 Names.insert((IgnoreCase && !UseRegex) ? StringRef(name).lower() : name);
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000411
Adrian Prantl61913a12017-09-30 00:22:25 +0000412 filterByName(Names, DICtx.compile_units(), OS);
413 filterByName(Names, DICtx.dwo_compile_units(), OS);
414 return true;
415 }
416
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000417 // Handle the --find option and lower it to --debug-info=<offset>.
418 if (!Find.empty()) {
Pavel Labath59870af2018-05-31 08:47:00 +0000419 filterByAccelName(Find, DICtx, OS);
420 return true;
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000421 }
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000422
Frederic Riss40c017932015-08-03 00:10:25 +0000423 // Dump the complete DWARF structure.
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000424 DICtx.dump(OS, getDumpOpts(), DumpOffsets);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000425 return true;
Frederic Riss40c017932015-08-03 00:10:25 +0000426}
427
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000428static bool verifyObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000429 Twine Filename, raw_ostream &OS) {
Greg Clayton48432cf2017-05-01 22:07:02 +0000430 // Verify the DWARF and exit with non-zero exit status if verification
431 // fails.
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000432 raw_ostream &stream = Quiet ? nulls() : OS;
Greg Clayton48432cf2017-05-01 22:07:02 +0000433 stream << "Verifying " << Filename.str() << ":\tfile format "
434 << Obj.getFileFormatName() << "\n";
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000435 bool Result = DICtx.verify(stream, getDumpOpts());
Greg Clayton48432cf2017-05-01 22:07:02 +0000436 if (Result)
437 stream << "No errors.\n";
438 else
439 stream << "Errors detected.\n";
440 return Result;
441}
442
Adrian Prantld866b472017-09-13 23:16:13 +0000443static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000444 HandlerFn HandleObj, raw_ostream &OS);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000445
446static bool handleArchive(StringRef Filename, Archive &Arch,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000447 HandlerFn HandleObj, raw_ostream &OS) {
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000448 bool Result = true;
449 Error Err = Error::success();
450 for (auto Child : Arch.children(Err)) {
451 auto BuffOrErr = Child.getMemoryBufferRef();
452 error(Filename, errorToErrorCode(BuffOrErr.takeError()));
453 auto NameOrErr = Child.getName();
454 error(Filename, errorToErrorCode(NameOrErr.takeError()));
455 std::string Name = (Filename + "(" + NameOrErr.get() + ")").str();
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000456 Result &= handleBuffer(Name, BuffOrErr.get(), HandleObj, OS);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000457 }
458 error(Filename, errorToErrorCode(std::move(Err)));
459
460 return Result;
461}
462
463static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000464 HandlerFn HandleObj, raw_ostream &OS) {
Adrian Prantld866b472017-09-13 23:16:13 +0000465 Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buffer);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000466 error(Filename, errorToErrorCode(BinOrErr.takeError()));
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000467
Greg Clayton48432cf2017-05-01 22:07:02 +0000468 bool Result = true;
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000469 if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) {
470 if (filterArch(*Obj)) {
471 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(*Obj);
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000472 Result = HandleObj(*Obj, *DICtx, Filename, OS);
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000473 }
474 }
Greg Clayton48432cf2017-05-01 22:07:02 +0000475 else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get()))
476 for (auto &ObjForArch : Fat->objects()) {
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000477 std::string ObjName =
478 (Filename + "(" + ObjForArch.getArchFlagName() + ")").str();
479 if (auto MachOOrErr = ObjForArch.getAsObjectFile()) {
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000480 auto &Obj = **MachOOrErr;
481 if (filterArch(Obj)) {
482 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(Obj);
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000483 Result &= HandleObj(Obj, *DICtx, ObjName, OS);
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000484 }
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000485 continue;
486 } else
487 consumeError(MachOOrErr.takeError());
488 if (auto ArchiveOrErr = ObjForArch.getAsArchive()) {
489 error(ObjName, errorToErrorCode(ArchiveOrErr.takeError()));
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000490 Result &= handleArchive(ObjName, *ArchiveOrErr.get(), HandleObj, OS);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000491 continue;
492 } else
493 consumeError(ArchiveOrErr.takeError());
Greg Clayton48432cf2017-05-01 22:07:02 +0000494 }
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000495 else if (auto *Arch = dyn_cast<Archive>(BinOrErr->get()))
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000496 Result = handleArchive(Filename, *Arch, HandleObj, OS);
Greg Clayton48432cf2017-05-01 22:07:02 +0000497 return Result;
498}
499
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000500static bool handleFile(StringRef Filename, HandlerFn HandleObj,
501 raw_ostream &OS) {
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000502 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
503 MemoryBuffer::getFileOrSTDIN(Filename);
504 error(Filename, BuffOrErr.getError());
505 std::unique_ptr<MemoryBuffer> Buffer = std::move(BuffOrErr.get());
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000506 return handleBuffer(Filename, *Buffer, HandleObj, OS);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000507}
508
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000509/// If the input path is a .dSYM bundle (as created by the dsymutil tool),
510/// replace it with individual entries for each of the object files inside the
511/// bundle otherwise return the input path.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000512static std::vector<std::string> expandBundle(const std::string &InputPath) {
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000513 std::vector<std::string> BundlePaths;
514 SmallString<256> BundlePath(InputPath);
Jonas Devliegherefba754a2018-02-08 16:31:01 +0000515 // Normalize input path. This is necessary to accept `bundle.dSYM/`.
516 sys::path::remove_dots(BundlePath);
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000517 // Manually open up the bundle to avoid introducing additional dependencies.
518 if (sys::fs::is_directory(BundlePath) &&
519 sys::path::extension(BundlePath) == ".dSYM") {
520 std::error_code EC;
521 sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
522 for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
523 Dir != DirEnd && !EC; Dir.increment(EC)) {
524 const std::string &Path = Dir->path();
525 sys::fs::file_status Status;
526 EC = sys::fs::status(Path, Status);
527 error(Path, EC);
528 switch (Status.type()) {
529 case sys::fs::file_type::regular_file:
530 case sys::fs::file_type::symlink_file:
531 case sys::fs::file_type::type_unknown:
532 BundlePaths.push_back(Path);
533 break;
534 default: /*ignore*/;
535 }
536 }
537 error(BundlePath, EC);
538 }
539 if (!BundlePaths.size())
540 BundlePaths.push_back(InputPath);
541 return BundlePaths;
542}
543
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000544int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000545 InitLLVM X(argc, argv);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000546
Reid Klecknera0587362017-08-29 21:41:21 +0000547 llvm::InitializeAllTargetInfos();
548 llvm::InitializeAllTargetMCs();
549
Jonas Devlieghere27126f52018-05-24 11:36:57 +0000550 HideUnrelatedOptions({&DwarfDumpCategory, &SectionCategory, &ColorCategory});
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000551 cl::ParseCommandLineOptions(
552 argc, argv,
553 "pretty-print DWARF debug information in object files"
554 " and debug info archives.\n");
555
556 if (Help) {
557 PrintHelpMessage(/*Hidden =*/false, /*Categorized =*/true);
558 return 0;
559 }
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000560
Reid Kleckner2590edf2017-09-23 01:04:42 +0000561 std::unique_ptr<ToolOutputFile> OutputFile;
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000562 if (!OutputFilename.empty()) {
563 std::error_code EC;
Reid Kleckner2590edf2017-09-23 01:04:42 +0000564 OutputFile = llvm::make_unique<ToolOutputFile>(OutputFilename, EC,
Jonas Devlieghere489604c2017-09-22 09:38:52 +0000565 sys::fs::F_None);
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000566 error("Unable to open output file" + OutputFilename, EC);
567 // Don't remove output file if we exit with an error.
568 OutputFile->keep();
569 }
570
571 raw_ostream &OS = OutputFile ? OutputFile->os() : outs();
Adrian Prantl5da51f42017-11-29 01:12:22 +0000572 bool OffsetRequested = false;
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000573
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000574 // Defaults to dumping all sections, unless brief mode is specified in which
575 // case only the .debug_info section in dumped.
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000576#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \
Adrian Prantl057d3362017-09-15 23:04:04 +0000577 if (Dump##ENUM_NAME.IsRequested) { \
578 DumpType |= DIDT_##ENUM_NAME; \
Adrian Prantl5da51f42017-11-29 01:12:22 +0000579 if (Dump##ENUM_NAME.HasValue) { \
Adrian Prantl057d3362017-09-15 23:04:04 +0000580 DumpOffsets[DIDT_ID_##ENUM_NAME] = Dump##ENUM_NAME.Val; \
Adrian Prantl5da51f42017-11-29 01:12:22 +0000581 OffsetRequested = true; \
582 } \
Adrian Prantl057d3362017-09-15 23:04:04 +0000583 }
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000584#include "llvm/BinaryFormat/Dwarf.def"
585#undef HANDLE_DWARF_SECTION
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000586 if (DumpUUID)
587 DumpType |= DIDT_UUID;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000588 if (DumpAll)
589 DumpType = DIDT_All;
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000590 if (DumpType == DIDT_Null) {
Adrian Prantl16aa4cf2017-09-11 23:05:20 +0000591 if (Verbose)
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000592 DumpType = DIDT_All;
Adrian Prantl16aa4cf2017-09-11 23:05:20 +0000593 else
594 DumpType = DIDT_DebugInfo;
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000595 }
596
Adrian Prantl5da51f42017-11-29 01:12:22 +0000597 // Unless dumping a specific DIE, default to --show-children.
598 if (!ShowChildren && !Verify && !OffsetRequested && Name.empty() && Find.empty())
599 ShowChildren = true;
600
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000601 // Defaults to a.out if no filenames specified.
Fangrui Songbd088562018-05-08 06:21:12 +0000602 if (InputFilenames.empty())
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000603 InputFilenames.push_back("a.out");
604
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000605 // Expand any .dSYM bundles to the individual object files contained therein.
606 std::vector<std::string> Objects;
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000607 for (const auto &F : InputFilenames) {
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000608 auto Objs = expandBundle(F);
609 Objects.insert(Objects.end(), Objs.begin(), Objs.end());
610 }
611
Greg Clayton48432cf2017-05-01 22:07:02 +0000612 if (Verify) {
613 // If we encountered errors during verify, exit with a non-zero exit status.
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000614 if (!std::all_of(Objects.begin(), Objects.end(), [&](std::string Object) {
615 return handleFile(Object, verifyObjectFile, OS);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000616 }))
Greg Clayton48432cf2017-05-01 22:07:02 +0000617 exit(1);
Adrian Prantl59f30b82017-10-06 20:24:34 +0000618 } else if (Statistics)
619 for (auto Object : Objects)
620 handleFile(Object, collectStatsForObjectFile, OS);
621 else
Adrian Prantlb8f08422017-09-18 22:11:33 +0000622 for (auto Object : Objects)
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000623 handleFile(Object, dumpObjectFile, OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000624
Davide Italiano4376ddb2015-07-26 05:35:59 +0000625 return EXIT_SUCCESS;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000626}