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