1 //===- llvm-readobj.cpp - Dump contents of an Object File -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is a tool similar to readelf, except it works on multiple object file 10 // formats. The main purpose of this tool is to provide detailed output suitable 11 // for FileCheck. 12 // 13 // Flags should be similar to readelf where supported, but the output format 14 // does not need to be identical. The point is to not make users learn yet 15 // another set of flags. 16 // 17 // Output should be specialized for each format where appropriate. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #include "llvm-readobj.h" 22 #include "Error.h" 23 #include "ObjDumper.h" 24 #include "WindowsResourceDumper.h" 25 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h" 26 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h" 27 #include "llvm/Object/Archive.h" 28 #include "llvm/Object/COFFImportFile.h" 29 #include "llvm/Object/MachOUniversal.h" 30 #include "llvm/Object/ObjectFile.h" 31 #include "llvm/Object/WindowsResource.h" 32 #include "llvm/Support/Casting.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/DataTypes.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/FileSystem.h" 37 #include "llvm/Support/FormatVariadic.h" 38 #include "llvm/Support/InitLLVM.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/ScopedPrinter.h" 41 #include "llvm/Support/TargetRegistry.h" 42 #include "llvm/Support/WithColor.h" 43 44 using namespace llvm; 45 using namespace llvm::object; 46 47 namespace opts { 48 cl::list<std::string> InputFilenames(cl::Positional, 49 cl::desc("<input object files>"), 50 cl::ZeroOrMore); 51 52 // --all, -a 53 cl::opt<bool> 54 All("all", 55 cl::desc("Equivalent to setting: --file-headers, --program-headers, " 56 "--section-headers, --symbols, --relocations, " 57 "--dynamic-table, --notes, --version-info, --unwind, " 58 "--section-groups and --elf-hash-histogram.")); 59 cl::alias AllShort("a", cl::desc("Alias for --all"), cl::aliasopt(All)); 60 61 // --dependent-libraries 62 cl::opt<bool> 63 DependentLibraries("dependent-libraries", 64 cl::desc("Display the dependent libraries section")); 65 66 // --headers -e 67 cl::opt<bool> 68 Headers("headers", 69 cl::desc("Equivalent to setting: --file-headers, --program-headers, " 70 "--section-headers")); 71 cl::alias HeadersShort("e", cl::desc("Alias for --headers"), 72 cl::aliasopt(Headers)); 73 74 // --wide, -W 75 cl::opt<bool> 76 WideOutput("wide", cl::desc("Ignored for compatibility with GNU readelf"), 77 cl::Hidden); 78 cl::alias WideOutputShort("W", 79 cl::desc("Alias for --wide"), 80 cl::aliasopt(WideOutput)); 81 82 // --file-headers, --file-header, -h 83 cl::opt<bool> FileHeaders("file-headers", 84 cl::desc("Display file headers ")); 85 cl::alias FileHeadersShort("h", cl::desc("Alias for --file-headers"), 86 cl::aliasopt(FileHeaders), cl::NotHidden); 87 cl::alias FileHeadersSingular("file-header", 88 cl::desc("Alias for --file-headers"), 89 cl::aliasopt(FileHeaders)); 90 91 // --section-headers, --sections, -S 92 // Also -s in llvm-readobj mode. 93 cl::opt<bool> SectionHeaders("section-headers", 94 cl::desc("Display all section headers.")); 95 cl::alias SectionsShortUpper("S", cl::desc("Alias for --section-headers"), 96 cl::aliasopt(SectionHeaders), cl::NotHidden); 97 cl::alias SectionHeadersAlias("sections", 98 cl::desc("Alias for --section-headers"), 99 cl::aliasopt(SectionHeaders), cl::NotHidden); 100 101 // --section-relocations 102 // Also --sr in llvm-readobj mode. 103 cl::opt<bool> SectionRelocations("section-relocations", 104 cl::desc("Display relocations for each section shown.")); 105 106 // --section-symbols 107 // Also --st in llvm-readobj mode. 108 cl::opt<bool> SectionSymbols("section-symbols", 109 cl::desc("Display symbols for each section shown.")); 110 111 // --section-data 112 // Also --sd in llvm-readobj mode. 113 cl::opt<bool> SectionData("section-data", 114 cl::desc("Display section data for each section shown.")); 115 116 // --section-mapping 117 cl::opt<cl::boolOrDefault> 118 SectionMapping("section-mapping", 119 cl::desc("Display the section to segment mapping.")); 120 121 // --relocations, --relocs, -r 122 cl::opt<bool> Relocations("relocations", 123 cl::desc("Display the relocation entries in the file")); 124 cl::alias RelocationsShort("r", cl::desc("Alias for --relocations"), 125 cl::aliasopt(Relocations), cl::NotHidden); 126 cl::alias RelocationsGNU("relocs", cl::desc("Alias for --relocations"), 127 cl::aliasopt(Relocations)); 128 129 // --notes, -n 130 cl::opt<bool> Notes("notes", cl::desc("Display the ELF notes in the file")); 131 cl::alias NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes)); 132 133 // --dyn-relocations 134 cl::opt<bool> DynRelocs("dyn-relocations", 135 cl::desc("Display the dynamic relocation entries in the file")); 136 137 // --symbols 138 // Also -s in llvm-readelf mode, or -t in llvm-readobj mode. 139 cl::opt<bool> 140 Symbols("symbols", 141 cl::desc("Display the symbol table. Also display the dynamic " 142 "symbol table when using GNU output style for ELF")); 143 cl::alias SymbolsGNU("syms", cl::desc("Alias for --symbols"), 144 cl::aliasopt(Symbols)); 145 146 // --dyn-symbols, --dyn-syms 147 // Also --dt in llvm-readobj mode. 148 cl::opt<bool> DynamicSymbols("dyn-symbols", 149 cl::desc("Display the dynamic symbol table")); 150 cl::alias DynSymsGNU("dyn-syms", cl::desc("Alias for --dyn-symbols"), 151 cl::aliasopt(DynamicSymbols)); 152 153 // --hash-symbols 154 cl::opt<bool> HashSymbols( 155 "hash-symbols", 156 cl::desc("Display the dynamic symbols derived from the hash section")); 157 158 // --unwind, -u 159 cl::opt<bool> UnwindInfo("unwind", 160 cl::desc("Display unwind information")); 161 cl::alias UnwindInfoShort("u", 162 cl::desc("Alias for --unwind"), 163 cl::aliasopt(UnwindInfo)); 164 165 // --dynamic-table, --dynamic, -d 166 cl::opt<bool> DynamicTable("dynamic-table", 167 cl::desc("Display the ELF .dynamic section table")); 168 cl::alias DynamicTableShort("d", cl::desc("Alias for --dynamic-table"), 169 cl::aliasopt(DynamicTable), cl::NotHidden); 170 cl::alias DynamicTableAlias("dynamic", cl::desc("Alias for --dynamic-table"), 171 cl::aliasopt(DynamicTable)); 172 173 // --needed-libs 174 cl::opt<bool> NeededLibraries("needed-libs", 175 cl::desc("Display the needed libraries")); 176 177 // --program-headers, --segments, -l 178 cl::opt<bool> ProgramHeaders("program-headers", 179 cl::desc("Display ELF program headers")); 180 cl::alias ProgramHeadersShort("l", cl::desc("Alias for --program-headers"), 181 cl::aliasopt(ProgramHeaders), cl::NotHidden); 182 cl::alias SegmentsAlias("segments", cl::desc("Alias for --program-headers"), 183 cl::aliasopt(ProgramHeaders)); 184 185 // --string-dump, -p 186 cl::list<std::string> StringDump("string-dump", cl::desc("<number|name>"), 187 cl::ZeroOrMore); 188 cl::alias StringDumpShort("p", cl::desc("Alias for --string-dump"), 189 cl::aliasopt(StringDump), cl::Prefix); 190 191 // --hex-dump, -x 192 cl::list<std::string> HexDump("hex-dump", cl::desc("<number|name>"), 193 cl::ZeroOrMore); 194 cl::alias HexDumpShort("x", cl::desc("Alias for --hex-dump"), 195 cl::aliasopt(HexDump), cl::Prefix); 196 197 // --demangle, -C 198 cl::opt<bool> Demangle("demangle", 199 cl::desc("Demangle symbol names in output")); 200 cl::alias DemangleShort("C", cl::desc("Alias for --demangle"), 201 cl::aliasopt(Demangle), cl::NotHidden); 202 203 // --hash-table 204 cl::opt<bool> HashTable("hash-table", 205 cl::desc("Display ELF hash table")); 206 207 // --gnu-hash-table 208 cl::opt<bool> GnuHashTable("gnu-hash-table", 209 cl::desc("Display ELF .gnu.hash section")); 210 211 // --expand-relocs 212 cl::opt<bool> ExpandRelocs("expand-relocs", 213 cl::desc("Expand each shown relocation to multiple lines")); 214 215 // --raw-relr 216 cl::opt<bool> RawRelr("raw-relr", 217 cl::desc("Do not decode relocations in SHT_RELR section, display raw contents")); 218 219 // --codeview 220 cl::opt<bool> CodeView("codeview", 221 cl::desc("Display CodeView debug information")); 222 223 // --codeview-merged-types 224 cl::opt<bool> 225 CodeViewMergedTypes("codeview-merged-types", 226 cl::desc("Display the merged CodeView type stream")); 227 228 // --codeview-ghash 229 cl::opt<bool> CodeViewEnableGHash( 230 "codeview-ghash", 231 cl::desc( 232 "Enable global hashing for CodeView type stream de-duplication")); 233 234 // --codeview-subsection-bytes 235 cl::opt<bool> CodeViewSubsectionBytes( 236 "codeview-subsection-bytes", 237 cl::desc("Dump raw contents of codeview debug sections and records")); 238 239 // --arch-specific 240 cl::opt<bool> ArchSpecificInfo("arch-specific", 241 cl::desc("Displays architecture-specific information, if there is any.")); 242 cl::alias ArchSpecifcInfoShort("A", cl::desc("Alias for --arch-specific"), 243 cl::aliasopt(ArchSpecificInfo), cl::NotHidden); 244 245 // --coff-imports 246 cl::opt<bool> 247 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table")); 248 249 // --coff-exports 250 cl::opt<bool> 251 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table")); 252 253 // --coff-directives 254 cl::opt<bool> 255 COFFDirectives("coff-directives", 256 cl::desc("Display the PE/COFF .drectve section")); 257 258 // --coff-basereloc 259 cl::opt<bool> 260 COFFBaseRelocs("coff-basereloc", 261 cl::desc("Display the PE/COFF .reloc section")); 262 263 // --coff-debug-directory 264 cl::opt<bool> 265 COFFDebugDirectory("coff-debug-directory", 266 cl::desc("Display the PE/COFF debug directory")); 267 268 // --coff-resources 269 cl::opt<bool> COFFResources("coff-resources", 270 cl::desc("Display the PE/COFF .rsrc section")); 271 272 // --coff-load-config 273 cl::opt<bool> 274 COFFLoadConfig("coff-load-config", 275 cl::desc("Display the PE/COFF load config")); 276 277 // --elf-linker-options 278 cl::opt<bool> 279 ELFLinkerOptions("elf-linker-options", 280 cl::desc("Display the ELF .linker-options section")); 281 282 // --macho-data-in-code 283 cl::opt<bool> 284 MachODataInCode("macho-data-in-code", 285 cl::desc("Display MachO Data in Code command")); 286 287 // --macho-indirect-symbols 288 cl::opt<bool> 289 MachOIndirectSymbols("macho-indirect-symbols", 290 cl::desc("Display MachO indirect symbols")); 291 292 // --macho-linker-options 293 cl::opt<bool> 294 MachOLinkerOptions("macho-linker-options", 295 cl::desc("Display MachO linker options")); 296 297 // --macho-segment 298 cl::opt<bool> 299 MachOSegment("macho-segment", 300 cl::desc("Display MachO Segment command")); 301 302 // --macho-version-min 303 cl::opt<bool> 304 MachOVersionMin("macho-version-min", 305 cl::desc("Display MachO version min command")); 306 307 // --macho-dysymtab 308 cl::opt<bool> 309 MachODysymtab("macho-dysymtab", 310 cl::desc("Display MachO Dysymtab command")); 311 312 // --stackmap 313 cl::opt<bool> 314 PrintStackMap("stackmap", 315 cl::desc("Display contents of stackmap section")); 316 317 // --stack-sizes 318 cl::opt<bool> 319 PrintStackSizes("stack-sizes", 320 cl::desc("Display contents of all stack sizes sections")); 321 322 // --version-info, -V 323 cl::opt<bool> 324 VersionInfo("version-info", 325 cl::desc("Display ELF version sections (if present)")); 326 cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"), 327 cl::aliasopt(VersionInfo)); 328 329 // --elf-section-groups, --section-groups, -g 330 cl::opt<bool> SectionGroups("elf-section-groups", 331 cl::desc("Display ELF section group contents")); 332 cl::alias SectionGroupsAlias("section-groups", 333 cl::desc("Alias for -elf-sections-groups"), 334 cl::aliasopt(SectionGroups)); 335 cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"), 336 cl::aliasopt(SectionGroups)); 337 338 // --elf-hash-histogram, --histogram, -I 339 cl::opt<bool> HashHistogram( 340 "elf-hash-histogram", 341 cl::desc("Display bucket list histogram for hash sections")); 342 cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"), 343 cl::aliasopt(HashHistogram)); 344 cl::alias HistogramAlias("histogram", 345 cl::desc("Alias for --elf-hash-histogram"), 346 cl::aliasopt(HashHistogram)); 347 348 // --elf-cg-profile 349 cl::opt<bool> CGProfile("elf-cg-profile", cl::desc("Display callgraph profile section")); 350 351 // -addrsig 352 cl::opt<bool> Addrsig("addrsig", 353 cl::desc("Display address-significance table")); 354 355 // -elf-output-style 356 cl::opt<OutputStyleTy> 357 Output("elf-output-style", cl::desc("Specify ELF dump style"), 358 cl::values(clEnumVal(LLVM, "LLVM default style"), 359 clEnumVal(GNU, "GNU readelf style")), 360 cl::init(LLVM)); 361 362 cl::extrahelp 363 HelpResponse("\nPass @FILE as argument to read options from FILE.\n"); 364 } // namespace opts 365 366 static StringRef ToolName; 367 368 namespace llvm { 369 370 LLVM_ATTRIBUTE_NORETURN static void error(Twine Msg) { 371 // Flush the standard output to print the error at a 372 // proper place. 373 fouts().flush(); 374 WithColor::error(errs(), ToolName) << Msg << "\n"; 375 exit(1); 376 } 377 378 LLVM_ATTRIBUTE_NORETURN void reportError(Error Err, StringRef Input) { 379 assert(Err); 380 if (Input == "-") 381 Input = "<stdin>"; 382 handleAllErrors(createFileError(Input, std::move(Err)), 383 [&](const ErrorInfoBase &EI) { error(EI.message()); }); 384 llvm_unreachable("error() call should never return"); 385 } 386 387 void reportWarning(Error Err, StringRef Input) { 388 assert(Err); 389 if (Input == "-") 390 Input = "<stdin>"; 391 392 // Flush the standard output to print the warning at a 393 // proper place. 394 fouts().flush(); 395 handleAllErrors( 396 createFileError(Input, std::move(Err)), [&](const ErrorInfoBase &EI) { 397 WithColor::warning(errs(), ToolName) << EI.message() << "\n"; 398 }); 399 } 400 401 } // namespace llvm 402 403 namespace { 404 struct ReadObjTypeTableBuilder { 405 ReadObjTypeTableBuilder() 406 : Allocator(), IDTable(Allocator), TypeTable(Allocator), 407 GlobalIDTable(Allocator), GlobalTypeTable(Allocator) {} 408 409 llvm::BumpPtrAllocator Allocator; 410 llvm::codeview::MergingTypeTableBuilder IDTable; 411 llvm::codeview::MergingTypeTableBuilder TypeTable; 412 llvm::codeview::GlobalTypeTableBuilder GlobalIDTable; 413 llvm::codeview::GlobalTypeTableBuilder GlobalTypeTable; 414 std::vector<OwningBinary<Binary>> Binaries; 415 }; 416 } // namespace 417 static ReadObjTypeTableBuilder CVTypes; 418 419 /// Creates an format-specific object file dumper. 420 static std::error_code createDumper(const ObjectFile *Obj, 421 ScopedPrinter &Writer, 422 std::unique_ptr<ObjDumper> &Result) { 423 if (!Obj) 424 return readobj_error::unsupported_file_format; 425 426 if (Obj->isCOFF()) 427 return createCOFFDumper(Obj, Writer, Result); 428 if (Obj->isELF()) 429 return createELFDumper(Obj, Writer, Result); 430 if (Obj->isMachO()) 431 return createMachODumper(Obj, Writer, Result); 432 if (Obj->isWasm()) 433 return createWasmDumper(Obj, Writer, Result); 434 if (Obj->isXCOFF()) 435 return createXCOFFDumper(Obj, Writer, Result); 436 437 return readobj_error::unsupported_obj_file_format; 438 } 439 440 /// Dumps the specified object file. 441 static void dumpObject(const ObjectFile *Obj, ScopedPrinter &Writer, 442 const Archive *A = nullptr) { 443 std::string FileStr = 444 A ? Twine(A->getFileName() + "(" + Obj->getFileName() + ")").str() 445 : Obj->getFileName().str(); 446 447 std::unique_ptr<ObjDumper> Dumper; 448 if (std::error_code EC = createDumper(Obj, Writer, Dumper)) 449 reportError(errorCodeToError(EC), FileStr); 450 451 if (opts::Output == opts::LLVM || opts::InputFilenames.size() > 1 || A) { 452 Writer.startLine() << "\n"; 453 Writer.printString("File", FileStr); 454 } 455 if (opts::Output == opts::LLVM) { 456 Writer.printString("Format", Obj->getFileFormatName()); 457 Writer.printString("Arch", Triple::getArchTypeName( 458 (llvm::Triple::ArchType)Obj->getArch())); 459 Writer.printString("AddressSize", 460 formatv("{0}bit", 8 * Obj->getBytesInAddress())); 461 Dumper->printLoadName(); 462 } 463 464 if (opts::FileHeaders) 465 Dumper->printFileHeaders(); 466 if (opts::SectionHeaders) 467 Dumper->printSectionHeaders(); 468 if (opts::Relocations) 469 Dumper->printRelocations(); 470 if (opts::DynRelocs) 471 Dumper->printDynamicRelocations(); 472 if (opts::Symbols || opts::DynamicSymbols) 473 Dumper->printSymbols(opts::Symbols, opts::DynamicSymbols); 474 if (opts::HashSymbols) 475 Dumper->printHashSymbols(); 476 if (opts::UnwindInfo) 477 Dumper->printUnwindInfo(); 478 if (opts::DynamicTable) 479 Dumper->printDynamicTable(); 480 if (opts::NeededLibraries) 481 Dumper->printNeededLibraries(); 482 if (opts::ProgramHeaders || opts::SectionMapping == cl::BOU_TRUE) 483 Dumper->printProgramHeaders(opts::ProgramHeaders, opts::SectionMapping); 484 if (!opts::StringDump.empty()) 485 Dumper->printSectionsAsString(Obj, opts::StringDump); 486 if (!opts::HexDump.empty()) 487 Dumper->printSectionsAsHex(Obj, opts::HexDump); 488 if (opts::HashTable) 489 Dumper->printHashTable(); 490 if (opts::GnuHashTable) 491 Dumper->printGnuHashTable(); 492 if (opts::VersionInfo) 493 Dumper->printVersionInfo(); 494 if (Obj->isELF()) { 495 if (opts::DependentLibraries) 496 Dumper->printDependentLibs(); 497 if (opts::ELFLinkerOptions) 498 Dumper->printELFLinkerOptions(); 499 if (opts::ArchSpecificInfo) 500 Dumper->printArchSpecificInfo(); 501 if (opts::SectionGroups) 502 Dumper->printGroupSections(); 503 if (opts::HashHistogram) 504 Dumper->printHashHistogram(); 505 if (opts::CGProfile) 506 Dumper->printCGProfile(); 507 if (opts::Addrsig) 508 Dumper->printAddrsig(); 509 if (opts::Notes) 510 Dumper->printNotes(); 511 } 512 if (Obj->isCOFF()) { 513 if (opts::COFFImports) 514 Dumper->printCOFFImports(); 515 if (opts::COFFExports) 516 Dumper->printCOFFExports(); 517 if (opts::COFFDirectives) 518 Dumper->printCOFFDirectives(); 519 if (opts::COFFBaseRelocs) 520 Dumper->printCOFFBaseReloc(); 521 if (opts::COFFDebugDirectory) 522 Dumper->printCOFFDebugDirectory(); 523 if (opts::COFFResources) 524 Dumper->printCOFFResources(); 525 if (opts::COFFLoadConfig) 526 Dumper->printCOFFLoadConfig(); 527 if (opts::Addrsig) 528 Dumper->printAddrsig(); 529 if (opts::CodeView) 530 Dumper->printCodeViewDebugInfo(); 531 if (opts::CodeViewMergedTypes) 532 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable, 533 CVTypes.GlobalIDTable, CVTypes.GlobalTypeTable, 534 opts::CodeViewEnableGHash); 535 } 536 if (Obj->isMachO()) { 537 if (opts::MachODataInCode) 538 Dumper->printMachODataInCode(); 539 if (opts::MachOIndirectSymbols) 540 Dumper->printMachOIndirectSymbols(); 541 if (opts::MachOLinkerOptions) 542 Dumper->printMachOLinkerOptions(); 543 if (opts::MachOSegment) 544 Dumper->printMachOSegment(); 545 if (opts::MachOVersionMin) 546 Dumper->printMachOVersionMin(); 547 if (opts::MachODysymtab) 548 Dumper->printMachODysymtab(); 549 } 550 if (opts::PrintStackMap) 551 Dumper->printStackMap(); 552 if (opts::PrintStackSizes) 553 Dumper->printStackSizes(); 554 } 555 556 /// Dumps each object file in \a Arc; 557 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) { 558 Error Err = Error::success(); 559 for (auto &Child : Arc->children(Err)) { 560 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 561 if (!ChildOrErr) { 562 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 563 reportError(std::move(E), Arc->getFileName()); 564 continue; 565 } 566 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 567 dumpObject(Obj, Writer, Arc); 568 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 569 dumpCOFFImportFile(Imp, Writer); 570 else 571 reportError(errorCodeToError(readobj_error::unrecognized_file_format), 572 Arc->getFileName()); 573 } 574 if (Err) 575 reportError(std::move(Err), Arc->getFileName()); 576 } 577 578 /// Dumps each object file in \a MachO Universal Binary; 579 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary, 580 ScopedPrinter &Writer) { 581 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) { 582 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile(); 583 if (ObjOrErr) 584 dumpObject(&*ObjOrErr.get(), Writer); 585 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) 586 reportError(ObjOrErr.takeError(), UBinary->getFileName()); 587 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) 588 dumpArchive(&*AOrErr.get(), Writer); 589 } 590 } 591 592 /// Dumps \a WinRes, Windows Resource (.res) file; 593 static void dumpWindowsResourceFile(WindowsResource *WinRes, 594 ScopedPrinter &Printer) { 595 WindowsRes::Dumper Dumper(WinRes, Printer); 596 if (auto Err = Dumper.printData()) 597 reportError(std::move(Err), WinRes->getFileName()); 598 } 599 600 601 /// Opens \a File and dumps it. 602 static void dumpInput(StringRef File, ScopedPrinter &Writer) { 603 // Attempt to open the binary. 604 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File); 605 if (!BinaryOrErr) 606 reportError(BinaryOrErr.takeError(), File); 607 Binary &Binary = *BinaryOrErr.get().getBinary(); 608 609 if (Archive *Arc = dyn_cast<Archive>(&Binary)) 610 dumpArchive(Arc, Writer); 611 else if (MachOUniversalBinary *UBinary = 612 dyn_cast<MachOUniversalBinary>(&Binary)) 613 dumpMachOUniversalBinary(UBinary, Writer); 614 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary)) 615 dumpObject(Obj, Writer); 616 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary)) 617 dumpCOFFImportFile(Import, Writer); 618 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary)) 619 dumpWindowsResourceFile(WinRes, Writer); 620 else 621 reportError(errorCodeToError(readobj_error::unrecognized_file_format), 622 File); 623 624 CVTypes.Binaries.push_back(std::move(*BinaryOrErr)); 625 } 626 627 /// Registers aliases that should only be allowed by readobj. 628 static void registerReadobjAliases() { 629 // -s has meant --sections for a very long time in llvm-readobj despite 630 // meaning --symbols in readelf. 631 static cl::alias SectionsShort("s", cl::desc("Alias for --section-headers"), 632 cl::aliasopt(opts::SectionHeaders), 633 cl::NotHidden); 634 635 // Only register -t in llvm-readobj, as readelf reserves it for 636 // --section-details (not implemented yet). 637 static cl::alias SymbolsShort("t", cl::desc("Alias for --symbols"), 638 cl::aliasopt(opts::Symbols), cl::NotHidden); 639 640 // The following two-letter aliases are only provided for readobj, as readelf 641 // allows single-letter args to be grouped together. 642 static cl::alias SectionRelocationsShort( 643 "sr", cl::desc("Alias for --section-relocations"), 644 cl::aliasopt(opts::SectionRelocations)); 645 static cl::alias SectionDataShort("sd", cl::desc("Alias for --section-data"), 646 cl::aliasopt(opts::SectionData)); 647 static cl::alias SectionSymbolsShort("st", 648 cl::desc("Alias for --section-symbols"), 649 cl::aliasopt(opts::SectionSymbols)); 650 static cl::alias DynamicSymbolsShort("dt", 651 cl::desc("Alias for --dyn-symbols"), 652 cl::aliasopt(opts::DynamicSymbols)); 653 } 654 655 /// Registers aliases that should only be allowed by readelf. 656 static void registerReadelfAliases() { 657 // -s is here because for readobj it means --sections. 658 static cl::alias SymbolsShort("s", cl::desc("Alias for --symbols"), 659 cl::aliasopt(opts::Symbols), cl::NotHidden, 660 cl::Grouping); 661 662 // Allow all single letter flags to be grouped together. 663 for (auto &OptEntry : cl::getRegisteredOptions()) { 664 StringRef ArgName = OptEntry.getKey(); 665 cl::Option *Option = OptEntry.getValue(); 666 if (ArgName.size() == 1) 667 apply(Option, cl::Grouping); 668 } 669 } 670 671 int main(int argc, const char *argv[]) { 672 InitLLVM X(argc, argv); 673 ToolName = argv[0]; 674 675 // Register the target printer for --version. 676 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 677 678 if (sys::path::stem(argv[0]).contains("readelf")) { 679 opts::Output = opts::GNU; 680 registerReadelfAliases(); 681 } else { 682 registerReadobjAliases(); 683 } 684 685 cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n"); 686 687 if (opts::All) { 688 opts::FileHeaders = true; 689 opts::ProgramHeaders = true; 690 opts::SectionHeaders = true; 691 opts::Symbols = true; 692 opts::Relocations = true; 693 opts::DynamicTable = true; 694 opts::Notes = true; 695 opts::VersionInfo = true; 696 opts::UnwindInfo = true; 697 opts::SectionGroups = true; 698 opts::HashHistogram = true; 699 if (opts::Output == opts::LLVM) { 700 opts::Addrsig = true; 701 opts::PrintStackSizes = true; 702 } 703 } 704 705 if (opts::Headers) { 706 opts::FileHeaders = true; 707 opts::ProgramHeaders = true; 708 opts::SectionHeaders = true; 709 } 710 711 // Default to stdin if no filename is specified. 712 if (opts::InputFilenames.empty()) 713 opts::InputFilenames.push_back("-"); 714 715 ScopedPrinter Writer(fouts()); 716 for (const std::string &I : opts::InputFilenames) 717 dumpInput(I, Writer); 718 719 if (opts::CodeViewMergedTypes) { 720 if (opts::CodeViewEnableGHash) 721 dumpCodeViewMergedTypes(Writer, CVTypes.GlobalIDTable.records(), 722 CVTypes.GlobalTypeTable.records()); 723 else 724 dumpCodeViewMergedTypes(Writer, CVTypes.IDTable.records(), 725 CVTypes.TypeTable.records()); 726 } 727 728 return 0; 729 } 730