blob: 0f75f36af7e43da1fa33312a004e5cd34ee67a33 [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"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000015#include "llvm/ADT/Triple.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000016#include "llvm/DebugInfo/DIContext.h"
17#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Adrian Prantl5fd3d492017-09-14 17:01:53 +000018#include "llvm/Object/Archive.h"
Frederic Riss4c5d3572015-08-03 00:10:31 +000019#include "llvm/Object/MachOUniversal.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000020#include "llvm/Object/ObjectFile.h"
Eric Christopher7c678de2012-11-07 23:22:07 +000021#include "llvm/Object/RelocVisitor.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"
29#include "llvm/Support/Signals.h"
Reid Klecknera0587362017-08-29 21:41:21 +000030#include "llvm/Support/TargetSelect.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000031#include "llvm/Support/raw_ostream.h"
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000032#include <algorithm>
33#include <cstring>
Eric Christopher7c678de2012-11-07 23:22:07 +000034#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000035#include <system_error>
Eric Christopher7c678de2012-11-07 23:22:07 +000036
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000037using namespace llvm;
38using namespace object;
39
Adrian Prantl057d3362017-09-15 23:04:04 +000040/// Parser for options that take an optional offest argument.
41/// @{
42struct OffsetOption {
43 uint64_t Val = 0;
44 bool HasValue = false;
45 bool IsRequested = false;
46};
47
48namespace llvm {
49namespace cl {
50template <>
51class parser<OffsetOption> final : public basic_parser<OffsetOption> {
52public:
53 parser(Option &O) : basic_parser(O) {}
54
55 /// Return true on error.
56 bool parse(Option &O, StringRef ArgName, StringRef Arg, OffsetOption &Val) {
57 if (Arg == "") {
58 Val.Val = 0;
59 Val.HasValue = false;
60 Val.IsRequested = true;
61 return false;
62 }
63 if (Arg.getAsInteger(0, Val.Val))
64 return O.error("'" + Arg + "' value invalid for integer argument!");
65 Val.HasValue = true;
66 Val.IsRequested = true;
67 return false;
68 }
69
70 enum ValueExpected getValueExpectedFlagDefault() const {
71 return ValueOptional;
72 }
73
74 void printOptionInfo(const Option &O, size_t GlobalWidth) const {
75 outs() << " -" << O.ArgStr;
76 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
77 }
78
79 void printOptionDiff(const Option &O, OffsetOption V, OptVal Default,
80 size_t GlobalWidth) const {
81 printOptionName(O, GlobalWidth);
82 outs() << "[=offset]";
83 }
84
85 // An out-of-line virtual method to provide a 'home' for this class.
86 void anchor() override {};
87};
88} // cl
89} // llvm
90
91/// @}
92/// Command line options.
93/// @{
94
Adrian Prantl7c5b45d2017-09-12 22:32:53 +000095namespace {
Adrian Prantl057d3362017-09-15 23:04:04 +000096using namespace cl;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +000097
Adrian Prantl7c5b45d2017-09-12 22:32:53 +000098OptionCategory DwarfDumpCategory("Specific Options");
99static opt<bool> Help("h", desc("Alias for -help"), Hidden,
100 cat(DwarfDumpCategory));
101static list<std::string>
102 InputFilenames(Positional, desc("<input object files or .dSYM bundles>"),
103 ZeroOrMore, cat(DwarfDumpCategory));
104
Adrian Prantl057d3362017-09-15 23:04:04 +0000105cl::OptionCategory SectionCategory("Section-specific Dump Options",
106 "These control which sections are dumped. "
107 "Where applicable these parameters take an "
108 "optional =<offset> argument to dump only "
109 "the entry at the specified offset.");
110
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000111static opt<bool> DumpAll("all", desc("Dump all debug info sections"),
112 cat(SectionCategory));
113static alias DumpAllAlias("a", desc("Alias for -all"), aliasopt(DumpAll));
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000114
Adrian Prantl057d3362017-09-15 23:04:04 +0000115// Options for dumping specific sections.
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000116static unsigned DumpType = DIDT_Null;
Adrian Prantlccc21c42017-09-19 20:58:57 +0000117static std::array<llvm::Optional<uint64_t>, (unsigned)DIDT_ID_Count>
118 DumpOffsets;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000119#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \
Adrian Prantl057d3362017-09-15 23:04:04 +0000120 static opt<OffsetOption> Dump##ENUM_NAME( \
121 CMDLINE_NAME, desc("Dump the " ELF_NAME " section"), \
122 cat(SectionCategory));
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000123#include "llvm/BinaryFormat/Dwarf.def"
124#undef HANDLE_DWARF_SECTION
Adrian Prantl057d3362017-09-15 23:04:04 +0000125
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000126static alias DumpDebugFrameAlias("eh-frame", desc("Alias for -debug-frame"),
Adrian Prantl31819b32017-09-20 23:29:31 +0000127 NotHidden, cat(SectionCategory),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000128 aliasopt(DumpDebugFrame));
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000129static opt<bool> DumpUUID("uuid", desc("Show the UUID for each architecture"),
130 cat(DwarfDumpCategory));
131static alias DumpUUIDAlias("u", desc("Alias for -uuid"), aliasopt(DumpUUID));
Eli Bendersky7a94daa2013-01-25 20:26:43 +0000132
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000133static opt<bool>
Adrian Prantl597aa482017-09-16 17:28:00 +0000134 ShowChildren("show-children",
135 desc("Show a debug info entry's children when selectively "
Adrian Prantlccc21c42017-09-19 20:58:57 +0000136 "printing with the =<offset> option"),
137 cat(DwarfDumpCategory));
Adrian Prantl597aa482017-09-16 17:28:00 +0000138static alias ShowChildrenAlias("c", desc("Alias for -show-children"),
139 aliasopt(ShowChildren));
140static opt<bool>
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000141 ShowParents("show-parents",
142 desc("Show a debug info entry's parents when selectively "
Adrian Prantlccc21c42017-09-19 20:58:57 +0000143 "printing with the =<offset> option"),
144 cat(DwarfDumpCategory));
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000145static alias ShowParentsAlias("p", desc("Alias for -show-parents"),
146 aliasopt(ShowParents));
Adrian Prantld3f9f212017-09-20 17:44:00 +0000147static opt<unsigned> RecurseDepth(
148 "recurse-depth",
149 desc("Only recurse to a depth of N when displaying debug info entries."),
150 cat(DwarfDumpCategory), init(-1U), value_desc("N"));
151static alias RecurseDepthAlias("r", desc("Alias for -recurse-depth"),
152 aliasopt(RecurseDepth));
153
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000154static opt<bool>
David Blaikie50cc27e2016-10-18 21:09:48 +0000155 SummarizeTypes("summarize-types",
Adrian Prantlccc21c42017-09-19 20:58:57 +0000156 desc("Abbreviate the description of type unit entries"),
157 cat(DwarfDumpCategory));
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000158static opt<bool> Verify("verify", desc("Verify the DWARF debug info"),
159 cat(DwarfDumpCategory));
160static opt<bool> Quiet("quiet", desc("Use with -verify to not emit to STDOUT."),
161 cat(DwarfDumpCategory));
162static opt<bool> Verbose("verbose",
163 desc("Print more low-level encoding details"),
164 cat(DwarfDumpCategory));
165static alias VerboseAlias("v", desc("Alias for -verbose"), aliasopt(Verbose),
166 cat(DwarfDumpCategory));
167} // namespace
Adrian Prantl057d3362017-09-15 23:04:04 +0000168/// @}
169//===----------------------------------------------------------------------===//
170
Adrian Prantl318d1192017-06-06 23:28:45 +0000171
Davide Italiano4376ddb2015-07-26 05:35:59 +0000172static void error(StringRef Filename, std::error_code EC) {
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000173 if (!EC)
Davide Italiano4376ddb2015-07-26 05:35:59 +0000174 return;
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000175 errs() << Filename << ": " << EC.message() << "\n";
Davide Italiano4376ddb2015-07-26 05:35:59 +0000176 exit(1);
Alexey Samsonov85c7d662015-06-25 23:40:15 +0000177}
178
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000179static DIDumpOptions getDumpOpts() {
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000180 DIDumpOptions DumpOpts;
181 DumpOpts.DumpType = DumpType;
Adrian Prantld3f9f212017-09-20 17:44:00 +0000182 DumpOpts.RecurseDepth = RecurseDepth;
Adrian Prantl597aa482017-09-16 17:28:00 +0000183 DumpOpts.ShowChildren = ShowChildren;
Adrian Prantlc2bc7172017-09-18 21:27:44 +0000184 DumpOpts.ShowParents = ShowParents;
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000185 DumpOpts.SummarizeTypes = SummarizeTypes;
186 DumpOpts.Verbose = Verbose;
Adrian Prantld3f9f212017-09-20 17:44:00 +0000187 // In -verify mode, print DIEs without children in error messages.
188 if (Verify)
189 return DumpOpts.noImplicitRecursion();
Jonas Devlieghere27476ce2017-09-13 09:43:05 +0000190 return DumpOpts;
191}
192
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000193static bool dumpObjectFile(ObjectFile &Obj, Twine Filename) {
Reid Klecknera0587362017-08-29 21:41:21 +0000194 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(Obj);
195 logAllUnhandledErrors(DICtx->loadRegisterInfo(Obj), errs(),
196 Filename.str() + ": ");
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000197 // The UUID dump already contains all the same information.
198 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All)
Adrian Prantl3ae35eb2017-09-13 22:09:01 +0000199 outs() << Filename << ":\tfile format " << Obj.getFileFormatName() << '\n';
Spyridoula Gravanicc0d13a2017-06-12 19:04:28 +0000200
Frederic Riss40c017932015-08-03 00:10:25 +0000201 // Dump the complete DWARF structure.
Adrian Prantl057d3362017-09-15 23:04:04 +0000202 DICtx->dump(outs(), getDumpOpts(), DumpOffsets);
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000203 return true;
Frederic Riss40c017932015-08-03 00:10:25 +0000204}
205
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000206static bool verifyObjectFile(ObjectFile &Obj, Twine Filename) {
Rafael Espindolac398e672017-07-19 22:27:28 +0000207 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj);
208
Greg Clayton48432cf2017-05-01 22:07:02 +0000209 // Verify the DWARF and exit with non-zero exit status if verification
210 // fails.
211 raw_ostream &stream = Quiet ? nulls() : outs();
212 stream << "Verifying " << Filename.str() << ":\tfile format "
213 << Obj.getFileFormatName() << "\n";
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000214 bool Result = DICtx->verify(stream, getDumpOpts());
Greg Clayton48432cf2017-05-01 22:07:02 +0000215 if (Result)
216 stream << "No errors.\n";
217 else
218 stream << "Errors detected.\n";
219 return Result;
220}
221
Adrian Prantld866b472017-09-13 23:16:13 +0000222static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000223 std::function<bool(ObjectFile &, Twine)> HandleObj);
224
225static bool handleArchive(StringRef Filename, Archive &Arch,
226 std::function<bool(ObjectFile &, Twine)> HandleObj) {
227 bool Result = true;
228 Error Err = Error::success();
229 for (auto Child : Arch.children(Err)) {
230 auto BuffOrErr = Child.getMemoryBufferRef();
231 error(Filename, errorToErrorCode(BuffOrErr.takeError()));
232 auto NameOrErr = Child.getName();
233 error(Filename, errorToErrorCode(NameOrErr.takeError()));
234 std::string Name = (Filename + "(" + NameOrErr.get() + ")").str();
235 Result &= handleBuffer(Name, BuffOrErr.get(), HandleObj);
236 }
237 error(Filename, errorToErrorCode(std::move(Err)));
238
239 return Result;
240}
241
242static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000243 std::function<bool(ObjectFile &, Twine)> HandleObj) {
Adrian Prantld866b472017-09-13 23:16:13 +0000244 Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buffer);
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000245 error(Filename, errorToErrorCode(BinOrErr.takeError()));
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000246
Greg Clayton48432cf2017-05-01 22:07:02 +0000247 bool Result = true;
248 if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get()))
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000249 Result = HandleObj(*Obj, Filename);
Greg Clayton48432cf2017-05-01 22:07:02 +0000250 else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get()))
251 for (auto &ObjForArch : Fat->objects()) {
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000252 std::string ObjName =
253 (Filename + "(" + ObjForArch.getArchFlagName() + ")").str();
254 if (auto MachOOrErr = ObjForArch.getAsObjectFile()) {
255 Result &= HandleObj(**MachOOrErr, ObjName);
256 continue;
257 } else
258 consumeError(MachOOrErr.takeError());
259 if (auto ArchiveOrErr = ObjForArch.getAsArchive()) {
260 error(ObjName, errorToErrorCode(ArchiveOrErr.takeError()));
261 Result &= handleArchive(ObjName, *ArchiveOrErr.get(), HandleObj);
262 continue;
263 } else
264 consumeError(ArchiveOrErr.takeError());
Greg Clayton48432cf2017-05-01 22:07:02 +0000265 }
Adrian Prantl5fd3d492017-09-14 17:01:53 +0000266 else if (auto *Arch = dyn_cast<Archive>(BinOrErr->get()))
267 Result = handleArchive(Filename, *Arch, HandleObj);
Greg Clayton48432cf2017-05-01 22:07:02 +0000268 return Result;
269}
270
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000271static bool handleFile(StringRef Filename,
272 std::function<bool(ObjectFile &, Twine)> HandleObj) {
273 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
274 MemoryBuffer::getFileOrSTDIN(Filename);
275 error(Filename, BuffOrErr.getError());
276 std::unique_ptr<MemoryBuffer> Buffer = std::move(BuffOrErr.get());
277 return handleBuffer(Filename, *Buffer, HandleObj);
278}
279
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000280/// If the input path is a .dSYM bundle (as created by the dsymutil tool),
281/// replace it with individual entries for each of the object files inside the
282/// bundle otherwise return the input path.
Benjamin Kramerc321e532016-06-08 19:09:22 +0000283static std::vector<std::string> expandBundle(const std::string &InputPath) {
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000284 std::vector<std::string> BundlePaths;
285 SmallString<256> BundlePath(InputPath);
286 // Manually open up the bundle to avoid introducing additional dependencies.
287 if (sys::fs::is_directory(BundlePath) &&
288 sys::path::extension(BundlePath) == ".dSYM") {
289 std::error_code EC;
290 sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
291 for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
292 Dir != DirEnd && !EC; Dir.increment(EC)) {
293 const std::string &Path = Dir->path();
294 sys::fs::file_status Status;
295 EC = sys::fs::status(Path, Status);
296 error(Path, EC);
297 switch (Status.type()) {
298 case sys::fs::file_type::regular_file:
299 case sys::fs::file_type::symlink_file:
300 case sys::fs::file_type::type_unknown:
301 BundlePaths.push_back(Path);
302 break;
303 default: /*ignore*/;
304 }
305 }
306 error(BundlePath, EC);
307 }
308 if (!BundlePaths.size())
309 BundlePaths.push_back(InputPath);
310 return BundlePaths;
311}
312
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000313int main(int argc, char **argv) {
314 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000315 sys::PrintStackTraceOnErrorSignal(argv[0]);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000316 PrettyStackTraceProgram X(argc, argv);
317 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
318
Reid Klecknera0587362017-08-29 21:41:21 +0000319 llvm::InitializeAllTargetInfos();
320 llvm::InitializeAllTargetMCs();
321
Adrian Prantl7c5b45d2017-09-12 22:32:53 +0000322 HideUnrelatedOptions({&DwarfDumpCategory, &SectionCategory});
323 cl::ParseCommandLineOptions(
324 argc, argv,
325 "pretty-print DWARF debug information in object files"
326 " and debug info archives.\n");
327
328 if (Help) {
329 PrintHelpMessage(/*Hidden =*/false, /*Categorized =*/true);
330 return 0;
331 }
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000332
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000333 // Defaults to dumping all sections, unless brief mode is specified in which
334 // case only the .debug_info section in dumped.
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000335#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \
Adrian Prantl057d3362017-09-15 23:04:04 +0000336 if (Dump##ENUM_NAME.IsRequested) { \
337 DumpType |= DIDT_##ENUM_NAME; \
338 if (Dump##ENUM_NAME.HasValue) \
339 DumpOffsets[DIDT_ID_##ENUM_NAME] = Dump##ENUM_NAME.Val; \
340 }
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000341#include "llvm/BinaryFormat/Dwarf.def"
342#undef HANDLE_DWARF_SECTION
Adrian Prantl3dcd1222017-09-13 18:22:59 +0000343 if (DumpUUID)
344 DumpType |= DIDT_UUID;
Adrian Prantl7bc1b282017-09-11 22:59:45 +0000345 if (DumpAll)
346 DumpType = DIDT_All;
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000347 if (DumpType == DIDT_Null) {
Adrian Prantl16aa4cf2017-09-11 23:05:20 +0000348 if (Verbose)
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000349 DumpType = DIDT_All;
Adrian Prantl16aa4cf2017-09-11 23:05:20 +0000350 else
351 DumpType = DIDT_DebugInfo;
Jonas Devlieghere8ac8df02017-08-31 16:44:47 +0000352 }
353
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000354 // Defaults to a.out if no filenames specified.
355 if (InputFilenames.size() == 0)
356 InputFilenames.push_back("a.out");
357
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000358 // Expand any .dSYM bundles to the individual object files contained therein.
359 std::vector<std::string> Objects;
Benjamin Kramer4fed9282016-05-27 12:30:51 +0000360 for (const auto &F : InputFilenames) {
Adrian Prantl8e7d3b92015-12-23 21:51:13 +0000361 auto Objs = expandBundle(F);
362 Objects.insert(Objects.end(), Objs.begin(), Objs.end());
363 }
364
Greg Clayton48432cf2017-05-01 22:07:02 +0000365 if (Verify) {
366 // If we encountered errors during verify, exit with a non-zero exit status.
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000367 if (!std::all_of(Objects.begin(), Objects.end(), [](std::string Object) {
368 return handleFile(Object, verifyObjectFile);
369 }))
Greg Clayton48432cf2017-05-01 22:07:02 +0000370 exit(1);
Adrian Prantlb8f08422017-09-18 22:11:33 +0000371 } else
372 for (auto Object : Objects)
Adrian Prantl2611ffe2017-09-13 23:07:24 +0000373 handleFile(Object, dumpObjectFile);
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000374
Davide Italiano4376ddb2015-07-26 05:35:59 +0000375 return EXIT_SUCCESS;
Benjamin Krameraa2f78f2011-09-13 19:42:23 +0000376}