[StackMaps] Add a lightweight parser for stackmap version 1 sections.
[oota-llvm.git] / 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 "StreamWriter.h"
26 #include "llvm/Object/Archive.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/Signals.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include <string>
41 #include <system_error>
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   // -file-headers, -h
52   cl::opt<bool> FileHeaders("file-headers",
53     cl::desc("Display file headers "));
54   cl::alias FileHeadersShort("h",
55     cl::desc("Alias for --file-headers"),
56     cl::aliasopt(FileHeaders));
57
58   // -sections, -s
59   cl::opt<bool> Sections("sections",
60     cl::desc("Display all sections."));
61   cl::alias SectionsShort("s",
62     cl::desc("Alias for --sections"),
63     cl::aliasopt(Sections));
64
65   // -section-relocations, -sr
66   cl::opt<bool> SectionRelocations("section-relocations",
67     cl::desc("Display relocations for each section shown."));
68   cl::alias SectionRelocationsShort("sr",
69     cl::desc("Alias for --section-relocations"),
70     cl::aliasopt(SectionRelocations));
71
72   // -section-symbols, -st
73   cl::opt<bool> SectionSymbols("section-symbols",
74     cl::desc("Display symbols for each section shown."));
75   cl::alias SectionSymbolsShort("st",
76     cl::desc("Alias for --section-symbols"),
77     cl::aliasopt(SectionSymbols));
78
79   // -section-data, -sd
80   cl::opt<bool> SectionData("section-data",
81     cl::desc("Display section data for each section shown."));
82   cl::alias SectionDataShort("sd",
83     cl::desc("Alias for --section-data"),
84     cl::aliasopt(SectionData));
85
86   // -relocations, -r
87   cl::opt<bool> Relocations("relocations",
88     cl::desc("Display the relocation entries in the file"));
89   cl::alias RelocationsShort("r",
90     cl::desc("Alias for --relocations"),
91     cl::aliasopt(Relocations));
92
93   // -dyn-relocations
94   cl::opt<bool> DynRelocs("dyn-relocations",
95     cl::desc("Display the dynamic relocation entries in the file"));
96
97   // -symbols, -t
98   cl::opt<bool> Symbols("symbols",
99     cl::desc("Display the symbol table"));
100   cl::alias SymbolsShort("t",
101     cl::desc("Alias for --symbols"),
102     cl::aliasopt(Symbols));
103
104   // -dyn-symbols, -dt
105   cl::opt<bool> DynamicSymbols("dyn-symbols",
106     cl::desc("Display the dynamic symbol table"));
107   cl::alias DynamicSymbolsShort("dt",
108     cl::desc("Alias for --dyn-symbols"),
109     cl::aliasopt(DynamicSymbols));
110
111   // -unwind, -u
112   cl::opt<bool> UnwindInfo("unwind",
113     cl::desc("Display unwind information"));
114   cl::alias UnwindInfoShort("u",
115     cl::desc("Alias for --unwind"),
116     cl::aliasopt(UnwindInfo));
117
118   // -dynamic-table
119   cl::opt<bool> DynamicTable("dynamic-table",
120     cl::desc("Display the ELF .dynamic section table"));
121
122   // -needed-libs
123   cl::opt<bool> NeededLibraries("needed-libs",
124     cl::desc("Display the needed libraries"));
125
126   // -program-headers
127   cl::opt<bool> ProgramHeaders("program-headers",
128     cl::desc("Display ELF program headers"));
129
130   // -expand-relocs
131   cl::opt<bool> ExpandRelocs("expand-relocs",
132     cl::desc("Expand each shown relocation to multiple lines"));
133
134   // -codeview
135   cl::opt<bool> CodeView("codeview",
136                          cl::desc("Display CodeView debug information"));
137
138   // -codeview-subsection-bytes
139   cl::opt<bool> CodeViewSubsectionBytes(
140       "codeview-subsection-bytes",
141       cl::desc("Dump raw contents of codeview debug sections and records"));
142
143   // -arm-attributes, -a
144   cl::opt<bool> ARMAttributes("arm-attributes",
145                               cl::desc("Display the ARM attributes section"));
146   cl::alias ARMAttributesShort("-a", cl::desc("Alias for --arm-attributes"),
147                                cl::aliasopt(ARMAttributes));
148
149   // -mips-plt-got
150   cl::opt<bool>
151   MipsPLTGOT("mips-plt-got",
152              cl::desc("Display the MIPS GOT and PLT GOT sections"));
153
154   // -mips-abi-flags
155   cl::opt<bool> MipsABIFlags("mips-abi-flags",
156                              cl::desc("Display the MIPS.abiflags section"));
157
158   // -mips-reginfo
159   cl::opt<bool> MipsReginfo("mips-reginfo",
160                             cl::desc("Display the MIPS .reginfo section"));
161
162   // -coff-imports
163   cl::opt<bool>
164   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
165
166   // -coff-exports
167   cl::opt<bool>
168   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
169
170   // -coff-directives
171   cl::opt<bool>
172   COFFDirectives("coff-directives",
173                  cl::desc("Display the PE/COFF .drectve section"));
174
175   // -coff-basereloc
176   cl::opt<bool>
177   COFFBaseRelocs("coff-basereloc",
178                  cl::desc("Display the PE/COFF .reloc section"));
179
180   // -stackmap
181   cl::opt<bool>
182   PrintStackMap("stackmap",
183                 cl::desc("Display contents of stackmap section"));
184
185 } // namespace opts
186
187 static int ReturnValue = EXIT_SUCCESS;
188
189 namespace llvm {
190
191 bool error(std::error_code EC) {
192   if (!EC)
193     return false;
194
195   ReturnValue = EXIT_FAILURE;
196   outs() << "\nError reading file: " << EC.message() << ".\n";
197   outs().flush();
198   return true;
199 }
200
201 bool relocAddressLess(RelocationRef a, RelocationRef b) {
202   uint64_t a_addr, b_addr;
203   if (error(a.getOffset(a_addr))) exit(ReturnValue);
204   if (error(b.getOffset(b_addr))) exit(ReturnValue);
205   return a_addr < b_addr;
206 }
207
208 } // namespace llvm
209
210 static void reportError(StringRef Input, std::error_code EC) {
211   if (Input == "-")
212     Input = "<stdin>";
213
214   errs() << Input << ": " << EC.message() << "\n";
215   errs().flush();
216   ReturnValue = EXIT_FAILURE;
217 }
218
219 static void reportError(StringRef Input, StringRef Message) {
220   if (Input == "-")
221     Input = "<stdin>";
222
223   errs() << Input << ": " << Message << "\n";
224   ReturnValue = EXIT_FAILURE;
225 }
226
227 static bool isMipsArch(unsigned Arch) {
228   switch (Arch) {
229   case llvm::Triple::mips:
230   case llvm::Triple::mipsel:
231   case llvm::Triple::mips64:
232   case llvm::Triple::mips64el:
233     return true;
234   default:
235     return false;
236   }
237 }
238
239 /// @brief Creates an format-specific object file dumper.
240 static std::error_code createDumper(const ObjectFile *Obj, StreamWriter &Writer,
241                                     std::unique_ptr<ObjDumper> &Result) {
242   if (!Obj)
243     return readobj_error::unsupported_file_format;
244
245   if (Obj->isCOFF())
246     return createCOFFDumper(Obj, Writer, Result);
247   if (Obj->isELF())
248     return createELFDumper(Obj, Writer, Result);
249   if (Obj->isMachO())
250     return createMachODumper(Obj, Writer, Result);
251
252   return readobj_error::unsupported_obj_file_format;
253 }
254
255 static StringRef getLoadName(const ObjectFile *Obj) {
256   if (auto *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
257     return ELF->getLoadName();
258   if (auto *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
259     return ELF->getLoadName();
260   if (auto *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
261     return ELF->getLoadName();
262   if (auto *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
263     return ELF->getLoadName();
264   llvm_unreachable("Not ELF");
265 }
266
267 /// @brief Dumps the specified object file.
268 static void dumpObject(const ObjectFile *Obj) {
269   StreamWriter Writer(outs());
270   std::unique_ptr<ObjDumper> Dumper;
271   if (std::error_code EC = createDumper(Obj, Writer, Dumper)) {
272     reportError(Obj->getFileName(), EC);
273     return;
274   }
275
276   outs() << '\n';
277   outs() << "File: " << Obj->getFileName() << "\n";
278   outs() << "Format: " << Obj->getFileFormatName() << "\n";
279   outs() << "Arch: "
280          << Triple::getArchTypeName((llvm::Triple::ArchType)Obj->getArch())
281          << "\n";
282   outs() << "AddressSize: " << (8*Obj->getBytesInAddress()) << "bit\n";
283   if (Obj->isELF())
284     outs() << "LoadName: " << getLoadName(Obj) << "\n";
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 (Obj->getArch() == llvm::Triple::arm && Obj->isELF())
307     if (opts::ARMAttributes)
308       Dumper->printAttributes();
309   if (isMipsArch(Obj->getArch()) && Obj->isELF()) {
310     if (opts::MipsPLTGOT)
311       Dumper->printMipsPLTGOT();
312     if (opts::MipsABIFlags)
313       Dumper->printMipsABIFlags();
314     if (opts::MipsReginfo)
315       Dumper->printMipsReginfo();
316   }
317   if (opts::COFFImports)
318     Dumper->printCOFFImports();
319   if (opts::COFFExports)
320     Dumper->printCOFFExports();
321   if (opts::COFFDirectives)
322     Dumper->printCOFFDirectives();
323   if (opts::COFFBaseRelocs)
324     Dumper->printCOFFBaseReloc();
325
326   if (opts::PrintStackMap)
327     Dumper->printStackMap();
328 }
329
330 /// @brief Dumps each object file in \a Arc;
331 static void dumpArchive(const Archive *Arc) {
332   for (Archive::child_iterator ArcI = Arc->child_begin(),
333                                ArcE = Arc->child_end();
334                                ArcI != ArcE; ++ArcI) {
335     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcI->getAsBinary();
336     if (std::error_code EC = ChildOrErr.getError()) {
337       // Ignore non-object files.
338       if (EC != object_error::invalid_file_type)
339         reportError(Arc->getFileName(), EC.message());
340       continue;
341     }
342
343     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
344       dumpObject(Obj);
345     else
346       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
347   }
348 }
349
350 /// @brief Dumps each object file in \a MachO Universal Binary;
351 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) {
352   for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
353     ErrorOr<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
354     if (ObjOrErr)
355       dumpObject(&*ObjOrErr.get());
356     else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
357       dumpArchive(&*AOrErr.get());
358     else
359       reportError(UBinary->getFileName(), ObjOrErr.getError().message());
360   }
361 }
362
363 /// @brief Opens \a File and dumps it.
364 static void dumpInput(StringRef File) {
365   // If file isn't stdin, check that it exists.
366   if (File != "-" && !sys::fs::exists(File)) {
367     reportError(File, readobj_error::file_not_found);
368     return;
369   }
370
371   // Attempt to open the binary.
372   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
373   if (std::error_code EC = BinaryOrErr.getError()) {
374     reportError(File, EC);
375     return;
376   }
377   Binary &Binary = *BinaryOrErr.get().getBinary();
378
379   if (Archive *Arc = dyn_cast<Archive>(&Binary))
380     dumpArchive(Arc);
381   else if (MachOUniversalBinary *UBinary =
382                dyn_cast<MachOUniversalBinary>(&Binary))
383     dumpMachOUniversalBinary(UBinary);
384   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
385     dumpObject(Obj);
386   else
387     reportError(File, readobj_error::unrecognized_file_format);
388 }
389
390 int main(int argc, const char *argv[]) {
391   sys::PrintStackTraceOnErrorSignal();
392   PrettyStackTraceProgram X(argc, argv);
393   llvm_shutdown_obj Y;
394
395   // Register the target printer for --version.
396   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
397
398   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
399
400   // Default to stdin if no filename is specified.
401   if (opts::InputFilenames.size() == 0)
402     opts::InputFilenames.push_back("-");
403
404   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
405                 dumpInput);
406
407   return ReturnValue;
408 }