1 //===- llvm-readobj.cpp - Dump contents of an Object File -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This is a tool similar to readelf, except it works on multiple object file 11 // formats. The main purpose of this tool is to provide detailed output suitable 12 // for FileCheck. 13 // 14 // Flags should be similar to readelf where supported, but the output format 15 // does not need to be identical. The point is to not make users learn yet 16 // another set of flags. 17 // 18 // Output should be specialized for each format where appropriate. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "llvm-readobj.h" 23 #include "Error.h" 24 #include "ObjDumper.h" 25 #include "WindowsResourceDumper.h" 26 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h" 27 #include "llvm/Object/Archive.h" 28 #include "llvm/Object/COFFImportFile.h" 29 #include "llvm/Object/MachOUniversal.h" 30 #include "llvm/Object/ObjectFile.h" 31 #include "llvm/Object/WindowsResource.h" 32 #include "llvm/Support/Casting.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/DataTypes.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/FileSystem.h" 37 #include "llvm/Support/FormatVariadic.h" 38 #include "llvm/Support/InitLLVM.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/ScopedPrinter.h" 41 #include "llvm/Support/TargetRegistry.h" 42 43 using namespace llvm; 44 using namespace llvm::object; 45 46 namespace opts { 47 cl::list<std::string> InputFilenames(cl::Positional, 48 cl::desc("<input object files>"), 49 cl::ZeroOrMore); 50 51 // -wide, -W 52 cl::opt<bool> WideOutput("wide", 53 cl::desc("Ignored for compatibility with GNU readelf")); 54 cl::alias WideOutputShort("W", 55 cl::desc("Alias for --wide"), 56 cl::aliasopt(WideOutput)); 57 58 // -file-headers, -h 59 cl::opt<bool> FileHeaders("file-headers", 60 cl::desc("Display file headers ")); 61 cl::alias FileHeadersShort("h", 62 cl::desc("Alias for --file-headers"), 63 cl::aliasopt(FileHeaders)); 64 65 // -sections, -s, -S 66 // Note: In GNU readelf, -s means --symbols! 67 cl::opt<bool> Sections("sections", 68 cl::desc("Display all sections.")); 69 cl::alias SectionsShort("s", 70 cl::desc("Alias for --sections"), 71 cl::aliasopt(Sections)); 72 cl::alias SectionsShortUpper("S", 73 cl::desc("Alias for --sections"), 74 cl::aliasopt(Sections)); 75 76 // -section-relocations, -sr 77 cl::opt<bool> SectionRelocations("section-relocations", 78 cl::desc("Display relocations for each section shown.")); 79 cl::alias SectionRelocationsShort("sr", 80 cl::desc("Alias for --section-relocations"), 81 cl::aliasopt(SectionRelocations)); 82 83 // -section-symbols, -st 84 cl::opt<bool> SectionSymbols("section-symbols", 85 cl::desc("Display symbols for each section shown.")); 86 cl::alias SectionSymbolsShort("st", 87 cl::desc("Alias for --section-symbols"), 88 cl::aliasopt(SectionSymbols)); 89 90 // -section-data, -sd 91 cl::opt<bool> SectionData("section-data", 92 cl::desc("Display section data for each section shown.")); 93 cl::alias SectionDataShort("sd", 94 cl::desc("Alias for --section-data"), 95 cl::aliasopt(SectionData)); 96 97 // -relocations, -r 98 cl::opt<bool> Relocations("relocations", 99 cl::desc("Display the relocation entries in the file")); 100 cl::alias RelocationsShort("r", 101 cl::desc("Alias for --relocations"), 102 cl::aliasopt(Relocations)); 103 104 // -notes, -n 105 cl::opt<bool> Notes("notes", cl::desc("Display the ELF notes in the file")); 106 cl::alias NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes)); 107 108 // -dyn-relocations 109 cl::opt<bool> DynRelocs("dyn-relocations", 110 cl::desc("Display the dynamic relocation entries in the file")); 111 112 // -symbols, -t 113 cl::opt<bool> Symbols("symbols", 114 cl::desc("Display the symbol table")); 115 cl::alias SymbolsShort("t", 116 cl::desc("Alias for --symbols"), 117 cl::aliasopt(Symbols)); 118 119 // -dyn-symbols, -dt 120 cl::opt<bool> DynamicSymbols("dyn-symbols", 121 cl::desc("Display the dynamic symbol table")); 122 cl::alias DynamicSymbolsShort("dt", 123 cl::desc("Alias for --dyn-symbols"), 124 cl::aliasopt(DynamicSymbols)); 125 126 // -unwind, -u 127 cl::opt<bool> UnwindInfo("unwind", 128 cl::desc("Display unwind information")); 129 cl::alias UnwindInfoShort("u", 130 cl::desc("Alias for --unwind"), 131 cl::aliasopt(UnwindInfo)); 132 133 // -dynamic-table 134 cl::opt<bool> DynamicTable("dynamic-table", 135 cl::desc("Display the ELF .dynamic section table")); 136 cl::alias DynamicTableShort("d", cl::desc("Alias for --dynamic-table"), 137 cl::aliasopt(DynamicTable)); 138 139 // -needed-libs 140 cl::opt<bool> NeededLibraries("needed-libs", 141 cl::desc("Display the needed libraries")); 142 143 // -program-headers 144 cl::opt<bool> ProgramHeaders("program-headers", 145 cl::desc("Display ELF program headers")); 146 cl::alias ProgramHeadersShort("l", cl::desc("Alias for --program-headers"), 147 cl::aliasopt(ProgramHeaders)); 148 149 // -string-dump 150 cl::list<std::string> StringDump("string-dump", cl::desc("<number|name>"), 151 cl::ZeroOrMore); 152 cl::alias StringDumpShort("p", cl::desc("Alias for --string-dump"), 153 cl::aliasopt(StringDump)); 154 155 // -hash-table 156 cl::opt<bool> HashTable("hash-table", 157 cl::desc("Display ELF hash table")); 158 159 // -gnu-hash-table 160 cl::opt<bool> GnuHashTable("gnu-hash-table", 161 cl::desc("Display ELF .gnu.hash section")); 162 163 // -expand-relocs 164 cl::opt<bool> ExpandRelocs("expand-relocs", 165 cl::desc("Expand each shown relocation to multiple lines")); 166 167 // -codeview 168 cl::opt<bool> CodeView("codeview", 169 cl::desc("Display CodeView debug information")); 170 171 // -codeview-merged-types 172 cl::opt<bool> 173 CodeViewMergedTypes("codeview-merged-types", 174 cl::desc("Display the merged CodeView type stream")); 175 176 // -codeview-subsection-bytes 177 cl::opt<bool> CodeViewSubsectionBytes( 178 "codeview-subsection-bytes", 179 cl::desc("Dump raw contents of codeview debug sections and records")); 180 181 // -arm-attributes, -a 182 cl::opt<bool> ARMAttributes("arm-attributes", 183 cl::desc("Display the ARM attributes section")); 184 cl::alias ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"), 185 cl::aliasopt(ARMAttributes)); 186 187 // -mips-plt-got 188 cl::opt<bool> 189 MipsPLTGOT("mips-plt-got", 190 cl::desc("Display the MIPS GOT and PLT GOT sections")); 191 192 // -mips-abi-flags 193 cl::opt<bool> MipsABIFlags("mips-abi-flags", 194 cl::desc("Display the MIPS.abiflags section")); 195 196 // -mips-reginfo 197 cl::opt<bool> MipsReginfo("mips-reginfo", 198 cl::desc("Display the MIPS .reginfo section")); 199 200 // -mips-options 201 cl::opt<bool> MipsOptions("mips-options", 202 cl::desc("Display the MIPS .MIPS.options section")); 203 204 // -coff-imports 205 cl::opt<bool> 206 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table")); 207 208 // -coff-exports 209 cl::opt<bool> 210 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table")); 211 212 // -coff-directives 213 cl::opt<bool> 214 COFFDirectives("coff-directives", 215 cl::desc("Display the PE/COFF .drectve section")); 216 217 // -coff-basereloc 218 cl::opt<bool> 219 COFFBaseRelocs("coff-basereloc", 220 cl::desc("Display the PE/COFF .reloc section")); 221 222 // -coff-debug-directory 223 cl::opt<bool> 224 COFFDebugDirectory("coff-debug-directory", 225 cl::desc("Display the PE/COFF debug directory")); 226 227 // -coff-resources 228 cl::opt<bool> COFFResources("coff-resources", 229 cl::desc("Display the PE/COFF .rsrc section")); 230 231 // -coff-load-config 232 cl::opt<bool> 233 COFFLoadConfig("coff-load-config", 234 cl::desc("Display the PE/COFF load config")); 235 236 // -elf-linker-options 237 cl::opt<bool> 238 ELFLinkerOptions("elf-linker-options", 239 cl::desc("Display the ELF .linker-options section")); 240 241 // -macho-data-in-code 242 cl::opt<bool> 243 MachODataInCode("macho-data-in-code", 244 cl::desc("Display MachO Data in Code command")); 245 246 // -macho-indirect-symbols 247 cl::opt<bool> 248 MachOIndirectSymbols("macho-indirect-symbols", 249 cl::desc("Display MachO indirect symbols")); 250 251 // -macho-linker-options 252 cl::opt<bool> 253 MachOLinkerOptions("macho-linker-options", 254 cl::desc("Display MachO linker options")); 255 256 // -macho-segment 257 cl::opt<bool> 258 MachOSegment("macho-segment", 259 cl::desc("Display MachO Segment command")); 260 261 // -macho-version-min 262 cl::opt<bool> 263 MachOVersionMin("macho-version-min", 264 cl::desc("Display MachO version min command")); 265 266 // -macho-dysymtab 267 cl::opt<bool> 268 MachODysymtab("macho-dysymtab", 269 cl::desc("Display MachO Dysymtab command")); 270 271 // -stackmap 272 cl::opt<bool> 273 PrintStackMap("stackmap", 274 cl::desc("Display contents of stackmap section")); 275 276 // -version-info 277 cl::opt<bool> 278 VersionInfo("version-info", 279 cl::desc("Display ELF version sections (if present)")); 280 cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"), 281 cl::aliasopt(VersionInfo)); 282 283 cl::opt<bool> SectionGroups("elf-section-groups", 284 cl::desc("Display ELF section group contents")); 285 cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"), 286 cl::aliasopt(SectionGroups)); 287 cl::opt<bool> HashHistogram( 288 "elf-hash-histogram", 289 cl::desc("Display bucket list histogram for hash sections")); 290 cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"), 291 cl::aliasopt(HashHistogram)); 292 293 cl::opt<bool> CGProfile("elf-cg-profile", cl::desc("Display callgraph profile section")); 294 295 cl::opt<OutputStyleTy> 296 Output("elf-output-style", cl::desc("Specify ELF dump style"), 297 cl::values(clEnumVal(LLVM, "LLVM default style"), 298 clEnumVal(GNU, "GNU readelf style")), 299 cl::init(LLVM)); 300 } // namespace opts 301 302 namespace llvm { 303 304 LLVM_ATTRIBUTE_NORETURN void reportError(Twine Msg) { 305 errs() << "\nError reading file: " << Msg << ".\n"; 306 errs().flush(); 307 exit(1); 308 } 309 310 void error(Error EC) { 311 if (!EC) 312 return; 313 handleAllErrors(std::move(EC), 314 [&](const ErrorInfoBase &EI) { reportError(EI.message()); }); 315 } 316 317 void error(std::error_code EC) { 318 if (!EC) 319 return; 320 reportError(EC.message()); 321 } 322 323 bool relocAddressLess(RelocationRef a, RelocationRef b) { 324 return a.getOffset() < b.getOffset(); 325 } 326 327 } // namespace llvm 328 329 static void reportError(StringRef Input, std::error_code EC) { 330 if (Input == "-") 331 Input = "<stdin>"; 332 333 reportError(Twine(Input) + ": " + EC.message()); 334 } 335 336 static void reportError(StringRef Input, Error Err) { 337 if (Input == "-") 338 Input = "<stdin>"; 339 std::string ErrMsg; 340 { 341 raw_string_ostream ErrStream(ErrMsg); 342 logAllUnhandledErrors(std::move(Err), ErrStream, Input + ": "); 343 } 344 reportError(ErrMsg); 345 } 346 347 static bool isMipsArch(unsigned Arch) { 348 switch (Arch) { 349 case llvm::Triple::mips: 350 case llvm::Triple::mipsel: 351 case llvm::Triple::mips64: 352 case llvm::Triple::mips64el: 353 return true; 354 default: 355 return false; 356 } 357 } 358 namespace { 359 struct ReadObjTypeTableBuilder { 360 ReadObjTypeTableBuilder() 361 : Allocator(), IDTable(Allocator), TypeTable(Allocator) {} 362 363 llvm::BumpPtrAllocator Allocator; 364 llvm::codeview::MergingTypeTableBuilder IDTable; 365 llvm::codeview::MergingTypeTableBuilder TypeTable; 366 }; 367 } 368 static ReadObjTypeTableBuilder CVTypes; 369 370 /// Creates an format-specific object file dumper. 371 static std::error_code createDumper(const ObjectFile *Obj, 372 ScopedPrinter &Writer, 373 std::unique_ptr<ObjDumper> &Result) { 374 if (!Obj) 375 return readobj_error::unsupported_file_format; 376 377 if (Obj->isCOFF()) 378 return createCOFFDumper(Obj, Writer, Result); 379 if (Obj->isELF()) 380 return createELFDumper(Obj, Writer, Result); 381 if (Obj->isMachO()) 382 return createMachODumper(Obj, Writer, Result); 383 if (Obj->isWasm()) 384 return createWasmDumper(Obj, Writer, Result); 385 386 return readobj_error::unsupported_obj_file_format; 387 } 388 389 /// Dumps the specified object file. 390 static void dumpObject(const ObjectFile *Obj, ScopedPrinter &Writer) { 391 std::unique_ptr<ObjDumper> Dumper; 392 if (std::error_code EC = createDumper(Obj, Writer, Dumper)) 393 reportError(Obj->getFileName(), EC); 394 395 if (opts::Output == opts::LLVM) { 396 Writer.startLine() << "\n"; 397 Writer.printString("File", Obj->getFileName()); 398 Writer.printString("Format", Obj->getFileFormatName()); 399 Writer.printString("Arch", Triple::getArchTypeName( 400 (llvm::Triple::ArchType)Obj->getArch())); 401 Writer.printString("AddressSize", 402 formatv("{0}bit", 8 * Obj->getBytesInAddress())); 403 Dumper->printLoadName(); 404 } 405 406 if (opts::FileHeaders) 407 Dumper->printFileHeaders(); 408 if (opts::Sections) 409 Dumper->printSections(); 410 if (opts::Relocations) 411 Dumper->printRelocations(); 412 if (opts::DynRelocs) 413 Dumper->printDynamicRelocations(); 414 if (opts::Symbols) 415 Dumper->printSymbols(); 416 if (opts::DynamicSymbols) 417 Dumper->printDynamicSymbols(); 418 if (opts::UnwindInfo) 419 Dumper->printUnwindInfo(); 420 if (opts::DynamicTable) 421 Dumper->printDynamicTable(); 422 if (opts::NeededLibraries) 423 Dumper->printNeededLibraries(); 424 if (opts::ProgramHeaders) 425 Dumper->printProgramHeaders(); 426 if (!opts::StringDump.empty()) 427 llvm::for_each(opts::StringDump, [&Dumper](StringRef SectionName) { 428 Dumper->printSectionAsString(SectionName); 429 }); 430 if (opts::HashTable) 431 Dumper->printHashTable(); 432 if (opts::GnuHashTable) 433 Dumper->printGnuHashTable(); 434 if (opts::VersionInfo) 435 Dumper->printVersionInfo(); 436 if (Obj->isELF()) { 437 if (opts::ELFLinkerOptions) 438 Dumper->printELFLinkerOptions(); 439 if (Obj->getArch() == llvm::Triple::arm) 440 if (opts::ARMAttributes) 441 Dumper->printAttributes(); 442 if (isMipsArch(Obj->getArch())) { 443 if (opts::MipsPLTGOT) 444 Dumper->printMipsPLTGOT(); 445 if (opts::MipsABIFlags) 446 Dumper->printMipsABIFlags(); 447 if (opts::MipsReginfo) 448 Dumper->printMipsReginfo(); 449 if (opts::MipsOptions) 450 Dumper->printMipsOptions(); 451 } 452 if (opts::SectionGroups) 453 Dumper->printGroupSections(); 454 if (opts::HashHistogram) 455 Dumper->printHashHistogram(); 456 if (opts::CGProfile) 457 Dumper->printCGProfile(); 458 if (opts::Notes) 459 Dumper->printNotes(); 460 } 461 if (Obj->isCOFF()) { 462 if (opts::COFFImports) 463 Dumper->printCOFFImports(); 464 if (opts::COFFExports) 465 Dumper->printCOFFExports(); 466 if (opts::COFFDirectives) 467 Dumper->printCOFFDirectives(); 468 if (opts::COFFBaseRelocs) 469 Dumper->printCOFFBaseReloc(); 470 if (opts::COFFDebugDirectory) 471 Dumper->printCOFFDebugDirectory(); 472 if (opts::COFFResources) 473 Dumper->printCOFFResources(); 474 if (opts::COFFLoadConfig) 475 Dumper->printCOFFLoadConfig(); 476 if (opts::CodeView) 477 Dumper->printCodeViewDebugInfo(); 478 if (opts::CodeViewMergedTypes) 479 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable); 480 } 481 if (Obj->isMachO()) { 482 if (opts::MachODataInCode) 483 Dumper->printMachODataInCode(); 484 if (opts::MachOIndirectSymbols) 485 Dumper->printMachOIndirectSymbols(); 486 if (opts::MachOLinkerOptions) 487 Dumper->printMachOLinkerOptions(); 488 if (opts::MachOSegment) 489 Dumper->printMachOSegment(); 490 if (opts::MachOVersionMin) 491 Dumper->printMachOVersionMin(); 492 if (opts::MachODysymtab) 493 Dumper->printMachODysymtab(); 494 } 495 if (opts::PrintStackMap) 496 Dumper->printStackMap(); 497 } 498 499 /// Dumps each object file in \a Arc; 500 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) { 501 Error Err = Error::success(); 502 for (auto &Child : Arc->children(Err)) { 503 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 504 if (!ChildOrErr) { 505 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) { 506 reportError(Arc->getFileName(), ChildOrErr.takeError()); 507 } 508 continue; 509 } 510 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 511 dumpObject(Obj, Writer); 512 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 513 dumpCOFFImportFile(Imp, Writer); 514 else 515 reportError(Arc->getFileName(), readobj_error::unrecognized_file_format); 516 } 517 if (Err) 518 reportError(Arc->getFileName(), std::move(Err)); 519 } 520 521 /// Dumps each object file in \a MachO Universal Binary; 522 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary, 523 ScopedPrinter &Writer) { 524 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) { 525 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile(); 526 if (ObjOrErr) 527 dumpObject(&*ObjOrErr.get(), Writer); 528 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 529 reportError(UBinary->getFileName(), ObjOrErr.takeError()); 530 } 531 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) 532 dumpArchive(&*AOrErr.get(), Writer); 533 } 534 } 535 536 /// Dumps \a WinRes, Windows Resource (.res) file; 537 static void dumpWindowsResourceFile(WindowsResource *WinRes) { 538 ScopedPrinter Printer{outs()}; 539 WindowsRes::Dumper Dumper(WinRes, Printer); 540 if (auto Err = Dumper.printData()) 541 reportError(WinRes->getFileName(), std::move(Err)); 542 } 543 544 545 /// Opens \a File and dumps it. 546 static void dumpInput(StringRef File) { 547 ScopedPrinter Writer(outs()); 548 549 // Attempt to open the binary. 550 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File); 551 if (!BinaryOrErr) 552 reportError(File, BinaryOrErr.takeError()); 553 Binary &Binary = *BinaryOrErr.get().getBinary(); 554 555 if (Archive *Arc = dyn_cast<Archive>(&Binary)) 556 dumpArchive(Arc, Writer); 557 else if (MachOUniversalBinary *UBinary = 558 dyn_cast<MachOUniversalBinary>(&Binary)) 559 dumpMachOUniversalBinary(UBinary, Writer); 560 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary)) 561 dumpObject(Obj, Writer); 562 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary)) 563 dumpCOFFImportFile(Import, Writer); 564 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary)) 565 dumpWindowsResourceFile(WinRes); 566 else 567 reportError(File, readobj_error::unrecognized_file_format); 568 } 569 570 int main(int argc, const char *argv[]) { 571 InitLLVM X(argc, argv); 572 573 // Register the target printer for --version. 574 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 575 576 opts::WideOutput.setHiddenFlag(cl::Hidden); 577 578 if (sys::path::stem(argv[0]).find("readelf") != StringRef::npos) 579 opts::Output = opts::GNU; 580 581 cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n"); 582 583 // Default to stdin if no filename is specified. 584 if (opts::InputFilenames.size() == 0) 585 opts::InputFilenames.push_back("-"); 586 587 llvm::for_each(opts::InputFilenames, dumpInput); 588 589 if (opts::CodeViewMergedTypes) { 590 ScopedPrinter W(outs()); 591 dumpCodeViewMergedTypes(W, CVTypes.IDTable, CVTypes.TypeTable); 592 } 593 594 return 0; 595 } 596