blob: 61e75a7899a9746cca72130346ccf0a052c48113 [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"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000025#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000026#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCDisassembler.h"
28#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000030#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000031#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000032#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000033#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCRelocationInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Object/Archive.h"
Rafael Espindola37070a52015-06-03 04:48:06 +000037#include "llvm/Object/ELFObjectFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/COFF.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000039#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000041#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000044#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000045#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000047#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/Host.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/PrettyStackTrace.h"
52#include "llvm/Support/Signals.h"
53#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000054#include "llvm/Support/TargetRegistry.h"
55#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000058#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000061
Michael J. Spencer2670c252011-01-20 06:39:06 +000062using namespace llvm;
63using namespace object;
64
Benjamin Kramer43a772e2011-09-19 17:56:04 +000065static cl::list<std::string>
66InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000067
Kevin Enderbye2297dd2015-01-07 21:02:18 +000068cl::opt<bool>
69llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000070 cl::desc("Display assembler mnemonics for the machine instructions"));
71static cl::alias
72Disassembled("d", cl::desc("Alias for --disassemble"),
73 cl::aliasopt(Disassemble));
Michael J. Spencer2670c252011-01-20 06:39:06 +000074
Kevin Enderby98da6132015-01-20 21:47:46 +000075cl::opt<bool>
76llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000077
Kevin Enderby98da6132015-01-20 21:47:46 +000078cl::opt<bool>
79llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000080
Kevin Enderby98da6132015-01-20 21:47:46 +000081cl::opt<bool>
82llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000083
Kevin Enderbye2297dd2015-01-07 21:02:18 +000084cl::opt<bool>
85llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000086
Kevin Enderbye2297dd2015-01-07 21:02:18 +000087cl::opt<bool>
88llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000089
Kevin Enderbye2297dd2015-01-07 21:02:18 +000090cl::opt<bool>
91llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000092
Kevin Enderbye2297dd2015-01-07 21:02:18 +000093cl::opt<bool>
94llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000095
Kevin Enderbye2297dd2015-01-07 21:02:18 +000096cl::opt<bool>
97llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000098
99static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000100MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000101static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000102MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000103
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000104cl::opt<std::string>
105llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
106 "see -version for available targets"));
107
108cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000109llvm::MCPU("mcpu",
110 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111 cl::value_desc("cpu-name"),
112 cl::init(""));
113
114cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000115llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000116 "see -version for available targets"));
117
Kevin Enderby98da6132015-01-20 21:47:46 +0000118cl::opt<bool>
119llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
120 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000121static cl::alias
122SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
124static cl::alias
125SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
126 cl::aliasopt(SectionHeaders));
127
Kevin Enderbyc9595622014-08-06 23:24:41 +0000128cl::list<std::string>
129llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000130 cl::CommaSeparated,
131 cl::desc("Target specific attributes"),
132 cl::value_desc("a1,+a2,-a3,..."));
133
Kevin Enderbybf246f52014-09-24 23:08:22 +0000134cl::opt<bool>
135llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
136 "instructions, do not print "
137 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000138
Kevin Enderby98da6132015-01-20 21:47:46 +0000139cl::opt<bool>
140llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000141
142static cl::alias
143UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
144 cl::aliasopt(UnwindInfo));
145
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000146cl::opt<bool>
147llvm::PrivateHeaders("private-headers",
148 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000149
150static cl::alias
151PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
152 cl::aliasopt(PrivateHeaders));
153
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000154cl::opt<bool>
155 llvm::PrintImmHex("print-imm-hex",
156 cl::desc("Use hex format for immediate values"));
157
Sanjoy Das6f567a42015-06-22 18:03:02 +0000158cl::opt<bool> PrintFaultMaps("fault-map-section",
159 cl::desc("Display contents of faultmap section"));
160
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000161static StringRef ToolName;
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000162static int ReturnValue = EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000163
Rafael Espindola4453e42942014-06-13 03:07:50 +0000164bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000165 if (!EC)
166 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000167
Mark Seaborneb03ac52014-01-25 00:32:01 +0000168 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000169 outs().flush();
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000170 ReturnValue = EXIT_FAILURE;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000172}
173
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000174static void report_error(StringRef File, std::error_code EC) {
175 assert(EC);
176 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
177 ReturnValue = EXIT_FAILURE;
178}
179
Craig Toppere6cb63e2014-04-25 04:24:47 +0000180static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000181 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000182 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000183 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000184 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000185 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000186 // TheTriple defaults to ELF, and COFF doesn't have an environment:
187 // the best we can do here is indicate that it is mach-o.
188 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000189 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000190
191 if (Obj->isCOFF()) {
192 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
193 if (COFFObj->getArch() == Triple::thumb)
194 TheTriple.setTriple("thumbv7-windows");
195 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000196 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000197 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000198 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000199
200 // Get the target specific parser.
201 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000202 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
203 Error);
204 if (!TheTarget) {
205 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000206 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000207 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000208
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000209 // Update the triple name and return the found target.
210 TripleName = TheTriple.getTriple();
211 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000212}
213
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000214bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Michael J. Spencer51862b32011-10-13 22:17:18 +0000215 uint64_t a_addr, b_addr;
Rafael Espindola1e483872013-04-25 12:28:45 +0000216 if (error(a.getOffset(a_addr))) return false;
217 if (error(b.getOffset(b_addr))) return false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000218 return a_addr < b_addr;
219}
220
Colin LeMahieufb76b002015-05-28 19:07:14 +0000221namespace {
222class PrettyPrinter {
223public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000224 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000225 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000226 ArrayRef<uint8_t> Bytes, uint64_t Address,
227 raw_ostream &OS, StringRef Annot,
228 MCSubtargetInfo const &STI) {
229 outs() << format("%8" PRIx64 ":", Address);
230 if (!NoShowRawInsn) {
231 outs() << "\t";
232 dumpBytes(Bytes, outs());
233 }
234 IP.printInst(MI, outs(), "", STI);
235 }
236};
237PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000238class HexagonPrettyPrinter : public PrettyPrinter {
239public:
240 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
241 raw_ostream &OS) {
242 uint32_t opcode =
243 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
244 OS << format("%8" PRIx64 ":", Address);
245 if (!NoShowRawInsn) {
246 OS << "\t";
247 dumpBytes(Bytes.slice(0, 4), OS);
248 OS << format("%08" PRIx32, opcode);
249 }
250 }
251 void printInst(MCInstPrinter &IP, const MCInst *MI,
252 ArrayRef<uint8_t> Bytes, uint64_t Address,
253 raw_ostream &OS, StringRef Annot,
254 MCSubtargetInfo const &STI) override {
255 std::string Buffer;
256 {
257 raw_string_ostream TempStream(Buffer);
258 IP.printInst(MI, TempStream, "", STI);
259 }
260 StringRef Contents(Buffer);
261 // Split off bundle attributes
262 auto PacketBundle = Contents.rsplit('\n');
263 // Split off first instruction from the rest
264 auto HeadTail = PacketBundle.first.split('\n');
265 auto Preamble = " { ";
266 auto Separator = "";
267 while(!HeadTail.first.empty()) {
268 OS << Separator;
269 Separator = "\n";
270 printLead(Bytes, Address, OS);
271 OS << Preamble;
272 Preamble = " ";
273 StringRef Inst;
274 auto Duplex = HeadTail.first.split('\v');
275 if(!Duplex.second.empty()){
276 OS << Duplex.first;
277 OS << "; ";
278 Inst = Duplex.second;
279 }
280 else
281 Inst = HeadTail.first;
282 OS << Inst;
283 Bytes = Bytes.slice(4);
284 Address += 4;
285 HeadTail = HeadTail.second.split('\n');
286 }
287 OS << " } " << PacketBundle.second;
288 }
289};
290HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000291PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000292 switch(Triple.getArch()) {
293 default:
294 return PrettyPrinterInst;
295 case Triple::hexagon:
296 return HexagonPrettyPrinterInst;
297 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000298}
299}
300
Rafael Espindola37070a52015-06-03 04:48:06 +0000301template <class ELFT>
302static const typename ELFObjectFile<ELFT>::Elf_Rel *
303getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
304 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
305 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
306}
307
308template <class ELFT>
309static const typename ELFObjectFile<ELFT>::Elf_Rela *
310getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
311 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
312 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
313}
314
315template <class ELFT>
316static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
317 DataRefImpl Rel,
318 SmallVectorImpl<char> &Result) {
319 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
320 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
321 const ELFFile<ELFT> &EF = *Obj->getELFFile();
322
323 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
324 uint8_t type;
325 StringRef res;
326 int64_t addend = 0;
327 uint16_t symbol_index = 0;
328 switch (sec->sh_type) {
329 default:
330 return object_error::parse_failed;
331 case ELF::SHT_REL: {
332 type = getRel(EF, Rel)->getType(EF.isMips64EL());
333 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
334 // TODO: Read implicit addend from section data.
335 break;
336 }
337 case ELF::SHT_RELA: {
338 type = getRela(EF, Rel)->getType(EF.isMips64EL());
339 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
340 addend = getRela(EF, Rel)->r_addend;
341 break;
342 }
343 }
344 const Elf_Sym *symb =
345 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000346 StringRef Target;
347 const Elf_Shdr *SymSec = EF.getSection(symb);
348 if (symb->getType() == ELF::STT_SECTION) {
349 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
350 if (std::error_code EC = SecName.getError())
351 return EC;
352 Target = *SecName;
353 } else {
354 ErrorOr<StringRef> SymName =
355 EF.getSymbolName(EF.getSection(sec->sh_link), symb);
356 if (!SymName)
357 return SymName.getError();
358 Target = *SymName;
359 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000360 switch (EF.getHeader()->e_machine) {
361 case ELF::EM_X86_64:
362 switch (type) {
363 case ELF::R_X86_64_PC8:
364 case ELF::R_X86_64_PC16:
365 case ELF::R_X86_64_PC32: {
366 std::string fmtbuf;
367 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000368 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000369 fmt.flush();
370 Result.append(fmtbuf.begin(), fmtbuf.end());
371 } break;
372 case ELF::R_X86_64_8:
373 case ELF::R_X86_64_16:
374 case ELF::R_X86_64_32:
375 case ELF::R_X86_64_32S:
376 case ELF::R_X86_64_64: {
377 std::string fmtbuf;
378 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000379 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000380 fmt.flush();
381 Result.append(fmtbuf.begin(), fmtbuf.end());
382 } break;
383 default:
384 res = "Unknown";
385 }
386 break;
387 case ELF::EM_AARCH64: {
388 std::string fmtbuf;
389 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000390 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000391 if (addend != 0)
392 fmt << (addend < 0 ? "" : "+") << addend;
393 fmt.flush();
394 Result.append(fmtbuf.begin(), fmtbuf.end());
395 break;
396 }
397 case ELF::EM_386:
398 case ELF::EM_ARM:
399 case ELF::EM_HEXAGON:
400 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000401 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000402 break;
403 default:
404 res = "Unknown";
405 }
406 if (Result.empty())
407 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000408 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000409}
410
411static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
412 const RelocationRef &RelRef,
413 SmallVectorImpl<char> &Result) {
414 DataRefImpl Rel = RelRef.getRawDataRefImpl();
415 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
416 return getRelocationValueString(ELF32LE, Rel, Result);
417 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
418 return getRelocationValueString(ELF64LE, Rel, Result);
419 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
420 return getRelocationValueString(ELF32BE, Rel, Result);
421 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
422 return getRelocationValueString(ELF64BE, Rel, Result);
423}
424
425static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
426 const RelocationRef &Rel,
427 SmallVectorImpl<char> &Result) {
428 symbol_iterator SymI = Rel.getSymbol();
429 StringRef SymName;
430 if (std::error_code EC = SymI->getName(SymName))
431 return EC;
432 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000433 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000434}
435
436static void printRelocationTargetName(const MachOObjectFile *O,
437 const MachO::any_relocation_info &RE,
438 raw_string_ostream &fmt) {
439 bool IsScattered = O->isRelocationScattered(RE);
440
441 // Target of a scattered relocation is an address. In the interest of
442 // generating pretty output, scan through the symbol table looking for a
443 // symbol that aligns with that address. If we find one, print it.
444 // Otherwise, we just print the hex address of the target.
445 if (IsScattered) {
446 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
447
448 for (const SymbolRef &Symbol : O->symbols()) {
449 std::error_code ec;
450 uint64_t Addr;
451 StringRef Name;
452
453 if ((ec = Symbol.getAddress(Addr)))
454 report_fatal_error(ec.message());
455 if (Addr != Val)
456 continue;
457 if ((ec = Symbol.getName(Name)))
458 report_fatal_error(ec.message());
459 fmt << Name;
460 return;
461 }
462
463 // If we couldn't find a symbol that this relocation refers to, try
464 // to find a section beginning instead.
465 for (const SectionRef &Section : O->sections()) {
466 std::error_code ec;
467
468 StringRef Name;
469 uint64_t Addr = Section.getAddress();
470 if (Addr != Val)
471 continue;
472 if ((ec = Section.getName(Name)))
473 report_fatal_error(ec.message());
474 fmt << Name;
475 return;
476 }
477
478 fmt << format("0x%x", Val);
479 return;
480 }
481
482 StringRef S;
483 bool isExtern = O->getPlainRelocationExternal(RE);
484 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
485
486 if (isExtern) {
487 symbol_iterator SI = O->symbol_begin();
488 advance(SI, Val);
489 SI->getName(S);
490 } else {
491 section_iterator SI = O->section_begin();
492 // Adjust for the fact that sections are 1-indexed.
493 advance(SI, Val - 1);
494 SI->getName(S);
495 }
496
497 fmt << S;
498}
499
500static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
501 const RelocationRef &RelRef,
502 SmallVectorImpl<char> &Result) {
503 DataRefImpl Rel = RelRef.getRawDataRefImpl();
504 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
505
506 unsigned Arch = Obj->getArch();
507
508 std::string fmtbuf;
509 raw_string_ostream fmt(fmtbuf);
510 unsigned Type = Obj->getAnyRelocationType(RE);
511 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
512
513 // Determine any addends that should be displayed with the relocation.
514 // These require decoding the relocation type, which is triple-specific.
515
516 // X86_64 has entirely custom relocation types.
517 if (Arch == Triple::x86_64) {
518 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
519
520 switch (Type) {
521 case MachO::X86_64_RELOC_GOT_LOAD:
522 case MachO::X86_64_RELOC_GOT: {
523 printRelocationTargetName(Obj, RE, fmt);
524 fmt << "@GOT";
525 if (isPCRel)
526 fmt << "PCREL";
527 break;
528 }
529 case MachO::X86_64_RELOC_SUBTRACTOR: {
530 DataRefImpl RelNext = Rel;
531 Obj->moveRelocationNext(RelNext);
532 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
533
534 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
535 // X86_64_RELOC_UNSIGNED.
536 // NOTE: Scattered relocations don't exist on x86_64.
537 unsigned RType = Obj->getAnyRelocationType(RENext);
538 if (RType != MachO::X86_64_RELOC_UNSIGNED)
539 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
540 "X86_64_RELOC_SUBTRACTOR.");
541
542 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
543 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
544 printRelocationTargetName(Obj, RENext, fmt);
545 fmt << "-";
546 printRelocationTargetName(Obj, RE, fmt);
547 break;
548 }
549 case MachO::X86_64_RELOC_TLV:
550 printRelocationTargetName(Obj, RE, fmt);
551 fmt << "@TLV";
552 if (isPCRel)
553 fmt << "P";
554 break;
555 case MachO::X86_64_RELOC_SIGNED_1:
556 printRelocationTargetName(Obj, RE, fmt);
557 fmt << "-1";
558 break;
559 case MachO::X86_64_RELOC_SIGNED_2:
560 printRelocationTargetName(Obj, RE, fmt);
561 fmt << "-2";
562 break;
563 case MachO::X86_64_RELOC_SIGNED_4:
564 printRelocationTargetName(Obj, RE, fmt);
565 fmt << "-4";
566 break;
567 default:
568 printRelocationTargetName(Obj, RE, fmt);
569 break;
570 }
571 // X86 and ARM share some relocation types in common.
572 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
573 Arch == Triple::ppc) {
574 // Generic relocation types...
575 switch (Type) {
576 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000577 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000578 case MachO::GENERIC_RELOC_SECTDIFF: {
579 DataRefImpl RelNext = Rel;
580 Obj->moveRelocationNext(RelNext);
581 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
582
583 // X86 sect diff's must be followed by a relocation of type
584 // GENERIC_RELOC_PAIR.
585 unsigned RType = Obj->getAnyRelocationType(RENext);
586
587 if (RType != MachO::GENERIC_RELOC_PAIR)
588 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
589 "GENERIC_RELOC_SECTDIFF.");
590
591 printRelocationTargetName(Obj, RE, fmt);
592 fmt << "-";
593 printRelocationTargetName(Obj, RENext, fmt);
594 break;
595 }
596 }
597
598 if (Arch == Triple::x86 || Arch == Triple::ppc) {
599 switch (Type) {
600 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
601 DataRefImpl RelNext = Rel;
602 Obj->moveRelocationNext(RelNext);
603 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
604
605 // X86 sect diff's must be followed by a relocation of type
606 // GENERIC_RELOC_PAIR.
607 unsigned RType = Obj->getAnyRelocationType(RENext);
608 if (RType != MachO::GENERIC_RELOC_PAIR)
609 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
610 "GENERIC_RELOC_LOCAL_SECTDIFF.");
611
612 printRelocationTargetName(Obj, RE, fmt);
613 fmt << "-";
614 printRelocationTargetName(Obj, RENext, fmt);
615 break;
616 }
617 case MachO::GENERIC_RELOC_TLV: {
618 printRelocationTargetName(Obj, RE, fmt);
619 fmt << "@TLV";
620 if (IsPCRel)
621 fmt << "P";
622 break;
623 }
624 default:
625 printRelocationTargetName(Obj, RE, fmt);
626 }
627 } else { // ARM-specific relocations
628 switch (Type) {
629 case MachO::ARM_RELOC_HALF:
630 case MachO::ARM_RELOC_HALF_SECTDIFF: {
631 // Half relocations steal a bit from the length field to encode
632 // whether this is an upper16 or a lower16 relocation.
633 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
634
635 if (isUpper)
636 fmt << ":upper16:(";
637 else
638 fmt << ":lower16:(";
639 printRelocationTargetName(Obj, RE, fmt);
640
641 DataRefImpl RelNext = Rel;
642 Obj->moveRelocationNext(RelNext);
643 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
644
645 // ARM half relocs must be followed by a relocation of type
646 // ARM_RELOC_PAIR.
647 unsigned RType = Obj->getAnyRelocationType(RENext);
648 if (RType != MachO::ARM_RELOC_PAIR)
649 report_fatal_error("Expected ARM_RELOC_PAIR after "
650 "ARM_RELOC_HALF");
651
652 // NOTE: The half of the target virtual address is stashed in the
653 // address field of the secondary relocation, but we can't reverse
654 // engineer the constant offset from it without decoding the movw/movt
655 // instruction to find the other half in its immediate field.
656
657 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
658 // symbol/section pointer of the follow-on relocation.
659 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
660 fmt << "-";
661 printRelocationTargetName(Obj, RENext, fmt);
662 }
663
664 fmt << ")";
665 break;
666 }
667 default: { printRelocationTargetName(Obj, RE, fmt); }
668 }
669 }
670 } else
671 printRelocationTargetName(Obj, RE, fmt);
672
673 fmt.flush();
674 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000675 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000676}
677
678static std::error_code getRelocationValueString(const RelocationRef &Rel,
679 SmallVectorImpl<char> &Result) {
680 const ObjectFile *Obj = Rel.getObjectFile();
681 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
682 return getRelocationValueString(ELF, Rel, Result);
683 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
684 return getRelocationValueString(COFF, Rel, Result);
685 auto *MachO = cast<MachOObjectFile>(Obj);
686 return getRelocationValueString(MachO, Rel, Result);
687}
688
Michael J. Spencer51862b32011-10-13 22:17:18 +0000689static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000690 const Target *TheTarget = getTarget(Obj);
691 // getTarget() will have already issued a diagnostic if necessary, so
692 // just bail here if it failed.
693 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000694 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000695
Jack Carter551efd72012-08-28 19:24:49 +0000696 // Package up features to be passed to target/subtarget
697 std::string FeaturesStr;
698 if (MAttrs.size()) {
699 SubtargetFeatures Features;
700 for (unsigned i = 0; i != MAttrs.size(); ++i)
701 Features.AddFeature(MAttrs[i]);
702 FeaturesStr = Features.getString();
703 }
704
Ahmed Charles56440fd2014-03-06 05:51:42 +0000705 std::unique_ptr<const MCRegisterInfo> MRI(
706 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000707 if (!MRI) {
708 errs() << "error: no register info for target " << TripleName << "\n";
709 return;
710 }
711
712 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000713 std::unique_ptr<const MCAsmInfo> AsmInfo(
714 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000715 if (!AsmInfo) {
716 errs() << "error: no assembly info for target " << TripleName << "\n";
717 return;
718 }
719
Ahmed Charles56440fd2014-03-06 05:51:42 +0000720 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000721 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000722 if (!STI) {
723 errs() << "error: no subtarget info for target " << TripleName << "\n";
724 return;
725 }
726
Ahmed Charles56440fd2014-03-06 05:51:42 +0000727 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000728 if (!MII) {
729 errs() << "error: no instruction info for target " << TripleName << "\n";
730 return;
731 }
732
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000733 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
734 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
735
736 std::unique_ptr<MCDisassembler> DisAsm(
737 TheTarget->createMCDisassembler(*STI, Ctx));
738
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000739 if (!DisAsm) {
740 errs() << "error: no disassembler for target " << TripleName << "\n";
741 return;
742 }
743
Ahmed Charles56440fd2014-03-06 05:51:42 +0000744 std::unique_ptr<const MCInstrAnalysis> MIA(
745 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000746
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000747 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000748 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000749 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000750 if (!IP) {
751 errs() << "error: no instruction printer for target " << TripleName
752 << '\n';
753 return;
754 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000755 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000756 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000757
Greg Fitzgerald18432272014-03-20 22:55:15 +0000758 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
759 "\t\t\t%08" PRIx64 ": ";
760
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000761 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
762 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000763 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000764 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
765 for (const SectionRef &Section : Obj->sections()) {
766 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000767 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000768 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000769 }
770
Alexey Samsonov48803e52014-03-13 14:37:36 +0000771 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000772 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000773 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000774
Rafael Espindola80291272014-10-08 15:28:58 +0000775 uint64_t SectionAddr = Section.getAddress();
776 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000777 if (!SectSize)
778 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000779
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000780 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000781 std::vector<std::pair<uint64_t, StringRef>> Symbols;
782 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000783 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000784 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000785 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000786 break;
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000787 if (Address == UnknownAddress)
Mark Seaborneb03ac52014-01-25 00:32:01 +0000788 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000789 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000790 if (Address >= SectSize)
791 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000792
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000793 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000794 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000795 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000796 Symbols.push_back(std::make_pair(Address, Name));
797 }
798 }
799
800 // Sort the symbols by address, just in case they didn't come in that way.
801 array_pod_sort(Symbols.begin(), Symbols.end());
802
Michael J. Spencer51862b32011-10-13 22:17:18 +0000803 // Make a list of all the relocations for this section.
804 std::vector<RelocationRef> Rels;
805 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000806 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
807 for (const RelocationRef &Reloc : RelocSec.relocations()) {
808 Rels.push_back(Reloc);
809 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000810 }
811 }
812
813 // Sort relocations by address.
814 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
815
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000816 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000817 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000818 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000819 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000820 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000821 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000822 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000823 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000824 outs() << "Disassembly of section ";
825 if (!SegmentName.empty())
826 outs() << SegmentName << ",";
827 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000828
Rafael Espindola7884c952015-06-04 15:01:05 +0000829 // If the section has no symbol at the start, just insert a dummy one.
830 if (Symbols.empty() || Symbols[0].first != 0)
831 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000832
833 SmallString<40> Comments;
834 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000835
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000836 StringRef BytesStr;
837 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000838 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000839 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
840 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000841
Michael J. Spencer2670c252011-01-20 06:39:06 +0000842 uint64_t Size;
843 uint64_t Index;
844
Michael J. Spencer51862b32011-10-13 22:17:18 +0000845 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
846 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000847 // Disassemble symbol by symbol.
848 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000849
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000850 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000851 // The end is either the section end or the beginning of the next symbol.
852 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
853 // If this symbol has the same address as the next symbol, then skip it.
854 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000855 continue;
856
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000857 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000858
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000859#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000860 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000861#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000862 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000863#endif
864
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000865 for (Index = Start; Index < End; Index += Size) {
866 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000867
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000868 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
869 SectionAddr + Index, DebugOut,
870 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000871 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000872 Bytes.slice(Index, Size),
873 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000874 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000875 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000876 outs() << "\n";
877 } else {
878 errs() << ToolName << ": warning: invalid instruction encoding\n";
879 if (Size == 0)
880 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000881 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000882
883 // Print relocation for instruction.
884 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000885 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000886 uint64_t addr;
887 SmallString<16> name;
888 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000889
890 // If this relocation is hidden, skip it.
891 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
892 if (hidden) goto skip_print_rel;
893
Rafael Espindola1e483872013-04-25 12:28:45 +0000894 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000895 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000896 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000897 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
Rafael Espindola37070a52015-06-03 04:48:06 +0000898 if (error(getRelocationValueString(*rel_cur, val)))
899 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000900 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000901 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000902
903 skip_print_rel:
904 ++rel_cur;
905 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000906 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000907 }
908 }
909}
910
Kevin Enderby98da6132015-01-20 21:47:46 +0000911void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000912 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
913 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000914 // Regular objdump doesn't print relocations in non-relocatable object
915 // files.
916 if (!Obj->isRelocatableObject())
917 return;
918
Alexey Samsonov48803e52014-03-13 14:37:36 +0000919 for (const SectionRef &Section : Obj->sections()) {
920 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000921 continue;
922 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000923 if (error(Section.getName(secname)))
924 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000925 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000926 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000927 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000928 uint64_t address;
929 SmallString<32> relocname;
930 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000931 if (error(Reloc.getHidden(hidden)))
932 continue;
933 if (hidden)
934 continue;
935 if (error(Reloc.getTypeName(relocname)))
936 continue;
937 if (error(Reloc.getOffset(address)))
938 continue;
Rafael Espindola37070a52015-06-03 04:48:06 +0000939 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000940 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000941 outs() << format(Fmt.data(), address) << " " << relocname << " "
942 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000943 }
944 outs() << "\n";
945 }
946}
947
Kevin Enderby98da6132015-01-20 21:47:46 +0000948void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000949 outs() << "Sections:\n"
950 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000951 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000952 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000953 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000954 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000955 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000956 uint64_t Address = Section.getAddress();
957 uint64_t Size = Section.getSize();
958 bool Text = Section.isText();
959 bool Data = Section.isData();
960 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000961 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000962 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000963 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
964 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000965 ++i;
966 }
967}
968
Kevin Enderby98da6132015-01-20 21:47:46 +0000969void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000970 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000971 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000972 StringRef Name;
973 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000974 if (error(Section.getName(Name)))
975 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000976 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +0000977 uint64_t Size = Section.getSize();
978 if (!Size)
979 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000980
981 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +0000982 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +0000983 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000984 ", %04" PRIx64 ")>\n",
985 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000986 continue;
987 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000988
David Majnemer8f6b04c2014-07-14 16:20:14 +0000989 if (error(Section.getContents(Contents)))
990 continue;
991
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000992 // Dump out the content as hex and printable ascii characters.
993 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000994 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000995 // Dump line of hex.
996 for (std::size_t i = 0; i < 16; ++i) {
997 if (i != 0 && i % 4 == 0)
998 outs() << ' ';
999 if (addr + i < end)
1000 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1001 << hexdigit(Contents[addr + i] & 0xF, true);
1002 else
1003 outs() << " ";
1004 }
1005 // Print ascii.
1006 outs() << " ";
1007 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001008 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001009 outs() << Contents[addr + i];
1010 else
1011 outs() << ".";
1012 }
1013 outs() << "\n";
1014 }
1015 }
1016}
1017
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001018static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001019 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1020 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001021 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001022 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001023 return;
1024
David Majnemer44f51e52014-09-10 12:51:52 +00001025 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001026 return;
1027
1028 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001029 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001030 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001031 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1032 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1033 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1034 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001035 << Name << "\n";
1036
David Majnemer44f51e52014-09-10 12:51:52 +00001037 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001038 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001039 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001040 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001041 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001042
David Majnemer4d571592014-09-15 19:42:42 +00001043 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1044
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001045 outs() << "AUX "
1046 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1047 , unsigned(asd->Length)
1048 , unsigned(asd->NumberOfRelocations)
1049 , unsigned(asd->NumberOfLinenumbers)
1050 , unsigned(asd->CheckSum))
1051 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001052 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001053 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001054 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001055 const char *FileName;
1056 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001057 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001058
David Majnemer44f51e52014-09-10 12:51:52 +00001059 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1060 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001061 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001062
David Majnemer44f51e52014-09-10 12:51:52 +00001063 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001064 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001065 } else {
1066 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001067 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001068 }
1069 }
1070}
1071
Kevin Enderby98da6132015-01-20 21:47:46 +00001072void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001073 outs() << "SYMBOL TABLE:\n";
1074
Rui Ueyama4e39f712014-03-18 18:58:51 +00001075 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001076 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001077 return;
1078 }
1079 for (const SymbolRef &Symbol : o->symbols()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001080 uint64_t Address;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001081 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001082 uint32_t Flags = Symbol.getFlags();
1083 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001084 if (error(Symbol.getAddress(Address)))
1085 continue;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001086 if (error(Symbol.getSection(Section)))
1087 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001088 StringRef Name;
1089 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1090 Section->getName(Name);
1091 } else if (error(Symbol.getName(Name))) {
1092 continue;
1093 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001094
Rui Ueyama4e39f712014-03-18 18:58:51 +00001095 bool Global = Flags & SymbolRef::SF_Global;
1096 bool Weak = Flags & SymbolRef::SF_Weak;
1097 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001098 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001099 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001100
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001101 if (Common)
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001102 Address = Symbol.getCommonSize();
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001103
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001104 if (Address == UnknownAddress)
Rui Ueyama4e39f712014-03-18 18:58:51 +00001105 Address = 0;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001106 char GlobLoc = ' ';
1107 if (Type != SymbolRef::ST_Unknown)
1108 GlobLoc = Global ? 'g' : 'l';
1109 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1110 ? 'd' : ' ';
1111 char FileFunc = ' ';
1112 if (Type == SymbolRef::ST_File)
1113 FileFunc = 'f';
1114 else if (Type == SymbolRef::ST_Function)
1115 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001116
Rui Ueyama4e39f712014-03-18 18:58:51 +00001117 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1118 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001119
Rui Ueyama4e39f712014-03-18 18:58:51 +00001120 outs() << format(Fmt, Address) << " "
1121 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1122 << (Weak ? 'w' : ' ') // Weak?
1123 << ' ' // Constructor. Not supported yet.
1124 << ' ' // Warning. Not supported yet.
1125 << ' ' // Indirect reference to another symbol.
1126 << Debug // Debugging (d) or dynamic (D) symbol.
1127 << FileFunc // Name of function (F), file (f) or object (O).
1128 << ' ';
1129 if (Absolute) {
1130 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001131 } else if (Common) {
1132 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001133 } else if (Section == o->section_end()) {
1134 outs() << "*UND*";
1135 } else {
1136 if (const MachOObjectFile *MachO =
1137 dyn_cast<const MachOObjectFile>(o)) {
1138 DataRefImpl DR = Section->getRawDataRefImpl();
1139 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1140 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001141 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001142 StringRef SectionName;
1143 if (error(Section->getName(SectionName)))
1144 SectionName = "";
1145 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001146 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001147
1148 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001149 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001150 uint64_t Val =
1151 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001152 outs() << format("\t %08" PRIx64 " ", Val);
1153 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001154
Davide Italianocd2514d2015-04-30 23:08:53 +00001155 if (Hidden) {
1156 outs() << ".hidden ";
1157 }
1158 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001159 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001160 }
1161}
1162
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001163static void PrintUnwindInfo(const ObjectFile *o) {
1164 outs() << "Unwind info:\n\n";
1165
1166 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1167 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001168 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1169 printMachOUnwindInfo(MachO);
1170 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001171 // TODO: Extract DWARF dump tool to objdump.
1172 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001173 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001174 return;
1175 }
1176}
1177
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001178void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001179 outs() << "Exports trie:\n";
1180 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1181 printMachOExportsTrie(MachO);
1182 else {
1183 errs() << "This operation is only currently supported "
1184 "for Mach-O executable files.\n";
1185 return;
1186 }
1187}
1188
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001189void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001190 outs() << "Rebase table:\n";
1191 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1192 printMachORebaseTable(MachO);
1193 else {
1194 errs() << "This operation is only currently supported "
1195 "for Mach-O executable files.\n";
1196 return;
1197 }
1198}
1199
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001200void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001201 outs() << "Bind table:\n";
1202 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1203 printMachOBindTable(MachO);
1204 else {
1205 errs() << "This operation is only currently supported "
1206 "for Mach-O executable files.\n";
1207 return;
1208 }
1209}
1210
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001211void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001212 outs() << "Lazy bind table:\n";
1213 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1214 printMachOLazyBindTable(MachO);
1215 else {
1216 errs() << "This operation is only currently supported "
1217 "for Mach-O executable files.\n";
1218 return;
1219 }
1220}
1221
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001222void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001223 outs() << "Weak bind table:\n";
1224 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1225 printMachOWeakBindTable(MachO);
1226 else {
1227 errs() << "This operation is only currently supported "
1228 "for Mach-O executable files.\n";
1229 return;
1230 }
1231}
Nick Kledzikac431442014-09-12 21:34:15 +00001232
Sanjoy Das6f567a42015-06-22 18:03:02 +00001233static void printFaultMaps(const ObjectFile *Obj) {
1234 const char *FaultMapSectionName = nullptr;
1235
1236 if (isa<ELFObjectFileBase>(Obj)) {
1237 FaultMapSectionName = ".llvm_faultmaps";
1238 } else if (isa<MachOObjectFile>(Obj)) {
1239 FaultMapSectionName = "__llvm_faultmaps";
1240 } else {
1241 errs() << "This operation is only currently supported "
1242 "for ELF and Mach-O executable files.\n";
1243 return;
1244 }
1245
1246 Optional<object::SectionRef> FaultMapSection;
1247
1248 for (auto Sec : Obj->sections()) {
1249 StringRef Name;
1250 Sec.getName(Name);
1251 if (Name == FaultMapSectionName) {
1252 FaultMapSection = Sec;
1253 break;
1254 }
1255 }
1256
1257 outs() << "FaultMap table:\n";
1258
1259 if (!FaultMapSection.hasValue()) {
1260 outs() << "<not found>\n";
1261 return;
1262 }
1263
1264 StringRef FaultMapContents;
1265 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1266 errs() << "Could not read the " << FaultMapContents << " section!\n";
1267 return;
1268 }
1269
1270 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1271 FaultMapContents.bytes_end());
1272
1273 outs() << FMP;
1274}
1275
Rui Ueyamac2bed422013-09-27 21:04:00 +00001276static void printPrivateFileHeader(const ObjectFile *o) {
1277 if (o->isELF()) {
1278 printELFFileHeader(o);
1279 } else if (o->isCOFF()) {
1280 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001281 } else if (o->isMachO()) {
1282 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001283 }
1284}
1285
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001286static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001287 outs() << '\n';
1288 outs() << o->getFileName()
1289 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1290
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001291 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001292 DisassembleObject(o, Relocations);
1293 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001294 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001295 if (SectionHeaders)
1296 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001297 if (SectionContents)
1298 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001299 if (SymbolTable)
1300 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001301 if (UnwindInfo)
1302 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001303 if (PrivateHeaders)
1304 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001305 if (ExportsTrie)
1306 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001307 if (Rebase)
1308 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001309 if (Bind)
1310 printBindTable(o);
1311 if (LazyBind)
1312 printLazyBindTable(o);
1313 if (WeakBind)
1314 printWeakBindTable(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001315 if (PrintFaultMaps)
1316 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001317}
1318
1319/// @brief Dump each object file in \a a;
1320static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001321 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1322 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001323 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1324 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001325 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001326 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001327 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001328 continue;
1329 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001330 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001331 DumpObject(o);
1332 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001333 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001334 }
1335}
1336
1337/// @brief Open file and figure out how to dump it.
1338static void DumpInput(StringRef file) {
1339 // If file isn't stdin, check that it exists.
1340 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001341 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001342 return;
1343 }
1344
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001345 // If we are using the Mach-O specific object file parser, then let it parse
1346 // the file and process the command line options. So the -arch flags can
1347 // be used to select specific slices, etc.
1348 if (MachOOpt) {
1349 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001350 return;
1351 }
1352
1353 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001354 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001355 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001356 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001357 return;
1358 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001359 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001360
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001361 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001362 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001363 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001364 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001365 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001366 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001367}
1368
Michael J. Spencer2670c252011-01-20 06:39:06 +00001369int main(int argc, char **argv) {
1370 // Print a stack trace if we signal out.
1371 sys::PrintStackTraceOnErrorSignal();
1372 PrettyStackTraceProgram X(argc, argv);
1373 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1374
1375 // Initialize targets and assembly printers/parsers.
1376 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001377 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001378 llvm::InitializeAllAsmParsers();
1379 llvm::InitializeAllDisassemblers();
1380
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001381 // Register the target printer for --version.
1382 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1383
Michael J. Spencer2670c252011-01-20 06:39:06 +00001384 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1385 TripleName = Triple::normalize(TripleName);
1386
1387 ToolName = argv[0];
1388
1389 // Defaults to a.out if no filenames specified.
1390 if (InputFilenames.size() == 0)
1391 InputFilenames.push_back("a.out");
1392
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001393 if (!Disassemble
1394 && !Relocations
1395 && !SectionHeaders
1396 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001397 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001398 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001399 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001400 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001401 && !Rebase
1402 && !Bind
1403 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001404 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001405 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001406 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001407 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001408 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001409 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001410 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001411 && !(DylibsUsed && MachOOpt)
1412 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001413 && !(ObjcMetaData && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001414 && !(DumpSections.size() != 0 && MachOOpt)
1415 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001416 cl::PrintHelpMessage();
1417 return 2;
1418 }
1419
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001420 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1421 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001422
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001423 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001424}