blob: 58f6db0465d42175c614d1d1e0c0cbb68200515e [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"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000042#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000043#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000044#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000045#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/Host.h"
47#include "llvm/Support/ManagedStatic.h"
48#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/PrettyStackTrace.h"
50#include "llvm/Support/Signals.h"
51#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000052#include "llvm/Support/TargetRegistry.h"
53#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000056#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000058#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000059
Michael J. Spencer2670c252011-01-20 06:39:06 +000060using namespace llvm;
61using namespace object;
62
Benjamin Kramer43a772e2011-09-19 17:56:04 +000063static cl::list<std::string>
64InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000065
Kevin Enderbye2297dd2015-01-07 21:02:18 +000066cl::opt<bool>
67llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000068 cl::desc("Display assembler mnemonics for the machine instructions"));
69static cl::alias
70Disassembled("d", cl::desc("Alias for --disassemble"),
71 cl::aliasopt(Disassemble));
Michael J. Spencer2670c252011-01-20 06:39:06 +000072
Kevin Enderby98da6132015-01-20 21:47:46 +000073cl::opt<bool>
74llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000075
Kevin Enderby98da6132015-01-20 21:47:46 +000076cl::opt<bool>
77llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000078
Kevin Enderby98da6132015-01-20 21:47:46 +000079cl::opt<bool>
80llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000081
Kevin Enderbye2297dd2015-01-07 21:02:18 +000082cl::opt<bool>
83llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000084
Kevin Enderbye2297dd2015-01-07 21:02:18 +000085cl::opt<bool>
86llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000087
Kevin Enderbye2297dd2015-01-07 21:02:18 +000088cl::opt<bool>
89llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000090
Kevin Enderbye2297dd2015-01-07 21:02:18 +000091cl::opt<bool>
92llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000093
Kevin Enderbye2297dd2015-01-07 21:02:18 +000094cl::opt<bool>
95llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000096
97static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000098MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +000099static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000100MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000101
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000102cl::opt<std::string>
103llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
104 "see -version for available targets"));
105
106cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000107llvm::MCPU("mcpu",
108 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
109 cl::value_desc("cpu-name"),
110 cl::init(""));
111
112cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000113llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000114 "see -version for available targets"));
115
Kevin Enderby98da6132015-01-20 21:47:46 +0000116cl::opt<bool>
117llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
118 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000119static cl::alias
120SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
121 cl::aliasopt(SectionHeaders));
122static cl::alias
123SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
124 cl::aliasopt(SectionHeaders));
125
Kevin Enderbyc9595622014-08-06 23:24:41 +0000126cl::list<std::string>
127llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000128 cl::CommaSeparated,
129 cl::desc("Target specific attributes"),
130 cl::value_desc("a1,+a2,-a3,..."));
131
Kevin Enderbybf246f52014-09-24 23:08:22 +0000132cl::opt<bool>
133llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
134 "instructions, do not print "
135 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000136
Kevin Enderby98da6132015-01-20 21:47:46 +0000137cl::opt<bool>
138llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000139
140static cl::alias
141UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
142 cl::aliasopt(UnwindInfo));
143
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000144cl::opt<bool>
145llvm::PrivateHeaders("private-headers",
146 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000147
148static cl::alias
149PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
150 cl::aliasopt(PrivateHeaders));
151
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000152static StringRef ToolName;
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000153static int ReturnValue = EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000154
Rafael Espindola4453e42942014-06-13 03:07:50 +0000155bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000156 if (!EC)
157 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000158
Mark Seaborneb03ac52014-01-25 00:32:01 +0000159 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000160 outs().flush();
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000161 ReturnValue = EXIT_FAILURE;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000163}
164
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000165static void report_error(StringRef File, std::error_code EC) {
166 assert(EC);
167 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
168 ReturnValue = EXIT_FAILURE;
169}
170
Craig Toppere6cb63e2014-04-25 04:24:47 +0000171static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000172 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000173 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000174 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000175 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000176 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000177 // TheTriple defaults to ELF, and COFF doesn't have an environment:
178 // the best we can do here is indicate that it is mach-o.
179 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000180 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000181
182 if (Obj->isCOFF()) {
183 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
184 if (COFFObj->getArch() == Triple::thumb)
185 TheTriple.setTriple("thumbv7-windows");
186 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000187 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000188 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000189 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000190
191 // Get the target specific parser.
192 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000193 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
194 Error);
195 if (!TheTarget) {
196 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000197 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000198 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000199
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000200 // Update the triple name and return the found target.
201 TripleName = TheTriple.getTriple();
202 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000203}
204
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000205bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000206 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000207 if (error(a.getOffset(a_addr))) return false;
208 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000209 return a_addr < b_addr;
210}
211
Colin LeMahieufb76b002015-05-28 19:07:14 +0000212namespace {
213class PrettyPrinter {
214public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000215 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000216 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000217 ArrayRef<uint8_t> Bytes, uint64_t Address,
218 raw_ostream &OS, StringRef Annot,
219 MCSubtargetInfo const &STI) {
220 outs() << format("%8" PRIx64 ":", Address);
221 if (!NoShowRawInsn) {
222 outs() << "\t";
223 dumpBytes(Bytes, outs());
224 }
225 IP.printInst(MI, outs(), "", STI);
226 }
227};
228PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000229class HexagonPrettyPrinter : public PrettyPrinter {
230public:
231 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
232 raw_ostream &OS) {
233 uint32_t opcode =
234 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
235 OS << format("%8" PRIx64 ":", Address);
236 if (!NoShowRawInsn) {
237 OS << "\t";
238 dumpBytes(Bytes.slice(0, 4), OS);
239 OS << format("%08" PRIx32, opcode);
240 }
241 }
242 void printInst(MCInstPrinter &IP, const MCInst *MI,
243 ArrayRef<uint8_t> Bytes, uint64_t Address,
244 raw_ostream &OS, StringRef Annot,
245 MCSubtargetInfo const &STI) override {
246 std::string Buffer;
247 {
248 raw_string_ostream TempStream(Buffer);
249 IP.printInst(MI, TempStream, "", STI);
250 }
251 StringRef Contents(Buffer);
252 // Split off bundle attributes
253 auto PacketBundle = Contents.rsplit('\n');
254 // Split off first instruction from the rest
255 auto HeadTail = PacketBundle.first.split('\n');
256 auto Preamble = " { ";
257 auto Separator = "";
258 while(!HeadTail.first.empty()) {
259 OS << Separator;
260 Separator = "\n";
261 printLead(Bytes, Address, OS);
262 OS << Preamble;
263 Preamble = " ";
264 StringRef Inst;
265 auto Duplex = HeadTail.first.split('\v');
266 if(!Duplex.second.empty()){
267 OS << Duplex.first;
268 OS << "; ";
269 Inst = Duplex.second;
270 }
271 else
272 Inst = HeadTail.first;
273 OS << Inst;
274 Bytes = Bytes.slice(4);
275 Address += 4;
276 HeadTail = HeadTail.second.split('\n');
277 }
278 OS << " } " << PacketBundle.second;
279 }
280};
281HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000282PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000283 switch(Triple.getArch()) {
284 default:
285 return PrettyPrinterInst;
286 case Triple::hexagon:
287 return HexagonPrettyPrinterInst;
288 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000289}
290}
291
Rafael Espindola37070a52015-06-03 04:48:06 +0000292template <class ELFT>
293static const typename ELFObjectFile<ELFT>::Elf_Rel *
294getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
295 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
296 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
297}
298
299template <class ELFT>
300static const typename ELFObjectFile<ELFT>::Elf_Rela *
301getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
302 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
303 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
304}
305
306template <class ELFT>
307static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
308 DataRefImpl Rel,
309 SmallVectorImpl<char> &Result) {
310 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
311 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
312 const ELFFile<ELFT> &EF = *Obj->getELFFile();
313
314 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
315 uint8_t type;
316 StringRef res;
317 int64_t addend = 0;
318 uint16_t symbol_index = 0;
319 switch (sec->sh_type) {
320 default:
321 return object_error::parse_failed;
322 case ELF::SHT_REL: {
323 type = getRel(EF, Rel)->getType(EF.isMips64EL());
324 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
325 // TODO: Read implicit addend from section data.
326 break;
327 }
328 case ELF::SHT_RELA: {
329 type = getRela(EF, Rel)->getType(EF.isMips64EL());
330 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
331 addend = getRela(EF, Rel)->r_addend;
332 break;
333 }
334 }
335 const Elf_Sym *symb =
336 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000337 StringRef Target;
338 const Elf_Shdr *SymSec = EF.getSection(symb);
339 if (symb->getType() == ELF::STT_SECTION) {
340 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
341 if (std::error_code EC = SecName.getError())
342 return EC;
343 Target = *SecName;
344 } else {
345 ErrorOr<StringRef> SymName =
346 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
347 if (!SymName)
348 return SymName.getError();
349 Target = *SymName;
350 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000351 switch (EF.getHeader()->e_machine) {
352 case ELF::EM_X86_64:
353 switch (type) {
354 case ELF::R_X86_64_PC8:
355 case ELF::R_X86_64_PC16:
356 case ELF::R_X86_64_PC32: {
357 std::string fmtbuf;
358 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000359 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000360 fmt.flush();
361 Result.append(fmtbuf.begin(), fmtbuf.end());
362 } break;
363 case ELF::R_X86_64_8:
364 case ELF::R_X86_64_16:
365 case ELF::R_X86_64_32:
366 case ELF::R_X86_64_32S:
367 case ELF::R_X86_64_64: {
368 std::string fmtbuf;
369 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000370 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000371 fmt.flush();
372 Result.append(fmtbuf.begin(), fmtbuf.end());
373 } break;
374 default:
375 res = "Unknown";
376 }
377 break;
378 case ELF::EM_AARCH64: {
379 std::string fmtbuf;
380 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000381 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000382 if (addend != 0)
383 fmt << (addend < 0 ? "" : "+") << addend;
384 fmt.flush();
385 Result.append(fmtbuf.begin(), fmtbuf.end());
386 break;
387 }
388 case ELF::EM_386:
389 case ELF::EM_ARM:
390 case ELF::EM_HEXAGON:
391 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000392 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000393 break;
394 default:
395 res = "Unknown";
396 }
397 if (Result.empty())
398 Result.append(res.begin(), res.end());
399 return object_error::success;
400}
401
402static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
403 const RelocationRef &RelRef,
404 SmallVectorImpl<char> &Result) {
405 DataRefImpl Rel = RelRef.getRawDataRefImpl();
406 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
407 return getRelocationValueString(ELF32LE, Rel, Result);
408 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
409 return getRelocationValueString(ELF64LE, Rel, Result);
410 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
411 return getRelocationValueString(ELF32BE, Rel, Result);
412 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
413 return getRelocationValueString(ELF64BE, Rel, Result);
414}
415
416static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
417 const RelocationRef &Rel,
418 SmallVectorImpl<char> &Result) {
419 symbol_iterator SymI = Rel.getSymbol();
420 StringRef SymName;
421 if (std::error_code EC = SymI->getName(SymName))
422 return EC;
423 Result.append(SymName.begin(), SymName.end());
424 return object_error::success;
425}
426
427static void printRelocationTargetName(const MachOObjectFile *O,
428 const MachO::any_relocation_info &RE,
429 raw_string_ostream &fmt) {
430 bool IsScattered = O->isRelocationScattered(RE);
431
432 // Target of a scattered relocation is an address. In the interest of
433 // generating pretty output, scan through the symbol table looking for a
434 // symbol that aligns with that address. If we find one, print it.
435 // Otherwise, we just print the hex address of the target.
436 if (IsScattered) {
437 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
438
439 for (const SymbolRef &Symbol : O->symbols()) {
440 std::error_code ec;
441 uint64_t Addr;
442 StringRef Name;
443
444 if ((ec = Symbol.getAddress(Addr)))
445 report_fatal_error(ec.message());
446 if (Addr != Val)
447 continue;
448 if ((ec = Symbol.getName(Name)))
449 report_fatal_error(ec.message());
450 fmt << Name;
451 return;
452 }
453
454 // If we couldn't find a symbol that this relocation refers to, try
455 // to find a section beginning instead.
456 for (const SectionRef &Section : O->sections()) {
457 std::error_code ec;
458
459 StringRef Name;
460 uint64_t Addr = Section.getAddress();
461 if (Addr != Val)
462 continue;
463 if ((ec = Section.getName(Name)))
464 report_fatal_error(ec.message());
465 fmt << Name;
466 return;
467 }
468
469 fmt << format("0x%x", Val);
470 return;
471 }
472
473 StringRef S;
474 bool isExtern = O->getPlainRelocationExternal(RE);
475 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
476
477 if (isExtern) {
478 symbol_iterator SI = O->symbol_begin();
479 advance(SI, Val);
480 SI->getName(S);
481 } else {
482 section_iterator SI = O->section_begin();
483 // Adjust for the fact that sections are 1-indexed.
484 advance(SI, Val - 1);
485 SI->getName(S);
486 }
487
488 fmt << S;
489}
490
491static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
492 const RelocationRef &RelRef,
493 SmallVectorImpl<char> &Result) {
494 DataRefImpl Rel = RelRef.getRawDataRefImpl();
495 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
496
497 unsigned Arch = Obj->getArch();
498
499 std::string fmtbuf;
500 raw_string_ostream fmt(fmtbuf);
501 unsigned Type = Obj->getAnyRelocationType(RE);
502 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
503
504 // Determine any addends that should be displayed with the relocation.
505 // These require decoding the relocation type, which is triple-specific.
506
507 // X86_64 has entirely custom relocation types.
508 if (Arch == Triple::x86_64) {
509 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
510
511 switch (Type) {
512 case MachO::X86_64_RELOC_GOT_LOAD:
513 case MachO::X86_64_RELOC_GOT: {
514 printRelocationTargetName(Obj, RE, fmt);
515 fmt << "@GOT";
516 if (isPCRel)
517 fmt << "PCREL";
518 break;
519 }
520 case MachO::X86_64_RELOC_SUBTRACTOR: {
521 DataRefImpl RelNext = Rel;
522 Obj->moveRelocationNext(RelNext);
523 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
524
525 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
526 // X86_64_RELOC_UNSIGNED.
527 // NOTE: Scattered relocations don't exist on x86_64.
528 unsigned RType = Obj->getAnyRelocationType(RENext);
529 if (RType != MachO::X86_64_RELOC_UNSIGNED)
530 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
531 "X86_64_RELOC_SUBTRACTOR.");
532
533 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
534 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
535 printRelocationTargetName(Obj, RENext, fmt);
536 fmt << "-";
537 printRelocationTargetName(Obj, RE, fmt);
538 break;
539 }
540 case MachO::X86_64_RELOC_TLV:
541 printRelocationTargetName(Obj, RE, fmt);
542 fmt << "@TLV";
543 if (isPCRel)
544 fmt << "P";
545 break;
546 case MachO::X86_64_RELOC_SIGNED_1:
547 printRelocationTargetName(Obj, RE, fmt);
548 fmt << "-1";
549 break;
550 case MachO::X86_64_RELOC_SIGNED_2:
551 printRelocationTargetName(Obj, RE, fmt);
552 fmt << "-2";
553 break;
554 case MachO::X86_64_RELOC_SIGNED_4:
555 printRelocationTargetName(Obj, RE, fmt);
556 fmt << "-4";
557 break;
558 default:
559 printRelocationTargetName(Obj, RE, fmt);
560 break;
561 }
562 // X86 and ARM share some relocation types in common.
563 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
564 Arch == Triple::ppc) {
565 // Generic relocation types...
566 switch (Type) {
567 case MachO::GENERIC_RELOC_PAIR: // prints no info
568 return object_error::success;
569 case MachO::GENERIC_RELOC_SECTDIFF: {
570 DataRefImpl RelNext = Rel;
571 Obj->moveRelocationNext(RelNext);
572 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
573
574 // X86 sect diff's must be followed by a relocation of type
575 // GENERIC_RELOC_PAIR.
576 unsigned RType = Obj->getAnyRelocationType(RENext);
577
578 if (RType != MachO::GENERIC_RELOC_PAIR)
579 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
580 "GENERIC_RELOC_SECTDIFF.");
581
582 printRelocationTargetName(Obj, RE, fmt);
583 fmt << "-";
584 printRelocationTargetName(Obj, RENext, fmt);
585 break;
586 }
587 }
588
589 if (Arch == Triple::x86 || Arch == Triple::ppc) {
590 switch (Type) {
591 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
592 DataRefImpl RelNext = Rel;
593 Obj->moveRelocationNext(RelNext);
594 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
595
596 // X86 sect diff's must be followed by a relocation of type
597 // GENERIC_RELOC_PAIR.
598 unsigned RType = Obj->getAnyRelocationType(RENext);
599 if (RType != MachO::GENERIC_RELOC_PAIR)
600 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
601 "GENERIC_RELOC_LOCAL_SECTDIFF.");
602
603 printRelocationTargetName(Obj, RE, fmt);
604 fmt << "-";
605 printRelocationTargetName(Obj, RENext, fmt);
606 break;
607 }
608 case MachO::GENERIC_RELOC_TLV: {
609 printRelocationTargetName(Obj, RE, fmt);
610 fmt << "@TLV";
611 if (IsPCRel)
612 fmt << "P";
613 break;
614 }
615 default:
616 printRelocationTargetName(Obj, RE, fmt);
617 }
618 } else { // ARM-specific relocations
619 switch (Type) {
620 case MachO::ARM_RELOC_HALF:
621 case MachO::ARM_RELOC_HALF_SECTDIFF: {
622 // Half relocations steal a bit from the length field to encode
623 // whether this is an upper16 or a lower16 relocation.
624 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
625
626 if (isUpper)
627 fmt << ":upper16:(";
628 else
629 fmt << ":lower16:(";
630 printRelocationTargetName(Obj, RE, fmt);
631
632 DataRefImpl RelNext = Rel;
633 Obj->moveRelocationNext(RelNext);
634 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
635
636 // ARM half relocs must be followed by a relocation of type
637 // ARM_RELOC_PAIR.
638 unsigned RType = Obj->getAnyRelocationType(RENext);
639 if (RType != MachO::ARM_RELOC_PAIR)
640 report_fatal_error("Expected ARM_RELOC_PAIR after "
641 "ARM_RELOC_HALF");
642
643 // NOTE: The half of the target virtual address is stashed in the
644 // address field of the secondary relocation, but we can't reverse
645 // engineer the constant offset from it without decoding the movw/movt
646 // instruction to find the other half in its immediate field.
647
648 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
649 // symbol/section pointer of the follow-on relocation.
650 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
651 fmt << "-";
652 printRelocationTargetName(Obj, RENext, fmt);
653 }
654
655 fmt << ")";
656 break;
657 }
658 default: { printRelocationTargetName(Obj, RE, fmt); }
659 }
660 }
661 } else
662 printRelocationTargetName(Obj, RE, fmt);
663
664 fmt.flush();
665 Result.append(fmtbuf.begin(), fmtbuf.end());
666 return object_error::success;
667}
668
669static std::error_code getRelocationValueString(const RelocationRef &Rel,
670 SmallVectorImpl<char> &Result) {
671 const ObjectFile *Obj = Rel.getObjectFile();
672 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
673 return getRelocationValueString(ELF, Rel, Result);
674 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
675 return getRelocationValueString(COFF, Rel, Result);
676 auto *MachO = cast<MachOObjectFile>(Obj);
677 return getRelocationValueString(MachO, Rel, Result);
678}
679
Michael J. Spencer51862b32011-10-13 22:17:18 +0000680static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000681 const Target *TheTarget = getTarget(Obj);
682 // getTarget() will have already issued a diagnostic if necessary, so
683 // just bail here if it failed.
684 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000685 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000686
Jack Carter551efd72012-08-28 19:24:49 +0000687 // Package up features to be passed to target/subtarget
688 std::string FeaturesStr;
689 if (MAttrs.size()) {
690 SubtargetFeatures Features;
691 for (unsigned i = 0; i != MAttrs.size(); ++i)
692 Features.AddFeature(MAttrs[i]);
693 FeaturesStr = Features.getString();
694 }
695
Ahmed Charles56440fd2014-03-06 05:51:42 +0000696 std::unique_ptr<const MCRegisterInfo> MRI(
697 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000698 if (!MRI) {
699 errs() << "error: no register info for target " << TripleName << "\n";
700 return;
701 }
702
703 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000704 std::unique_ptr<const MCAsmInfo> AsmInfo(
705 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000706 if (!AsmInfo) {
707 errs() << "error: no assembly info for target " << TripleName << "\n";
708 return;
709 }
710
Ahmed Charles56440fd2014-03-06 05:51:42 +0000711 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000712 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000713 if (!STI) {
714 errs() << "error: no subtarget info for target " << TripleName << "\n";
715 return;
716 }
717
Ahmed Charles56440fd2014-03-06 05:51:42 +0000718 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000719 if (!MII) {
720 errs() << "error: no instruction info for target " << TripleName << "\n";
721 return;
722 }
723
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000724 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
725 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
726
727 std::unique_ptr<MCDisassembler> DisAsm(
728 TheTarget->createMCDisassembler(*STI, Ctx));
729
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000730 if (!DisAsm) {
731 errs() << "error: no disassembler for target " << TripleName << "\n";
732 return;
733 }
734
Ahmed Charles56440fd2014-03-06 05:51:42 +0000735 std::unique_ptr<const MCInstrAnalysis> MIA(
736 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000737
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000738 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000739 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000740 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000741 if (!IP) {
742 errs() << "error: no instruction printer for target " << TripleName
743 << '\n';
744 return;
745 }
Colin LeMahieu35436a22015-05-29 14:48:25 +0000746 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000747
Greg Fitzgerald18432272014-03-20 22:55:15 +0000748 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
749 "\t\t\t%08" PRIx64 ": ";
750
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000751 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
752 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000753 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000754 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
755 for (const SectionRef &Section : Obj->sections()) {
756 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000757 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000758 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000759 }
760
Alexey Samsonov48803e52014-03-13 14:37:36 +0000761 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000762 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000763 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000764
Rafael Espindola80291272014-10-08 15:28:58 +0000765 uint64_t SectionAddr = Section.getAddress();
766 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000767 if (!SectSize)
768 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000769
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000770 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000771 std::vector<std::pair<uint64_t, StringRef>> Symbols;
772 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000773 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000774 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000775 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000776 break;
777 if (Address == UnknownAddressOrSize)
778 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000779 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000780 if (Address >= SectSize)
781 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000782
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000783 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000784 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000785 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000786 Symbols.push_back(std::make_pair(Address, Name));
787 }
788 }
789
790 // Sort the symbols by address, just in case they didn't come in that way.
791 array_pod_sort(Symbols.begin(), Symbols.end());
792
Michael J. Spencer51862b32011-10-13 22:17:18 +0000793 // Make a list of all the relocations for this section.
794 std::vector<RelocationRef> Rels;
795 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000796 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
797 for (const RelocationRef &Reloc : RelocSec.relocations()) {
798 Rels.push_back(Reloc);
799 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000800 }
801 }
802
803 // Sort relocations by address.
804 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
805
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000806 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000807 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000808 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000809 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000810 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000811 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000812 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000813 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000814 outs() << "Disassembly of section ";
815 if (!SegmentName.empty())
816 outs() << SegmentName << ",";
817 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000818
Rafael Espindola7884c952015-06-04 15:01:05 +0000819 // If the section has no symbol at the start, just insert a dummy one.
820 if (Symbols.empty() || Symbols[0].first != 0)
821 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000822
823 SmallString<40> Comments;
824 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000825
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000826 StringRef BytesStr;
827 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000828 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000829 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
830 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000831
Michael J. Spencer2670c252011-01-20 06:39:06 +0000832 uint64_t Size;
833 uint64_t Index;
834
Michael J. Spencer51862b32011-10-13 22:17:18 +0000835 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
836 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000837 // Disassemble symbol by symbol.
838 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000839
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000840 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000841 // The end is either the section end or the beginning of the next symbol.
842 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
843 // If this symbol has the same address as the next symbol, then skip it.
844 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000845 continue;
846
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000847 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000848
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000849#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000850 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000851#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000852 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000853#endif
854
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000855 for (Index = Start; Index < End; Index += Size) {
856 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000857
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000858 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
859 SectionAddr + Index, DebugOut,
860 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000861 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000862 Bytes.slice(Index, Size),
863 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000864 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000865 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000866 outs() << "\n";
867 } else {
868 errs() << ToolName << ": warning: invalid instruction encoding\n";
869 if (Size == 0)
870 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000871 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000872
873 // Print relocation for instruction.
874 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000875 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000876 uint64_t addr;
877 SmallString<16> name;
878 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000879
880 // If this relocation is hidden, skip it.
881 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
882 if (hidden) goto skip_print_rel;
883
Rafael Espindola1e483872013-04-25 12:28:45 +0000884 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000885 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000886 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000887 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
Rafael Espindola37070a52015-06-03 04:48:06 +0000888 if (error(getRelocationValueString(*rel_cur, val)))
889 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000890 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000891 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000892
893 skip_print_rel:
894 ++rel_cur;
895 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000896 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000897 }
898 }
899}
900
Kevin Enderby98da6132015-01-20 21:47:46 +0000901void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000902 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
903 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000904 // Regular objdump doesn't print relocations in non-relocatable object
905 // files.
906 if (!Obj->isRelocatableObject())
907 return;
908
Alexey Samsonov48803e52014-03-13 14:37:36 +0000909 for (const SectionRef &Section : Obj->sections()) {
910 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000911 continue;
912 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000913 if (error(Section.getName(secname)))
914 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000915 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000916 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000917 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000918 uint64_t address;
919 SmallString<32> relocname;
920 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000921 if (error(Reloc.getHidden(hidden)))
922 continue;
923 if (hidden)
924 continue;
925 if (error(Reloc.getTypeName(relocname)))
926 continue;
927 if (error(Reloc.getOffset(address)))
928 continue;
Rafael Espindola37070a52015-06-03 04:48:06 +0000929 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000930 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000931 outs() << format(Fmt.data(), address) << " " << relocname << " "
932 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000933 }
934 outs() << "\n";
935 }
936}
937
Kevin Enderby98da6132015-01-20 21:47:46 +0000938void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000939 outs() << "Sections:\n"
940 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000941 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000942 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000943 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000944 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000945 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000946 uint64_t Address = Section.getAddress();
947 uint64_t Size = Section.getSize();
948 bool Text = Section.isText();
949 bool Data = Section.isData();
950 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000951 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000952 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000953 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
954 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000955 ++i;
956 }
957}
958
Kevin Enderby98da6132015-01-20 21:47:46 +0000959void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000960 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000961 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000962 StringRef Name;
963 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000964 if (error(Section.getName(Name)))
965 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000966 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +0000967 uint64_t Size = Section.getSize();
968 if (!Size)
969 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000970
971 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +0000972 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +0000973 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000974 ", %04" PRIx64 ")>\n",
975 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000976 continue;
977 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000978
David Majnemer8f6b04c2014-07-14 16:20:14 +0000979 if (error(Section.getContents(Contents)))
980 continue;
981
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000982 // Dump out the content as hex and printable ascii characters.
983 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000984 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000985 // Dump line of hex.
986 for (std::size_t i = 0; i < 16; ++i) {
987 if (i != 0 && i % 4 == 0)
988 outs() << ' ';
989 if (addr + i < end)
990 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
991 << hexdigit(Contents[addr + i] & 0xF, true);
992 else
993 outs() << " ";
994 }
995 // Print ascii.
996 outs() << " ";
997 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +0000998 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000999 outs() << Contents[addr + i];
1000 else
1001 outs() << ".";
1002 }
1003 outs() << "\n";
1004 }
1005 }
1006}
1007
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001008static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001009 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1010 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001011 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001012 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001013 return;
1014
David Majnemer44f51e52014-09-10 12:51:52 +00001015 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001016 return;
1017
1018 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001019 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001020 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001021 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1022 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1023 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1024 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001025 << Name << "\n";
1026
David Majnemer44f51e52014-09-10 12:51:52 +00001027 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001028 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001029 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001030 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001031 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001032
David Majnemer4d571592014-09-15 19:42:42 +00001033 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1034
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001035 outs() << "AUX "
1036 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1037 , unsigned(asd->Length)
1038 , unsigned(asd->NumberOfRelocations)
1039 , unsigned(asd->NumberOfLinenumbers)
1040 , unsigned(asd->CheckSum))
1041 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001042 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001043 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001044 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001045 const char *FileName;
1046 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001047 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001048
David Majnemer44f51e52014-09-10 12:51:52 +00001049 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1050 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001051 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001052
David Majnemer44f51e52014-09-10 12:51:52 +00001053 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001054 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001055 } else {
1056 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001057 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001058 }
1059 }
1060}
1061
Kevin Enderby98da6132015-01-20 21:47:46 +00001062void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001063 outs() << "SYMBOL TABLE:\n";
1064
Rui Ueyama4e39f712014-03-18 18:58:51 +00001065 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001066 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001067 return;
1068 }
1069 for (const SymbolRef &Symbol : o->symbols()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001070 uint64_t Address;
1071 SymbolRef::Type Type;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001072 uint32_t Flags = Symbol.getFlags();
1073 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001074 if (error(Symbol.getAddress(Address)))
1075 continue;
1076 if (error(Symbol.getType(Type)))
1077 continue;
Rafael Espindola5eb02e42015-06-01 00:27:26 +00001078 uint64_t Size = Symbol.getSize();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001079 if (error(Symbol.getSection(Section)))
1080 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001081 StringRef Name;
1082 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1083 Section->getName(Name);
1084 } else if (error(Symbol.getName(Name))) {
1085 continue;
1086 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001087
Rui Ueyama4e39f712014-03-18 18:58:51 +00001088 bool Global = Flags & SymbolRef::SF_Global;
1089 bool Weak = Flags & SymbolRef::SF_Weak;
1090 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001091 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001092 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001093
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001094 if (Common) {
Rafael Espindolaa4d224722015-05-31 23:52:50 +00001095 uint32_t Alignment = Symbol.getAlignment();
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001096 Address = Size;
1097 Size = Alignment;
1098 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001099 if (Address == UnknownAddressOrSize)
1100 Address = 0;
1101 if (Size == UnknownAddressOrSize)
1102 Size = 0;
1103 char GlobLoc = ' ';
1104 if (Type != SymbolRef::ST_Unknown)
1105 GlobLoc = Global ? 'g' : 'l';
1106 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1107 ? 'd' : ' ';
1108 char FileFunc = ' ';
1109 if (Type == SymbolRef::ST_File)
1110 FileFunc = 'f';
1111 else if (Type == SymbolRef::ST_Function)
1112 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001113
Rui Ueyama4e39f712014-03-18 18:58:51 +00001114 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1115 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001116
Rui Ueyama4e39f712014-03-18 18:58:51 +00001117 outs() << format(Fmt, Address) << " "
1118 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1119 << (Weak ? 'w' : ' ') // Weak?
1120 << ' ' // Constructor. Not supported yet.
1121 << ' ' // Warning. Not supported yet.
1122 << ' ' // Indirect reference to another symbol.
1123 << Debug // Debugging (d) or dynamic (D) symbol.
1124 << FileFunc // Name of function (F), file (f) or object (O).
1125 << ' ';
1126 if (Absolute) {
1127 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001128 } else if (Common) {
1129 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001130 } else if (Section == o->section_end()) {
1131 outs() << "*UND*";
1132 } else {
1133 if (const MachOObjectFile *MachO =
1134 dyn_cast<const MachOObjectFile>(o)) {
1135 DataRefImpl DR = Section->getRawDataRefImpl();
1136 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1137 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001138 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001139 StringRef SectionName;
1140 if (error(Section->getName(SectionName)))
1141 SectionName = "";
1142 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001143 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001144 outs() << '\t'
Davide Italianocd2514d2015-04-30 23:08:53 +00001145 << format("%08" PRIx64 " ", Size);
1146 if (Hidden) {
1147 outs() << ".hidden ";
1148 }
1149 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001150 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001151 }
1152}
1153
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001154static void PrintUnwindInfo(const ObjectFile *o) {
1155 outs() << "Unwind info:\n\n";
1156
1157 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1158 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001159 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1160 printMachOUnwindInfo(MachO);
1161 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001162 // TODO: Extract DWARF dump tool to objdump.
1163 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001164 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001165 return;
1166 }
1167}
1168
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001169void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001170 outs() << "Exports trie:\n";
1171 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1172 printMachOExportsTrie(MachO);
1173 else {
1174 errs() << "This operation is only currently supported "
1175 "for Mach-O executable files.\n";
1176 return;
1177 }
1178}
1179
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001180void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001181 outs() << "Rebase table:\n";
1182 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1183 printMachORebaseTable(MachO);
1184 else {
1185 errs() << "This operation is only currently supported "
1186 "for Mach-O executable files.\n";
1187 return;
1188 }
1189}
1190
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001191void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001192 outs() << "Bind table:\n";
1193 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1194 printMachOBindTable(MachO);
1195 else {
1196 errs() << "This operation is only currently supported "
1197 "for Mach-O executable files.\n";
1198 return;
1199 }
1200}
1201
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001202void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001203 outs() << "Lazy bind table:\n";
1204 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1205 printMachOLazyBindTable(MachO);
1206 else {
1207 errs() << "This operation is only currently supported "
1208 "for Mach-O executable files.\n";
1209 return;
1210 }
1211}
1212
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001213void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001214 outs() << "Weak bind table:\n";
1215 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1216 printMachOWeakBindTable(MachO);
1217 else {
1218 errs() << "This operation is only currently supported "
1219 "for Mach-O executable files.\n";
1220 return;
1221 }
1222}
Nick Kledzikac431442014-09-12 21:34:15 +00001223
Rui Ueyamac2bed422013-09-27 21:04:00 +00001224static void printPrivateFileHeader(const ObjectFile *o) {
1225 if (o->isELF()) {
1226 printELFFileHeader(o);
1227 } else if (o->isCOFF()) {
1228 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001229 } else if (o->isMachO()) {
1230 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001231 }
1232}
1233
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001234static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001235 outs() << '\n';
1236 outs() << o->getFileName()
1237 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1238
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001239 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001240 DisassembleObject(o, Relocations);
1241 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001242 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001243 if (SectionHeaders)
1244 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001245 if (SectionContents)
1246 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001247 if (SymbolTable)
1248 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001249 if (UnwindInfo)
1250 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001251 if (PrivateHeaders)
1252 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001253 if (ExportsTrie)
1254 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001255 if (Rebase)
1256 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001257 if (Bind)
1258 printBindTable(o);
1259 if (LazyBind)
1260 printLazyBindTable(o);
1261 if (WeakBind)
1262 printWeakBindTable(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001263}
1264
1265/// @brief Dump each object file in \a a;
1266static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001267 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1268 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001269 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1270 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001271 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001272 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001273 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001274 continue;
1275 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001276 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001277 DumpObject(o);
1278 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001279 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001280 }
1281}
1282
1283/// @brief Open file and figure out how to dump it.
1284static void DumpInput(StringRef file) {
1285 // If file isn't stdin, check that it exists.
1286 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001287 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001288 return;
1289 }
1290
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001291 // If we are using the Mach-O specific object file parser, then let it parse
1292 // the file and process the command line options. So the -arch flags can
1293 // be used to select specific slices, etc.
1294 if (MachOOpt) {
1295 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001296 return;
1297 }
1298
1299 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001300 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001301 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001302 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001303 return;
1304 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001305 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001306
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001307 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001308 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001309 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001310 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001311 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001312 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001313}
1314
Michael J. Spencer2670c252011-01-20 06:39:06 +00001315int main(int argc, char **argv) {
1316 // Print a stack trace if we signal out.
1317 sys::PrintStackTraceOnErrorSignal();
1318 PrettyStackTraceProgram X(argc, argv);
1319 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1320
1321 // Initialize targets and assembly printers/parsers.
1322 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001323 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001324 llvm::InitializeAllAsmParsers();
1325 llvm::InitializeAllDisassemblers();
1326
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001327 // Register the target printer for --version.
1328 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1329
Michael J. Spencer2670c252011-01-20 06:39:06 +00001330 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1331 TripleName = Triple::normalize(TripleName);
1332
1333 ToolName = argv[0];
1334
1335 // Defaults to a.out if no filenames specified.
1336 if (InputFilenames.size() == 0)
1337 InputFilenames.push_back("a.out");
1338
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001339 if (!Disassemble
1340 && !Relocations
1341 && !SectionHeaders
1342 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001343 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001344 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001345 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001346 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001347 && !Rebase
1348 && !Bind
1349 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001350 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001351 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001352 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001353 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001354 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001355 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001356 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001357 && !(DylibsUsed && MachOOpt)
1358 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001359 && !(ObjcMetaData && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001360 && !(DumpSections.size() != 0 && MachOOpt)) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001361 cl::PrintHelpMessage();
1362 return 2;
1363 }
1364
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001365 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1366 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001367
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001368 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001369}