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