1 //===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===// 2 // 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 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/StringSet.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/DebugInfo/DIContext.h" 18 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 19 #include "llvm/Object/Archive.h" 20 #include "llvm/Object/MachOUniversal.h" 21 #include "llvm/Object/ObjectFile.h" 22 #include "llvm/Object/RelocVisitor.h" 23 #include "llvm/Support/CommandLine.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/Format.h" 26 #include "llvm/Support/ManagedStatic.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/PrettyStackTrace.h" 30 #include "llvm/Support/Regex.h" 31 #include "llvm/Support/Signals.h" 32 #include "llvm/Support/TargetSelect.h" 33 #include "llvm/Support/ToolOutputFile.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <algorithm> 36 #include <cstring> 37 #include <string> 38 #include <system_error> 39 40 using namespace llvm; 41 using namespace object; 42 43 /// Parser for options that take an optional offest argument. 44 /// @{ 45 struct OffsetOption { 46 uint64_t Val = 0; 47 bool HasValue = false; 48 bool IsRequested = false; 49 }; 50 51 namespace llvm { 52 namespace cl { 53 template <> 54 class parser<OffsetOption> final : public basic_parser<OffsetOption> { 55 public: 56 parser(Option &O) : basic_parser(O) {} 57 58 /// Return true on error. 59 bool parse(Option &O, StringRef ArgName, StringRef Arg, OffsetOption &Val) { 60 if (Arg == "") { 61 Val.Val = 0; 62 Val.HasValue = false; 63 Val.IsRequested = true; 64 return false; 65 } 66 if (Arg.getAsInteger(0, Val.Val)) 67 return O.error("'" + Arg + "' value invalid for integer argument!"); 68 Val.HasValue = true; 69 Val.IsRequested = true; 70 return false; 71 } 72 73 enum ValueExpected getValueExpectedFlagDefault() const { 74 return ValueOptional; 75 } 76 77 void printOptionInfo(const Option &O, size_t GlobalWidth) const { 78 outs() << " -" << O.ArgStr; 79 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O)); 80 } 81 82 void printOptionDiff(const Option &O, OffsetOption V, OptVal Default, 83 size_t GlobalWidth) const { 84 printOptionName(O, GlobalWidth); 85 outs() << "[=offset]"; 86 } 87 88 // An out-of-line virtual method to provide a 'home' for this class. 89 void anchor() override {}; 90 }; 91 } // cl 92 } // llvm 93 94 /// @} 95 /// Command line options. 96 /// @{ 97 98 namespace { 99 using namespace cl; 100 101 OptionCategory DwarfDumpCategory("Specific Options"); 102 static opt<bool> Help("h", desc("Alias for -help"), Hidden, 103 cat(DwarfDumpCategory)); 104 static list<std::string> 105 InputFilenames(Positional, desc("<input object files or .dSYM bundles>"), 106 ZeroOrMore, cat(DwarfDumpCategory)); 107 108 cl::OptionCategory SectionCategory("Section-specific Dump Options", 109 "These control which sections are dumped. " 110 "Where applicable these parameters take an " 111 "optional =<offset> argument to dump only " 112 "the entry at the specified offset."); 113 114 static opt<bool> DumpAll("all", desc("Dump all debug info sections"), 115 cat(SectionCategory)); 116 static alias DumpAllAlias("a", desc("Alias for -all"), aliasopt(DumpAll)); 117 118 // Options for dumping specific sections. 119 static unsigned DumpType = DIDT_Null; 120 static std::array<llvm::Optional<uint64_t>, (unsigned)DIDT_ID_Count> 121 DumpOffsets; 122 #define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \ 123 static opt<OffsetOption> Dump##ENUM_NAME( \ 124 CMDLINE_NAME, desc("Dump the " ELF_NAME " section"), \ 125 cat(SectionCategory)); 126 #include "llvm/BinaryFormat/Dwarf.def" 127 #undef HANDLE_DWARF_SECTION 128 129 static alias DumpDebugFrameAlias("eh-frame", desc("Alias for -debug-frame"), 130 NotHidden, cat(SectionCategory), 131 aliasopt(DumpDebugFrame)); 132 static list<std::string> 133 ArchFilters("arch", 134 desc("Dump debug information for the specified CPU " 135 "architecture only. Architectures may be specified by " 136 "name or by number. This option can be specified " 137 "multiple times, once for each desired architecture."), 138 cat(DwarfDumpCategory)); 139 static list<std::string> 140 Find("find", 141 desc("Search for the exact match for <name> in the accelerator tables " 142 "and print the matching debug information entries. When no " 143 "accelerator tables are available, the slower but more complete " 144 "-name option can be used instead."), 145 value_desc("name"), cat(DwarfDumpCategory)); 146 static alias FindAlias("f", desc("Alias for -find"), aliasopt(Find)); 147 static opt<bool> 148 IgnoreCase("ignore-case", 149 desc("Ignore case distinctions in when searching by name."), 150 value_desc("i"), cat(DwarfDumpCategory)); 151 static alias IgnoreCaseAlias("i", desc("Alias for -ignore-case"), 152 aliasopt(IgnoreCase)); 153 static list<std::string> Name( 154 "name", 155 desc("Find and print all debug info entries whose name (DW_AT_name " 156 "attribute) matches the exact text in <pattern>. When used with the " 157 "the -regex option <pattern> is interpreted as a regular expression."), 158 value_desc("pattern"), cat(DwarfDumpCategory)); 159 static alias NameAlias("n", desc("Alias for -name"), aliasopt(Name)); 160 static opt<std::string> 161 OutputFilename("out-file", cl::init(""), 162 cl::desc("Redirect output to the specified file"), 163 cl::value_desc("filename")); 164 static alias OutputFilenameAlias("o", desc("Alias for -out-file"), 165 aliasopt(OutputFilename), 166 cat(DwarfDumpCategory)); 167 static opt<bool> 168 UseRegex("regex", 169 desc("Treat any <pattern> strings as regular expressions when " 170 "searching instead of just as an exact string match."), 171 cat(DwarfDumpCategory)); 172 static alias RegexAlias("x", desc("Alias for -regex"), aliasopt(UseRegex)); 173 static opt<bool> 174 ShowChildren("show-children", 175 desc("Show a debug info entry's children when selectively " 176 "printing with the =<offset> option"), 177 cat(DwarfDumpCategory)); 178 static alias ShowChildrenAlias("c", desc("Alias for -show-children"), 179 aliasopt(ShowChildren)); 180 static opt<bool> 181 ShowParents("show-parents", 182 desc("Show a debug info entry's parents when selectively " 183 "printing with the =<offset> option"), 184 cat(DwarfDumpCategory)); 185 static alias ShowParentsAlias("p", desc("Alias for -show-parents"), 186 aliasopt(ShowParents)); 187 static opt<bool> 188 ShowForm("show-form", 189 desc("Show DWARF form types after the DWARF attribute types."), 190 cat(DwarfDumpCategory)); 191 static alias ShowFormAlias("F", desc("Alias for -show-form"), 192 aliasopt(ShowForm), cat(DwarfDumpCategory)); 193 static opt<unsigned> RecurseDepth( 194 "recurse-depth", 195 desc("Only recurse to a depth of N when displaying debug info entries."), 196 cat(DwarfDumpCategory), init(-1U), value_desc("N")); 197 static alias RecurseDepthAlias("r", desc("Alias for -recurse-depth"), 198 aliasopt(RecurseDepth)); 199 200 static opt<bool> 201 SummarizeTypes("summarize-types", 202 desc("Abbreviate the description of type unit entries"), 203 cat(DwarfDumpCategory)); 204 static opt<bool> Verify("verify", desc("Verify the DWARF debug info"), 205 cat(DwarfDumpCategory)); 206 static opt<bool> Quiet("quiet", desc("Use with -verify to not emit to STDOUT."), 207 cat(DwarfDumpCategory)); 208 static opt<bool> DumpUUID("uuid", desc("Show the UUID for each architecture"), 209 cat(DwarfDumpCategory)); 210 static alias DumpUUIDAlias("u", desc("Alias for -uuid"), aliasopt(DumpUUID)); 211 static opt<bool> Verbose("verbose", 212 desc("Print more low-level encoding details"), 213 cat(DwarfDumpCategory)); 214 static alias VerboseAlias("v", desc("Alias for -verbose"), aliasopt(Verbose), 215 cat(DwarfDumpCategory)); 216 } // namespace 217 /// @} 218 //===----------------------------------------------------------------------===// 219 220 static void error(StringRef Prefix, std::error_code EC) { 221 if (!EC) 222 return; 223 errs() << Prefix << ": " << EC.message() << "\n"; 224 exit(1); 225 } 226 227 static DIDumpOptions getDumpOpts() { 228 DIDumpOptions DumpOpts; 229 DumpOpts.DumpType = DumpType; 230 DumpOpts.RecurseDepth = RecurseDepth; 231 DumpOpts.ShowChildren = ShowChildren; 232 DumpOpts.ShowParents = ShowParents; 233 DumpOpts.ShowForm = ShowForm; 234 DumpOpts.SummarizeTypes = SummarizeTypes; 235 DumpOpts.Verbose = Verbose; 236 // In -verify mode, print DIEs without children in error messages. 237 if (Verify) 238 return DumpOpts.noImplicitRecursion(); 239 return DumpOpts; 240 } 241 242 static uint32_t getCPUType(MachOObjectFile &MachO) { 243 if (MachO.is64Bit()) 244 return MachO.getHeader64().cputype; 245 else 246 return MachO.getHeader().cputype; 247 } 248 249 /// Return true if the object file has not been filtered by an --arch option. 250 static bool filterArch(ObjectFile &Obj) { 251 if (ArchFilters.empty()) 252 return true; 253 254 if (auto *MachO = dyn_cast<MachOObjectFile>(&Obj)) { 255 std::string ObjArch = 256 Triple::getArchTypeName(MachO->getArchTriple().getArch()); 257 258 for (auto Arch : ArchFilters) { 259 // Match name. 260 if (Arch == ObjArch) 261 return true; 262 263 // Match architecture number. 264 unsigned Value; 265 if (!StringRef(Arch).getAsInteger(0, Value)) 266 if (Value == getCPUType(*MachO)) 267 return true; 268 } 269 } 270 return false; 271 } 272 273 using HandlerFn = std::function<bool(ObjectFile &, DWARFContext &DICtx, Twine, 274 raw_ostream &)>; 275 276 /// Print only DIEs that have a certain name. 277 static void filterByName(const StringSet<> &Names, 278 DWARFContext::cu_iterator_range CUs, raw_ostream &OS) { 279 for (const auto &CU : CUs) 280 for (const auto &Entry : CU->dies()) { 281 DWARFDie Die = {CU.get(), &Entry}; 282 if (const char *NamePtr = Die.getName(DINameKind::ShortName)) { 283 std::string Name = 284 (IgnoreCase && !UseRegex) ? StringRef(NamePtr).lower() : NamePtr; 285 // Match regular expression. 286 if (UseRegex) 287 for (auto Pattern : Names.keys()) { 288 Regex RE(Pattern, IgnoreCase ? Regex::IgnoreCase : Regex::NoFlags); 289 std::string Error; 290 if (!RE.isValid(Error)) { 291 errs() << "error in regular expression: " << Error << "\n"; 292 exit(1); 293 } 294 if (RE.match(Name)) 295 Die.dump(OS, 0, getDumpOpts()); 296 } 297 // Match full text. 298 else if (Names.count(Name)) 299 Die.dump(OS, 0, getDumpOpts()); 300 } 301 } 302 } 303 304 static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx, Twine Filename, 305 raw_ostream &OS) { 306 logAllUnhandledErrors(DICtx.loadRegisterInfo(Obj), errs(), 307 Filename.str() + ": "); 308 309 // The UUID dump already contains all the same information. 310 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All) 311 OS << Filename << ":\tfile format " << Obj.getFileFormatName() << '\n'; 312 313 // Handle the --name option. 314 if (!Name.empty()) { 315 StringSet<> Names; 316 for (auto name : Name) 317 Names.insert((IgnoreCase && !UseRegex) ? StringRef(name).lower() : name); 318 319 filterByName(Names, DICtx.compile_units(), OS); 320 filterByName(Names, DICtx.dwo_compile_units(), OS); 321 return true; 322 } 323 324 // Handle the --find option and lower it to --debug-info=<offset>. 325 if (!Find.empty()) { 326 DumpOffsets[DIDT_ID_DebugInfo] = [&]() -> llvm::Optional<uint64_t> { 327 for (auto Name : Find) { 328 auto find = [&](const DWARFAcceleratorTable &Accel) 329 -> llvm::Optional<uint64_t> { 330 for (auto Entry : Accel.equal_range(Name)) 331 for (auto Atom : Entry) 332 if (auto Offset = Atom.getAsSectionOffset()) 333 return Offset; 334 return None; 335 }; 336 if (auto Offset = find(DICtx.getAppleNames())) 337 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset; 338 if (auto Offset = find(DICtx.getAppleTypes())) 339 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset; 340 if (auto Offset = find(DICtx.getAppleNamespaces())) 341 return DumpOffsets[DIDT_ID_DebugInfo] = *Offset; 342 } 343 return None; 344 }(); 345 // Early exit if --find was specified but the current file doesn't have it. 346 if (!DumpOffsets[DIDT_ID_DebugInfo]) 347 return true; 348 } 349 350 // Dump the complete DWARF structure. 351 DICtx.dump(OS, getDumpOpts(), DumpOffsets); 352 return true; 353 } 354 355 static bool verifyObjectFile(ObjectFile &Obj, DWARFContext &DICtx, 356 Twine Filename, raw_ostream &OS) { 357 // Verify the DWARF and exit with non-zero exit status if verification 358 // fails. 359 raw_ostream &stream = Quiet ? nulls() : OS; 360 stream << "Verifying " << Filename.str() << ":\tfile format " 361 << Obj.getFileFormatName() << "\n"; 362 bool Result = DICtx.verify(stream, getDumpOpts()); 363 if (Result) 364 stream << "No errors.\n"; 365 else 366 stream << "Errors detected.\n"; 367 return Result; 368 } 369 370 static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer, 371 HandlerFn HandleObj, raw_ostream &OS); 372 373 static bool handleArchive(StringRef Filename, Archive &Arch, 374 HandlerFn HandleObj, raw_ostream &OS) { 375 bool Result = true; 376 Error Err = Error::success(); 377 for (auto Child : Arch.children(Err)) { 378 auto BuffOrErr = Child.getMemoryBufferRef(); 379 error(Filename, errorToErrorCode(BuffOrErr.takeError())); 380 auto NameOrErr = Child.getName(); 381 error(Filename, errorToErrorCode(NameOrErr.takeError())); 382 std::string Name = (Filename + "(" + NameOrErr.get() + ")").str(); 383 Result &= handleBuffer(Name, BuffOrErr.get(), HandleObj, OS); 384 } 385 error(Filename, errorToErrorCode(std::move(Err))); 386 387 return Result; 388 } 389 390 static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer, 391 HandlerFn HandleObj, raw_ostream &OS) { 392 Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Buffer); 393 error(Filename, errorToErrorCode(BinOrErr.takeError())); 394 395 bool Result = true; 396 if (auto *Obj = dyn_cast<ObjectFile>(BinOrErr->get())) { 397 if (filterArch(*Obj)) { 398 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(*Obj); 399 Result = HandleObj(*Obj, *DICtx, Filename, OS); 400 } 401 } 402 else if (auto *Fat = dyn_cast<MachOUniversalBinary>(BinOrErr->get())) 403 for (auto &ObjForArch : Fat->objects()) { 404 std::string ObjName = 405 (Filename + "(" + ObjForArch.getArchFlagName() + ")").str(); 406 if (auto MachOOrErr = ObjForArch.getAsObjectFile()) { 407 auto &Obj = **MachOOrErr; 408 if (filterArch(Obj)) { 409 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(Obj); 410 Result &= HandleObj(Obj, *DICtx, ObjName, OS); 411 } 412 continue; 413 } else 414 consumeError(MachOOrErr.takeError()); 415 if (auto ArchiveOrErr = ObjForArch.getAsArchive()) { 416 error(ObjName, errorToErrorCode(ArchiveOrErr.takeError())); 417 Result &= handleArchive(ObjName, *ArchiveOrErr.get(), HandleObj, OS); 418 continue; 419 } else 420 consumeError(ArchiveOrErr.takeError()); 421 } 422 else if (auto *Arch = dyn_cast<Archive>(BinOrErr->get())) 423 Result = handleArchive(Filename, *Arch, HandleObj, OS); 424 return Result; 425 } 426 427 static bool handleFile(StringRef Filename, HandlerFn HandleObj, 428 raw_ostream &OS) { 429 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = 430 MemoryBuffer::getFileOrSTDIN(Filename); 431 error(Filename, BuffOrErr.getError()); 432 std::unique_ptr<MemoryBuffer> Buffer = std::move(BuffOrErr.get()); 433 return handleBuffer(Filename, *Buffer, HandleObj, OS); 434 } 435 436 /// If the input path is a .dSYM bundle (as created by the dsymutil tool), 437 /// replace it with individual entries for each of the object files inside the 438 /// bundle otherwise return the input path. 439 static std::vector<std::string> expandBundle(const std::string &InputPath) { 440 std::vector<std::string> BundlePaths; 441 SmallString<256> BundlePath(InputPath); 442 // Manually open up the bundle to avoid introducing additional dependencies. 443 if (sys::fs::is_directory(BundlePath) && 444 sys::path::extension(BundlePath) == ".dSYM") { 445 std::error_code EC; 446 sys::path::append(BundlePath, "Contents", "Resources", "DWARF"); 447 for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd; 448 Dir != DirEnd && !EC; Dir.increment(EC)) { 449 const std::string &Path = Dir->path(); 450 sys::fs::file_status Status; 451 EC = sys::fs::status(Path, Status); 452 error(Path, EC); 453 switch (Status.type()) { 454 case sys::fs::file_type::regular_file: 455 case sys::fs::file_type::symlink_file: 456 case sys::fs::file_type::type_unknown: 457 BundlePaths.push_back(Path); 458 break; 459 default: /*ignore*/; 460 } 461 } 462 error(BundlePath, EC); 463 } 464 if (!BundlePaths.size()) 465 BundlePaths.push_back(InputPath); 466 return BundlePaths; 467 } 468 469 int main(int argc, char **argv) { 470 // Print a stack trace if we signal out. 471 sys::PrintStackTraceOnErrorSignal(argv[0]); 472 PrettyStackTraceProgram X(argc, argv); 473 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 474 475 llvm::InitializeAllTargetInfos(); 476 llvm::InitializeAllTargetMCs(); 477 478 HideUnrelatedOptions({&DwarfDumpCategory, &SectionCategory}); 479 cl::ParseCommandLineOptions( 480 argc, argv, 481 "pretty-print DWARF debug information in object files" 482 " and debug info archives.\n"); 483 484 if (Help) { 485 PrintHelpMessage(/*Hidden =*/false, /*Categorized =*/true); 486 return 0; 487 } 488 489 std::unique_ptr<ToolOutputFile> OutputFile; 490 if (!OutputFilename.empty()) { 491 std::error_code EC; 492 OutputFile = llvm::make_unique<ToolOutputFile>(OutputFilename, EC, 493 sys::fs::F_None); 494 error("Unable to open output file" + OutputFilename, EC); 495 // Don't remove output file if we exit with an error. 496 OutputFile->keep(); 497 } 498 499 raw_ostream &OS = OutputFile ? OutputFile->os() : outs(); 500 501 // Defaults to dumping all sections, unless brief mode is specified in which 502 // case only the .debug_info section in dumped. 503 #define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME) \ 504 if (Dump##ENUM_NAME.IsRequested) { \ 505 DumpType |= DIDT_##ENUM_NAME; \ 506 if (Dump##ENUM_NAME.HasValue) \ 507 DumpOffsets[DIDT_ID_##ENUM_NAME] = Dump##ENUM_NAME.Val; \ 508 } 509 #include "llvm/BinaryFormat/Dwarf.def" 510 #undef HANDLE_DWARF_SECTION 511 if (DumpUUID) 512 DumpType |= DIDT_UUID; 513 if (DumpAll) 514 DumpType = DIDT_All; 515 if (DumpType == DIDT_Null) { 516 if (Verbose) 517 DumpType = DIDT_All; 518 else 519 DumpType = DIDT_DebugInfo; 520 } 521 522 // Defaults to a.out if no filenames specified. 523 if (InputFilenames.size() == 0) 524 InputFilenames.push_back("a.out"); 525 526 // Expand any .dSYM bundles to the individual object files contained therein. 527 std::vector<std::string> Objects; 528 for (const auto &F : InputFilenames) { 529 auto Objs = expandBundle(F); 530 Objects.insert(Objects.end(), Objs.begin(), Objs.end()); 531 } 532 533 if (Verify) { 534 // If we encountered errors during verify, exit with a non-zero exit status. 535 if (!std::all_of(Objects.begin(), Objects.end(), [&](std::string Object) { 536 return handleFile(Object, verifyObjectFile, OS); 537 })) 538 exit(1); 539 } else 540 for (auto Object : Objects) 541 handleFile(Object, dumpObjectFile, OS); 542 543 return EXIT_SUCCESS; 544 } 545