blob: d03556c461599e2aee1372f4443fd8696e586856 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- 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//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000020#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000021#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000022#include "llvm/ADT/Triple.h"
23#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000024#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000025#include "llvm/MC/MCDisassembler.h"
26#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000028#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000029#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000030#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000032#include "llvm/MC/MCRelocationInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000033#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include "llvm/Object/Archive.h"
Rafael Espindola37070a52015-06-03 04:48:06 +000035#include "llvm/Object/ELFObjectFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Object/COFF.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000037#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000039#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000040#include "llvm/Support/CommandLine.h"
41#include "llvm/Support/Debug.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000042#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000043#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000044#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000045#include "llvm/Support/Host.h"
46#include "llvm/Support/ManagedStatic.h"
47#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/PrettyStackTrace.h"
49#include "llvm/Support/Signals.h"
50#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000051#include "llvm/Support/TargetRegistry.h"
52#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000055#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000057#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000058
Michael J. Spencer2670c252011-01-20 06:39:06 +000059using namespace llvm;
60using namespace object;
61
Benjamin Kramer43a772e2011-09-19 17:56:04 +000062static cl::list<std::string>
63InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000064
Kevin Enderbye2297dd2015-01-07 21:02:18 +000065cl::opt<bool>
66llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000067 cl::desc("Display assembler mnemonics for the machine instructions"));
68static cl::alias
69Disassembled("d", cl::desc("Alias for --disassemble"),
70 cl::aliasopt(Disassemble));
Michael J. Spencer2670c252011-01-20 06:39:06 +000071
Kevin Enderby98da6132015-01-20 21:47:46 +000072cl::opt<bool>
73llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000074
Kevin Enderby98da6132015-01-20 21:47:46 +000075cl::opt<bool>
76llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000077
Kevin Enderby98da6132015-01-20 21:47:46 +000078cl::opt<bool>
79llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000080
Kevin Enderbye2297dd2015-01-07 21:02:18 +000081cl::opt<bool>
82llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000083
Kevin Enderbye2297dd2015-01-07 21:02:18 +000084cl::opt<bool>
85llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000086
Kevin Enderbye2297dd2015-01-07 21:02:18 +000087cl::opt<bool>
88llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000089
Kevin Enderbye2297dd2015-01-07 21:02:18 +000090cl::opt<bool>
91llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000092
Kevin Enderbye2297dd2015-01-07 21:02:18 +000093cl::opt<bool>
94llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000095
96static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000097MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +000098static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000099MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000100
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000101cl::opt<std::string>
102llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
103 "see -version for available targets"));
104
105cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000106llvm::MCPU("mcpu",
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
109 cl::init(""));
110
111cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000112llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000113 "see -version for available targets"));
114
Kevin Enderby98da6132015-01-20 21:47:46 +0000115cl::opt<bool>
116llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
117 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000118static cl::alias
119SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
120 cl::aliasopt(SectionHeaders));
121static cl::alias
122SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
124
Kevin Enderbyc9595622014-08-06 23:24:41 +0000125cl::list<std::string>
126llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000127 cl::CommaSeparated,
128 cl::desc("Target specific attributes"),
129 cl::value_desc("a1,+a2,-a3,..."));
130
Kevin Enderbybf246f52014-09-24 23:08:22 +0000131cl::opt<bool>
132llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
133 "instructions, do not print "
134 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000135
Kevin Enderby98da6132015-01-20 21:47:46 +0000136cl::opt<bool>
137llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000138
139static cl::alias
140UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
141 cl::aliasopt(UnwindInfo));
142
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000143cl::opt<bool>
144llvm::PrivateHeaders("private-headers",
145 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000146
147static cl::alias
148PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
149 cl::aliasopt(PrivateHeaders));
150
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151static StringRef ToolName;
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000152static int ReturnValue = EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000153
Rafael Espindola4453e42942014-06-13 03:07:50 +0000154bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000155 if (!EC)
156 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000157
Mark Seaborneb03ac52014-01-25 00:32:01 +0000158 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159 outs().flush();
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000160 ReturnValue = EXIT_FAILURE;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000161 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000162}
163
Craig Toppere6cb63e2014-04-25 04:24:47 +0000164static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000165 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000166 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000167 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000168 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000169 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000170 // TheTriple defaults to ELF, and COFF doesn't have an environment:
171 // the best we can do here is indicate that it is mach-o.
172 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000173 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000174
175 if (Obj->isCOFF()) {
176 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
177 if (COFFObj->getArch() == Triple::thumb)
178 TheTriple.setTriple("thumbv7-windows");
179 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000180 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000181 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000182 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000183
184 // Get the target specific parser.
185 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000186 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
187 Error);
188 if (!TheTarget) {
189 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000190 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000191 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000192
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000193 // Update the triple name and return the found target.
194 TripleName = TheTriple.getTriple();
195 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000196}
197
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000198bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000199 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000200 if (error(a.getOffset(a_addr))) return false;
201 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000202 return a_addr < b_addr;
203}
204
Colin LeMahieufb76b002015-05-28 19:07:14 +0000205namespace {
206class PrettyPrinter {
207public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000208 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000209 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000210 ArrayRef<uint8_t> Bytes, uint64_t Address,
211 raw_ostream &OS, StringRef Annot,
212 MCSubtargetInfo const &STI) {
213 outs() << format("%8" PRIx64 ":", Address);
214 if (!NoShowRawInsn) {
215 outs() << "\t";
216 dumpBytes(Bytes, outs());
217 }
218 IP.printInst(MI, outs(), "", STI);
219 }
220};
221PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000222class HexagonPrettyPrinter : public PrettyPrinter {
223public:
224 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
225 raw_ostream &OS) {
226 uint32_t opcode =
227 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
228 OS << format("%8" PRIx64 ":", Address);
229 if (!NoShowRawInsn) {
230 OS << "\t";
231 dumpBytes(Bytes.slice(0, 4), OS);
232 OS << format("%08" PRIx32, opcode);
233 }
234 }
235 void printInst(MCInstPrinter &IP, const MCInst *MI,
236 ArrayRef<uint8_t> Bytes, uint64_t Address,
237 raw_ostream &OS, StringRef Annot,
238 MCSubtargetInfo const &STI) override {
239 std::string Buffer;
240 {
241 raw_string_ostream TempStream(Buffer);
242 IP.printInst(MI, TempStream, "", STI);
243 }
244 StringRef Contents(Buffer);
245 // Split off bundle attributes
246 auto PacketBundle = Contents.rsplit('\n');
247 // Split off first instruction from the rest
248 auto HeadTail = PacketBundle.first.split('\n');
249 auto Preamble = " { ";
250 auto Separator = "";
251 while(!HeadTail.first.empty()) {
252 OS << Separator;
253 Separator = "\n";
254 printLead(Bytes, Address, OS);
255 OS << Preamble;
256 Preamble = " ";
257 StringRef Inst;
258 auto Duplex = HeadTail.first.split('\v');
259 if(!Duplex.second.empty()){
260 OS << Duplex.first;
261 OS << "; ";
262 Inst = Duplex.second;
263 }
264 else
265 Inst = HeadTail.first;
266 OS << Inst;
267 Bytes = Bytes.slice(4);
268 Address += 4;
269 HeadTail = HeadTail.second.split('\n');
270 }
271 OS << " } " << PacketBundle.second;
272 }
273};
274HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000275PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000276 switch(Triple.getArch()) {
277 default:
278 return PrettyPrinterInst;
279 case Triple::hexagon:
280 return HexagonPrettyPrinterInst;
281 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000282}
283}
284
Rafael Espindola37070a52015-06-03 04:48:06 +0000285template <class ELFT>
286static const typename ELFObjectFile<ELFT>::Elf_Rel *
287getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
288 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
289 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
290}
291
292template <class ELFT>
293static const typename ELFObjectFile<ELFT>::Elf_Rela *
294getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
295 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
296 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
297}
298
299template <class ELFT>
300static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
301 DataRefImpl Rel,
302 SmallVectorImpl<char> &Result) {
303 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
304 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
305 const ELFFile<ELFT> &EF = *Obj->getELFFile();
306
307 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
308 uint8_t type;
309 StringRef res;
310 int64_t addend = 0;
311 uint16_t symbol_index = 0;
312 switch (sec->sh_type) {
313 default:
314 return object_error::parse_failed;
315 case ELF::SHT_REL: {
316 type = getRel(EF, Rel)->getType(EF.isMips64EL());
317 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
318 // TODO: Read implicit addend from section data.
319 break;
320 }
321 case ELF::SHT_RELA: {
322 type = getRela(EF, Rel)->getType(EF.isMips64EL());
323 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
324 addend = getRela(EF, Rel)->r_addend;
325 break;
326 }
327 }
328 const Elf_Sym *symb =
329 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000330 StringRef Target;
331 const Elf_Shdr *SymSec = EF.getSection(symb);
332 if (symb->getType() == ELF::STT_SECTION) {
333 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
334 if (std::error_code EC = SecName.getError())
335 return EC;
336 Target = *SecName;
337 } else {
338 ErrorOr<StringRef> SymName =
339 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
340 if (!SymName)
341 return SymName.getError();
342 Target = *SymName;
343 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000344 switch (EF.getHeader()->e_machine) {
345 case ELF::EM_X86_64:
346 switch (type) {
347 case ELF::R_X86_64_PC8:
348 case ELF::R_X86_64_PC16:
349 case ELF::R_X86_64_PC32: {
350 std::string fmtbuf;
351 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000352 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000353 fmt.flush();
354 Result.append(fmtbuf.begin(), fmtbuf.end());
355 } break;
356 case ELF::R_X86_64_8:
357 case ELF::R_X86_64_16:
358 case ELF::R_X86_64_32:
359 case ELF::R_X86_64_32S:
360 case ELF::R_X86_64_64: {
361 std::string fmtbuf;
362 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000363 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000364 fmt.flush();
365 Result.append(fmtbuf.begin(), fmtbuf.end());
366 } break;
367 default:
368 res = "Unknown";
369 }
370 break;
371 case ELF::EM_AARCH64: {
372 std::string fmtbuf;
373 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000374 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000375 if (addend != 0)
376 fmt << (addend < 0 ? "" : "+") << addend;
377 fmt.flush();
378 Result.append(fmtbuf.begin(), fmtbuf.end());
379 break;
380 }
381 case ELF::EM_386:
382 case ELF::EM_ARM:
383 case ELF::EM_HEXAGON:
384 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000385 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000386 break;
387 default:
388 res = "Unknown";
389 }
390 if (Result.empty())
391 Result.append(res.begin(), res.end());
392 return object_error::success;
393}
394
395static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
396 const RelocationRef &RelRef,
397 SmallVectorImpl<char> &Result) {
398 DataRefImpl Rel = RelRef.getRawDataRefImpl();
399 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
400 return getRelocationValueString(ELF32LE, Rel, Result);
401 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
402 return getRelocationValueString(ELF64LE, Rel, Result);
403 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
404 return getRelocationValueString(ELF32BE, Rel, Result);
405 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
406 return getRelocationValueString(ELF64BE, Rel, Result);
407}
408
409static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
410 const RelocationRef &Rel,
411 SmallVectorImpl<char> &Result) {
412 symbol_iterator SymI = Rel.getSymbol();
413 StringRef SymName;
414 if (std::error_code EC = SymI->getName(SymName))
415 return EC;
416 Result.append(SymName.begin(), SymName.end());
417 return object_error::success;
418}
419
420static void printRelocationTargetName(const MachOObjectFile *O,
421 const MachO::any_relocation_info &RE,
422 raw_string_ostream &fmt) {
423 bool IsScattered = O->isRelocationScattered(RE);
424
425 // Target of a scattered relocation is an address. In the interest of
426 // generating pretty output, scan through the symbol table looking for a
427 // symbol that aligns with that address. If we find one, print it.
428 // Otherwise, we just print the hex address of the target.
429 if (IsScattered) {
430 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
431
432 for (const SymbolRef &Symbol : O->symbols()) {
433 std::error_code ec;
434 uint64_t Addr;
435 StringRef Name;
436
437 if ((ec = Symbol.getAddress(Addr)))
438 report_fatal_error(ec.message());
439 if (Addr != Val)
440 continue;
441 if ((ec = Symbol.getName(Name)))
442 report_fatal_error(ec.message());
443 fmt << Name;
444 return;
445 }
446
447 // If we couldn't find a symbol that this relocation refers to, try
448 // to find a section beginning instead.
449 for (const SectionRef &Section : O->sections()) {
450 std::error_code ec;
451
452 StringRef Name;
453 uint64_t Addr = Section.getAddress();
454 if (Addr != Val)
455 continue;
456 if ((ec = Section.getName(Name)))
457 report_fatal_error(ec.message());
458 fmt << Name;
459 return;
460 }
461
462 fmt << format("0x%x", Val);
463 return;
464 }
465
466 StringRef S;
467 bool isExtern = O->getPlainRelocationExternal(RE);
468 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
469
470 if (isExtern) {
471 symbol_iterator SI = O->symbol_begin();
472 advance(SI, Val);
473 SI->getName(S);
474 } else {
475 section_iterator SI = O->section_begin();
476 // Adjust for the fact that sections are 1-indexed.
477 advance(SI, Val - 1);
478 SI->getName(S);
479 }
480
481 fmt << S;
482}
483
484static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
485 const RelocationRef &RelRef,
486 SmallVectorImpl<char> &Result) {
487 DataRefImpl Rel = RelRef.getRawDataRefImpl();
488 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
489
490 unsigned Arch = Obj->getArch();
491
492 std::string fmtbuf;
493 raw_string_ostream fmt(fmtbuf);
494 unsigned Type = Obj->getAnyRelocationType(RE);
495 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
496
497 // Determine any addends that should be displayed with the relocation.
498 // These require decoding the relocation type, which is triple-specific.
499
500 // X86_64 has entirely custom relocation types.
501 if (Arch == Triple::x86_64) {
502 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
503
504 switch (Type) {
505 case MachO::X86_64_RELOC_GOT_LOAD:
506 case MachO::X86_64_RELOC_GOT: {
507 printRelocationTargetName(Obj, RE, fmt);
508 fmt << "@GOT";
509 if (isPCRel)
510 fmt << "PCREL";
511 break;
512 }
513 case MachO::X86_64_RELOC_SUBTRACTOR: {
514 DataRefImpl RelNext = Rel;
515 Obj->moveRelocationNext(RelNext);
516 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
517
518 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
519 // X86_64_RELOC_UNSIGNED.
520 // NOTE: Scattered relocations don't exist on x86_64.
521 unsigned RType = Obj->getAnyRelocationType(RENext);
522 if (RType != MachO::X86_64_RELOC_UNSIGNED)
523 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
524 "X86_64_RELOC_SUBTRACTOR.");
525
526 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
527 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
528 printRelocationTargetName(Obj, RENext, fmt);
529 fmt << "-";
530 printRelocationTargetName(Obj, RE, fmt);
531 break;
532 }
533 case MachO::X86_64_RELOC_TLV:
534 printRelocationTargetName(Obj, RE, fmt);
535 fmt << "@TLV";
536 if (isPCRel)
537 fmt << "P";
538 break;
539 case MachO::X86_64_RELOC_SIGNED_1:
540 printRelocationTargetName(Obj, RE, fmt);
541 fmt << "-1";
542 break;
543 case MachO::X86_64_RELOC_SIGNED_2:
544 printRelocationTargetName(Obj, RE, fmt);
545 fmt << "-2";
546 break;
547 case MachO::X86_64_RELOC_SIGNED_4:
548 printRelocationTargetName(Obj, RE, fmt);
549 fmt << "-4";
550 break;
551 default:
552 printRelocationTargetName(Obj, RE, fmt);
553 break;
554 }
555 // X86 and ARM share some relocation types in common.
556 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
557 Arch == Triple::ppc) {
558 // Generic relocation types...
559 switch (Type) {
560 case MachO::GENERIC_RELOC_PAIR: // prints no info
561 return object_error::success;
562 case MachO::GENERIC_RELOC_SECTDIFF: {
563 DataRefImpl RelNext = Rel;
564 Obj->moveRelocationNext(RelNext);
565 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
566
567 // X86 sect diff's must be followed by a relocation of type
568 // GENERIC_RELOC_PAIR.
569 unsigned RType = Obj->getAnyRelocationType(RENext);
570
571 if (RType != MachO::GENERIC_RELOC_PAIR)
572 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
573 "GENERIC_RELOC_SECTDIFF.");
574
575 printRelocationTargetName(Obj, RE, fmt);
576 fmt << "-";
577 printRelocationTargetName(Obj, RENext, fmt);
578 break;
579 }
580 }
581
582 if (Arch == Triple::x86 || Arch == Triple::ppc) {
583 switch (Type) {
584 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
585 DataRefImpl RelNext = Rel;
586 Obj->moveRelocationNext(RelNext);
587 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
588
589 // X86 sect diff's must be followed by a relocation of type
590 // GENERIC_RELOC_PAIR.
591 unsigned RType = Obj->getAnyRelocationType(RENext);
592 if (RType != MachO::GENERIC_RELOC_PAIR)
593 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
594 "GENERIC_RELOC_LOCAL_SECTDIFF.");
595
596 printRelocationTargetName(Obj, RE, fmt);
597 fmt << "-";
598 printRelocationTargetName(Obj, RENext, fmt);
599 break;
600 }
601 case MachO::GENERIC_RELOC_TLV: {
602 printRelocationTargetName(Obj, RE, fmt);
603 fmt << "@TLV";
604 if (IsPCRel)
605 fmt << "P";
606 break;
607 }
608 default:
609 printRelocationTargetName(Obj, RE, fmt);
610 }
611 } else { // ARM-specific relocations
612 switch (Type) {
613 case MachO::ARM_RELOC_HALF:
614 case MachO::ARM_RELOC_HALF_SECTDIFF: {
615 // Half relocations steal a bit from the length field to encode
616 // whether this is an upper16 or a lower16 relocation.
617 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
618
619 if (isUpper)
620 fmt << ":upper16:(";
621 else
622 fmt << ":lower16:(";
623 printRelocationTargetName(Obj, RE, fmt);
624
625 DataRefImpl RelNext = Rel;
626 Obj->moveRelocationNext(RelNext);
627 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
628
629 // ARM half relocs must be followed by a relocation of type
630 // ARM_RELOC_PAIR.
631 unsigned RType = Obj->getAnyRelocationType(RENext);
632 if (RType != MachO::ARM_RELOC_PAIR)
633 report_fatal_error("Expected ARM_RELOC_PAIR after "
634 "ARM_RELOC_HALF");
635
636 // NOTE: The half of the target virtual address is stashed in the
637 // address field of the secondary relocation, but we can't reverse
638 // engineer the constant offset from it without decoding the movw/movt
639 // instruction to find the other half in its immediate field.
640
641 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
642 // symbol/section pointer of the follow-on relocation.
643 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
644 fmt << "-";
645 printRelocationTargetName(Obj, RENext, fmt);
646 }
647
648 fmt << ")";
649 break;
650 }
651 default: { printRelocationTargetName(Obj, RE, fmt); }
652 }
653 }
654 } else
655 printRelocationTargetName(Obj, RE, fmt);
656
657 fmt.flush();
658 Result.append(fmtbuf.begin(), fmtbuf.end());
659 return object_error::success;
660}
661
662static std::error_code getRelocationValueString(const RelocationRef &Rel,
663 SmallVectorImpl<char> &Result) {
664 const ObjectFile *Obj = Rel.getObjectFile();
665 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
666 return getRelocationValueString(ELF, Rel, Result);
667 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
668 return getRelocationValueString(COFF, Rel, Result);
669 auto *MachO = cast<MachOObjectFile>(Obj);
670 return getRelocationValueString(MachO, Rel, Result);
671}
672
Michael J. Spencer51862b32011-10-13 22:17:18 +0000673static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000674 const Target *TheTarget = getTarget(Obj);
675 // getTarget() will have already issued a diagnostic if necessary, so
676 // just bail here if it failed.
677 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000678 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000679
Jack Carter551efd72012-08-28 19:24:49 +0000680 // Package up features to be passed to target/subtarget
681 std::string FeaturesStr;
682 if (MAttrs.size()) {
683 SubtargetFeatures Features;
684 for (unsigned i = 0; i != MAttrs.size(); ++i)
685 Features.AddFeature(MAttrs[i]);
686 FeaturesStr = Features.getString();
687 }
688
Ahmed Charles56440fd2014-03-06 05:51:42 +0000689 std::unique_ptr<const MCRegisterInfo> MRI(
690 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000691 if (!MRI) {
692 errs() << "error: no register info for target " << TripleName << "\n";
693 return;
694 }
695
696 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000697 std::unique_ptr<const MCAsmInfo> AsmInfo(
698 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000699 if (!AsmInfo) {
700 errs() << "error: no assembly info for target " << TripleName << "\n";
701 return;
702 }
703
Ahmed Charles56440fd2014-03-06 05:51:42 +0000704 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000705 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000706 if (!STI) {
707 errs() << "error: no subtarget info for target " << TripleName << "\n";
708 return;
709 }
710
Ahmed Charles56440fd2014-03-06 05:51:42 +0000711 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000712 if (!MII) {
713 errs() << "error: no instruction info for target " << TripleName << "\n";
714 return;
715 }
716
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000717 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
718 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
719
720 std::unique_ptr<MCDisassembler> DisAsm(
721 TheTarget->createMCDisassembler(*STI, Ctx));
722
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000723 if (!DisAsm) {
724 errs() << "error: no disassembler for target " << TripleName << "\n";
725 return;
726 }
727
Ahmed Charles56440fd2014-03-06 05:51:42 +0000728 std::unique_ptr<const MCInstrAnalysis> MIA(
729 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000730
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000731 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000732 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000733 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000734 if (!IP) {
735 errs() << "error: no instruction printer for target " << TripleName
736 << '\n';
737 return;
738 }
Colin LeMahieu35436a22015-05-29 14:48:25 +0000739 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000740
Greg Fitzgerald18432272014-03-20 22:55:15 +0000741 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
742 "\t\t\t%08" PRIx64 ": ";
743
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000744 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
745 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000746 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000747 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
748 for (const SectionRef &Section : Obj->sections()) {
749 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000750 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000751 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000752 }
753
Alexey Samsonov48803e52014-03-13 14:37:36 +0000754 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000755 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000756 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000757
Rafael Espindola80291272014-10-08 15:28:58 +0000758 uint64_t SectionAddr = Section.getAddress();
759 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000760 if (!SectSize)
761 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000762
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000763 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000764 std::vector<std::pair<uint64_t, StringRef>> Symbols;
765 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000766 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000767 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000768 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000769 break;
770 if (Address == UnknownAddressOrSize)
771 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000772 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000773 if (Address >= SectSize)
774 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000775
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000776 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000777 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000778 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000779 Symbols.push_back(std::make_pair(Address, Name));
780 }
781 }
782
783 // Sort the symbols by address, just in case they didn't come in that way.
784 array_pod_sort(Symbols.begin(), Symbols.end());
785
Michael J. Spencer51862b32011-10-13 22:17:18 +0000786 // Make a list of all the relocations for this section.
787 std::vector<RelocationRef> Rels;
788 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000789 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
790 for (const RelocationRef &Reloc : RelocSec.relocations()) {
791 Rels.push_back(Reloc);
792 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000793 }
794 }
795
796 // Sort relocations by address.
797 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
798
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000799 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000800 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000801 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000802 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000803 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000804 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000805 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000806 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000807 outs() << "Disassembly of section ";
808 if (!SegmentName.empty())
809 outs() << SegmentName << ",";
810 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000811
812 // If the section has no symbols just insert a dummy one and disassemble
813 // the whole section.
814 if (Symbols.empty())
815 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000816
Alp Tokere69170a2014-06-26 22:52:05 +0000817
818 SmallString<40> Comments;
819 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000820
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000821 StringRef BytesStr;
822 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000823 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000824 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
825 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000826
Michael J. Spencer2670c252011-01-20 06:39:06 +0000827 uint64_t Size;
828 uint64_t Index;
829
Michael J. Spencer51862b32011-10-13 22:17:18 +0000830 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
831 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000832 // Disassemble symbol by symbol.
833 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000834
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000835 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000836 // The end is either the section end or the beginning of the next symbol.
837 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
838 // If this symbol has the same address as the next symbol, then skip it.
839 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000840 continue;
841
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000842 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000843
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000844#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000845 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000846#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000847 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000848#endif
849
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000850 for (Index = Start; Index < End; Index += Size) {
851 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000852
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000853 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
854 SectionAddr + Index, DebugOut,
855 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000856 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000857 Bytes.slice(Index, Size),
858 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000859 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000860 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000861 outs() << "\n";
862 } else {
863 errs() << ToolName << ": warning: invalid instruction encoding\n";
864 if (Size == 0)
865 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000866 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000867
868 // Print relocation for instruction.
869 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000870 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000871 uint64_t addr;
872 SmallString<16> name;
873 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000874
875 // If this relocation is hidden, skip it.
876 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
877 if (hidden) goto skip_print_rel;
878
Rafael Espindola1e483872013-04-25 12:28:45 +0000879 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000880 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000881 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000882 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
Rafael Espindola37070a52015-06-03 04:48:06 +0000883 if (error(getRelocationValueString(*rel_cur, val)))
884 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000885 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000886 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000887
888 skip_print_rel:
889 ++rel_cur;
890 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000891 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000892 }
893 }
894}
895
Kevin Enderby98da6132015-01-20 21:47:46 +0000896void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000897 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
898 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000899 // Regular objdump doesn't print relocations in non-relocatable object
900 // files.
901 if (!Obj->isRelocatableObject())
902 return;
903
Alexey Samsonov48803e52014-03-13 14:37:36 +0000904 for (const SectionRef &Section : Obj->sections()) {
905 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000906 continue;
907 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000908 if (error(Section.getName(secname)))
909 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000910 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000911 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000912 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000913 uint64_t address;
914 SmallString<32> relocname;
915 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000916 if (error(Reloc.getHidden(hidden)))
917 continue;
918 if (hidden)
919 continue;
920 if (error(Reloc.getTypeName(relocname)))
921 continue;
922 if (error(Reloc.getOffset(address)))
923 continue;
Rafael Espindola37070a52015-06-03 04:48:06 +0000924 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000925 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000926 outs() << format(Fmt.data(), address) << " " << relocname << " "
927 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000928 }
929 outs() << "\n";
930 }
931}
932
Kevin Enderby98da6132015-01-20 21:47:46 +0000933void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000934 outs() << "Sections:\n"
935 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000936 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000937 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000938 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000939 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000940 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000941 uint64_t Address = Section.getAddress();
942 uint64_t Size = Section.getSize();
943 bool Text = Section.isText();
944 bool Data = Section.isData();
945 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000946 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000947 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000948 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
949 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000950 ++i;
951 }
952}
953
Kevin Enderby98da6132015-01-20 21:47:46 +0000954void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000955 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000956 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000957 StringRef Name;
958 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000959 if (error(Section.getName(Name)))
960 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000961 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +0000962 uint64_t Size = Section.getSize();
963 if (!Size)
964 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000965
966 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +0000967 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +0000968 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000969 ", %04" PRIx64 ")>\n",
970 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000971 continue;
972 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000973
David Majnemer8f6b04c2014-07-14 16:20:14 +0000974 if (error(Section.getContents(Contents)))
975 continue;
976
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000977 // Dump out the content as hex and printable ascii characters.
978 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000979 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000980 // Dump line of hex.
981 for (std::size_t i = 0; i < 16; ++i) {
982 if (i != 0 && i % 4 == 0)
983 outs() << ' ';
984 if (addr + i < end)
985 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
986 << hexdigit(Contents[addr + i] & 0xF, true);
987 else
988 outs() << " ";
989 }
990 // Print ascii.
991 outs() << " ";
992 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000993 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000994 outs() << Contents[addr + i];
995 else
996 outs() << ".";
997 }
998 outs() << "\n";
999 }
1000 }
1001}
1002
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001003static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001004 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1005 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001006 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001007 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001008 return;
1009
David Majnemer44f51e52014-09-10 12:51:52 +00001010 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001011 return;
1012
1013 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001014 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001015 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001016 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1017 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1018 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1019 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001020 << Name << "\n";
1021
David Majnemer44f51e52014-09-10 12:51:52 +00001022 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001023 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001024 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001025 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001026 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001027
David Majnemer4d571592014-09-15 19:42:42 +00001028 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1029
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001030 outs() << "AUX "
1031 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1032 , unsigned(asd->Length)
1033 , unsigned(asd->NumberOfRelocations)
1034 , unsigned(asd->NumberOfLinenumbers)
1035 , unsigned(asd->CheckSum))
1036 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001037 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001038 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001039 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001040 const char *FileName;
1041 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001042 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001043
David Majnemer44f51e52014-09-10 12:51:52 +00001044 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1045 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001046 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001047
David Majnemer44f51e52014-09-10 12:51:52 +00001048 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001049 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001050 } else {
1051 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001052 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001053 }
1054 }
1055}
1056
Kevin Enderby98da6132015-01-20 21:47:46 +00001057void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001058 outs() << "SYMBOL TABLE:\n";
1059
Rui Ueyama4e39f712014-03-18 18:58:51 +00001060 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001061 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001062 return;
1063 }
1064 for (const SymbolRef &Symbol : o->symbols()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001065 uint64_t Address;
1066 SymbolRef::Type Type;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001067 uint32_t Flags = Symbol.getFlags();
1068 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001069 if (error(Symbol.getAddress(Address)))
1070 continue;
1071 if (error(Symbol.getType(Type)))
1072 continue;
Rafael Espindola5eb02e42015-06-01 00:27:26 +00001073 uint64_t Size = Symbol.getSize();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001074 if (error(Symbol.getSection(Section)))
1075 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001076 StringRef Name;
1077 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1078 Section->getName(Name);
1079 } else if (error(Symbol.getName(Name))) {
1080 continue;
1081 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001082
Rui Ueyama4e39f712014-03-18 18:58:51 +00001083 bool Global = Flags & SymbolRef::SF_Global;
1084 bool Weak = Flags & SymbolRef::SF_Weak;
1085 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001086 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001087 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001088
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001089 if (Common) {
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001090 uint32_t Alignment = Symbol.getAlignment();
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001091 Address = Size;
1092 Size = Alignment;
1093 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001094 if (Address == UnknownAddressOrSize)
1095 Address = 0;
1096 if (Size == UnknownAddressOrSize)
1097 Size = 0;
1098 char GlobLoc = ' ';
1099 if (Type != SymbolRef::ST_Unknown)
1100 GlobLoc = Global ? 'g' : 'l';
1101 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1102 ? 'd' : ' ';
1103 char FileFunc = ' ';
1104 if (Type == SymbolRef::ST_File)
1105 FileFunc = 'f';
1106 else if (Type == SymbolRef::ST_Function)
1107 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001108
Rui Ueyama4e39f712014-03-18 18:58:51 +00001109 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1110 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001111
Rui Ueyama4e39f712014-03-18 18:58:51 +00001112 outs() << format(Fmt, Address) << " "
1113 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1114 << (Weak ? 'w' : ' ') // Weak?
1115 << ' ' // Constructor. Not supported yet.
1116 << ' ' // Warning. Not supported yet.
1117 << ' ' // Indirect reference to another symbol.
1118 << Debug // Debugging (d) or dynamic (D) symbol.
1119 << FileFunc // Name of function (F), file (f) or object (O).
1120 << ' ';
1121 if (Absolute) {
1122 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001123 } else if (Common) {
1124 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001125 } else if (Section == o->section_end()) {
1126 outs() << "*UND*";
1127 } else {
1128 if (const MachOObjectFile *MachO =
1129 dyn_cast<const MachOObjectFile>(o)) {
1130 DataRefImpl DR = Section->getRawDataRefImpl();
1131 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1132 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001133 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001134 StringRef SectionName;
1135 if (error(Section->getName(SectionName)))
1136 SectionName = "";
1137 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001138 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001139 outs() << '\t'
Davide Italianocd2514d2015-04-30 23:08:53 +00001140 << format("%08" PRIx64 " ", Size);
1141 if (Hidden) {
1142 outs() << ".hidden ";
1143 }
1144 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001145 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001146 }
1147}
1148
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001149static void PrintUnwindInfo(const ObjectFile *o) {
1150 outs() << "Unwind info:\n\n";
1151
1152 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1153 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001154 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1155 printMachOUnwindInfo(MachO);
1156 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001157 // TODO: Extract DWARF dump tool to objdump.
1158 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001159 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001160 return;
1161 }
1162}
1163
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001164void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001165 outs() << "Exports trie:\n";
1166 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1167 printMachOExportsTrie(MachO);
1168 else {
1169 errs() << "This operation is only currently supported "
1170 "for Mach-O executable files.\n";
1171 return;
1172 }
1173}
1174
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001175void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001176 outs() << "Rebase table:\n";
1177 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1178 printMachORebaseTable(MachO);
1179 else {
1180 errs() << "This operation is only currently supported "
1181 "for Mach-O executable files.\n";
1182 return;
1183 }
1184}
1185
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001186void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001187 outs() << "Bind table:\n";
1188 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1189 printMachOBindTable(MachO);
1190 else {
1191 errs() << "This operation is only currently supported "
1192 "for Mach-O executable files.\n";
1193 return;
1194 }
1195}
1196
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001197void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001198 outs() << "Lazy bind table:\n";
1199 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1200 printMachOLazyBindTable(MachO);
1201 else {
1202 errs() << "This operation is only currently supported "
1203 "for Mach-O executable files.\n";
1204 return;
1205 }
1206}
1207
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001208void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001209 outs() << "Weak bind table:\n";
1210 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1211 printMachOWeakBindTable(MachO);
1212 else {
1213 errs() << "This operation is only currently supported "
1214 "for Mach-O executable files.\n";
1215 return;
1216 }
1217}
Nick Kledzikac431442014-09-12 21:34:15 +00001218
Rui Ueyamac2bed422013-09-27 21:04:00 +00001219static void printPrivateFileHeader(const ObjectFile *o) {
1220 if (o->isELF()) {
1221 printELFFileHeader(o);
1222 } else if (o->isCOFF()) {
1223 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001224 } else if (o->isMachO()) {
1225 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001226 }
1227}
1228
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001229static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001230 outs() << '\n';
1231 outs() << o->getFileName()
1232 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1233
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001234 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001235 DisassembleObject(o, Relocations);
1236 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001237 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001238 if (SectionHeaders)
1239 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001240 if (SectionContents)
1241 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001242 if (SymbolTable)
1243 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001244 if (UnwindInfo)
1245 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001246 if (PrivateHeaders)
1247 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001248 if (ExportsTrie)
1249 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001250 if (Rebase)
1251 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001252 if (Bind)
1253 printBindTable(o);
1254 if (LazyBind)
1255 printLazyBindTable(o);
1256 if (WeakBind)
1257 printWeakBindTable(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001258}
1259
1260/// @brief Dump each object file in \a a;
1261static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001262 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1263 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001264 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1265 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001266 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001267 if (EC != object_error::invalid_file_type)
1268 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
Michael J. Spencer53723de2011-11-16 01:24:41 +00001269 << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001270 continue;
1271 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001272 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001273 DumpObject(o);
1274 else
1275 errs() << ToolName << ": '" << a->getFileName() << "': "
1276 << "Unrecognized file type.\n";
1277 }
1278}
1279
1280/// @brief Open file and figure out how to dump it.
1281static void DumpInput(StringRef file) {
1282 // If file isn't stdin, check that it exists.
1283 if (file != "-" && !sys::fs::exists(file)) {
1284 errs() << ToolName << ": '" << file << "': " << "No such file\n";
1285 return;
1286 }
1287
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001288 // If we are using the Mach-O specific object file parser, then let it parse
1289 // the file and process the command line options. So the -arch flags can
1290 // be used to select specific slices, etc.
1291 if (MachOOpt) {
1292 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001293 return;
1294 }
1295
1296 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001297 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001298 if (std::error_code EC = BinaryOrErr.getError()) {
Rafael Espindola63da2952014-01-15 19:37:43 +00001299 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001300 return;
1301 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001302 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001303
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001304 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001305 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001306 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001307 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001308 else
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001309 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001310}
1311
Michael J. Spencer2670c252011-01-20 06:39:06 +00001312int main(int argc, char **argv) {
1313 // Print a stack trace if we signal out.
1314 sys::PrintStackTraceOnErrorSignal();
1315 PrettyStackTraceProgram X(argc, argv);
1316 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1317
1318 // Initialize targets and assembly printers/parsers.
1319 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001320 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001321 llvm::InitializeAllAsmParsers();
1322 llvm::InitializeAllDisassemblers();
1323
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001324 // Register the target printer for --version.
1325 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1326
Michael J. Spencer2670c252011-01-20 06:39:06 +00001327 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1328 TripleName = Triple::normalize(TripleName);
1329
1330 ToolName = argv[0];
1331
1332 // Defaults to a.out if no filenames specified.
1333 if (InputFilenames.size() == 0)
1334 InputFilenames.push_back("a.out");
1335
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001336 if (!Disassemble
1337 && !Relocations
1338 && !SectionHeaders
1339 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001340 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001341 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001342 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001343 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001344 && !Rebase
1345 && !Bind
1346 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001347 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001348 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001349 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001350 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001351 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001352 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001353 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001354 && !(DylibsUsed && MachOOpt)
1355 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001356 && !(ObjcMetaData && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001357 && !(DumpSections.size() != 0 && MachOOpt)) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001358 cl::PrintHelpMessage();
1359 return 2;
1360 }
1361
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001362 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1363 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001364
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001365 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001366}