blob: 2a9af874d2254d311b12df735c251546090cf860 [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"
25#include "llvm/Support/ManagedStatic.h"
26#include "llvm/Support/MemoryBuffer.h"
Adrian Prantl8e7d3b92015-12-23 21:51:13 +000027#include "llvm/Support/Path.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000028#include "llvm/Support/PrettyStackTrace.h"
Adrian Prantle5b93f22017-10-03 22:08:22 +000029#include "llvm/Support/Regex.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000030#include "llvm/Support/Signals.h"
Reid Klecknera0587362017-08-29 21:41:21 +000031#include "llvm/Support/TargetSelect.h"
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +000032#include "llvm/Support/ToolOutputFile.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000033#include "llvm/Support/raw_ostream.h"
Eric Christopher7c678de2012-11-07 23:22:07 +000034
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000035using namespace llvm;
36using namespace object;
37
Adrian Prantl057d3362017-09-15 23:04:04 +000038/// Parser for options that take an optional offest argument.
39/// @{
40struct OffsetOption {
41 uint64_t Val = 0;
42 bool HasValue = false;
43 bool IsRequested = false;
44};
45
46namespace llvm {
47namespace cl {
48template <>
49class parser<OffsetOption> final : public basic_parser<OffsetOption> {
50public:
51 parser(Option &O) : basic_parser(O) {}
52
53 /// Return true on error.
54 bool parse(Option &O, StringRef ArgName, StringRef Arg, OffsetOption &Val) {
55 if (Arg == "") {
56 Val.Val = 0;
57 Val.HasValue = false;
58 Val.IsRequested = true;
59 return false;
60 }
61 if (Arg.getAsInteger(0, Val.Val))
62 return O.error("'" + Arg + "' value invalid for integer argument!");
63 Val.HasValue = true;
64 Val.IsRequested = true;
65 return false;
66 }
67
68 enum ValueExpected getValueExpectedFlagDefault() const {
69 return ValueOptional;
70 }
71
72 void printOptionInfo(const Option &O, size_t GlobalWidth) const {
73 outs() << " -" << O.ArgStr;
74 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
75 }
76
77 void printOptionDiff(const Option &O, OffsetOption V, OptVal Default,
78 size_t GlobalWidth) const {
79 printOptionName(O, GlobalWidth);
80 outs() << "[=offset]";
81 }
82
83 // An out-of-line virtual method to provide a 'home' for this class.
84 void anchor() override {};
85};
86} // cl
87} // llvm
88
89/// @}
90/// Command line options.
91/// @{
92
Adrian Prantl7c5b45d2017-09-12 22:32:53 +000093namespace {
Adrian Prantl057d3362017-09-15 23:04:04 +000094using namespace cl;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000095
Adrian Prantl7c5b45d2017-09-12 22:32:53 +000096OptionCategory DwarfDumpCategory("Specific Options");
97static opt<bool> Help("h", desc("Alias for -help"), Hidden,
98 cat(DwarfDumpCategory));
99static list<std::string>
100 InputFilenames(Positional, desc("<input object files or .dSYM bundles>"),
101 ZeroOrMore, cat(DwarfDumpCategory));
102
Adrian Prantl057d3362017-09-15 23:04:04 +0000103cl::OptionCategory SectionCategory("Section-specific Dump Options",
104 "These control which sections are dumped. "
105 "Where applicable these parameters take an "
106 "optional =<offset> argument to dump only "
107 "the entry at the specified offset.");
108
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000109static opt<bool> DumpAll("all", desc("Dump all debug info sections"),
110 cat(SectionCategory));
111static alias DumpAllAlias("a", desc("Alias for -all"), aliasopt(DumpAll));
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000112
Adrian Prantl057d3362017-09-15 23:04:04 +0000113// Options for dumping specific sections.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000114static unsigned DumpType = DIDT_Null;
Adrian Prantlccc21c42017-09-19 20:58:57 +0000115static std::array<llvm::Optional<uint64_t>, (unsigned)DIDT_ID_Count>
116 DumpOffsets;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000117#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \
Adrian Prantl057d3362017-09-15 23:04:04 +0000118 static opt<OffsetOption> Dump##ENUM_NAME( \
119 CMDLINE_NAME, desc("Dump the " ELF_NAME " section"), \
120 cat(SectionCategory));
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000121#include "llvm/BinaryFormat/Dwarf.def"
122#undef HANDLE_DWARF_SECTION
Adrian Prantl057d3362017-09-15 23:04:04 +0000123
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000124static alias DumpDebugFrameAlias("eh-frame", desc("Alias for -debug-frame"),
Adrian Prantl31819b32017-09-20 23:29:31 +0000125 NotHidden, cat(SectionCategory),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000126 aliasopt(DumpDebugFrame));
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000127static list<std::string>
128 ArchFilters("arch",
129 desc("Dump debug information for the specified CPU "
130 "architecture only. Architectures may be specified by "
131 "name or by number. This option can be specified "
132 "multiple times, once for each desired architecture."),
133 cat(DwarfDumpCategory));
Adrian Prantl01fb31c2017-12-08 23:32:47 +0000134static opt<bool>
135 Diff("diff",
136 desc("Emit diff-friendly output by omitting offsets and addresses."),
137 cat(DwarfDumpCategory));
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000138static list<std::string>
139 Find("find",
140 desc("Search for the exact match for <name> in the accelerator tables "
Adrian Prantl17d0bb92017-09-30 00:31:15 +0000141 "and print the matching debug information entries. When no "
142 "accelerator tables are available, the slower but more complete "
143 "-name option can be used instead."),
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000144 value_desc("name"), cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000145static alias FindAlias("f", desc("Alias for -find."), aliasopt(Find));
Adrian Prantl46e006c2017-10-02 21:21:09 +0000146static opt<bool>
147 IgnoreCase("ignore-case",
148 desc("Ignore case distinctions in when searching by name."),
149 value_desc("i"), cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000150static alias IgnoreCaseAlias("i", desc("Alias for -ignore-case."),
Adrian Prantl46e006c2017-10-02 21:21:09 +0000151 aliasopt(IgnoreCase));
Adrian Prantle5b93f22017-10-03 22:08:22 +0000152static list<std::string> Name(
153 "name",
154 desc("Find and print all debug info entries whose name (DW_AT_name "
155 "attribute) matches the exact text in <pattern>. When used with the "
156 "the -regex option <pattern> is interpreted as a regular expression."),
157 value_desc("pattern"), cat(DwarfDumpCategory));
Adrian Prantl61913a12017-09-30 00:22:25 +0000158static alias NameAlias("n", desc("Alias for -name"), aliasopt(Name));
Jonas Devlieghereefb06382017-12-19 09:45:26 +0000159static opt<unsigned long long> Lookup("lookup",
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000160 desc("Lookup <address> in the debug information and print out any"
161 "available file, function, block and line table details."),
162 value_desc("address"), cat(DwarfDumpCategory));
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000163static opt<std::string>
164 OutputFilename("out-file", cl::init(""),
Adrian Prantl214babe2017-10-06 20:24:35 +0000165 cl::desc("Redirect output to the specified file."),
Hans Wennborgab2177e2017-10-03 18:39:13 +0000166 cl::value_desc("filename"));
Adrian Prantl214babe2017-10-06 20:24:35 +0000167static alias OutputFilenameAlias("o", desc("Alias for -out-file."),
Hans Wennborgab2177e2017-10-03 18:39:13 +0000168 aliasopt(OutputFilename),
169 cat(DwarfDumpCategory));
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000170static opt<bool>
Adrian Prantle5b93f22017-10-03 22:08:22 +0000171 UseRegex("regex",
172 desc("Treat any <pattern> strings as regular expressions when "
173 "searching instead of just as an exact string match."),
174 cat(DwarfDumpCategory));
175static alias RegexAlias("x", desc("Alias for -regex"), aliasopt(UseRegex));
176static opt<bool>
Adrian Prantl597aa482017-09-16 17:28:00 +0000177 ShowChildren("show-children",
178 desc("Show a debug info entry's children when selectively "
Adrian Prantl214babe2017-10-06 20:24:35 +0000179 "printing with the =<offset> option."),
Adrian Prantlccc21c42017-09-19 20:58:57 +0000180 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000181static alias ShowChildrenAlias("c", desc("Alias for -show-children."),
Adrian Prantl597aa482017-09-16 17:28:00 +0000182 aliasopt(ShowChildren));
183static opt<bool>
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000184 ShowParents("show-parents",
185 desc("Show a debug info entry's parents when selectively "
Adrian Prantl214babe2017-10-06 20:24:35 +0000186 "printing with the =<offset> option."),
Adrian Prantlccc21c42017-09-19 20:58:57 +0000187 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000188static alias ShowParentsAlias("p", desc("Alias for -show-parents."),
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000189 aliasopt(ShowParents));
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000190static opt<bool>
191 ShowForm("show-form",
192 desc("Show DWARF form types after the DWARF attribute types."),
193 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000194static alias ShowFormAlias("F", desc("Alias for -show-form."),
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000195 aliasopt(ShowForm), cat(DwarfDumpCategory));
Adrian Prantld3f9f212017-09-20 17:44:00 +0000196static opt<unsigned> RecurseDepth(
197 "recurse-depth",
198 desc("Only recurse to a depth of N when displaying debug info entries."),
199 cat(DwarfDumpCategory), init(-1U), value_desc("N"));
Adrian Prantl214babe2017-10-06 20:24:35 +0000200static alias RecurseDepthAlias("r", desc("Alias for -recurse-depth."),
Adrian Prantld3f9f212017-09-20 17:44:00 +0000201 aliasopt(RecurseDepth));
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000202
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000203static opt<bool>
David Blaikie50cc27e2016-10-18 21:09:48 +0000204 SummarizeTypes("summarize-types",
Adrian Prantl214babe2017-10-06 20:24:35 +0000205 desc("Abbreviate the description of type unit entries."),
Adrian Prantlccc21c42017-09-19 20:58:57 +0000206 cat(DwarfDumpCategory));
Adrian Prantl59f30b82017-10-06 20:24:34 +0000207static cl::opt<bool>
208 Statistics("statistics",
209 cl::desc("Emit JSON-formatted debug info quality metrics."),
210 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000211static opt<bool> Verify("verify", desc("Verify the DWARF debug info."),
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000212 cat(DwarfDumpCategory));
213static opt<bool> Quiet("quiet", desc("Use with -verify to not emit to STDOUT."),
214 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000215static opt<bool> DumpUUID("uuid", desc("Show the UUID for each architecture."),
Adrian Prantl61913a12017-09-30 00:22:25 +0000216 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000217static alias DumpUUIDAlias("u", desc("Alias for -uuid."), aliasopt(DumpUUID));
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000218static opt<bool> Verbose("verbose",
Adrian Prantl214babe2017-10-06 20:24:35 +0000219 desc("Print more low-level encoding details."),
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000220 cat(DwarfDumpCategory));
Adrian Prantl214babe2017-10-06 20:24:35 +0000221static alias VerboseAlias("v", desc("Alias for -verbose."), aliasopt(Verbose),
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000222 cat(DwarfDumpCategory));
223} // namespace
Adrian Prantl057d3362017-09-15 23:04:04 +0000224/// @}
225//===----------------------------------------------------------------------===//
226
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000227static void error(StringRef Prefix, std::error_code EC) {
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000228 if (!EC)
Davide Italiano4376ddb2015-07-26 05:35:59 +0000229 return;
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000230 errs() << Prefix << ": " << EC.message() << "\n";
Davide Italiano4376ddb2015-07-26 05:35:59 +0000231 exit(1);
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000232}
233
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000234static DIDumpOptions getDumpOpts() {
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000235 DIDumpOptions DumpOpts;
236 DumpOpts.DumpType = DumpType;
Adrian Prantld3f9f212017-09-20 17:44:00 +0000237 DumpOpts.RecurseDepth = RecurseDepth;
Adrian Prantl01fb31c2017-12-08 23:32:47 +0000238 DumpOpts.ShowAddresses = !Diff;
Adrian Prantl597aa482017-09-16 17:28:00 +0000239 DumpOpts.ShowChildren = ShowChildren;
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000240 DumpOpts.ShowParents = ShowParents;
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000241 DumpOpts.ShowForm = ShowForm;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000242 DumpOpts.SummarizeTypes = SummarizeTypes;
243 DumpOpts.Verbose = Verbose;
Adrian Prantld3f9f212017-09-20 17:44:00 +0000244 // In -verify mode, print DIEs without children in error messages.
245 if (Verify)
246 return DumpOpts.noImplicitRecursion();
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000247 return DumpOpts;
248}
249
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000250static uint32_t getCPUType(MachOObjectFile &MachO) {
251 if (MachO.is64Bit())
252 return MachO.getHeader64().cputype;
253 else
254 return MachO.getHeader().cputype;
255}
256
257/// Return true if the object file has not been filtered by an --arch option.
258static bool filterArch(ObjectFile &Obj) {
259 if (ArchFilters.empty())
260 return true;
Adrian Prantlfa163612017-09-30 00:22:21 +0000261
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000262 if (auto *MachO = dyn_cast<MachOObjectFile>(&Obj)) {
263 std::string ObjArch =
264 Triple::getArchTypeName(MachO->getArchTriple().getArch());
Adrian Prantlfa163612017-09-30 00:22:21 +0000265
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000266 for (auto Arch : ArchFilters) {
Adrian Prantlfa163612017-09-30 00:22:21 +0000267 // Match name.
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000268 if (Arch == ObjArch)
269 return true;
Adrian Prantlfa163612017-09-30 00:22:21 +0000270
271 // Match architecture number.
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000272 unsigned Value;
273 if (!StringRef(Arch).getAsInteger(0, Value))
274 if (Value == getCPUType(*MachO))
275 return true;
276 }
277 }
278 return false;
279}
280
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000281using HandlerFn = std::function<bool(ObjectFile &, DWARFContext &DICtx, Twine,
282 raw_ostream &)>;
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000283
Adrian Prantl61913a12017-09-30 00:22:25 +0000284/// Print only DIEs that have a certain name.
285static void filterByName(const StringSet<> &Names,
286 DWARFContext::cu_iterator_range CUs, raw_ostream &OS) {
287 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}
312
313/// Handle the --lookup option and dump the DIEs and line info for the given
314/// address.
315static bool lookup(DWARFContext &DICtx, uint64_t Address, raw_ostream &OS) {
316 auto DIEsForAddr = DICtx.getDIEsForAddress(Lookup);
317
318 if (!DIEsForAddr)
319 return false;
320
321 DIDumpOptions DumpOpts = getDumpOpts();
322 DumpOpts.RecurseDepth = 0;
323 DIEsForAddr.CompileUnit->dump(OS, DumpOpts);
324 if (DIEsForAddr.FunctionDIE) {
325 DIEsForAddr.FunctionDIE.dump(OS, 2, DumpOpts);
326 if (DIEsForAddr.BlockDIE)
327 DIEsForAddr.BlockDIE.dump(OS, 4, DumpOpts);
328 }
329
330 if (DILineInfo LineInfo = DICtx.getLineInfoForAddress(Lookup))
331 LineInfo.dump(OS);
332
333 return true;
Adrian Prantl61913a12017-09-30 00:22:25 +0000334}
335
Adrian Prantl59f30b82017-10-06 20:24:34 +0000336bool collectStatsForObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
337 Twine Filename, raw_ostream &OS);
338
Pavel Labathd99072b2018-02-24 00:35:21 +0000339template <typename AccelTable>
Pavel Labath725c0352018-02-24 00:54:31 +0000340static llvm::Optional<uint64_t> getDIEOffset(const AccelTable &Accel,
Pavel Labathd99072b2018-02-24 00:35:21 +0000341 StringRef Name) {
342 for (const auto &Entry : Accel.equal_range(Name))
Pavel Labath47c34722018-03-09 11:58:59 +0000343 if (llvm::Optional<uint64_t> Off = Entry.getDIESectionOffset())
Pavel Labathd99072b2018-02-24 00:35:21 +0000344 return *Off;
345 return None;
346}
347
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000348static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx, Twine Filename,
349 raw_ostream &OS) {
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000350 logAllUnhandledErrors(DICtx.loadRegisterInfo(Obj), errs(),
Reid Klecknera0587362017-08-29 21:41:21 +0000351 Filename.str() + ": ");
Adrian Prantl61913a12017-09-30 00:22:25 +0000352 // The UUID dump already contains all the same information.
353 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All)
354 OS << Filename << ":\tfile format " << Obj.getFileFormatName() << '\n';
355
Jonas Devliegheref63ee642017-10-25 21:56:41 +0000356 // Handle the --lookup option.
357 if (Lookup)
358 return lookup(DICtx, Lookup, OS);
359
Adrian Prantl61913a12017-09-30 00:22:25 +0000360 // Handle the --name option.
361 if (!Name.empty()) {
362 StringSet<> Names;
363 for (auto name : Name)
Adrian Prantle5b93f22017-10-03 22:08:22 +0000364 Names.insert((IgnoreCase && !UseRegex) ? StringRef(name).lower() : name);
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000365
Adrian Prantl61913a12017-09-30 00:22:25 +0000366 filterByName(Names, DICtx.compile_units(), OS);
367 filterByName(Names, DICtx.dwo_compile_units(), OS);
368 return true;
369 }
370
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000371 // Handle the --find option and lower it to --debug-info=<offset>.
372 if (!Find.empty()) {
Adrian Prantl367064a2017-09-28 18:27:00 +0000373 DumpOffsets[DIDT_ID_DebugInfo] = [&]() -> llvm::Optional<uint64_t> {
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000374 for (auto Name : Find) {
Pavel Labathd99072b2018-02-24 00:35:21 +0000375 if (auto Offset = getDIEOffset(DICtx.getAppleNames(), Name))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000376 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset;
Pavel Labathd99072b2018-02-24 00:35:21 +0000377 if (auto Offset = getDIEOffset(DICtx.getAppleTypes(), Name))
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000378 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset;
Pavel Labathd99072b2018-02-24 00:35:21 +0000379 if (auto Offset = getDIEOffset(DICtx.getAppleNamespaces(), Name))
Adrian Prantlf51e7802017-09-29 00:52:33 +0000380 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset;
Pavel Labathd99072b2018-02-24 00:35:21 +0000381 if (auto Offset = getDIEOffset(DICtx.getDebugNames(), Name))
382 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset;
Adrian Prantl714ee4d2017-09-29 00:33:22 +0000383 }
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000384 return None;
385 }();
386 // Early exit if --find was specified but the current file doesn't have it.
387 if (!DumpOffsets[DIDT_ID_DebugInfo])
388 return true;
389 }
Jonas Devliegheref91dc282017-10-02 16:02:04 +0000390
Frederic Riss40c017932015-08-03 00:10:25 +0000391 // Dump the complete DWARF structure.
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000392 DICtx.dump(OS, getDumpOpts(), DumpOffsets);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000393 return true;
Frederic Riss40c017932015-08-03 00:10:25 +0000394}
395
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000396static bool verifyObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000397 Twine Filename, raw_ostream &OS) {
Greg Clayton48432cf2017-05-01 22:07:02 +0000398 // Verify the DWARF and exit with non-zero exit status if verification
399 // fails.
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000400 raw_ostream &stream = Quiet ? nulls() : OS;
Greg Clayton48432cf2017-05-01 22:07:02 +0000401 stream << "Verifying " << Filename.str() << ":\tfile format "
402 << Obj.getFileFormatName() << "\n";
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000403 bool Result = DICtx.verify(stream, getDumpOpts());
Greg Clayton48432cf2017-05-01 22:07:02 +0000404 if (Result)
405 stream << "No errors.\n";
406 else
407 stream << "Errors detected.\n";
408 return Result;
409}
410
Adrian Prantld866b472017-09-13 23:16:13 +0000411static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000412 HandlerFn HandleObj, raw_ostream &OS);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000413
414static bool handleArchive(StringRef Filename, Archive &Arch,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000415 HandlerFn HandleObj, raw_ostream &OS) {
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000416 bool Result = true;
417 Error Err = Error::success();
418 for (auto Child : Arch.children(Err)) {
419 auto BuffOrErr = Child.getMemoryBufferRef();
420 error(Filename, errorToErrorCode(BuffOrErr.takeError()));
421 auto NameOrErr = Child.getName();
422 error(Filename, errorToErrorCode(NameOrErr.takeError()));
423 std::string Name = (Filename + "(" + NameOrErr.get() + ")").str();
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000424 Result &= handleBuffer(Name, BuffOrErr.get(), HandleObj, OS);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000425 }
426 error(Filename, errorToErrorCode(std::move(Err)));
427
428 return Result;
429}
430
431static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000432 HandlerFn HandleObj, raw_ostream &OS) {
Adrian Prantld866b472017-09-13 23:16:13 +0000433 Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buffer);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000434 error(Filename, errorToErrorCode(BinOrErr.takeError()));
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000435
Greg Clayton48432cf2017-05-01 22:07:02 +0000436 bool Result = true;
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000437 if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) {
438 if (filterArch(*Obj)) {
439 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(*Obj);
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000440 Result = HandleObj(*Obj, *DICtx, Filename, OS);
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000441 }
442 }
Greg Clayton48432cf2017-05-01 22:07:02 +0000443 else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get()))
444 for (auto &ObjForArch : Fat->objects()) {
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000445 std::string ObjName =
446 (Filename + "(" + ObjForArch.getArchFlagName() + ")").str();
447 if (auto MachOOrErr = ObjForArch.getAsObjectFile()) {
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000448 auto &Obj = **MachOOrErr;
449 if (filterArch(Obj)) {
450 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(Obj);
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000451 Result &= HandleObj(Obj, *DICtx, ObjName, OS);
Adrian Prantl5a919cb2017-09-21 16:26:18 +0000452 }
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000453 continue;
454 } else
455 consumeError(MachOOrErr.takeError());
456 if (auto ArchiveOrErr = ObjForArch.getAsArchive()) {
457 error(ObjName, errorToErrorCode(ArchiveOrErr.takeError()));
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000458 Result &= handleArchive(ObjName, *ArchiveOrErr.get(), HandleObj, OS);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000459 continue;
460 } else
461 consumeError(ArchiveOrErr.takeError());
Greg Clayton48432cf2017-05-01 22:07:02 +0000462 }
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000463 else if (auto *Arch = dyn_cast<Archive>(BinOrErr->get()))
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000464 Result = handleArchive(Filename, *Arch, HandleObj, OS);
Greg Clayton48432cf2017-05-01 22:07:02 +0000465 return Result;
466}
467
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000468static bool handleFile(StringRef Filename, HandlerFn HandleObj,
469 raw_ostream &OS) {
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000470 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
471 MemoryBuffer::getFileOrSTDIN(Filename);
472 error(Filename, BuffOrErr.getError());
473 std::unique_ptr<MemoryBuffer> Buffer = std::move(BuffOrErr.get());
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000474 return handleBuffer(Filename, *Buffer, HandleObj, OS);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000475}
476
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000477/// If the input path is a .dSYM bundle (as created by the dsymutil tool),
478/// replace it with individual entries for each of the object files inside the
479/// bundle otherwise return the input path.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000480static std::vector<std::string> expandBundle(const std::string &InputPath) {
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000481 std::vector<std::string> BundlePaths;
482 SmallString<256> BundlePath(InputPath);
Jonas Devliegherefba754a2018-02-08 16:31:01 +0000483 // Normalize input path. This is necessary to accept `bundle.dSYM/`.
484 sys::path::remove_dots(BundlePath);
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000485 // Manually open up the bundle to avoid introducing additional dependencies.
486 if (sys::fs::is_directory(BundlePath) &&
487 sys::path::extension(BundlePath) == ".dSYM") {
488 std::error_code EC;
489 sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
490 for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
491 Dir != DirEnd && !EC; Dir.increment(EC)) {
492 const std::string &Path = Dir->path();
493 sys::fs::file_status Status;
494 EC = sys::fs::status(Path, Status);
495 error(Path, EC);
496 switch (Status.type()) {
497 case sys::fs::file_type::regular_file:
498 case sys::fs::file_type::symlink_file:
499 case sys::fs::file_type::type_unknown:
500 BundlePaths.push_back(Path);
501 break;
502 default: /*ignore*/;
503 }
504 }
505 error(BundlePath, EC);
506 }
507 if (!BundlePaths.size())
508 BundlePaths.push_back(InputPath);
509 return BundlePaths;
510}
511
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000512int main(int argc, char **argv) {
513 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000514 sys::PrintStackTraceOnErrorSignal(argv[0]);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000515 PrettyStackTraceProgram X(argc, argv);
516 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
517
Reid Klecknera0587362017-08-29 21:41:21 +0000518 llvm::InitializeAllTargetInfos();
519 llvm::InitializeAllTargetMCs();
520
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000521 HideUnrelatedOptions({&DwarfDumpCategory, &SectionCategory});
522 cl::ParseCommandLineOptions(
523 argc, argv,
524 "pretty-print DWARF debug information in object files"
525 " and debug info archives.\n");
526
527 if (Help) {
528 PrintHelpMessage(/*Hidden =*/false, /*Categorized =*/true);
529 return 0;
530 }
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000531
Reid Kleckner2590edf2017-09-23 01:04:42 +0000532 std::unique_ptr<ToolOutputFile> OutputFile;
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000533 if (!OutputFilename.empty()) {
534 std::error_code EC;
Reid Kleckner2590edf2017-09-23 01:04:42 +0000535 OutputFile = llvm::make_unique<ToolOutputFile>(OutputFilename, EC,
Jonas Devlieghere489604c2017-09-22 09:38:52 +0000536 sys::fs::F_None);
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000537 error("Unable to open output file" + OutputFilename, EC);
538 // Don't remove output file if we exit with an error.
539 OutputFile->keep();
540 }
541
542 raw_ostream &OS = OutputFile ? OutputFile->os() : outs();
Adrian Prantl5da51f42017-11-29 01:12:22 +0000543 bool OffsetRequested = false;
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000544
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000545 // Defaults to dumping all sections, unless brief mode is specified in which
546 // case only the .debug_info section in dumped.
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000547#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \
Adrian Prantl057d3362017-09-15 23:04:04 +0000548 if (Dump##ENUM_NAME.IsRequested) { \
549 DumpType |= DIDT_##ENUM_NAME; \
Adrian Prantl5da51f42017-11-29 01:12:22 +0000550 if (Dump##ENUM_NAME.HasValue) { \
Adrian Prantl057d3362017-09-15 23:04:04 +0000551 DumpOffsets[DIDT_ID_##ENUM_NAME] = Dump##ENUM_NAME.Val; \
Adrian Prantl5da51f42017-11-29 01:12:22 +0000552 OffsetRequested = true; \
553 } \
Adrian Prantl057d3362017-09-15 23:04:04 +0000554 }
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000555#include "llvm/BinaryFormat/Dwarf.def"
556#undef HANDLE_DWARF_SECTION
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000557 if (DumpUUID)
558 DumpType |= DIDT_UUID;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000559 if (DumpAll)
560 DumpType = DIDT_All;
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000561 if (DumpType == DIDT_Null) {
Adrian Prantl16aa4cf2017-09-11 23:05:20 +0000562 if (Verbose)
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000563 DumpType = DIDT_All;
Adrian Prantl16aa4cf2017-09-11 23:05:20 +0000564 else
565 DumpType = DIDT_DebugInfo;
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000566 }
567
Adrian Prantl5da51f42017-11-29 01:12:22 +0000568 // Unless dumping a specific DIE, default to --show-children.
569 if (!ShowChildren && !Verify && !OffsetRequested && Name.empty() && Find.empty())
570 ShowChildren = true;
571
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000572 // Defaults to a.out if no filenames specified.
573 if (InputFilenames.size() == 0)
574 InputFilenames.push_back("a.out");
575
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000576 // Expand any .dSYM bundles to the individual object files contained therein.
577 std::vector<std::string> Objects;
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000578 for (const auto &F : InputFilenames) {
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000579 auto Objs = expandBundle(F);
580 Objects.insert(Objects.end(), Objs.begin(), Objs.end());
581 }
582
Greg Clayton48432cf2017-05-01 22:07:02 +0000583 if (Verify) {
584 // If we encountered errors during verify, exit with a non-zero exit status.
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000585 if (!std::all_of(Objects.begin(), Objects.end(), [&](std::string Object) {
586 return handleFile(Object, verifyObjectFile, OS);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000587 }))
Greg Clayton48432cf2017-05-01 22:07:02 +0000588 exit(1);
Adrian Prantl59f30b82017-10-06 20:24:34 +0000589 } else if (Statistics)
590 for (auto Object : Objects)
591 handleFile(Object, collectStatsForObjectFile, OS);
592 else
Adrian Prantlb8f08422017-09-18 22:11:33 +0000593 for (auto Object : Objects)
Jonas Devlieghere8f719ba2017-09-22 09:20:57 +0000594 handleFile(Object, dumpObjectFile, OS);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000595
Davide Italiano4376ddb2015-07-26 05:35:59 +0000596 return EXIT_SUCCESS;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000597}