OSDN Git Service

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