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
error(std::error_code EC)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
getTarget(const ObjectFile * Obj=nullptr)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
DumpBytes(ArrayRef<uint8_t> bytes)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
RelocAddressLess(RelocationRef a,RelocationRef b)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
DisassembleObject(const ObjectFile * Obj,bool InlineRelocs)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
PrintRelocations(const ObjectFile * Obj)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
PrintSectionHeaders(const ObjectFile * Obj)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
PrintSectionContents(const ObjectFile * Obj)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
PrintCOFFSymbolTable(const COFFObjectFile * coff)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
PrintSymbolTable(const ObjectFile * o)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
633 if (Common) {
634 uint32_t Alignment;
635 if (error(Symbol.getAlignment(Alignment)))
636 Alignment = 0;
637 Address = Size;
638 Size = Alignment;
639 }
640 if (Address == UnknownAddressOrSize)
641 Address = 0;
642 if (Size == UnknownAddressOrSize)
643 Size = 0;
644 char GlobLoc = ' ';
645 if (Type != SymbolRef::ST_Unknown)
646 GlobLoc = Global ? 'g' : 'l';
647 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
648 ? 'd' : ' ';
649 char FileFunc = ' ';
650 if (Type == SymbolRef::ST_File)
651 FileFunc = 'f';
652 else if (Type == SymbolRef::ST_Function)
653 FileFunc = 'F';
654
655 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
656 "%08" PRIx64;
657
658 outs() << format(Fmt, Address) << " "
659 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
660 << (Weak ? 'w' : ' ') // Weak?
661 << ' ' // Constructor. Not supported yet.
662 << ' ' // Warning. Not supported yet.
663 << ' ' // Indirect reference to another symbol.
664 << Debug // Debugging (d) or dynamic (D) symbol.
665 << FileFunc // Name of function (F), file (f) or object (O).
666 << ' ';
667 if (Absolute) {
668 outs() << "*ABS*";
669 } else if (Common) {
670 outs() << "*COM*";
671 } else if (Section == o->section_end()) {
672 outs() << "*UND*";
673 } else {
674 if (const MachOObjectFile *MachO =
675 dyn_cast<const MachOObjectFile>(o)) {
676 DataRefImpl DR = Section->getRawDataRefImpl();
677 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
678 outs() << SegmentName << ",";
679 }
680 StringRef SectionName;
681 if (error(Section->getName(SectionName)))
682 SectionName = "";
683 outs() << SectionName;
684 }
685 outs() << '\t'
686 << format("%08" PRIx64 " ", Size)
687 << Name
688 << '\n';
689 }
690 }
691
PrintUnwindInfo(const ObjectFile * o)692 static void PrintUnwindInfo(const ObjectFile *o) {
693 outs() << "Unwind info:\n\n";
694
695 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
696 printCOFFUnwindInfo(coff);
697 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
698 printMachOUnwindInfo(MachO);
699 else {
700 // TODO: Extract DWARF dump tool to objdump.
701 errs() << "This operation is only currently supported "
702 "for COFF and MachO object files.\n";
703 return;
704 }
705 }
706
printExportsTrie(const ObjectFile * o)707 void llvm::printExportsTrie(const ObjectFile *o) {
708 outs() << "Exports trie:\n";
709 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
710 printMachOExportsTrie(MachO);
711 else {
712 errs() << "This operation is only currently supported "
713 "for Mach-O executable files.\n";
714 return;
715 }
716 }
717
printRebaseTable(const ObjectFile * o)718 void llvm::printRebaseTable(const ObjectFile *o) {
719 outs() << "Rebase table:\n";
720 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
721 printMachORebaseTable(MachO);
722 else {
723 errs() << "This operation is only currently supported "
724 "for Mach-O executable files.\n";
725 return;
726 }
727 }
728
printBindTable(const ObjectFile * o)729 void llvm::printBindTable(const ObjectFile *o) {
730 outs() << "Bind table:\n";
731 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
732 printMachOBindTable(MachO);
733 else {
734 errs() << "This operation is only currently supported "
735 "for Mach-O executable files.\n";
736 return;
737 }
738 }
739
printLazyBindTable(const ObjectFile * o)740 void llvm::printLazyBindTable(const ObjectFile *o) {
741 outs() << "Lazy bind table:\n";
742 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
743 printMachOLazyBindTable(MachO);
744 else {
745 errs() << "This operation is only currently supported "
746 "for Mach-O executable files.\n";
747 return;
748 }
749 }
750
printWeakBindTable(const ObjectFile * o)751 void llvm::printWeakBindTable(const ObjectFile *o) {
752 outs() << "Weak bind table:\n";
753 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
754 printMachOWeakBindTable(MachO);
755 else {
756 errs() << "This operation is only currently supported "
757 "for Mach-O executable files.\n";
758 return;
759 }
760 }
761
printPrivateFileHeader(const ObjectFile * o)762 static void printPrivateFileHeader(const ObjectFile *o) {
763 if (o->isELF()) {
764 printELFFileHeader(o);
765 } else if (o->isCOFF()) {
766 printCOFFFileHeader(o);
767 } else if (o->isMachO()) {
768 printMachOFileHeader(o);
769 }
770 }
771
DumpObject(const ObjectFile * o)772 static void DumpObject(const ObjectFile *o) {
773 outs() << '\n';
774 outs() << o->getFileName()
775 << ":\tfile format " << o->getFileFormatName() << "\n\n";
776
777 if (Disassemble)
778 DisassembleObject(o, Relocations);
779 if (Relocations && !Disassemble)
780 PrintRelocations(o);
781 if (SectionHeaders)
782 PrintSectionHeaders(o);
783 if (SectionContents)
784 PrintSectionContents(o);
785 if (SymbolTable)
786 PrintSymbolTable(o);
787 if (UnwindInfo)
788 PrintUnwindInfo(o);
789 if (PrivateHeaders)
790 printPrivateFileHeader(o);
791 if (ExportsTrie)
792 printExportsTrie(o);
793 if (Rebase)
794 printRebaseTable(o);
795 if (Bind)
796 printBindTable(o);
797 if (LazyBind)
798 printLazyBindTable(o);
799 if (WeakBind)
800 printWeakBindTable(o);
801 }
802
803 /// @brief Dump each object file in \a a;
DumpArchive(const Archive * a)804 static void DumpArchive(const Archive *a) {
805 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
806 ++i) {
807 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
808 if (std::error_code EC = ChildOrErr.getError()) {
809 // Ignore non-object files.
810 if (EC != object_error::invalid_file_type)
811 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
812 << ".\n";
813 continue;
814 }
815 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
816 DumpObject(o);
817 else
818 errs() << ToolName << ": '" << a->getFileName() << "': "
819 << "Unrecognized file type.\n";
820 }
821 }
822
823 /// @brief Open file and figure out how to dump it.
DumpInput(StringRef file)824 static void DumpInput(StringRef file) {
825 // If file isn't stdin, check that it exists.
826 if (file != "-" && !sys::fs::exists(file)) {
827 errs() << ToolName << ": '" << file << "': " << "No such file\n";
828 return;
829 }
830
831 // If we are using the Mach-O specific object file parser, then let it parse
832 // the file and process the command line options. So the -arch flags can
833 // be used to select specific slices, etc.
834 if (MachOOpt) {
835 ParseInputMachO(file);
836 return;
837 }
838
839 // Attempt to open the binary.
840 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
841 if (std::error_code EC = BinaryOrErr.getError()) {
842 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
843 return;
844 }
845 Binary &Binary = *BinaryOrErr.get().getBinary();
846
847 if (Archive *a = dyn_cast<Archive>(&Binary))
848 DumpArchive(a);
849 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
850 DumpObject(o);
851 else
852 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
853 }
854
main(int argc,char ** argv)855 int main(int argc, char **argv) {
856 // Print a stack trace if we signal out.
857 sys::PrintStackTraceOnErrorSignal();
858 PrettyStackTraceProgram X(argc, argv);
859 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
860
861 // Initialize targets and assembly printers/parsers.
862 llvm::InitializeAllTargetInfos();
863 llvm::InitializeAllTargetMCs();
864 llvm::InitializeAllAsmParsers();
865 llvm::InitializeAllDisassemblers();
866
867 // Register the target printer for --version.
868 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
869
870 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
871 TripleName = Triple::normalize(TripleName);
872
873 ToolName = argv[0];
874
875 // Defaults to a.out if no filenames specified.
876 if (InputFilenames.size() == 0)
877 InputFilenames.push_back("a.out");
878
879 if (!Disassemble
880 && !Relocations
881 && !SectionHeaders
882 && !SectionContents
883 && !SymbolTable
884 && !UnwindInfo
885 && !PrivateHeaders
886 && !ExportsTrie
887 && !Rebase
888 && !Bind
889 && !LazyBind
890 && !WeakBind
891 && !(UniversalHeaders && MachOOpt)
892 && !(ArchiveHeaders && MachOOpt)
893 && !(IndirectSymbols && MachOOpt)
894 && !(DataInCode && MachOOpt)
895 && !(LinkOptHints && MachOOpt)
896 && !(InfoPlist && MachOOpt)
897 && !(DylibsUsed && MachOOpt)
898 && !(DylibId && MachOOpt)
899 && !(ObjcMetaData && MachOOpt)
900 && !(DumpSections.size() != 0 && MachOOpt)) {
901 cl::PrintHelpMessage();
902 return 2;
903 }
904
905 std::for_each(InputFilenames.begin(), InputFilenames.end(),
906 DumpInput);
907
908 return ReturnValue;
909 }
910