OSDN Git Service

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