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