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 static constexpr 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 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::XCOFFExceptionSection = Args.hasArg(OPT_exception_section); 311 312 opts::InputFilenames = Args.getAllArgValues(OPT_INPUT); 313 } 314 315 namespace { 316 struct ReadObjTypeTableBuilder { 317 ReadObjTypeTableBuilder() 318 : IDTable(Allocator), TypeTable(Allocator), GlobalIDTable(Allocator), 319 GlobalTypeTable(Allocator) {} 320 321 llvm::BumpPtrAllocator Allocator; 322 llvm::codeview::MergingTypeTableBuilder IDTable; 323 llvm::codeview::MergingTypeTableBuilder TypeTable; 324 llvm::codeview::GlobalTypeTableBuilder GlobalIDTable; 325 llvm::codeview::GlobalTypeTableBuilder GlobalTypeTable; 326 std::vector<OwningBinary<Binary>> Binaries; 327 }; 328 } // namespace 329 static ReadObjTypeTableBuilder CVTypes; 330 331 /// Creates an format-specific object file dumper. 332 static Expected<std::unique_ptr<ObjDumper>> 333 createDumper(const ObjectFile &Obj, ScopedPrinter &Writer) { 334 if (const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(&Obj)) 335 return createCOFFDumper(*COFFObj, Writer); 336 337 if (const ELFObjectFileBase *ELFObj = dyn_cast<ELFObjectFileBase>(&Obj)) 338 return createELFDumper(*ELFObj, Writer); 339 340 if (const MachOObjectFile *MachOObj = dyn_cast<MachOObjectFile>(&Obj)) 341 return createMachODumper(*MachOObj, Writer); 342 343 if (const WasmObjectFile *WasmObj = dyn_cast<WasmObjectFile>(&Obj)) 344 return createWasmDumper(*WasmObj, Writer); 345 346 if (const XCOFFObjectFile *XObj = dyn_cast<XCOFFObjectFile>(&Obj)) 347 return createXCOFFDumper(*XObj, Writer); 348 349 return createStringError(errc::invalid_argument, 350 "unsupported object file format"); 351 } 352 353 /// Dumps the specified object file. 354 static void dumpObject(ObjectFile &Obj, ScopedPrinter &Writer, 355 const Archive *A = nullptr) { 356 std::string FileStr = 357 A ? Twine(A->getFileName() + "(" + Obj.getFileName() + ")").str() 358 : Obj.getFileName().str(); 359 360 std::string ContentErrString; 361 if (Error ContentErr = Obj.initContent()) 362 ContentErrString = "unable to continue dumping, the file is corrupt: " + 363 toString(std::move(ContentErr)); 364 365 ObjDumper *Dumper; 366 Optional<SymbolComparator> SymComp; 367 Expected<std::unique_ptr<ObjDumper>> DumperOrErr = createDumper(Obj, Writer); 368 if (!DumperOrErr) 369 reportError(DumperOrErr.takeError(), FileStr); 370 Dumper = (*DumperOrErr).get(); 371 372 if (!opts::SortKeys.empty()) { 373 if (Dumper->canCompareSymbols()) { 374 SymComp = SymbolComparator(); 375 for (SortSymbolKeyTy Key : opts::SortKeys) { 376 switch (Key) { 377 case NAME: 378 SymComp->addPredicate([Dumper](SymbolRef LHS, SymbolRef RHS) { 379 return Dumper->compareSymbolsByName(LHS, RHS); 380 }); 381 break; 382 case TYPE: 383 SymComp->addPredicate([Dumper](SymbolRef LHS, SymbolRef RHS) { 384 return Dumper->compareSymbolsByType(LHS, RHS); 385 }); 386 break; 387 case UNKNOWN: 388 llvm_unreachable("Unsupported sort key"); 389 } 390 } 391 392 } else { 393 reportWarning(createStringError( 394 errc::invalid_argument, 395 "--sort-symbols is not supported yet for this format"), 396 FileStr); 397 } 398 } 399 Dumper->printFileSummary(FileStr, Obj, opts::InputFilenames, A); 400 401 if (opts::FileHeaders) 402 Dumper->printFileHeaders(); 403 404 // Auxiliary header in XOCFF is right after the file header, so print the data 405 // here. 406 if (Obj.isXCOFF() && opts::XCOFFAuxiliaryHeader) 407 Dumper->printAuxiliaryHeader(); 408 409 // This is only used for ELF currently. In some cases, when an object is 410 // corrupt (e.g. truncated), we can't dump anything except the file header. 411 if (!ContentErrString.empty()) 412 reportError(createError(ContentErrString), FileStr); 413 414 if (opts::SectionDetails || opts::SectionHeaders) { 415 if (opts::Output == opts::GNU && opts::SectionDetails) 416 Dumper->printSectionDetails(); 417 else 418 Dumper->printSectionHeaders(); 419 } 420 421 if (opts::HashSymbols) 422 Dumper->printHashSymbols(); 423 if (opts::ProgramHeaders || opts::SectionMapping == cl::BOU_TRUE) 424 Dumper->printProgramHeaders(opts::ProgramHeaders, opts::SectionMapping); 425 if (opts::DynamicTable) 426 Dumper->printDynamicTable(); 427 if (opts::NeededLibraries) 428 Dumper->printNeededLibraries(); 429 if (opts::Relocations) 430 Dumper->printRelocations(); 431 if (opts::DynRelocs) 432 Dumper->printDynamicRelocations(); 433 if (opts::UnwindInfo) 434 Dumper->printUnwindInfo(); 435 if (opts::Symbols || opts::DynamicSymbols) 436 Dumper->printSymbols(opts::Symbols, opts::DynamicSymbols, SymComp); 437 if (!opts::StringDump.empty()) 438 Dumper->printSectionsAsString(Obj, opts::StringDump); 439 if (!opts::HexDump.empty()) 440 Dumper->printSectionsAsHex(Obj, opts::HexDump); 441 if (opts::HashTable) 442 Dumper->printHashTable(); 443 if (opts::GnuHashTable) 444 Dumper->printGnuHashTable(); 445 if (opts::VersionInfo) 446 Dumper->printVersionInfo(); 447 if (opts::StringTable) 448 Dumper->printStringTable(); 449 if (Obj.isELF()) { 450 if (opts::DependentLibraries) 451 Dumper->printDependentLibs(); 452 if (opts::ELFLinkerOptions) 453 Dumper->printELFLinkerOptions(); 454 if (opts::ArchSpecificInfo) 455 Dumper->printArchSpecificInfo(); 456 if (opts::SectionGroups) 457 Dumper->printGroupSections(); 458 if (opts::HashHistogram) 459 Dumper->printHashHistograms(); 460 if (opts::CGProfile) 461 Dumper->printCGProfile(); 462 if (opts::BBAddrMap) 463 Dumper->printBBAddrMaps(); 464 if (opts::Addrsig) 465 Dumper->printAddrsig(); 466 if (opts::Notes) 467 Dumper->printNotes(); 468 } 469 if (Obj.isCOFF()) { 470 if (opts::COFFImports) 471 Dumper->printCOFFImports(); 472 if (opts::COFFExports) 473 Dumper->printCOFFExports(); 474 if (opts::COFFDirectives) 475 Dumper->printCOFFDirectives(); 476 if (opts::COFFBaseRelocs) 477 Dumper->printCOFFBaseReloc(); 478 if (opts::COFFDebugDirectory) 479 Dumper->printCOFFDebugDirectory(); 480 if (opts::COFFTLSDirectory) 481 Dumper->printCOFFTLSDirectory(); 482 if (opts::COFFResources) 483 Dumper->printCOFFResources(); 484 if (opts::COFFLoadConfig) 485 Dumper->printCOFFLoadConfig(); 486 if (opts::CGProfile) 487 Dumper->printCGProfile(); 488 if (opts::Addrsig) 489 Dumper->printAddrsig(); 490 if (opts::CodeView) 491 Dumper->printCodeViewDebugInfo(); 492 if (opts::CodeViewMergedTypes) 493 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable, 494 CVTypes.GlobalIDTable, CVTypes.GlobalTypeTable, 495 opts::CodeViewEnableGHash); 496 } 497 if (Obj.isMachO()) { 498 if (opts::MachODataInCode) 499 Dumper->printMachODataInCode(); 500 if (opts::MachOIndirectSymbols) 501 Dumper->printMachOIndirectSymbols(); 502 if (opts::MachOLinkerOptions) 503 Dumper->printMachOLinkerOptions(); 504 if (opts::MachOSegment) 505 Dumper->printMachOSegment(); 506 if (opts::MachOVersionMin) 507 Dumper->printMachOVersionMin(); 508 if (opts::MachODysymtab) 509 Dumper->printMachODysymtab(); 510 if (opts::CGProfile) 511 Dumper->printCGProfile(); 512 } 513 514 if (Obj.isXCOFF()) { 515 if (opts::XCOFFLoaderSectionHeader || opts::XCOFFLoaderSectionSymbol) 516 Dumper->printLoaderSection(opts::XCOFFLoaderSectionHeader, 517 opts::XCOFFLoaderSectionSymbol); 518 519 if (opts::XCOFFExceptionSection) 520 Dumper->printExceptionSection(); 521 } 522 523 if (opts::PrintStackMap) 524 Dumper->printStackMap(); 525 if (opts::PrintStackSizes) 526 Dumper->printStackSizes(); 527 } 528 529 /// Dumps each object file in \a Arc; 530 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) { 531 Error Err = Error::success(); 532 for (auto &Child : Arc->children(Err)) { 533 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 534 if (!ChildOrErr) { 535 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 536 reportError(std::move(E), Arc->getFileName()); 537 continue; 538 } 539 540 Binary *Bin = ChildOrErr->get(); 541 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Bin)) 542 dumpObject(*Obj, Writer, Arc); 543 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(Bin)) 544 dumpCOFFImportFile(Imp, Writer); 545 else 546 reportWarning(createStringError(errc::invalid_argument, 547 Bin->getFileName() + 548 " has an unsupported file type"), 549 Arc->getFileName()); 550 } 551 if (Err) 552 reportError(std::move(Err), Arc->getFileName()); 553 } 554 555 /// Dumps each object file in \a MachO Universal Binary; 556 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary, 557 ScopedPrinter &Writer) { 558 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) { 559 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile(); 560 if (ObjOrErr) 561 dumpObject(*ObjOrErr.get(), Writer); 562 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) 563 reportError(ObjOrErr.takeError(), UBinary->getFileName()); 564 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) 565 dumpArchive(&*AOrErr.get(), Writer); 566 } 567 } 568 569 /// Dumps \a WinRes, Windows Resource (.res) file; 570 static void dumpWindowsResourceFile(WindowsResource *WinRes, 571 ScopedPrinter &Printer) { 572 WindowsRes::Dumper Dumper(WinRes, Printer); 573 if (auto Err = Dumper.printData()) 574 reportError(std::move(Err), WinRes->getFileName()); 575 } 576 577 578 /// Opens \a File and dumps it. 579 static void dumpInput(StringRef File, ScopedPrinter &Writer) { 580 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 581 MemoryBuffer::getFileOrSTDIN(File, /*IsText=*/false, 582 /*RequiresNullTerminator=*/false); 583 if (std::error_code EC = FileOrErr.getError()) 584 return reportError(errorCodeToError(EC), File); 585 586 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get(); 587 file_magic Type = identify_magic(Buffer->getBuffer()); 588 if (Type == file_magic::bitcode) { 589 reportWarning(createStringError(errc::invalid_argument, 590 "bitcode files are not supported"), 591 File); 592 return; 593 } 594 595 Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary( 596 Buffer->getMemBufferRef(), /*Context=*/nullptr, /*InitContent=*/false); 597 if (!BinaryOrErr) 598 reportError(BinaryOrErr.takeError(), File); 599 600 std::unique_ptr<Binary> Bin = std::move(*BinaryOrErr); 601 if (Archive *Arc = dyn_cast<Archive>(Bin.get())) 602 dumpArchive(Arc, Writer); 603 else if (MachOUniversalBinary *UBinary = 604 dyn_cast<MachOUniversalBinary>(Bin.get())) 605 dumpMachOUniversalBinary(UBinary, Writer); 606 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(Bin.get())) 607 dumpObject(*Obj, Writer); 608 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(Bin.get())) 609 dumpCOFFImportFile(Import, Writer); 610 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(Bin.get())) 611 dumpWindowsResourceFile(WinRes, Writer); 612 else 613 llvm_unreachable("unrecognized file type"); 614 615 CVTypes.Binaries.push_back( 616 OwningBinary<Binary>(std::move(Bin), std::move(Buffer))); 617 } 618 619 std::unique_ptr<ScopedPrinter> createWriter() { 620 if (opts::Output == opts::JSON) 621 return std::make_unique<JSONScopedPrinter>( 622 fouts(), opts::PrettyPrint ? 2 : 0, std::make_unique<ListScope>()); 623 return std::make_unique<ScopedPrinter>(fouts()); 624 } 625 626 int llvm_readobj_main(int argc, char **argv) { 627 InitLLVM X(argc, argv); 628 BumpPtrAllocator A; 629 StringSaver Saver(A); 630 ReadobjOptTable Tbl; 631 ToolName = argv[0]; 632 opt::InputArgList Args = 633 Tbl.parseArgs(argc, argv, OPT_UNKNOWN, Saver, [&](StringRef Msg) { 634 error(Msg); 635 exit(1); 636 }); 637 if (Args.hasArg(OPT_help)) { 638 Tbl.printHelp( 639 outs(), 640 (Twine(ToolName) + " [options] <input object files>").str().c_str(), 641 "LLVM Object Reader"); 642 // TODO Replace this with OptTable API once it adds extrahelp support. 643 outs() << "\nPass @FILE as argument to read options from FILE.\n"; 644 return 0; 645 } 646 if (Args.hasArg(OPT_version)) { 647 cl::PrintVersionMessage(); 648 return 0; 649 } 650 651 if (sys::path::stem(argv[0]).contains("readelf")) 652 opts::Output = opts::GNU; 653 parseOptions(Args); 654 655 // Default to print error if no filename is specified. 656 if (opts::InputFilenames.empty()) { 657 error("no input files specified"); 658 } 659 660 if (opts::All) { 661 opts::FileHeaders = true; 662 opts::XCOFFAuxiliaryHeader = true; 663 opts::ProgramHeaders = true; 664 opts::SectionHeaders = true; 665 opts::Symbols = true; 666 opts::Relocations = true; 667 opts::DynamicTable = true; 668 opts::Notes = true; 669 opts::VersionInfo = true; 670 opts::UnwindInfo = true; 671 opts::SectionGroups = true; 672 opts::HashHistogram = true; 673 if (opts::Output == opts::LLVM) { 674 opts::Addrsig = true; 675 opts::PrintStackSizes = true; 676 } 677 } 678 679 if (opts::Headers) { 680 opts::FileHeaders = true; 681 opts::XCOFFAuxiliaryHeader = true; 682 opts::ProgramHeaders = true; 683 opts::SectionHeaders = true; 684 } 685 686 std::unique_ptr<ScopedPrinter> Writer = createWriter(); 687 688 for (const std::string &I : opts::InputFilenames) 689 dumpInput(I, *Writer.get()); 690 691 if (opts::CodeViewMergedTypes) { 692 if (opts::CodeViewEnableGHash) 693 dumpCodeViewMergedTypes(*Writer.get(), CVTypes.GlobalIDTable.records(), 694 CVTypes.GlobalTypeTable.records()); 695 else 696 dumpCodeViewMergedTypes(*Writer.get(), CVTypes.IDTable.records(), 697 CVTypes.TypeTable.records()); 698 } 699 700 return 0; 701 } 702