[Object] Teach Object and llvm-objdump about ".hidden"
[oota-llvm.git] / tools / llvm-objdump / llvm-objdump.cpp
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
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 program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 // The flags and output of this program should be near identical to those of
15 // binutils objdump.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrAnalysis.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCRelocationInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/COFF.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/PrettyStackTrace.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <algorithm>
54 #include <cctype>
55 #include <cstring>
56 #include <system_error>
57
58 using namespace llvm;
59 using namespace object;
60
61 static cl::list<std::string>
62 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
63
64 cl::opt<bool>
65 llvm::Disassemble("disassemble",
66   cl::desc("Display assembler mnemonics for the machine instructions"));
67 static cl::alias
68 Disassembled("d", cl::desc("Alias for --disassemble"),
69              cl::aliasopt(Disassemble));
70
71 cl::opt<bool>
72 llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
73
74 cl::opt<bool>
75 llvm::SectionContents("s", cl::desc("Display the content of each section"));
76
77 cl::opt<bool>
78 llvm::SymbolTable("t", cl::desc("Display the symbol table"));
79
80 cl::opt<bool>
81 llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
82
83 cl::opt<bool>
84 llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
85
86 cl::opt<bool>
87 llvm::Bind("bind", cl::desc("Display mach-o binding info"));
88
89 cl::opt<bool>
90 llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
91
92 cl::opt<bool>
93 llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
94
95 static cl::opt<bool>
96 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
97 static cl::alias
98 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
99
100 cl::opt<std::string>
101 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
102                                     "see -version for available targets"));
103
104 cl::opt<std::string>
105 llvm::MCPU("mcpu",
106      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
107      cl::value_desc("cpu-name"),
108      cl::init(""));
109
110 cl::opt<std::string>
111 llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
112                                 "see -version for available targets"));
113
114 cl::opt<bool>
115 llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
116                                                  "headers for each section."));
117 static cl::alias
118 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
119                     cl::aliasopt(SectionHeaders));
120 static cl::alias
121 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
122                       cl::aliasopt(SectionHeaders));
123
124 cl::list<std::string>
125 llvm::MAttrs("mattr",
126   cl::CommaSeparated,
127   cl::desc("Target specific attributes"),
128   cl::value_desc("a1,+a2,-a3,..."));
129
130 cl::opt<bool>
131 llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
132                                                  "instructions, do not print "
133                                                  "the instruction bytes."));
134
135 cl::opt<bool>
136 llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
137
138 static cl::alias
139 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
140                 cl::aliasopt(UnwindInfo));
141
142 cl::opt<bool>
143 llvm::PrivateHeaders("private-headers",
144                      cl::desc("Display format specific file headers"));
145
146 static cl::alias
147 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
148                     cl::aliasopt(PrivateHeaders));
149
150 static StringRef ToolName;
151 static int ReturnValue = EXIT_SUCCESS;
152
153 bool llvm::error(std::error_code EC) {
154   if (!EC)
155     return false;
156
157   outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
158   outs().flush();
159   ReturnValue = EXIT_FAILURE;
160   return true;
161 }
162
163 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
164   // Figure out the target triple.
165   llvm::Triple TheTriple("unknown-unknown-unknown");
166   if (TripleName.empty()) {
167     if (Obj) {
168       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
169       // TheTriple defaults to ELF, and COFF doesn't have an environment:
170       // the best we can do here is indicate that it is mach-o.
171       if (Obj->isMachO())
172         TheTriple.setObjectFormat(Triple::MachO);
173
174       if (Obj->isCOFF()) {
175         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
176         if (COFFObj->getArch() == Triple::thumb)
177           TheTriple.setTriple("thumbv7-windows");
178       }
179     }
180   } else
181     TheTriple.setTriple(Triple::normalize(TripleName));
182
183   // Get the target specific parser.
184   std::string Error;
185   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
186                                                          Error);
187   if (!TheTarget) {
188     errs() << ToolName << ": " << Error;
189     return nullptr;
190   }
191
192   // Update the triple name and return the found target.
193   TripleName = TheTriple.getTriple();
194   return TheTarget;
195 }
196
197 void llvm::DumpBytes(ArrayRef<uint8_t> bytes) {
198   static const char hex_rep[] = "0123456789abcdef";
199   SmallString<64> output;
200
201   for (char i: bytes) {
202     output.push_back(hex_rep[(i & 0xF0) >> 4]);
203     output.push_back(hex_rep[i & 0xF]);
204     output.push_back(' ');
205   }
206
207   outs() << output.c_str();
208 }
209
210 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
211   uint64_t a_addr, b_addr;
212   if (error(a.getOffset(a_addr))) return false;
213   if (error(b.getOffset(b_addr))) return false;
214   return a_addr < b_addr;
215 }
216
217 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
218   const Target *TheTarget = getTarget(Obj);
219   // getTarget() will have already issued a diagnostic if necessary, so
220   // just bail here if it failed.
221   if (!TheTarget)
222     return;
223
224   // Package up features to be passed to target/subtarget
225   std::string FeaturesStr;
226   if (MAttrs.size()) {
227     SubtargetFeatures Features;
228     for (unsigned i = 0; i != MAttrs.size(); ++i)
229       Features.AddFeature(MAttrs[i]);
230     FeaturesStr = Features.getString();
231   }
232
233   std::unique_ptr<const MCRegisterInfo> MRI(
234       TheTarget->createMCRegInfo(TripleName));
235   if (!MRI) {
236     errs() << "error: no register info for target " << TripleName << "\n";
237     return;
238   }
239
240   // Set up disassembler.
241   std::unique_ptr<const MCAsmInfo> AsmInfo(
242       TheTarget->createMCAsmInfo(*MRI, TripleName));
243   if (!AsmInfo) {
244     errs() << "error: no assembly info for target " << TripleName << "\n";
245     return;
246   }
247
248   std::unique_ptr<const MCSubtargetInfo> STI(
249       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
250   if (!STI) {
251     errs() << "error: no subtarget info for target " << TripleName << "\n";
252     return;
253   }
254
255   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
256   if (!MII) {
257     errs() << "error: no instruction info for target " << TripleName << "\n";
258     return;
259   }
260
261   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
262   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
263
264   std::unique_ptr<MCDisassembler> DisAsm(
265     TheTarget->createMCDisassembler(*STI, Ctx));
266
267   if (!DisAsm) {
268     errs() << "error: no disassembler for target " << TripleName << "\n";
269     return;
270   }
271
272   std::unique_ptr<const MCInstrAnalysis> MIA(
273       TheTarget->createMCInstrAnalysis(MII.get()));
274
275   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
276   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
277       Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
278   if (!IP) {
279     errs() << "error: no instruction printer for target " << TripleName
280       << '\n';
281     return;
282   }
283
284   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
285                                                  "\t\t\t%08" PRIx64 ":  ";
286
287   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
288   // in RelocSecs contain the relocations for section S.
289   std::error_code EC;
290   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
291   for (const SectionRef &Section : Obj->sections()) {
292     section_iterator Sec2 = Section.getRelocatedSection();
293     if (Sec2 != Obj->section_end())
294       SectionRelocMap[*Sec2].push_back(Section);
295   }
296
297   for (const SectionRef &Section : Obj->sections()) {
298     if (!Section.isText() || Section.isVirtual())
299       continue;
300
301     uint64_t SectionAddr = Section.getAddress();
302     uint64_t SectSize = Section.getSize();
303     if (!SectSize)
304       continue;
305
306     // Make a list of all the symbols in this section.
307     std::vector<std::pair<uint64_t, StringRef>> Symbols;
308     for (const SymbolRef &Symbol : Obj->symbols()) {
309       if (Section.containsSymbol(Symbol)) {
310         uint64_t Address;
311         if (error(Symbol.getAddress(Address)))
312           break;
313         if (Address == UnknownAddressOrSize)
314           continue;
315         Address -= SectionAddr;
316         if (Address >= SectSize)
317           continue;
318
319         StringRef Name;
320         if (error(Symbol.getName(Name)))
321           break;
322         Symbols.push_back(std::make_pair(Address, Name));
323       }
324     }
325
326     // Sort the symbols by address, just in case they didn't come in that way.
327     array_pod_sort(Symbols.begin(), Symbols.end());
328
329     // Make a list of all the relocations for this section.
330     std::vector<RelocationRef> Rels;
331     if (InlineRelocs) {
332       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
333         for (const RelocationRef &Reloc : RelocSec.relocations()) {
334           Rels.push_back(Reloc);
335         }
336       }
337     }
338
339     // Sort relocations by address.
340     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
341
342     StringRef SegmentName = "";
343     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
344       DataRefImpl DR = Section.getRawDataRefImpl();
345       SegmentName = MachO->getSectionFinalSegmentName(DR);
346     }
347     StringRef name;
348     if (error(Section.getName(name)))
349       break;
350     outs() << "Disassembly of section ";
351     if (!SegmentName.empty())
352       outs() << SegmentName << ",";
353     outs() << name << ':';
354
355     // If the section has no symbols just insert a dummy one and disassemble
356     // the whole section.
357     if (Symbols.empty())
358       Symbols.push_back(std::make_pair(0, name));
359
360
361     SmallString<40> Comments;
362     raw_svector_ostream CommentStream(Comments);
363
364     StringRef BytesStr;
365     if (error(Section.getContents(BytesStr)))
366       break;
367     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
368                             BytesStr.size());
369
370     uint64_t Size;
371     uint64_t Index;
372
373     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
374     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
375     // Disassemble symbol by symbol.
376     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
377
378       uint64_t Start = Symbols[si].first;
379       // The end is either the section end or the beginning of the next symbol.
380       uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
381       // If this symbol has the same address as the next symbol, then skip it.
382       if (Start == End)
383         continue;
384
385       outs() << '\n' << Symbols[si].second << ":\n";
386
387 #ifndef NDEBUG
388       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
389 #else
390       raw_ostream &DebugOut = nulls();
391 #endif
392
393       for (Index = Start; Index < End; Index += Size) {
394         MCInst Inst;
395
396         if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
397                                    SectionAddr + Index, DebugOut,
398                                    CommentStream)) {
399           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
400           if (!NoShowRawInsn) {
401             outs() << "\t";
402             DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
403           }
404           IP->printInst(&Inst, outs(), "", *STI);
405           outs() << CommentStream.str();
406           Comments.clear();
407           outs() << "\n";
408         } else {
409           errs() << ToolName << ": warning: invalid instruction encoding\n";
410           if (Size == 0)
411             Size = 1; // skip illegible bytes
412         }
413
414         // Print relocation for instruction.
415         while (rel_cur != rel_end) {
416           bool hidden = false;
417           uint64_t addr;
418           SmallString<16> name;
419           SmallString<32> val;
420
421           // If this relocation is hidden, skip it.
422           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
423           if (hidden) goto skip_print_rel;
424
425           if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
426           // Stop when rel_cur's address is past the current instruction.
427           if (addr >= Index + Size) break;
428           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
429           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
430
431           outs() << format(Fmt.data(), SectionAddr + addr) << name
432                  << "\t" << val << "\n";
433
434         skip_print_rel:
435           ++rel_cur;
436         }
437       }
438     }
439   }
440 }
441
442 void llvm::PrintRelocations(const ObjectFile *Obj) {
443   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
444                                                  "%08" PRIx64;
445   // Regular objdump doesn't print relocations in non-relocatable object
446   // files.
447   if (!Obj->isRelocatableObject())
448     return;
449
450   for (const SectionRef &Section : Obj->sections()) {
451     if (Section.relocation_begin() == Section.relocation_end())
452       continue;
453     StringRef secname;
454     if (error(Section.getName(secname)))
455       continue;
456     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
457     for (const RelocationRef &Reloc : Section.relocations()) {
458       bool hidden;
459       uint64_t address;
460       SmallString<32> relocname;
461       SmallString<32> valuestr;
462       if (error(Reloc.getHidden(hidden)))
463         continue;
464       if (hidden)
465         continue;
466       if (error(Reloc.getTypeName(relocname)))
467         continue;
468       if (error(Reloc.getOffset(address)))
469         continue;
470       if (error(Reloc.getValueString(valuestr)))
471         continue;
472       outs() << format(Fmt.data(), address) << " " << relocname << " "
473              << valuestr << "\n";
474     }
475     outs() << "\n";
476   }
477 }
478
479 void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
480   outs() << "Sections:\n"
481             "Idx Name          Size      Address          Type\n";
482   unsigned i = 0;
483   for (const SectionRef &Section : Obj->sections()) {
484     StringRef Name;
485     if (error(Section.getName(Name)))
486       return;
487     uint64_t Address = Section.getAddress();
488     uint64_t Size = Section.getSize();
489     bool Text = Section.isText();
490     bool Data = Section.isData();
491     bool BSS = Section.isBSS();
492     std::string Type = (std::string(Text ? "TEXT " : "") +
493                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
494     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
495                      Name.str().c_str(), Size, Address, Type.c_str());
496     ++i;
497   }
498 }
499
500 void llvm::PrintSectionContents(const ObjectFile *Obj) {
501   std::error_code EC;
502   for (const SectionRef &Section : Obj->sections()) {
503     StringRef Name;
504     StringRef Contents;
505     if (error(Section.getName(Name)))
506       continue;
507     uint64_t BaseAddr = Section.getAddress();
508     uint64_t Size = Section.getSize();
509     if (!Size)
510       continue;
511
512     outs() << "Contents of section " << Name << ":\n";
513     if (Section.isBSS()) {
514       outs() << format("<skipping contents of bss section at [%04" PRIx64
515                        ", %04" PRIx64 ")>\n",
516                        BaseAddr, BaseAddr + Size);
517       continue;
518     }
519
520     if (error(Section.getContents(Contents)))
521       continue;
522
523     // Dump out the content as hex and printable ascii characters.
524     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
525       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
526       // Dump line of hex.
527       for (std::size_t i = 0; i < 16; ++i) {
528         if (i != 0 && i % 4 == 0)
529           outs() << ' ';
530         if (addr + i < end)
531           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
532                  << hexdigit(Contents[addr + i] & 0xF, true);
533         else
534           outs() << "  ";
535       }
536       // Print ascii.
537       outs() << "  ";
538       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
539         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
540           outs() << Contents[addr + i];
541         else
542           outs() << ".";
543       }
544       outs() << "\n";
545     }
546   }
547 }
548
549 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
550   for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
551     ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
552     StringRef Name;
553     if (error(Symbol.getError()))
554       return;
555
556     if (error(coff->getSymbolName(*Symbol, Name)))
557       return;
558
559     outs() << "[" << format("%2d", SI) << "]"
560            << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
561            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
562            << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
563            << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
564            << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
565            << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
566            << Name << "\n";
567
568     for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
569       if (Symbol->isSectionDefinition()) {
570         const coff_aux_section_definition *asd;
571         if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
572           return;
573
574         int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
575
576         outs() << "AUX "
577                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
578                          , unsigned(asd->Length)
579                          , unsigned(asd->NumberOfRelocations)
580                          , unsigned(asd->NumberOfLinenumbers)
581                          , unsigned(asd->CheckSum))
582                << format("assoc %d comdat %d\n"
583                          , unsigned(AuxNumber)
584                          , unsigned(asd->Selection));
585       } else if (Symbol->isFileRecord()) {
586         const char *FileName;
587         if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
588           return;
589
590         StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
591                                      coff->getSymbolTableEntrySize());
592         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
593
594         SI = SI + Symbol->getNumberOfAuxSymbols();
595         break;
596       } else {
597         outs() << "AUX Unknown\n";
598       }
599     }
600   }
601 }
602
603 void llvm::PrintSymbolTable(const ObjectFile *o) {
604   outs() << "SYMBOL TABLE:\n";
605
606   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
607     PrintCOFFSymbolTable(coff);
608     return;
609   }
610   for (const SymbolRef &Symbol : o->symbols()) {
611     StringRef Name;
612     uint64_t Address;
613     SymbolRef::Type Type;
614     uint64_t Size;
615     uint32_t Flags = Symbol.getFlags();
616     section_iterator Section = o->section_end();
617     if (error(Symbol.getName(Name)))
618       continue;
619     if (error(Symbol.getAddress(Address)))
620       continue;
621     if (error(Symbol.getType(Type)))
622       continue;
623     if (error(Symbol.getSize(Size)))
624       continue;
625     if (error(Symbol.getSection(Section)))
626       continue;
627
628     bool Global = Flags & SymbolRef::SF_Global;
629     bool Weak = Flags & SymbolRef::SF_Weak;
630     bool Absolute = Flags & SymbolRef::SF_Absolute;
631     bool Common = Flags & SymbolRef::SF_Common;
632     bool Hidden = Flags & SymbolRef::SF_Hidden;
633
634     if (Common) {
635       uint32_t Alignment;
636       if (error(Symbol.getAlignment(Alignment)))
637         Alignment = 0;
638       Address = Size;
639       Size = Alignment;
640     }
641     if (Address == UnknownAddressOrSize)
642       Address = 0;
643     if (Size == UnknownAddressOrSize)
644       Size = 0;
645     char GlobLoc = ' ';
646     if (Type != SymbolRef::ST_Unknown)
647       GlobLoc = Global ? 'g' : 'l';
648     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
649                  ? 'd' : ' ';
650     char FileFunc = ' ';
651     if (Type == SymbolRef::ST_File)
652       FileFunc = 'f';
653     else if (Type == SymbolRef::ST_Function)
654       FileFunc = 'F';
655
656     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
657                                                    "%08" PRIx64;
658
659     outs() << format(Fmt, Address) << " "
660            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
661            << (Weak ? 'w' : ' ') // Weak?
662            << ' ' // Constructor. Not supported yet.
663            << ' ' // Warning. Not supported yet.
664            << ' ' // Indirect reference to another symbol.
665            << Debug // Debugging (d) or dynamic (D) symbol.
666            << FileFunc // Name of function (F), file (f) or object (O).
667            << ' ';
668     if (Absolute) {
669       outs() << "*ABS*";
670     } else if (Common) {
671       outs() << "*COM*";
672     } else if (Section == o->section_end()) {
673       outs() << "*UND*";
674     } else {
675       if (const MachOObjectFile *MachO =
676           dyn_cast<const MachOObjectFile>(o)) {
677         DataRefImpl DR = Section->getRawDataRefImpl();
678         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
679         outs() << SegmentName << ",";
680       }
681       StringRef SectionName;
682       if (error(Section->getName(SectionName)))
683         SectionName = "";
684       outs() << SectionName;
685     }
686     outs() << '\t'
687            << format("%08" PRIx64 " ", Size);
688     if (Hidden) {
689       outs() << ".hidden ";
690     }
691     outs() << Name
692            << '\n';
693   }
694 }
695
696 static void PrintUnwindInfo(const ObjectFile *o) {
697   outs() << "Unwind info:\n\n";
698
699   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
700     printCOFFUnwindInfo(coff);
701   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
702     printMachOUnwindInfo(MachO);
703   else {
704     // TODO: Extract DWARF dump tool to objdump.
705     errs() << "This operation is only currently supported "
706               "for COFF and MachO object files.\n";
707     return;
708   }
709 }
710
711 void llvm::printExportsTrie(const ObjectFile *o) {
712   outs() << "Exports trie:\n";
713   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
714     printMachOExportsTrie(MachO);
715   else {
716     errs() << "This operation is only currently supported "
717               "for Mach-O executable files.\n";
718     return;
719   }
720 }
721
722 void llvm::printRebaseTable(const ObjectFile *o) {
723   outs() << "Rebase table:\n";
724   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
725     printMachORebaseTable(MachO);
726   else {
727     errs() << "This operation is only currently supported "
728               "for Mach-O executable files.\n";
729     return;
730   }
731 }
732
733 void llvm::printBindTable(const ObjectFile *o) {
734   outs() << "Bind table:\n";
735   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
736     printMachOBindTable(MachO);
737   else {
738     errs() << "This operation is only currently supported "
739               "for Mach-O executable files.\n";
740     return;
741   }
742 }
743
744 void llvm::printLazyBindTable(const ObjectFile *o) {
745   outs() << "Lazy bind table:\n";
746   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
747     printMachOLazyBindTable(MachO);
748   else {
749     errs() << "This operation is only currently supported "
750               "for Mach-O executable files.\n";
751     return;
752   }
753 }
754
755 void llvm::printWeakBindTable(const ObjectFile *o) {
756   outs() << "Weak bind table:\n";
757   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
758     printMachOWeakBindTable(MachO);
759   else {
760     errs() << "This operation is only currently supported "
761               "for Mach-O executable files.\n";
762     return;
763   }
764 }
765
766 static void printPrivateFileHeader(const ObjectFile *o) {
767   if (o->isELF()) {
768     printELFFileHeader(o);
769   } else if (o->isCOFF()) {
770     printCOFFFileHeader(o);
771   } else if (o->isMachO()) {
772     printMachOFileHeader(o);
773   }
774 }
775
776 static void DumpObject(const ObjectFile *o) {
777   outs() << '\n';
778   outs() << o->getFileName()
779          << ":\tfile format " << o->getFileFormatName() << "\n\n";
780
781   if (Disassemble)
782     DisassembleObject(o, Relocations);
783   if (Relocations && !Disassemble)
784     PrintRelocations(o);
785   if (SectionHeaders)
786     PrintSectionHeaders(o);
787   if (SectionContents)
788     PrintSectionContents(o);
789   if (SymbolTable)
790     PrintSymbolTable(o);
791   if (UnwindInfo)
792     PrintUnwindInfo(o);
793   if (PrivateHeaders)
794     printPrivateFileHeader(o);
795   if (ExportsTrie)
796     printExportsTrie(o);
797   if (Rebase)
798     printRebaseTable(o);
799   if (Bind)
800     printBindTable(o);
801   if (LazyBind)
802     printLazyBindTable(o);
803   if (WeakBind)
804     printWeakBindTable(o);
805 }
806
807 /// @brief Dump each object file in \a a;
808 static void DumpArchive(const Archive *a) {
809   for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
810        ++i) {
811     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
812     if (std::error_code EC = ChildOrErr.getError()) {
813       // Ignore non-object files.
814       if (EC != object_error::invalid_file_type)
815         errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
816                << ".\n";
817       continue;
818     }
819     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
820       DumpObject(o);
821     else
822       errs() << ToolName << ": '" << a->getFileName() << "': "
823               << "Unrecognized file type.\n";
824   }
825 }
826
827 /// @brief Open file and figure out how to dump it.
828 static void DumpInput(StringRef file) {
829   // If file isn't stdin, check that it exists.
830   if (file != "-" && !sys::fs::exists(file)) {
831     errs() << ToolName << ": '" << file << "': " << "No such file\n";
832     return;
833   }
834
835   // If we are using the Mach-O specific object file parser, then let it parse
836   // the file and process the command line options.  So the -arch flags can
837   // be used to select specific slices, etc.
838   if (MachOOpt) {
839     ParseInputMachO(file);
840     return;
841   }
842
843   // Attempt to open the binary.
844   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
845   if (std::error_code EC = BinaryOrErr.getError()) {
846     errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
847     return;
848   }
849   Binary &Binary = *BinaryOrErr.get().getBinary();
850
851   if (Archive *a = dyn_cast<Archive>(&Binary))
852     DumpArchive(a);
853   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
854     DumpObject(o);
855   else
856     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
857 }
858
859 int main(int argc, char **argv) {
860   // Print a stack trace if we signal out.
861   sys::PrintStackTraceOnErrorSignal();
862   PrettyStackTraceProgram X(argc, argv);
863   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
864
865   // Initialize targets and assembly printers/parsers.
866   llvm::InitializeAllTargetInfos();
867   llvm::InitializeAllTargetMCs();
868   llvm::InitializeAllAsmParsers();
869   llvm::InitializeAllDisassemblers();
870
871   // Register the target printer for --version.
872   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
873
874   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
875   TripleName = Triple::normalize(TripleName);
876
877   ToolName = argv[0];
878
879   // Defaults to a.out if no filenames specified.
880   if (InputFilenames.size() == 0)
881     InputFilenames.push_back("a.out");
882
883   if (!Disassemble
884       && !Relocations
885       && !SectionHeaders
886       && !SectionContents
887       && !SymbolTable
888       && !UnwindInfo
889       && !PrivateHeaders
890       && !ExportsTrie
891       && !Rebase
892       && !Bind
893       && !LazyBind
894       && !WeakBind
895       && !(UniversalHeaders && MachOOpt)
896       && !(ArchiveHeaders && MachOOpt)
897       && !(IndirectSymbols && MachOOpt)
898       && !(DataInCode && MachOOpt)
899       && !(LinkOptHints && MachOOpt)
900       && !(InfoPlist && MachOOpt)
901       && !(DylibsUsed && MachOOpt)
902       && !(DylibId && MachOOpt)
903       && !(ObjcMetaData && MachOOpt)
904       && !(DumpSections.size() != 0 && MachOOpt)) {
905     cl::PrintHelpMessage();
906     return 2;
907   }
908
909   std::for_each(InputFilenames.begin(), InputFilenames.end(),
910                 DumpInput);
911
912   return ReturnValue;
913 }