llvm-readobj.cpp 16 KB

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