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