blob: 75099314037a5200411c3b84ac9ebe7816fdbc6a [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);
330 ErrorOr<StringRef> SymName =
331 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
332 if (!SymName)
333 return SymName.getError();
334 switch (EF.getHeader()->e_machine) {
335 case ELF::EM_X86_64:
336 switch (type) {
337 case ELF::R_X86_64_PC8:
338 case ELF::R_X86_64_PC16:
339 case ELF::R_X86_64_PC32: {
340 std::string fmtbuf;
341 raw_string_ostream fmt(fmtbuf);
342 fmt << *SymName << (addend < 0 ? "" : "+") << addend << "-P";
343 fmt.flush();
344 Result.append(fmtbuf.begin(), fmtbuf.end());
345 } break;
346 case ELF::R_X86_64_8:
347 case ELF::R_X86_64_16:
348 case ELF::R_X86_64_32:
349 case ELF::R_X86_64_32S:
350 case ELF::R_X86_64_64: {
351 std::string fmtbuf;
352 raw_string_ostream fmt(fmtbuf);
353 fmt << *SymName << (addend < 0 ? "" : "+") << addend;
354 fmt.flush();
355 Result.append(fmtbuf.begin(), fmtbuf.end());
356 } break;
357 default:
358 res = "Unknown";
359 }
360 break;
361 case ELF::EM_AARCH64: {
362 std::string fmtbuf;
363 raw_string_ostream fmt(fmtbuf);
364 fmt << *SymName;
365 if (addend != 0)
366 fmt << (addend < 0 ? "" : "+") << addend;
367 fmt.flush();
368 Result.append(fmtbuf.begin(), fmtbuf.end());
369 break;
370 }
371 case ELF::EM_386:
372 case ELF::EM_ARM:
373 case ELF::EM_HEXAGON:
374 case ELF::EM_MIPS:
375 res = *SymName;
376 break;
377 default:
378 res = "Unknown";
379 }
380 if (Result.empty())
381 Result.append(res.begin(), res.end());
382 return object_error::success;
383}
384
385static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
386 const RelocationRef &RelRef,
387 SmallVectorImpl<char> &Result) {
388 DataRefImpl Rel = RelRef.getRawDataRefImpl();
389 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
390 return getRelocationValueString(ELF32LE, Rel, Result);
391 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
392 return getRelocationValueString(ELF64LE, Rel, Result);
393 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
394 return getRelocationValueString(ELF32BE, Rel, Result);
395 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
396 return getRelocationValueString(ELF64BE, Rel, Result);
397}
398
399static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
400 const RelocationRef &Rel,
401 SmallVectorImpl<char> &Result) {
402 symbol_iterator SymI = Rel.getSymbol();
403 StringRef SymName;
404 if (std::error_code EC = SymI->getName(SymName))
405 return EC;
406 Result.append(SymName.begin(), SymName.end());
407 return object_error::success;
408}
409
410static void printRelocationTargetName(const MachOObjectFile *O,
411 const MachO::any_relocation_info &RE,
412 raw_string_ostream &fmt) {
413 bool IsScattered = O->isRelocationScattered(RE);
414
415 // Target of a scattered relocation is an address. In the interest of
416 // generating pretty output, scan through the symbol table looking for a
417 // symbol that aligns with that address. If we find one, print it.
418 // Otherwise, we just print the hex address of the target.
419 if (IsScattered) {
420 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
421
422 for (const SymbolRef &Symbol : O->symbols()) {
423 std::error_code ec;
424 uint64_t Addr;
425 StringRef Name;
426
427 if ((ec = Symbol.getAddress(Addr)))
428 report_fatal_error(ec.message());
429 if (Addr != Val)
430 continue;
431 if ((ec = Symbol.getName(Name)))
432 report_fatal_error(ec.message());
433 fmt << Name;
434 return;
435 }
436
437 // If we couldn't find a symbol that this relocation refers to, try
438 // to find a section beginning instead.
439 for (const SectionRef &Section : O->sections()) {
440 std::error_code ec;
441
442 StringRef Name;
443 uint64_t Addr = Section.getAddress();
444 if (Addr != Val)
445 continue;
446 if ((ec = Section.getName(Name)))
447 report_fatal_error(ec.message());
448 fmt << Name;
449 return;
450 }
451
452 fmt << format("0x%x", Val);
453 return;
454 }
455
456 StringRef S;
457 bool isExtern = O->getPlainRelocationExternal(RE);
458 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
459
460 if (isExtern) {
461 symbol_iterator SI = O->symbol_begin();
462 advance(SI, Val);
463 SI->getName(S);
464 } else {
465 section_iterator SI = O->section_begin();
466 // Adjust for the fact that sections are 1-indexed.
467 advance(SI, Val - 1);
468 SI->getName(S);
469 }
470
471 fmt << S;
472}
473
474static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
475 const RelocationRef &RelRef,
476 SmallVectorImpl<char> &Result) {
477 DataRefImpl Rel = RelRef.getRawDataRefImpl();
478 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
479
480 unsigned Arch = Obj->getArch();
481
482 std::string fmtbuf;
483 raw_string_ostream fmt(fmtbuf);
484 unsigned Type = Obj->getAnyRelocationType(RE);
485 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
486
487 // Determine any addends that should be displayed with the relocation.
488 // These require decoding the relocation type, which is triple-specific.
489
490 // X86_64 has entirely custom relocation types.
491 if (Arch == Triple::x86_64) {
492 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
493
494 switch (Type) {
495 case MachO::X86_64_RELOC_GOT_LOAD:
496 case MachO::X86_64_RELOC_GOT: {
497 printRelocationTargetName(Obj, RE, fmt);
498 fmt << "@GOT";
499 if (isPCRel)
500 fmt << "PCREL";
501 break;
502 }
503 case MachO::X86_64_RELOC_SUBTRACTOR: {
504 DataRefImpl RelNext = Rel;
505 Obj->moveRelocationNext(RelNext);
506 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
507
508 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
509 // X86_64_RELOC_UNSIGNED.
510 // NOTE: Scattered relocations don't exist on x86_64.
511 unsigned RType = Obj->getAnyRelocationType(RENext);
512 if (RType != MachO::X86_64_RELOC_UNSIGNED)
513 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
514 "X86_64_RELOC_SUBTRACTOR.");
515
516 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
517 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
518 printRelocationTargetName(Obj, RENext, fmt);
519 fmt << "-";
520 printRelocationTargetName(Obj, RE, fmt);
521 break;
522 }
523 case MachO::X86_64_RELOC_TLV:
524 printRelocationTargetName(Obj, RE, fmt);
525 fmt << "@TLV";
526 if (isPCRel)
527 fmt << "P";
528 break;
529 case MachO::X86_64_RELOC_SIGNED_1:
530 printRelocationTargetName(Obj, RE, fmt);
531 fmt << "-1";
532 break;
533 case MachO::X86_64_RELOC_SIGNED_2:
534 printRelocationTargetName(Obj, RE, fmt);
535 fmt << "-2";
536 break;
537 case MachO::X86_64_RELOC_SIGNED_4:
538 printRelocationTargetName(Obj, RE, fmt);
539 fmt << "-4";
540 break;
541 default:
542 printRelocationTargetName(Obj, RE, fmt);
543 break;
544 }
545 // X86 and ARM share some relocation types in common.
546 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
547 Arch == Triple::ppc) {
548 // Generic relocation types...
549 switch (Type) {
550 case MachO::GENERIC_RELOC_PAIR: // prints no info
551 return object_error::success;
552 case MachO::GENERIC_RELOC_SECTDIFF: {
553 DataRefImpl RelNext = Rel;
554 Obj->moveRelocationNext(RelNext);
555 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
556
557 // X86 sect diff's must be followed by a relocation of type
558 // GENERIC_RELOC_PAIR.
559 unsigned RType = Obj->getAnyRelocationType(RENext);
560
561 if (RType != MachO::GENERIC_RELOC_PAIR)
562 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
563 "GENERIC_RELOC_SECTDIFF.");
564
565 printRelocationTargetName(Obj, RE, fmt);
566 fmt << "-";
567 printRelocationTargetName(Obj, RENext, fmt);
568 break;
569 }
570 }
571
572 if (Arch == Triple::x86 || Arch == Triple::ppc) {
573 switch (Type) {
574 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
575 DataRefImpl RelNext = Rel;
576 Obj->moveRelocationNext(RelNext);
577 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
578
579 // X86 sect diff's must be followed by a relocation of type
580 // GENERIC_RELOC_PAIR.
581 unsigned RType = Obj->getAnyRelocationType(RENext);
582 if (RType != MachO::GENERIC_RELOC_PAIR)
583 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
584 "GENERIC_RELOC_LOCAL_SECTDIFF.");
585
586 printRelocationTargetName(Obj, RE, fmt);
587 fmt << "-";
588 printRelocationTargetName(Obj, RENext, fmt);
589 break;
590 }
591 case MachO::GENERIC_RELOC_TLV: {
592 printRelocationTargetName(Obj, RE, fmt);
593 fmt << "@TLV";
594 if (IsPCRel)
595 fmt << "P";
596 break;
597 }
598 default:
599 printRelocationTargetName(Obj, RE, fmt);
600 }
601 } else { // ARM-specific relocations
602 switch (Type) {
603 case MachO::ARM_RELOC_HALF:
604 case MachO::ARM_RELOC_HALF_SECTDIFF: {
605 // Half relocations steal a bit from the length field to encode
606 // whether this is an upper16 or a lower16 relocation.
607 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
608
609 if (isUpper)
610 fmt << ":upper16:(";
611 else
612 fmt << ":lower16:(";
613 printRelocationTargetName(Obj, RE, fmt);
614
615 DataRefImpl RelNext = Rel;
616 Obj->moveRelocationNext(RelNext);
617 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
618
619 // ARM half relocs must be followed by a relocation of type
620 // ARM_RELOC_PAIR.
621 unsigned RType = Obj->getAnyRelocationType(RENext);
622 if (RType != MachO::ARM_RELOC_PAIR)
623 report_fatal_error("Expected ARM_RELOC_PAIR after "
624 "ARM_RELOC_HALF");
625
626 // NOTE: The half of the target virtual address is stashed in the
627 // address field of the secondary relocation, but we can't reverse
628 // engineer the constant offset from it without decoding the movw/movt
629 // instruction to find the other half in its immediate field.
630
631 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
632 // symbol/section pointer of the follow-on relocation.
633 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
634 fmt << "-";
635 printRelocationTargetName(Obj, RENext, fmt);
636 }
637
638 fmt << ")";
639 break;
640 }
641 default: { printRelocationTargetName(Obj, RE, fmt); }
642 }
643 }
644 } else
645 printRelocationTargetName(Obj, RE, fmt);
646
647 fmt.flush();
648 Result.append(fmtbuf.begin(), fmtbuf.end());
649 return object_error::success;
650}
651
652static std::error_code getRelocationValueString(const RelocationRef &Rel,
653 SmallVectorImpl<char> &Result) {
654 const ObjectFile *Obj = Rel.getObjectFile();
655 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
656 return getRelocationValueString(ELF, Rel, Result);
657 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
658 return getRelocationValueString(COFF, Rel, Result);
659 auto *MachO = cast<MachOObjectFile>(Obj);
660 return getRelocationValueString(MachO, Rel, Result);
661}
662
Michael J. Spencer51862b32011-10-13 22:17:18 +0000663static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000664 const Target *TheTarget = getTarget(Obj);
665 // getTarget() will have already issued a diagnostic if necessary, so
666 // just bail here if it failed.
667 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000668 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000669
Jack Carter551efd72012-08-28 19:24:49 +0000670 // Package up features to be passed to target/subtarget
671 std::string FeaturesStr;
672 if (MAttrs.size()) {
673 SubtargetFeatures Features;
674 for (unsigned i = 0; i != MAttrs.size(); ++i)
675 Features.AddFeature(MAttrs[i]);
676 FeaturesStr = Features.getString();
677 }
678
Ahmed Charles56440fd2014-03-06 05:51:42 +0000679 std::unique_ptr<const MCRegisterInfo> MRI(
680 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000681 if (!MRI) {
682 errs() << "error: no register info for target " << TripleName << "\n";
683 return;
684 }
685
686 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000687 std::unique_ptr<const MCAsmInfo> AsmInfo(
688 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000689 if (!AsmInfo) {
690 errs() << "error: no assembly info for target " << TripleName << "\n";
691 return;
692 }
693
Ahmed Charles56440fd2014-03-06 05:51:42 +0000694 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000695 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000696 if (!STI) {
697 errs() << "error: no subtarget info for target " << TripleName << "\n";
698 return;
699 }
700
Ahmed Charles56440fd2014-03-06 05:51:42 +0000701 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000702 if (!MII) {
703 errs() << "error: no instruction info for target " << TripleName << "\n";
704 return;
705 }
706
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000707 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
708 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
709
710 std::unique_ptr<MCDisassembler> DisAsm(
711 TheTarget->createMCDisassembler(*STI, Ctx));
712
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000713 if (!DisAsm) {
714 errs() << "error: no disassembler for target " << TripleName << "\n";
715 return;
716 }
717
Ahmed Charles56440fd2014-03-06 05:51:42 +0000718 std::unique_ptr<const MCInstrAnalysis> MIA(
719 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000720
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000721 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000722 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000723 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000724 if (!IP) {
725 errs() << "error: no instruction printer for target " << TripleName
726 << '\n';
727 return;
728 }
Colin LeMahieu35436a22015-05-29 14:48:25 +0000729 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000730
Greg Fitzgerald18432272014-03-20 22:55:15 +0000731 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
732 "\t\t\t%08" PRIx64 ": ";
733
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000734 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
735 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000736 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000737 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
738 for (const SectionRef &Section : Obj->sections()) {
739 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000740 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000741 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000742 }
743
Alexey Samsonov48803e52014-03-13 14:37:36 +0000744 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000745 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000746 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000747
Rafael Espindola80291272014-10-08 15:28:58 +0000748 uint64_t SectionAddr = Section.getAddress();
749 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000750 if (!SectSize)
751 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000752
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000753 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000754 std::vector<std::pair<uint64_t, StringRef>> Symbols;
755 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000756 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000757 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000758 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000759 break;
760 if (Address == UnknownAddressOrSize)
761 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000762 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000763 if (Address >= SectSize)
764 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000765
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000766 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000767 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000768 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000769 Symbols.push_back(std::make_pair(Address, Name));
770 }
771 }
772
773 // Sort the symbols by address, just in case they didn't come in that way.
774 array_pod_sort(Symbols.begin(), Symbols.end());
775
Michael J. Spencer51862b32011-10-13 22:17:18 +0000776 // Make a list of all the relocations for this section.
777 std::vector<RelocationRef> Rels;
778 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000779 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
780 for (const RelocationRef &Reloc : RelocSec.relocations()) {
781 Rels.push_back(Reloc);
782 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000783 }
784 }
785
786 // Sort relocations by address.
787 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
788
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000789 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000790 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000791 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000792 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000793 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000794 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000795 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000796 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000797 outs() << "Disassembly of section ";
798 if (!SegmentName.empty())
799 outs() << SegmentName << ",";
800 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000801
802 // If the section has no symbols just insert a dummy one and disassemble
803 // the whole section.
804 if (Symbols.empty())
805 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000806
Alp Tokere69170a2014-06-26 22:52:05 +0000807
808 SmallString<40> Comments;
809 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000810
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000811 StringRef BytesStr;
812 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000813 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000814 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
815 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000816
Michael J. Spencer2670c252011-01-20 06:39:06 +0000817 uint64_t Size;
818 uint64_t Index;
819
Michael J. Spencer51862b32011-10-13 22:17:18 +0000820 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
821 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000822 // Disassemble symbol by symbol.
823 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000824
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000825 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000826 // The end is either the section end or the beginning of the next symbol.
827 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
828 // If this symbol has the same address as the next symbol, then skip it.
829 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000830 continue;
831
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000832 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000833
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000834#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000835 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000836#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000837 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000838#endif
839
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000840 for (Index = Start; Index < End; Index += Size) {
841 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000842
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000843 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
844 SectionAddr + Index, DebugOut,
845 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000846 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000847 Bytes.slice(Index, Size),
848 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000849 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000850 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000851 outs() << "\n";
852 } else {
853 errs() << ToolName << ": warning: invalid instruction encoding\n";
854 if (Size == 0)
855 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000856 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000857
858 // Print relocation for instruction.
859 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000860 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000861 uint64_t addr;
862 SmallString<16> name;
863 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000864
865 // If this relocation is hidden, skip it.
866 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
867 if (hidden) goto skip_print_rel;
868
Rafael Espindola1e483872013-04-25 12:28:45 +0000869 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000870 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000871 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000872 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
Rafael Espindola37070a52015-06-03 04:48:06 +0000873 if (error(getRelocationValueString(*rel_cur, val)))
874 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000875 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000876 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000877
878 skip_print_rel:
879 ++rel_cur;
880 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000881 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000882 }
883 }
884}
885
Kevin Enderby98da6132015-01-20 21:47:46 +0000886void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000887 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
888 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000889 // Regular objdump doesn't print relocations in non-relocatable object
890 // files.
891 if (!Obj->isRelocatableObject())
892 return;
893
Alexey Samsonov48803e52014-03-13 14:37:36 +0000894 for (const SectionRef &Section : Obj->sections()) {
895 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000896 continue;
897 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000898 if (error(Section.getName(secname)))
899 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000900 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000901 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000902 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000903 uint64_t address;
904 SmallString<32> relocname;
905 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000906 if (error(Reloc.getHidden(hidden)))
907 continue;
908 if (hidden)
909 continue;
910 if (error(Reloc.getTypeName(relocname)))
911 continue;
912 if (error(Reloc.getOffset(address)))
913 continue;
Rafael Espindola37070a52015-06-03 04:48:06 +0000914 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000915 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000916 outs() << format(Fmt.data(), address) << " " << relocname << " "
917 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000918 }
919 outs() << "\n";
920 }
921}
922
Kevin Enderby98da6132015-01-20 21:47:46 +0000923void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000924 outs() << "Sections:\n"
925 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000926 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000927 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000928 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000929 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000930 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000931 uint64_t Address = Section.getAddress();
932 uint64_t Size = Section.getSize();
933 bool Text = Section.isText();
934 bool Data = Section.isData();
935 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000936 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000937 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000938 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
939 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000940 ++i;
941 }
942}
943
Kevin Enderby98da6132015-01-20 21:47:46 +0000944void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000945 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000946 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000947 StringRef Name;
948 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000949 if (error(Section.getName(Name)))
950 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000951 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +0000952 uint64_t Size = Section.getSize();
953 if (!Size)
954 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000955
956 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +0000957 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +0000958 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000959 ", %04" PRIx64 ")>\n",
960 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000961 continue;
962 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000963
David Majnemer8f6b04c2014-07-14 16:20:14 +0000964 if (error(Section.getContents(Contents)))
965 continue;
966
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000967 // Dump out the content as hex and printable ascii characters.
968 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000969 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000970 // Dump line of hex.
971 for (std::size_t i = 0; i < 16; ++i) {
972 if (i != 0 && i % 4 == 0)
973 outs() << ' ';
974 if (addr + i < end)
975 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
976 << hexdigit(Contents[addr + i] & 0xF, true);
977 else
978 outs() << " ";
979 }
980 // Print ascii.
981 outs() << " ";
982 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000983 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000984 outs() << Contents[addr + i];
985 else
986 outs() << ".";
987 }
988 outs() << "\n";
989 }
990 }
991}
992
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000993static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +0000994 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
995 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000996 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +0000997 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +0000998 return;
999
David Majnemer44f51e52014-09-10 12:51:52 +00001000 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001001 return;
1002
1003 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001004 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001005 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001006 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1007 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1008 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1009 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001010 << Name << "\n";
1011
David Majnemer44f51e52014-09-10 12:51:52 +00001012 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001013 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001014 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001015 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001016 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001017
David Majnemer4d571592014-09-15 19:42:42 +00001018 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1019
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001020 outs() << "AUX "
1021 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1022 , unsigned(asd->Length)
1023 , unsigned(asd->NumberOfRelocations)
1024 , unsigned(asd->NumberOfLinenumbers)
1025 , unsigned(asd->CheckSum))
1026 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001027 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001028 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001029 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001030 const char *FileName;
1031 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001032 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001033
David Majnemer44f51e52014-09-10 12:51:52 +00001034 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1035 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001036 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001037
David Majnemer44f51e52014-09-10 12:51:52 +00001038 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001039 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001040 } else {
1041 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001042 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001043 }
1044 }
1045}
1046
Kevin Enderby98da6132015-01-20 21:47:46 +00001047void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001048 outs() << "SYMBOL TABLE:\n";
1049
Rui Ueyama4e39f712014-03-18 18:58:51 +00001050 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001051 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001052 return;
1053 }
1054 for (const SymbolRef &Symbol : o->symbols()) {
1055 StringRef Name;
1056 uint64_t Address;
1057 SymbolRef::Type Type;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001058 uint32_t Flags = Symbol.getFlags();
1059 section_iterator Section = o->section_end();
1060 if (error(Symbol.getName(Name)))
1061 continue;
1062 if (error(Symbol.getAddress(Address)))
1063 continue;
1064 if (error(Symbol.getType(Type)))
1065 continue;
Rafael Espindola5eb02e42015-06-01 00:27:26 +00001066 uint64_t Size = Symbol.getSize();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001067 if (error(Symbol.getSection(Section)))
1068 continue;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001069
Rui Ueyama4e39f712014-03-18 18:58:51 +00001070 bool Global = Flags & SymbolRef::SF_Global;
1071 bool Weak = Flags & SymbolRef::SF_Weak;
1072 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001073 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001074 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001075
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001076 if (Common) {
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001077 uint32_t Alignment = Symbol.getAlignment();
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001078 Address = Size;
1079 Size = Alignment;
1080 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001081 if (Address == UnknownAddressOrSize)
1082 Address = 0;
1083 if (Size == UnknownAddressOrSize)
1084 Size = 0;
1085 char GlobLoc = ' ';
1086 if (Type != SymbolRef::ST_Unknown)
1087 GlobLoc = Global ? 'g' : 'l';
1088 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1089 ? 'd' : ' ';
1090 char FileFunc = ' ';
1091 if (Type == SymbolRef::ST_File)
1092 FileFunc = 'f';
1093 else if (Type == SymbolRef::ST_Function)
1094 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001095
Rui Ueyama4e39f712014-03-18 18:58:51 +00001096 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1097 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001098
Rui Ueyama4e39f712014-03-18 18:58:51 +00001099 outs() << format(Fmt, Address) << " "
1100 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1101 << (Weak ? 'w' : ' ') // Weak?
1102 << ' ' // Constructor. Not supported yet.
1103 << ' ' // Warning. Not supported yet.
1104 << ' ' // Indirect reference to another symbol.
1105 << Debug // Debugging (d) or dynamic (D) symbol.
1106 << FileFunc // Name of function (F), file (f) or object (O).
1107 << ' ';
1108 if (Absolute) {
1109 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001110 } else if (Common) {
1111 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001112 } else if (Section == o->section_end()) {
1113 outs() << "*UND*";
1114 } else {
1115 if (const MachOObjectFile *MachO =
1116 dyn_cast<const MachOObjectFile>(o)) {
1117 DataRefImpl DR = Section->getRawDataRefImpl();
1118 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1119 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001120 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001121 StringRef SectionName;
1122 if (error(Section->getName(SectionName)))
1123 SectionName = "";
1124 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001125 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001126 outs() << '\t'
Davide Italianocd2514d2015-04-30 23:08:53 +00001127 << format("%08" PRIx64 " ", Size);
1128 if (Hidden) {
1129 outs() << ".hidden ";
1130 }
1131 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001132 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001133 }
1134}
1135
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001136static void PrintUnwindInfo(const ObjectFile *o) {
1137 outs() << "Unwind info:\n\n";
1138
1139 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1140 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001141 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1142 printMachOUnwindInfo(MachO);
1143 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001144 // TODO: Extract DWARF dump tool to objdump.
1145 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001146 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001147 return;
1148 }
1149}
1150
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001151void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001152 outs() << "Exports trie:\n";
1153 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1154 printMachOExportsTrie(MachO);
1155 else {
1156 errs() << "This operation is only currently supported "
1157 "for Mach-O executable files.\n";
1158 return;
1159 }
1160}
1161
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001162void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001163 outs() << "Rebase table:\n";
1164 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1165 printMachORebaseTable(MachO);
1166 else {
1167 errs() << "This operation is only currently supported "
1168 "for Mach-O executable files.\n";
1169 return;
1170 }
1171}
1172
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001173void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001174 outs() << "Bind table:\n";
1175 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1176 printMachOBindTable(MachO);
1177 else {
1178 errs() << "This operation is only currently supported "
1179 "for Mach-O executable files.\n";
1180 return;
1181 }
1182}
1183
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001184void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001185 outs() << "Lazy bind table:\n";
1186 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1187 printMachOLazyBindTable(MachO);
1188 else {
1189 errs() << "This operation is only currently supported "
1190 "for Mach-O executable files.\n";
1191 return;
1192 }
1193}
1194
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001195void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001196 outs() << "Weak bind table:\n";
1197 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1198 printMachOWeakBindTable(MachO);
1199 else {
1200 errs() << "This operation is only currently supported "
1201 "for Mach-O executable files.\n";
1202 return;
1203 }
1204}
Nick Kledzikac431442014-09-12 21:34:15 +00001205
Rui Ueyamac2bed422013-09-27 21:04:00 +00001206static void printPrivateFileHeader(const ObjectFile *o) {
1207 if (o->isELF()) {
1208 printELFFileHeader(o);
1209 } else if (o->isCOFF()) {
1210 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001211 } else if (o->isMachO()) {
1212 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001213 }
1214}
1215
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001216static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001217 outs() << '\n';
1218 outs() << o->getFileName()
1219 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1220
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001221 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001222 DisassembleObject(o, Relocations);
1223 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001224 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001225 if (SectionHeaders)
1226 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001227 if (SectionContents)
1228 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001229 if (SymbolTable)
1230 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001231 if (UnwindInfo)
1232 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001233 if (PrivateHeaders)
1234 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001235 if (ExportsTrie)
1236 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001237 if (Rebase)
1238 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001239 if (Bind)
1240 printBindTable(o);
1241 if (LazyBind)
1242 printLazyBindTable(o);
1243 if (WeakBind)
1244 printWeakBindTable(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001245}
1246
1247/// @brief Dump each object file in \a a;
1248static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001249 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1250 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001251 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1252 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001253 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001254 if (EC != object_error::invalid_file_type)
1255 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
Michael J. Spencer53723de2011-11-16 01:24:41 +00001256 << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001257 continue;
1258 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001259 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001260 DumpObject(o);
1261 else
1262 errs() << ToolName << ": '" << a->getFileName() << "': "
1263 << "Unrecognized file type.\n";
1264 }
1265}
1266
1267/// @brief Open file and figure out how to dump it.
1268static void DumpInput(StringRef file) {
1269 // If file isn't stdin, check that it exists.
1270 if (file != "-" && !sys::fs::exists(file)) {
1271 errs() << ToolName << ": '" << file << "': " << "No such file\n";
1272 return;
1273 }
1274
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001275 // If we are using the Mach-O specific object file parser, then let it parse
1276 // the file and process the command line options. So the -arch flags can
1277 // be used to select specific slices, etc.
1278 if (MachOOpt) {
1279 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001280 return;
1281 }
1282
1283 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001284 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001285 if (std::error_code EC = BinaryOrErr.getError()) {
Rafael Espindola63da2952014-01-15 19:37:43 +00001286 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001287 return;
1288 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001289 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001290
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001291 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001292 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001293 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001294 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001295 else
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001296 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001297}
1298
Michael J. Spencer2670c252011-01-20 06:39:06 +00001299int main(int argc, char **argv) {
1300 // Print a stack trace if we signal out.
1301 sys::PrintStackTraceOnErrorSignal();
1302 PrettyStackTraceProgram X(argc, argv);
1303 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1304
1305 // Initialize targets and assembly printers/parsers.
1306 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001307 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001308 llvm::InitializeAllAsmParsers();
1309 llvm::InitializeAllDisassemblers();
1310
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001311 // Register the target printer for --version.
1312 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1313
Michael J. Spencer2670c252011-01-20 06:39:06 +00001314 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1315 TripleName = Triple::normalize(TripleName);
1316
1317 ToolName = argv[0];
1318
1319 // Defaults to a.out if no filenames specified.
1320 if (InputFilenames.size() == 0)
1321 InputFilenames.push_back("a.out");
1322
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001323 if (!Disassemble
1324 && !Relocations
1325 && !SectionHeaders
1326 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001327 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001328 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001329 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001330 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001331 && !Rebase
1332 && !Bind
1333 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001334 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001335 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001336 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001337 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001338 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001339 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001340 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001341 && !(DylibsUsed && MachOOpt)
1342 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001343 && !(ObjcMetaData && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001344 && !(DumpSections.size() != 0 && MachOOpt)) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001345 cl::PrintHelpMessage();
1346 return 2;
1347 }
1348
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001349 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1350 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001351
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001352 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001353}