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