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 // -hash-table 150 cl::opt<bool> HashTable("hash-table", 151 cl::desc("Display ELF hash table")); 152 153 // -gnu-hash-table 154 cl::opt<bool> GnuHashTable("gnu-hash-table", 155 cl::desc("Display ELF .gnu.hash section")); 156 157 // -expand-relocs 158 cl::opt<bool> ExpandRelocs("expand-relocs", 159 cl::desc("Expand each shown relocation to multiple lines")); 160 161 // -codeview 162 cl::opt<bool> CodeView("codeview", 163 cl::desc("Display CodeView debug information")); 164 165 // -codeview-merged-types 166 cl::opt<bool> 167 CodeViewMergedTypes("codeview-merged-types", 168 cl::desc("Display the merged CodeView type stream")); 169 170 // -codeview-subsection-bytes 171 cl::opt<bool> CodeViewSubsectionBytes( 172 "codeview-subsection-bytes", 173 cl::desc("Dump raw contents of codeview debug sections and records")); 174 175 // -arm-attributes, -a 176 cl::opt<bool> ARMAttributes("arm-attributes", 177 cl::desc("Display the ARM attributes section")); 178 cl::alias ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"), 179 cl::aliasopt(ARMAttributes)); 180 181 // -mips-plt-got 182 cl::opt<bool> 183 MipsPLTGOT("mips-plt-got", 184 cl::desc("Display the MIPS GOT and PLT GOT sections")); 185 186 // -mips-abi-flags 187 cl::opt<bool> MipsABIFlags("mips-abi-flags", 188 cl::desc("Display the MIPS.abiflags section")); 189 190 // -mips-reginfo 191 cl::opt<bool> MipsReginfo("mips-reginfo", 192 cl::desc("Display the MIPS .reginfo section")); 193 194 // -mips-options 195 cl::opt<bool> MipsOptions("mips-options", 196 cl::desc("Display the MIPS .MIPS.options section")); 197 198 // -coff-imports 199 cl::opt<bool> 200 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table")); 201 202 // -coff-exports 203 cl::opt<bool> 204 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table")); 205 206 // -coff-directives 207 cl::opt<bool> 208 COFFDirectives("coff-directives", 209 cl::desc("Display the PE/COFF .drectve section")); 210 211 // -coff-basereloc 212 cl::opt<bool> 213 COFFBaseRelocs("coff-basereloc", 214 cl::desc("Display the PE/COFF .reloc section")); 215 216 // -coff-debug-directory 217 cl::opt<bool> 218 COFFDebugDirectory("coff-debug-directory", 219 cl::desc("Display the PE/COFF debug directory")); 220 221 // -coff-resources 222 cl::opt<bool> COFFResources("coff-resources", 223 cl::desc("Display the PE/COFF .rsrc section")); 224 225 // -coff-load-config 226 cl::opt<bool> 227 COFFLoadConfig("coff-load-config", 228 cl::desc("Display the PE/COFF load config")); 229 230 // -elf-linker-options 231 cl::opt<bool> 232 ELFLinkerOptions("elf-linker-options", 233 cl::desc("Display the ELF .linker-options section")); 234 235 // -macho-data-in-code 236 cl::opt<bool> 237 MachODataInCode("macho-data-in-code", 238 cl::desc("Display MachO Data in Code command")); 239 240 // -macho-indirect-symbols 241 cl::opt<bool> 242 MachOIndirectSymbols("macho-indirect-symbols", 243 cl::desc("Display MachO indirect symbols")); 244 245 // -macho-linker-options 246 cl::opt<bool> 247 MachOLinkerOptions("macho-linker-options", 248 cl::desc("Display MachO linker options")); 249 250 // -macho-segment 251 cl::opt<bool> 252 MachOSegment("macho-segment", 253 cl::desc("Display MachO Segment command")); 254 255 // -macho-version-min 256 cl::opt<bool> 257 MachOVersionMin("macho-version-min", 258 cl::desc("Display MachO version min command")); 259 260 // -macho-dysymtab 261 cl::opt<bool> 262 MachODysymtab("macho-dysymtab", 263 cl::desc("Display MachO Dysymtab command")); 264 265 // -stackmap 266 cl::opt<bool> 267 PrintStackMap("stackmap", 268 cl::desc("Display contents of stackmap section")); 269 270 // -version-info 271 cl::opt<bool> 272 VersionInfo("version-info", 273 cl::desc("Display ELF version sections (if present)")); 274 cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"), 275 cl::aliasopt(VersionInfo)); 276 277 cl::opt<bool> SectionGroups("elf-section-groups", 278 cl::desc("Display ELF section group contents")); 279 cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"), 280 cl::aliasopt(SectionGroups)); 281 cl::opt<bool> HashHistogram( 282 "elf-hash-histogram", 283 cl::desc("Display bucket list histogram for hash sections")); 284 cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"), 285 cl::aliasopt(HashHistogram)); 286 287 cl::opt<OutputStyleTy> 288 Output("elf-output-style", cl::desc("Specify ELF dump style"), 289 cl::values(clEnumVal(LLVM, "LLVM default style"), 290 clEnumVal(GNU, "GNU readelf style")), 291 cl::init(LLVM)); 292 } // namespace opts 293 294 namespace llvm { 295 296 LLVM_ATTRIBUTE_NORETURN void reportError(Twine Msg) { 297 errs() << "\nError reading file: " << Msg << ".\n"; 298 errs().flush(); 299 exit(1); 300 } 301 302 void error(Error EC) { 303 if (!EC) 304 return; 305 handleAllErrors(std::move(EC), 306 [&](const ErrorInfoBase &EI) { reportError(EI.message()); }); 307 } 308 309 void error(std::error_code EC) { 310 if (!EC) 311 return; 312 reportError(EC.message()); 313 } 314 315 bool relocAddressLess(RelocationRef a, RelocationRef b) { 316 return a.getOffset() < b.getOffset(); 317 } 318 319 } // namespace llvm 320 321 static void reportError(StringRef Input, std::error_code EC) { 322 if (Input == "-") 323 Input = "<stdin>"; 324 325 reportError(Twine(Input) + ": " + EC.message()); 326 } 327 328 static void reportError(StringRef Input, Error Err) { 329 if (Input == "-") 330 Input = "<stdin>"; 331 std::string ErrMsg; 332 { 333 raw_string_ostream ErrStream(ErrMsg); 334 logAllUnhandledErrors(std::move(Err), ErrStream, Input + ": "); 335 } 336 reportError(ErrMsg); 337 } 338 339 static bool isMipsArch(unsigned Arch) { 340 switch (Arch) { 341 case llvm::Triple::mips: 342 case llvm::Triple::mipsel: 343 case llvm::Triple::mips64: 344 case llvm::Triple::mips64el: 345 return true; 346 default: 347 return false; 348 } 349 } 350 namespace { 351 struct ReadObjTypeTableBuilder { 352 ReadObjTypeTableBuilder() 353 : Allocator(), IDTable(Allocator), TypeTable(Allocator) {} 354 355 llvm::BumpPtrAllocator Allocator; 356 llvm::codeview::MergingTypeTableBuilder IDTable; 357 llvm::codeview::MergingTypeTableBuilder TypeTable; 358 }; 359 } 360 static ReadObjTypeTableBuilder CVTypes; 361 362 /// Creates an format-specific object file dumper. 363 static std::error_code createDumper(const ObjectFile *Obj, 364 ScopedPrinter &Writer, 365 std::unique_ptr<ObjDumper> &Result) { 366 if (!Obj) 367 return readobj_error::unsupported_file_format; 368 369 if (Obj->isCOFF()) 370 return createCOFFDumper(Obj, Writer, Result); 371 if (Obj->isELF()) 372 return createELFDumper(Obj, Writer, Result); 373 if (Obj->isMachO()) 374 return createMachODumper(Obj, Writer, Result); 375 if (Obj->isWasm()) 376 return createWasmDumper(Obj, Writer, Result); 377 378 return readobj_error::unsupported_obj_file_format; 379 } 380 381 /// Dumps the specified object file. 382 static void dumpObject(const ObjectFile *Obj, ScopedPrinter &Writer) { 383 std::unique_ptr<ObjDumper> Dumper; 384 if (std::error_code EC = createDumper(Obj, Writer, Dumper)) 385 reportError(Obj->getFileName(), EC); 386 387 if (opts::Output == opts::LLVM) { 388 Writer.startLine() << "\n"; 389 Writer.printString("File", Obj->getFileName()); 390 Writer.printString("Format", Obj->getFileFormatName()); 391 Writer.printString("Arch", Triple::getArchTypeName( 392 (llvm::Triple::ArchType)Obj->getArch())); 393 Writer.printString("AddressSize", 394 formatv("{0}bit", 8 * Obj->getBytesInAddress())); 395 Dumper->printLoadName(); 396 } 397 398 if (opts::FileHeaders) 399 Dumper->printFileHeaders(); 400 if (opts::Sections) 401 Dumper->printSections(); 402 if (opts::Relocations) 403 Dumper->printRelocations(); 404 if (opts::DynRelocs) 405 Dumper->printDynamicRelocations(); 406 if (opts::Symbols) 407 Dumper->printSymbols(); 408 if (opts::DynamicSymbols) 409 Dumper->printDynamicSymbols(); 410 if (opts::UnwindInfo) 411 Dumper->printUnwindInfo(); 412 if (opts::DynamicTable) 413 Dumper->printDynamicTable(); 414 if (opts::NeededLibraries) 415 Dumper->printNeededLibraries(); 416 if (opts::ProgramHeaders) 417 Dumper->printProgramHeaders(); 418 if (opts::HashTable) 419 Dumper->printHashTable(); 420 if (opts::GnuHashTable) 421 Dumper->printGnuHashTable(); 422 if (opts::VersionInfo) 423 Dumper->printVersionInfo(); 424 if (Obj->isELF()) { 425 if (opts::ELFLinkerOptions) 426 Dumper->printELFLinkerOptions(); 427 if (Obj->getArch() == llvm::Triple::arm) 428 if (opts::ARMAttributes) 429 Dumper->printAttributes(); 430 if (isMipsArch(Obj->getArch())) { 431 if (opts::MipsPLTGOT) 432 Dumper->printMipsPLTGOT(); 433 if (opts::MipsABIFlags) 434 Dumper->printMipsABIFlags(); 435 if (opts::MipsReginfo) 436 Dumper->printMipsReginfo(); 437 if (opts::MipsOptions) 438 Dumper->printMipsOptions(); 439 } 440 if (opts::SectionGroups) 441 Dumper->printGroupSections(); 442 if (opts::HashHistogram) 443 Dumper->printHashHistogram(); 444 if (opts::Notes) 445 Dumper->printNotes(); 446 } 447 if (Obj->isCOFF()) { 448 if (opts::COFFImports) 449 Dumper->printCOFFImports(); 450 if (opts::COFFExports) 451 Dumper->printCOFFExports(); 452 if (opts::COFFDirectives) 453 Dumper->printCOFFDirectives(); 454 if (opts::COFFBaseRelocs) 455 Dumper->printCOFFBaseReloc(); 456 if (opts::COFFDebugDirectory) 457 Dumper->printCOFFDebugDirectory(); 458 if (opts::COFFResources) 459 Dumper->printCOFFResources(); 460 if (opts::COFFLoadConfig) 461 Dumper->printCOFFLoadConfig(); 462 if (opts::CodeView) 463 Dumper->printCodeViewDebugInfo(); 464 if (opts::CodeViewMergedTypes) 465 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable); 466 } 467 if (Obj->isMachO()) { 468 if (opts::MachODataInCode) 469 Dumper->printMachODataInCode(); 470 if (opts::MachOIndirectSymbols) 471 Dumper->printMachOIndirectSymbols(); 472 if (opts::MachOLinkerOptions) 473 Dumper->printMachOLinkerOptions(); 474 if (opts::MachOSegment) 475 Dumper->printMachOSegment(); 476 if (opts::MachOVersionMin) 477 Dumper->printMachOVersionMin(); 478 if (opts::MachODysymtab) 479 Dumper->printMachODysymtab(); 480 } 481 if (opts::PrintStackMap) 482 Dumper->printStackMap(); 483 } 484 485 /// Dumps each object file in \a Arc; 486 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) { 487 Error Err = Error::success(); 488 for (auto &Child : Arc->children(Err)) { 489 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary(); 490 if (!ChildOrErr) { 491 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) { 492 reportError(Arc->getFileName(), ChildOrErr.takeError()); 493 } 494 continue; 495 } 496 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get())) 497 dumpObject(Obj, Writer); 498 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get())) 499 dumpCOFFImportFile(Imp, Writer); 500 else 501 reportError(Arc->getFileName(), readobj_error::unrecognized_file_format); 502 } 503 if (Err) 504 reportError(Arc->getFileName(), std::move(Err)); 505 } 506 507 /// Dumps each object file in \a MachO Universal Binary; 508 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary, 509 ScopedPrinter &Writer) { 510 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) { 511 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile(); 512 if (ObjOrErr) 513 dumpObject(&*ObjOrErr.get(), Writer); 514 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 515 reportError(UBinary->getFileName(), ObjOrErr.takeError()); 516 } 517 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive()) 518 dumpArchive(&*AOrErr.get(), Writer); 519 } 520 } 521 522 /// Dumps \a WinRes, Windows Resource (.res) file; 523 static void dumpWindowsResourceFile(WindowsResource *WinRes) { 524 ScopedPrinter Printer{outs()}; 525 WindowsRes::Dumper Dumper(WinRes, Printer); 526 if (auto Err = Dumper.printData()) 527 reportError(WinRes->getFileName(), std::move(Err)); 528 } 529 530 531 /// Opens \a File and dumps it. 532 static void dumpInput(StringRef File) { 533 ScopedPrinter Writer(outs()); 534 535 // Attempt to open the binary. 536 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File); 537 if (!BinaryOrErr) 538 reportError(File, BinaryOrErr.takeError()); 539 Binary &Binary = *BinaryOrErr.get().getBinary(); 540 541 if (Archive *Arc = dyn_cast<Archive>(&Binary)) 542 dumpArchive(Arc, Writer); 543 else if (MachOUniversalBinary *UBinary = 544 dyn_cast<MachOUniversalBinary>(&Binary)) 545 dumpMachOUniversalBinary(UBinary, Writer); 546 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary)) 547 dumpObject(Obj, Writer); 548 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary)) 549 dumpCOFFImportFile(Import, Writer); 550 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary)) 551 dumpWindowsResourceFile(WinRes); 552 else 553 reportError(File, readobj_error::unrecognized_file_format); 554 } 555 556 int main(int argc, const char *argv[]) { 557 InitLLVM X(argc, argv); 558 559 // Register the target printer for --version. 560 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 561 562 opts::WideOutput.setHiddenFlag(cl::Hidden); 563 564 if (sys::path::stem(argv[0]).find("readelf") != StringRef::npos) 565 opts::Output = opts::GNU; 566 567 cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n"); 568 569 // Default to stdin if no filename is specified. 570 if (opts::InputFilenames.size() == 0) 571 opts::InputFilenames.push_back("-"); 572 573 llvm::for_each(opts::InputFilenames, dumpInput); 574 575 if (opts::CodeViewMergedTypes) { 576 ScopedPrinter W(outs()); 577 dumpCodeViewMergedTypes(W, CVTypes.IDTable, CVTypes.TypeTable); 578 } 579 580 return 0; 581 } 582