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