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/MC/TargetRegistry.h" 27 #include "llvm/Object/Archive.h" 28 #include "llvm/Object/COFFImportFile.h" 29 #include "llvm/Object/ELFObjectFile.h" 30 #include "llvm/Object/MachOUniversal.h" 31 #include "llvm/Object/ObjectFile.h" 32 #include "llvm/Object/Wasm.h" 33 #include "llvm/Object/WindowsResource.h" 34 #include "llvm/Object/XCOFFObjectFile.h" 35 #include "llvm/Option/Arg.h" 36 #include "llvm/Option/ArgList.h" 37 #include "llvm/Option/Option.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/CommandLine.h" 40 #include "llvm/Support/DataTypes.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/Errc.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/FormatVariadic.h" 45 #include "llvm/Support/InitLLVM.h" 46 #include "llvm/Support/Path.h" 47 #include "llvm/Support/ScopedPrinter.h" 48 #include "llvm/Support/WithColor.h" 49 50 using namespace llvm; 51 using namespace llvm::object; 52 53 namespace { 54 using namespace llvm::opt; // for HelpHidden in Opts.inc 55 enum ID { 56 OPT_INVALID = 0, // This is not an option ID. 57 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 58 HELPTEXT, METAVAR, VALUES) \ 59 OPT_##ID, 60 #include "Opts.inc" 61 #undef OPTION 62 }; 63 64 #define PREFIX(NAME, VALUE) \ 65 static constexpr std::initializer_list<StringLiteral> NAME = VALUE; 66 #include "Opts.inc" 67 #undef PREFIX 68 69 static constexpr std::initializer_list<opt::OptTable::Info> InfoTable = { 70 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ 71 HELPTEXT, METAVAR, VALUES) \ 72 { \ 73 PREFIX, NAME, HELPTEXT, \ 74 METAVAR, OPT_##ID, opt::Option::KIND##Class, \ 75 PARAM, FLAGS, OPT_##GROUP, \ 76 OPT_##ALIAS, ALIASARGS, VALUES}, 77 #include "Opts.inc" 78 #undef OPTION 79 }; 80 81 class ReadobjOptTable : public opt::OptTable { 82 public: 83 ReadobjOptTable() : OptTable(InfoTable) { setGroupedShortOptions(true); } 84 }; 85 86 enum OutputFormatTy { bsd, sysv, posix, darwin, just_symbols }; 87 88 enum SortSymbolKeyTy { 89 NAME = 0, 90 TYPE = 1, 91 UNKNOWN = 100, 92 // TODO: add ADDRESS, SIZE as needed. 93 }; 94 95 } // namespace 96 97 namespace opts { 98 static bool Addrsig; 99 static bool All; 100 static bool ArchSpecificInfo; 101 static bool BBAddrMap; 102 bool ExpandRelocs; 103 static bool CGProfile; 104 bool Demangle; 105 static bool DependentLibraries; 106 static bool DynRelocs; 107 static bool DynamicSymbols; 108 static bool FileHeaders; 109 static bool Headers; 110 static std::vector<std::string> HexDump; 111 static bool PrettyPrint; 112 static bool PrintStackMap; 113 static bool PrintStackSizes; 114 static bool Relocations; 115 bool SectionData; 116 static bool SectionDetails; 117 static bool SectionHeaders; 118 bool SectionRelocations; 119 bool SectionSymbols; 120 static std::vector<std::string> StringDump; 121 static bool StringTable; 122 static bool Symbols; 123 static bool UnwindInfo; 124 static cl::boolOrDefault SectionMapping; 125 static SmallVector<SortSymbolKeyTy> SortKeys; 126 127 // ELF specific options. 128 static bool DynamicTable; 129 static bool ELFLinkerOptions; 130 static bool GnuHashTable; 131 static bool HashSymbols; 132 static bool HashTable; 133 static bool HashHistogram; 134 static bool NeededLibraries; 135 static bool Notes; 136 static bool ProgramHeaders; 137 bool RawRelr; 138 static bool SectionGroups; 139 static bool VersionInfo; 140 141 // Mach-O specific options. 142 static bool MachODataInCode; 143 static bool MachODysymtab; 144 static bool MachOIndirectSymbols; 145 static bool MachOLinkerOptions; 146 static bool MachOSegment; 147 static bool MachOVersionMin; 148 149 // PE/COFF specific options. 150 static bool CodeView; 151 static bool CodeViewEnableGHash; 152 static bool CodeViewMergedTypes; 153 bool CodeViewSubsectionBytes; 154 static bool COFFBaseRelocs; 155 static bool COFFDebugDirectory; 156 static bool COFFDirectives; 157 static bool COFFExports; 158 static bool COFFImports; 159 static bool COFFLoadConfig; 160 static bool COFFResources; 161 static bool COFFTLSDirectory; 162 163 // XCOFF specific options. 164 static bool XCOFFAuxiliaryHeader; 165 static bool XCOFFLoaderSectionHeader; 166 static bool XCOFFLoaderSectionSymbol; 167 static bool XCOFFLoaderSectionRelocation; 168 static bool XCOFFExceptionSection; 169 170 OutputStyleTy Output = OutputStyleTy::LLVM; 171 static std::vector<std::string> InputFilenames; 172 } // namespace opts 173 174 static StringRef ToolName; 175 176 namespace llvm { 177 178 [[noreturn]] static void error(Twine Msg) { 179 // Flush the standard output to print the error at a 180 // proper place. 181 fouts().flush(); 182 WithColor::error(errs(), ToolName) << Msg << "\n"; 183 exit(1); 184 } 185 186 [[noreturn]] void reportError(Error Err, StringRef Input) { 187 assert(Err); 188 if (Input == "-") 189 Input = "<stdin>"; 190 handleAllErrors(createFileError(Input, std::move(Err)), 191 [&](const ErrorInfoBase &EI) { error(EI.message()); }); 192 llvm_unreachable("error() call should never return"); 193 } 194 195 void reportWarning(Error Err, StringRef Input) { 196 assert(Err); 197 if (Input == "-") 198 Input = "<stdin>"; 199 200 // Flush the standard output to print the warning at a 201 // proper place. 202 fouts().flush(); 203 handleAllErrors( 204 createFileError(Input, std::move(Err)), [&](const ErrorInfoBase &EI) { 205 WithColor::warning(errs(), ToolName) << EI.message() << "\n"; 206 }); 207 } 208 209 } // namespace llvm 210 211 static void parseOptions(const opt::InputArgList &Args) { 212 opts::Addrsig = Args.hasArg(OPT_addrsig); 213 opts::All = Args.hasArg(OPT_all); 214 opts::ArchSpecificInfo = Args.hasArg(OPT_arch_specific); 215 opts::BBAddrMap = Args.hasArg(OPT_bb_addr_map); 216 opts::CGProfile = Args.hasArg(OPT_cg_profile); 217 opts::Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, false); 218 opts::DependentLibraries = Args.hasArg(OPT_dependent_libraries); 219 opts::DynRelocs = Args.hasArg(OPT_dyn_relocations); 220 opts::DynamicSymbols = Args.hasArg(OPT_dyn_syms); 221 opts::ExpandRelocs = Args.hasArg(OPT_expand_relocs); 222 opts::FileHeaders = Args.hasArg(OPT_file_header); 223 opts::Headers = Args.hasArg(OPT_headers); 224 opts::HexDump = Args.getAllArgValues(OPT_hex_dump_EQ); 225 opts::Relocations = Args.hasArg(OPT_relocs); 226 opts::SectionData = Args.hasArg(OPT_section_data); 227 opts::SectionDetails = Args.hasArg(OPT_section_details); 228 opts::SectionHeaders = Args.hasArg(OPT_section_headers); 229 opts::SectionRelocations = Args.hasArg(OPT_section_relocations); 230 opts::SectionSymbols = Args.hasArg(OPT_section_symbols); 231 if (Args.hasArg(OPT_section_mapping)) 232 opts::SectionMapping = cl::BOU_TRUE; 233 else if (Args.hasArg(OPT_section_mapping_EQ_false)) 234 opts::SectionMapping = cl::BOU_FALSE; 235 else 236 opts::SectionMapping = cl::BOU_UNSET; 237 opts::PrintStackSizes = Args.hasArg(OPT_stack_sizes); 238 opts::PrintStackMap = Args.hasArg(OPT_stackmap); 239 opts::StringDump = Args.getAllArgValues(OPT_string_dump_EQ); 240 opts::StringTable = Args.hasArg(OPT_string_table); 241 opts::Symbols = Args.hasArg(OPT_symbols); 242 opts::UnwindInfo = Args.hasArg(OPT_unwind); 243 244 // ELF specific options. 245 opts::DynamicTable = Args.hasArg(OPT_dynamic_table); 246 opts::ELFLinkerOptions = Args.hasArg(OPT_elf_linker_options); 247 if (Arg *A = Args.getLastArg(OPT_elf_output_style_EQ)) { 248 std::string OutputStyleChoice = A->getValue(); 249 opts::Output = StringSwitch<opts::OutputStyleTy>(OutputStyleChoice) 250 .Case("LLVM", opts::OutputStyleTy::LLVM) 251 .Case("GNU", opts::OutputStyleTy::GNU) 252 .Case("JSON", opts::OutputStyleTy::JSON) 253 .Default(opts::OutputStyleTy::UNKNOWN); 254 if (opts::Output == opts::OutputStyleTy::UNKNOWN) { 255 error("--elf-output-style value should be either 'LLVM', 'GNU', or " 256 "'JSON', but was '" + 257 OutputStyleChoice + "'"); 258 } 259 } 260 opts::GnuHashTable = Args.hasArg(OPT_gnu_hash_table); 261 opts::HashSymbols = Args.hasArg(OPT_hash_symbols); 262 opts::HashTable = Args.hasArg(OPT_hash_table); 263 opts::HashHistogram = Args.hasArg(OPT_histogram); 264 opts::NeededLibraries = Args.hasArg(OPT_needed_libs); 265 opts::Notes = Args.hasArg(OPT_notes); 266 opts::PrettyPrint = Args.hasArg(OPT_pretty_print); 267 opts::ProgramHeaders = Args.hasArg(OPT_program_headers); 268 opts::RawRelr = Args.hasArg(OPT_raw_relr); 269 opts::SectionGroups = Args.hasArg(OPT_section_groups); 270 if (Arg *A = Args.getLastArg(OPT_sort_symbols_EQ)) { 271 std::string SortKeysString = A->getValue(); 272 for (StringRef KeyStr : llvm::split(A->getValue(), ",")) { 273 SortSymbolKeyTy KeyType = StringSwitch<SortSymbolKeyTy>(KeyStr) 274 .Case("name", SortSymbolKeyTy::NAME) 275 .Case("type", SortSymbolKeyTy::TYPE) 276 .Default(SortSymbolKeyTy::UNKNOWN); 277 if (KeyType == SortSymbolKeyTy::UNKNOWN) 278 error("--sort-symbols value should be 'name' or 'type', but was '" + 279 Twine(KeyStr) + "'"); 280 opts::SortKeys.push_back(KeyType); 281 } 282 } 283 opts::VersionInfo = Args.hasArg(OPT_version_info); 284 285 // Mach-O specific options. 286 opts::MachODataInCode = Args.hasArg(OPT_macho_data_in_code); 287 opts::MachODysymtab = Args.hasArg(OPT_macho_dysymtab); 288 opts::MachOIndirectSymbols = Args.hasArg(OPT_macho_indirect_symbols); 289 opts::MachOLinkerOptions = Args.hasArg(OPT_macho_linker_options); 290 opts::MachOSegment = Args.hasArg(OPT_macho_segment); 291 opts::MachOVersionMin = Args.hasArg(OPT_macho_version_min); 292 293 // PE/COFF specific options. 294 opts::CodeView = Args.hasArg(OPT_codeview); 295 opts::CodeViewEnableGHash = Args.hasArg(OPT_codeview_ghash); 296 opts::CodeViewMergedTypes = Args.hasArg(OPT_codeview_merged_types); 297 opts::CodeViewSubsectionBytes = Args.hasArg(OPT_codeview_subsection_bytes); 298 opts::COFFBaseRelocs = Args.hasArg(OPT_coff_basereloc); 299 opts::COFFDebugDirectory = Args.hasArg(OPT_coff_debug_directory); 300 opts::COFFDirectives = Args.hasArg(OPT_coff_directives); 301 opts::COFFExports = Args.hasArg(OPT_coff_exports); 302 opts::COFFImports = Args.hasArg(OPT_coff_imports); 303 opts::COFFLoadConfig = Args.hasArg(OPT_coff_load_config); 304 opts::COFFResources = Args.hasArg(OPT_coff_resources); 305 opts::COFFTLSDirectory = Args.hasArg(OPT_coff_tls_directory); 306 307 // XCOFF specific options. 308 opts::XCOFFAuxiliaryHeader = Args.hasArg(OPT_auxiliary_header); 309 opts::XCOFFLoaderSectionHeader = Args.hasArg(OPT_loader_section_header); 310 opts::XCOFFLoaderSectionSymbol = Args.hasArg(OPT_loader_section_symbols); 311 opts::XCOFFLoaderSectionRelocation = 312 Args.hasArg(OPT_loader_section_relocations); 313 opts::XCOFFExceptionSection = Args.hasArg(OPT_exception_section); 314 315 opts::InputFilenames = Args.getAllArgValues(OPT_INPUT); 316 } 317 318 namespace { 319 struct ReadObjTypeTableBuilder { 320 ReadObjTypeTableBuilder() 321 : IDTable(Allocator), TypeTable(Allocator), GlobalIDTable(Allocator), 322 GlobalTypeTable(Allocator) {} 323 324 llvm::BumpPtrAllocator Allocator; 325 llvm::codeview::MergingTypeTableBuilder IDTable; 326 llvm::codeview::MergingTypeTableBuilder TypeTable; 327 llvm::codeview::GlobalTypeTableBuilder GlobalIDTable; 328 llvm::codeview::GlobalTypeTableBuilder GlobalTypeTable; 329 std::vector<OwningBinary<Binary>> Binaries; 330 }; 331 } // namespace 332 static ReadObjTypeTableBuilder CVTypes; 333 334 /// Creates an format-specific object file dumper. 335 static Expected<std::unique_ptr<ObjDumper>> 336 createDumper(const ObjectFile &Obj, ScopedPrinter &Writer) { 337 if (const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) 338 return createCOFFDumper(*COFFObj, Writer); 339 340 if (const ELFObjectFileBase *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) 341 return createELFDumper(*ELFObj, Writer); 342 343 if (const MachOObjectFile *MachOObj = dyn_cast<MachOObjectFile>(&Obj)) 344 return createMachODumper(*MachOObj, Writer); 345 346 if (const WasmObjectFile *WasmObj = dyn_cast<WasmObjectFile>(&Obj)) 347 return createWasmDumper(*WasmObj, Writer); 348 349 if (const XCOFFObjectFile *XObj = dyn_cast<XCOFFObjectFile>(&Obj)) 350 return createXCOFFDumper(*XObj, Writer); 351 352 return createStringError(errc::invalid_argument, 353 "unsupported object file format"); 354 } 355 356 /// Dumps the specified object file. 357 static void dumpObject(ObjectFile &Obj, ScopedPrinter &Writer, 358 const Archive *A = nullptr) { 359 std::string FileStr = 360 A ? Twine(A->getFileName() + "(" + Obj.getFileName() + ")").str() 361 : Obj.getFileName().str(); 362 363 std::string ContentErrString; 364 if (Error ContentErr = Obj.initContent()) 365 ContentErrString = "unable to continue dumping, the file is corrupt: " + 366 toString(std::move(ContentErr)); 367 368 ObjDumper *Dumper; 369 std::optional<SymbolComparator> SymComp; 370 Expected<std::unique_ptr<ObjDumper>> DumperOrErr = createDumper(Obj, Writer); 371 if (!DumperOrErr) 372 reportError(DumperOrErr.takeError(), FileStr); 373 Dumper = (*DumperOrErr).get(); 374 375 if (!opts::SortKeys.empty()) { 376 if (Dumper->canCompareSymbols()) { 377 SymComp = SymbolComparator(); 378 for (SortSymbolKeyTy Key : opts::SortKeys) { 379 switch (Key) { 380 case NAME: 381 SymComp->addPredicate([Dumper](SymbolRef LHS, SymbolRef RHS) { 382 return Dumper->compareSymbolsByName(LHS, RHS); 383 }); 384 break; 385 case TYPE: 386 SymComp->addPredicate([Dumper](SymbolRef LHS, SymbolRef RHS) { 387 return Dumper->compareSymbolsByType(LHS, RHS); 388 }); 389 break; 390 case UNKNOWN: 391 llvm_unreachable("Unsupported sort key"); 392 } 393 } 394 395 } else { 396 reportWarning(createStringError( 397 errc::invalid_argument, 398 "--sort-symbols is not supported yet for this format"), 399 FileStr); 400 } 401 } 402 Dumper->printFileSummary(FileStr, Obj, opts::InputFilenames, A); 403 404 if (opts::FileHeaders) 405 Dumper->printFileHeaders(); 406 407 // Auxiliary header in XOCFF is right after the file header, so print the data 408 // here. 409 if (Obj.isXCOFF() && opts::XCOFFAuxiliaryHeader) 410 Dumper->printAuxiliaryHeader(); 411 412 // This is only used for ELF currently. In some cases, when an object is 413 // corrupt (e.g. truncated), we can't dump anything except the file header. 414 if (!ContentErrString.empty()) 415 reportError(createError(ContentErrString), FileStr); 416 417 if (opts::SectionDetails || opts::SectionHeaders) { 418 if (opts::Output == opts::GNU && opts::SectionDetails) 419 Dumper->printSectionDetails(); 420 else 421 Dumper->printSectionHeaders(); 422 } 423 424 if (opts::HashSymbols) 425 Dumper->printHashSymbols(); 426 if (opts::ProgramHeaders || opts::SectionMapping == cl::BOU_TRUE) 427 Dumper->printProgramHeaders(opts::ProgramHeaders, opts::SectionMapping); 428 if (opts::DynamicTable) 429 Dumper->printDynamicTable(); 430 if (opts::NeededLibraries) 431 Dumper->printNeededLibraries(); 432 if (opts::Relocations) 433 Dumper->printRelocations(); 434 if (opts::DynRelocs) 435 Dumper->printDynamicRelocations(); 436 if (opts::UnwindInfo) 437 Dumper->printUnwindInfo(); 438 if (opts::Symbols || opts::DynamicSymbols) 439 Dumper->printSymbols(opts::Symbols, opts::DynamicSymbols, SymComp); 440 if (!opts::StringDump.empty()) 441 Dumper->printSectionsAsString(Obj, opts::StringDump); 442 if (!opts::HexDump.empty()) 443 Dumper->printSectionsAsHex(Obj, opts::HexDump); 444 if (opts::HashTable) 445 Dumper->printHashTable(); 446 if (opts::GnuHashTable) 447 Dumper->printGnuHashTable(); 448 if (opts::VersionInfo) 449 Dumper->printVersionInfo(); 450 if (opts::StringTable) 451 Dumper->printStringTable(); 452 if (Obj.isELF()) { 453 if (opts::DependentLibraries) 454 Dumper->printDependentLibs(); 455 if (opts::ELFLinkerOptions) 456 Dumper->printELFLinkerOptions(); 457 if (opts::ArchSpecificInfo) 458 Dumper->printArchSpecificInfo(); 459 if (opts::SectionGroups) 460 Dumper->printGroupSections(); 461 if (opts::HashHistogram) 462 Dumper->printHashHistograms(); 463 if (opts::CGProfile) 464 Dumper->printCGProfile(); 465 if (opts::BBAddrMap) 466 Dumper->printBBAddrMaps(); 467 if (opts::Addrsig) 468 Dumper->printAddrsig(); 469 if (opts::Notes) 470 Dumper->printNotes(); 471 } 472 if (Obj.isCOFF()) { 473 if (opts::COFFImports) 474 Dumper->printCOFFImports(); 475 if (opts::COFFExports) 476 Dumper->printCOFFExports(); 477 if (opts::COFFDirectives) 478 Dumper->printCOFFDirectives(); 479 if (opts::COFFBaseRelocs) 480 Dumper->printCOFFBaseReloc(); 481 if (opts::COFFDebugDirectory) 482 Dumper->printCOFFDebugDirectory(); 483 if (opts::COFFTLSDirectory) 484 Dumper->printCOFFTLSDirectory(); 485 if (opts::COFFResources) 486 Dumper->printCOFFResources(); 487 if (opts::COFFLoadConfig) 488 Dumper->printCOFFLoadConfig(); 489 if (opts::CGProfile) 490 Dumper->printCGProfile(); 491 if (opts::Addrsig) 492 Dumper->printAddrsig(); 493 if (opts::CodeView) 494 Dumper->printCodeViewDebugInfo(); 495 if (opts::CodeViewMergedTypes) 496 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable, 497 CVTypes.GlobalIDTable, CVTypes.GlobalTypeTable, 498 opts::CodeViewEnableGHash); 499 } 500 if (Obj.isMachO()) { 501 if (opts::MachODataInCode) 502 Dumper->printMachODataInCode(); 503 if (opts::MachOIndirectSymbols) 504 Dumper->printMachOIndirectSymbols(); 505 if (opts::MachOLinkerOptions) 506 Dumper->printMachOLinkerOptions(); 507 if (opts::MachOSegment) 508 Dumper->printMachOSegment(); 509 if (opts::MachOVersionMin) 510 Dumper->printMachOVersionMin(); 511 if (opts::MachODysymtab) 512 Dumper->printMachODysymtab(); 513 if (opts::CGProfile) 514 Dumper->printCGProfile(); 515 } 516 517 if (Obj.isXCOFF()) { 518 if (opts::XCOFFLoaderSectionHeader || opts::XCOFFLoaderSectionSymbol || 519 opts::XCOFFLoaderSectionRelocation) 520 Dumper->printLoaderSection(opts::XCOFFLoaderSectionHeader, 521 opts::XCOFFLoaderSectionSymbol, 522 opts::XCOFFLoaderSectionRelocation); 523 524 if (opts::XCOFFExceptionSection) 525 Dumper->printExceptionSection(); 526 } 527 528 if (opts::PrintStackMap) 529 Dumper->printStackMap(); 530 if (opts::PrintStackSizes) 531 Dumper->printStackSizes(); 532 } 533 534 /// Dumps each object file in \a Arc; 535 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) { 536 Error Err = Error::success(); 537 for (auto &Child : Arc->children(Err)) { 538 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 539 if (!ChildOrErr) { 540 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 541 reportError(std::move(E), Arc->getFileName()); 542 continue; 543 } 544 545 Binary *Bin = ChildOrErr->get(); 546 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Bin)) 547 dumpObject(*Obj, Writer, Arc); 548 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(Bin)) 549 dumpCOFFImportFile(Imp, Writer); 550 else 551 reportWarning(createStringError(errc::invalid_argument, 552 Bin->getFileName() + 553 " has an unsupported file type"), 554 Arc->getFileName()); 555 } 556 if (Err) 557 reportError(std::move(Err), Arc->getFileName()); 558 } 559 560 /// Dumps each object file in \a MachO Universal Binary; 561 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary, 562 ScopedPrinter &Writer) { 563 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) { 564 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile(); 565 if (ObjOrErr) 566 dumpObject(*ObjOrErr.get(), Writer); 567 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) 568 reportError(ObjOrErr.takeError(), UBinary->getFileName()); 569 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) 570 dumpArchive(&*AOrErr.get(), Writer); 571 } 572 } 573 574 /// Dumps \a WinRes, Windows Resource (.res) file; 575 static void dumpWindowsResourceFile(WindowsResource *WinRes, 576 ScopedPrinter &Printer) { 577 WindowsRes::Dumper Dumper(WinRes, Printer); 578 if (auto Err = Dumper.printData()) 579 reportError(std::move(Err), WinRes->getFileName()); 580 } 581 582 583 /// Opens \a File and dumps it. 584 static void dumpInput(StringRef File, ScopedPrinter &Writer) { 585 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 586 MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false, 587 /*RequiresNullTerminator=*/false); 588 if (std::error_code EC = FileOrErr.getError()) 589 return reportError(errorCodeToError(EC), File); 590 591 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get(); 592 file_magic Type = identify_magic(Buffer->getBuffer()); 593 if (Type == file_magic::bitcode) { 594 reportWarning(createStringError(errc::invalid_argument, 595 "bitcode files are not supported"), 596 File); 597 return; 598 } 599 600 Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary( 601 Buffer->getMemBufferRef(), /*Context=*/nullptr, /*InitContent=*/false); 602 if (!BinaryOrErr) 603 reportError(BinaryOrErr.takeError(), File); 604 605 std::unique_ptr<Binary> Bin = std::move(*BinaryOrErr); 606 if (Archive *Arc = dyn_cast<Archive>(Bin.get())) 607 dumpArchive(Arc, Writer); 608 else if (MachOUniversalBinary *UBinary = 609 dyn_cast<MachOUniversalBinary>(Bin.get())) 610 dumpMachOUniversalBinary(UBinary, Writer); 611 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(Bin.get())) 612 dumpObject(*Obj, Writer); 613 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(Bin.get())) 614 dumpCOFFImportFile(Import, Writer); 615 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(Bin.get())) 616 dumpWindowsResourceFile(WinRes, Writer); 617 else 618 llvm_unreachable("unrecognized file type"); 619 620 CVTypes.Binaries.push_back( 621 OwningBinary<Binary>(std::move(Bin), std::move(Buffer))); 622 } 623 624 std::unique_ptr<ScopedPrinter> createWriter() { 625 if (opts::Output == opts::JSON) 626 return std::make_unique<JSONScopedPrinter>( 627 fouts(), opts::PrettyPrint ? 2 : 0, std::make_unique<ListScope>()); 628 return std::make_unique<ScopedPrinter>(fouts()); 629 } 630 631 int llvm_readobj_main(int argc, char **argv) { 632 InitLLVM X(argc, argv); 633 BumpPtrAllocator A; 634 StringSaver Saver(A); 635 ReadobjOptTable Tbl; 636 ToolName = argv[0]; 637 opt::InputArgList Args = 638 Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) { 639 error(Msg); 640 exit(1); 641 }); 642 if (Args.hasArg(OPT_help)) { 643 Tbl.printHelp( 644 outs(), 645 (Twine(ToolName) + " [options] <input object files>").str().c_str(), 646 "LLVM Object Reader"); 647 // TODO Replace this with OptTable API once it adds extrahelp support. 648 outs() << "\nPass @FILE as argument to read options from FILE.\n"; 649 return 0; 650 } 651 if (Args.hasArg(OPT_version)) { 652 cl::PrintVersionMessage(); 653 return 0; 654 } 655 656 if (sys::path::stem(argv[0]).contains("readelf")) 657 opts::Output = opts::GNU; 658 parseOptions(Args); 659 660 // Default to print error if no filename is specified. 661 if (opts::InputFilenames.empty()) { 662 error("no input files specified"); 663 } 664 665 if (opts::All) { 666 opts::FileHeaders = true; 667 opts::XCOFFAuxiliaryHeader = true; 668 opts::ProgramHeaders = true; 669 opts::SectionHeaders = true; 670 opts::Symbols = true; 671 opts::Relocations = true; 672 opts::DynamicTable = true; 673 opts::Notes = true; 674 opts::VersionInfo = true; 675 opts::UnwindInfo = true; 676 opts::SectionGroups = true; 677 opts::HashHistogram = true; 678 if (opts::Output == opts::LLVM) { 679 opts::Addrsig = true; 680 opts::PrintStackSizes = true; 681 } 682 } 683 684 if (opts::Headers) { 685 opts::FileHeaders = true; 686 opts::XCOFFAuxiliaryHeader = true; 687 opts::ProgramHeaders = true; 688 opts::SectionHeaders = true; 689 } 690 691 std::unique_ptr<ScopedPrinter> Writer = createWriter(); 692 693 for (const std::string &I : opts::InputFilenames) 694 dumpInput(I, *Writer.get()); 695 696 if (opts::CodeViewMergedTypes) { 697 if (opts::CodeViewEnableGHash) 698 dumpCodeViewMergedTypes(*Writer.get(), CVTypes.GlobalIDTable.records(), 699 CVTypes.GlobalTypeTable.records()); 700 else 701 dumpCodeViewMergedTypes(*Writer.get(), CVTypes.IDTable.records(), 702 CVTypes.TypeTable.records()); 703 } 704 705 return 0; 706 } 707