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