blob: 6282c5172b6c5fcf6d92d1b9ac7c9f7bb7511cb5 [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) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000215 uint64_t a_addr = a.getOffset();
216 uint64_t b_addr = b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000217 return a_addr < b_addr;
218}
219
Colin LeMahieufb76b002015-05-28 19:07:14 +0000220namespace {
221class PrettyPrinter {
222public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000223 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000224 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000225 ArrayRef<uint8_t> Bytes, uint64_t Address,
226 raw_ostream &OS, StringRef Annot,
227 MCSubtargetInfo const &STI) {
228 outs() << format("%8" PRIx64 ":", Address);
229 if (!NoShowRawInsn) {
230 outs() << "\t";
231 dumpBytes(Bytes, outs());
232 }
233 IP.printInst(MI, outs(), "", STI);
234 }
235};
236PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000237class HexagonPrettyPrinter : public PrettyPrinter {
238public:
239 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
240 raw_ostream &OS) {
241 uint32_t opcode =
242 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
243 OS << format("%8" PRIx64 ":", Address);
244 if (!NoShowRawInsn) {
245 OS << "\t";
246 dumpBytes(Bytes.slice(0, 4), OS);
247 OS << format("%08" PRIx32, opcode);
248 }
249 }
250 void printInst(MCInstPrinter &IP, const MCInst *MI,
251 ArrayRef<uint8_t> Bytes, uint64_t Address,
252 raw_ostream &OS, StringRef Annot,
253 MCSubtargetInfo const &STI) override {
254 std::string Buffer;
255 {
256 raw_string_ostream TempStream(Buffer);
257 IP.printInst(MI, TempStream, "", STI);
258 }
259 StringRef Contents(Buffer);
260 // Split off bundle attributes
261 auto PacketBundle = Contents.rsplit('\n');
262 // Split off first instruction from the rest
263 auto HeadTail = PacketBundle.first.split('\n');
264 auto Preamble = " { ";
265 auto Separator = "";
266 while(!HeadTail.first.empty()) {
267 OS << Separator;
268 Separator = "\n";
269 printLead(Bytes, Address, OS);
270 OS << Preamble;
271 Preamble = " ";
272 StringRef Inst;
273 auto Duplex = HeadTail.first.split('\v');
274 if(!Duplex.second.empty()){
275 OS << Duplex.first;
276 OS << "; ";
277 Inst = Duplex.second;
278 }
279 else
280 Inst = HeadTail.first;
281 OS << Inst;
282 Bytes = Bytes.slice(4);
283 Address += 4;
284 HeadTail = HeadTail.second.split('\n');
285 }
286 OS << " } " << PacketBundle.second;
287 }
288};
289HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000290PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000291 switch(Triple.getArch()) {
292 default:
293 return PrettyPrinterInst;
294 case Triple::hexagon:
295 return HexagonPrettyPrinterInst;
296 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000297}
298}
299
Rafael Espindola37070a52015-06-03 04:48:06 +0000300template <class ELFT>
301static const typename ELFObjectFile<ELFT>::Elf_Rel *
302getRel(const ELFFile<ELFT> &EF, DataRefImpl Rel) {
303 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
304 return EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
305}
306
307template <class ELFT>
308static const typename ELFObjectFile<ELFT>::Elf_Rela *
309getRela(const ELFFile<ELFT> &EF, DataRefImpl Rela) {
310 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
311 return EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
312}
313
314template <class ELFT>
315static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
316 DataRefImpl Rel,
317 SmallVectorImpl<char> &Result) {
318 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
319 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
320 const ELFFile<ELFT> &EF = *Obj->getELFFile();
321
322 const Elf_Shdr *sec = EF.getSection(Rel.d.a);
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000323 const Elf_Shdr *SymTab = EF.getSection(sec->sh_link);
324 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
325 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000326 const Elf_Shdr *StrTabSec = EF.getSection(SymTab->sh_link);
327 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(StrTabSec);
328 if (std::error_code EC = StrTabOrErr.getError())
329 return EC;
330 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000331 uint8_t type;
332 StringRef res;
333 int64_t addend = 0;
334 uint16_t symbol_index = 0;
335 switch (sec->sh_type) {
336 default:
337 return object_error::parse_failed;
338 case ELF::SHT_REL: {
339 type = getRel(EF, Rel)->getType(EF.isMips64EL());
340 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
341 // TODO: Read implicit addend from section data.
342 break;
343 }
344 case ELF::SHT_RELA: {
345 type = getRela(EF, Rel)->getType(EF.isMips64EL());
346 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
347 addend = getRela(EF, Rel)->r_addend;
348 break;
349 }
350 }
351 const Elf_Sym *symb =
352 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000353 StringRef Target;
354 const Elf_Shdr *SymSec = EF.getSection(symb);
355 if (symb->getType() == ELF::STT_SECTION) {
356 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
357 if (std::error_code EC = SecName.getError())
358 return EC;
359 Target = *SecName;
360 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000361 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000362 if (!SymName)
363 return SymName.getError();
364 Target = *SymName;
365 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000366 switch (EF.getHeader()->e_machine) {
367 case ELF::EM_X86_64:
368 switch (type) {
369 case ELF::R_X86_64_PC8:
370 case ELF::R_X86_64_PC16:
371 case ELF::R_X86_64_PC32: {
372 std::string fmtbuf;
373 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000374 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000375 fmt.flush();
376 Result.append(fmtbuf.begin(), fmtbuf.end());
377 } break;
378 case ELF::R_X86_64_8:
379 case ELF::R_X86_64_16:
380 case ELF::R_X86_64_32:
381 case ELF::R_X86_64_32S:
382 case ELF::R_X86_64_64: {
383 std::string fmtbuf;
384 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000385 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000386 fmt.flush();
387 Result.append(fmtbuf.begin(), fmtbuf.end());
388 } break;
389 default:
390 res = "Unknown";
391 }
392 break;
393 case ELF::EM_AARCH64: {
394 std::string fmtbuf;
395 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000396 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000397 if (addend != 0)
398 fmt << (addend < 0 ? "" : "+") << addend;
399 fmt.flush();
400 Result.append(fmtbuf.begin(), fmtbuf.end());
401 break;
402 }
403 case ELF::EM_386:
404 case ELF::EM_ARM:
405 case ELF::EM_HEXAGON:
406 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000407 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000408 break;
409 default:
410 res = "Unknown";
411 }
412 if (Result.empty())
413 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000414 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000415}
416
417static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
418 const RelocationRef &RelRef,
419 SmallVectorImpl<char> &Result) {
420 DataRefImpl Rel = RelRef.getRawDataRefImpl();
421 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
422 return getRelocationValueString(ELF32LE, Rel, Result);
423 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
424 return getRelocationValueString(ELF64LE, Rel, Result);
425 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
426 return getRelocationValueString(ELF32BE, Rel, Result);
427 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
428 return getRelocationValueString(ELF64BE, Rel, Result);
429}
430
431static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
432 const RelocationRef &Rel,
433 SmallVectorImpl<char> &Result) {
434 symbol_iterator SymI = Rel.getSymbol();
435 StringRef SymName;
436 if (std::error_code EC = SymI->getName(SymName))
437 return EC;
438 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000439 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000440}
441
442static void printRelocationTargetName(const MachOObjectFile *O,
443 const MachO::any_relocation_info &RE,
444 raw_string_ostream &fmt) {
445 bool IsScattered = O->isRelocationScattered(RE);
446
447 // Target of a scattered relocation is an address. In the interest of
448 // generating pretty output, scan through the symbol table looking for a
449 // symbol that aligns with that address. If we find one, print it.
450 // Otherwise, we just print the hex address of the target.
451 if (IsScattered) {
452 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
453
454 for (const SymbolRef &Symbol : O->symbols()) {
455 std::error_code ec;
456 uint64_t Addr;
457 StringRef Name;
458
459 if ((ec = Symbol.getAddress(Addr)))
460 report_fatal_error(ec.message());
461 if (Addr != Val)
462 continue;
463 if ((ec = Symbol.getName(Name)))
464 report_fatal_error(ec.message());
465 fmt << Name;
466 return;
467 }
468
469 // If we couldn't find a symbol that this relocation refers to, try
470 // to find a section beginning instead.
471 for (const SectionRef &Section : O->sections()) {
472 std::error_code ec;
473
474 StringRef Name;
475 uint64_t Addr = Section.getAddress();
476 if (Addr != Val)
477 continue;
478 if ((ec = Section.getName(Name)))
479 report_fatal_error(ec.message());
480 fmt << Name;
481 return;
482 }
483
484 fmt << format("0x%x", Val);
485 return;
486 }
487
488 StringRef S;
489 bool isExtern = O->getPlainRelocationExternal(RE);
490 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
491
492 if (isExtern) {
493 symbol_iterator SI = O->symbol_begin();
494 advance(SI, Val);
495 SI->getName(S);
496 } else {
497 section_iterator SI = O->section_begin();
498 // Adjust for the fact that sections are 1-indexed.
499 advance(SI, Val - 1);
500 SI->getName(S);
501 }
502
503 fmt << S;
504}
505
506static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
507 const RelocationRef &RelRef,
508 SmallVectorImpl<char> &Result) {
509 DataRefImpl Rel = RelRef.getRawDataRefImpl();
510 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
511
512 unsigned Arch = Obj->getArch();
513
514 std::string fmtbuf;
515 raw_string_ostream fmt(fmtbuf);
516 unsigned Type = Obj->getAnyRelocationType(RE);
517 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
518
519 // Determine any addends that should be displayed with the relocation.
520 // These require decoding the relocation type, which is triple-specific.
521
522 // X86_64 has entirely custom relocation types.
523 if (Arch == Triple::x86_64) {
524 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
525
526 switch (Type) {
527 case MachO::X86_64_RELOC_GOT_LOAD:
528 case MachO::X86_64_RELOC_GOT: {
529 printRelocationTargetName(Obj, RE, fmt);
530 fmt << "@GOT";
531 if (isPCRel)
532 fmt << "PCREL";
533 break;
534 }
535 case MachO::X86_64_RELOC_SUBTRACTOR: {
536 DataRefImpl RelNext = Rel;
537 Obj->moveRelocationNext(RelNext);
538 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
539
540 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
541 // X86_64_RELOC_UNSIGNED.
542 // NOTE: Scattered relocations don't exist on x86_64.
543 unsigned RType = Obj->getAnyRelocationType(RENext);
544 if (RType != MachO::X86_64_RELOC_UNSIGNED)
545 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
546 "X86_64_RELOC_SUBTRACTOR.");
547
548 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
549 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
550 printRelocationTargetName(Obj, RENext, fmt);
551 fmt << "-";
552 printRelocationTargetName(Obj, RE, fmt);
553 break;
554 }
555 case MachO::X86_64_RELOC_TLV:
556 printRelocationTargetName(Obj, RE, fmt);
557 fmt << "@TLV";
558 if (isPCRel)
559 fmt << "P";
560 break;
561 case MachO::X86_64_RELOC_SIGNED_1:
562 printRelocationTargetName(Obj, RE, fmt);
563 fmt << "-1";
564 break;
565 case MachO::X86_64_RELOC_SIGNED_2:
566 printRelocationTargetName(Obj, RE, fmt);
567 fmt << "-2";
568 break;
569 case MachO::X86_64_RELOC_SIGNED_4:
570 printRelocationTargetName(Obj, RE, fmt);
571 fmt << "-4";
572 break;
573 default:
574 printRelocationTargetName(Obj, RE, fmt);
575 break;
576 }
577 // X86 and ARM share some relocation types in common.
578 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
579 Arch == Triple::ppc) {
580 // Generic relocation types...
581 switch (Type) {
582 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000583 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000584 case MachO::GENERIC_RELOC_SECTDIFF: {
585 DataRefImpl RelNext = Rel;
586 Obj->moveRelocationNext(RelNext);
587 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
588
589 // X86 sect diff's must be followed by a relocation of type
590 // GENERIC_RELOC_PAIR.
591 unsigned RType = Obj->getAnyRelocationType(RENext);
592
593 if (RType != MachO::GENERIC_RELOC_PAIR)
594 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
595 "GENERIC_RELOC_SECTDIFF.");
596
597 printRelocationTargetName(Obj, RE, fmt);
598 fmt << "-";
599 printRelocationTargetName(Obj, RENext, fmt);
600 break;
601 }
602 }
603
604 if (Arch == Triple::x86 || Arch == Triple::ppc) {
605 switch (Type) {
606 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
607 DataRefImpl RelNext = Rel;
608 Obj->moveRelocationNext(RelNext);
609 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
610
611 // X86 sect diff's must be followed by a relocation of type
612 // GENERIC_RELOC_PAIR.
613 unsigned RType = Obj->getAnyRelocationType(RENext);
614 if (RType != MachO::GENERIC_RELOC_PAIR)
615 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
616 "GENERIC_RELOC_LOCAL_SECTDIFF.");
617
618 printRelocationTargetName(Obj, RE, fmt);
619 fmt << "-";
620 printRelocationTargetName(Obj, RENext, fmt);
621 break;
622 }
623 case MachO::GENERIC_RELOC_TLV: {
624 printRelocationTargetName(Obj, RE, fmt);
625 fmt << "@TLV";
626 if (IsPCRel)
627 fmt << "P";
628 break;
629 }
630 default:
631 printRelocationTargetName(Obj, RE, fmt);
632 }
633 } else { // ARM-specific relocations
634 switch (Type) {
635 case MachO::ARM_RELOC_HALF:
636 case MachO::ARM_RELOC_HALF_SECTDIFF: {
637 // Half relocations steal a bit from the length field to encode
638 // whether this is an upper16 or a lower16 relocation.
639 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
640
641 if (isUpper)
642 fmt << ":upper16:(";
643 else
644 fmt << ":lower16:(";
645 printRelocationTargetName(Obj, RE, fmt);
646
647 DataRefImpl RelNext = Rel;
648 Obj->moveRelocationNext(RelNext);
649 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
650
651 // ARM half relocs must be followed by a relocation of type
652 // ARM_RELOC_PAIR.
653 unsigned RType = Obj->getAnyRelocationType(RENext);
654 if (RType != MachO::ARM_RELOC_PAIR)
655 report_fatal_error("Expected ARM_RELOC_PAIR after "
656 "ARM_RELOC_HALF");
657
658 // NOTE: The half of the target virtual address is stashed in the
659 // address field of the secondary relocation, but we can't reverse
660 // engineer the constant offset from it without decoding the movw/movt
661 // instruction to find the other half in its immediate field.
662
663 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
664 // symbol/section pointer of the follow-on relocation.
665 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
666 fmt << "-";
667 printRelocationTargetName(Obj, RENext, fmt);
668 }
669
670 fmt << ")";
671 break;
672 }
673 default: { printRelocationTargetName(Obj, RE, fmt); }
674 }
675 }
676 } else
677 printRelocationTargetName(Obj, RE, fmt);
678
679 fmt.flush();
680 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000681 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000682}
683
684static std::error_code getRelocationValueString(const RelocationRef &Rel,
685 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000686 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000687 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
688 return getRelocationValueString(ELF, Rel, Result);
689 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
690 return getRelocationValueString(COFF, Rel, Result);
691 auto *MachO = cast<MachOObjectFile>(Obj);
692 return getRelocationValueString(MachO, Rel, Result);
693}
694
Michael J. Spencer51862b32011-10-13 22:17:18 +0000695static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000696 const Target *TheTarget = getTarget(Obj);
697 // getTarget() will have already issued a diagnostic if necessary, so
698 // just bail here if it failed.
699 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000700 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000701
Jack Carter551efd72012-08-28 19:24:49 +0000702 // Package up features to be passed to target/subtarget
703 std::string FeaturesStr;
704 if (MAttrs.size()) {
705 SubtargetFeatures Features;
706 for (unsigned i = 0; i != MAttrs.size(); ++i)
707 Features.AddFeature(MAttrs[i]);
708 FeaturesStr = Features.getString();
709 }
710
Ahmed Charles56440fd2014-03-06 05:51:42 +0000711 std::unique_ptr<const MCRegisterInfo> MRI(
712 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000713 if (!MRI) {
714 errs() << "error: no register info for target " << TripleName << "\n";
715 return;
716 }
717
718 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000719 std::unique_ptr<const MCAsmInfo> AsmInfo(
720 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000721 if (!AsmInfo) {
722 errs() << "error: no assembly info for target " << TripleName << "\n";
723 return;
724 }
725
Ahmed Charles56440fd2014-03-06 05:51:42 +0000726 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000727 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000728 if (!STI) {
729 errs() << "error: no subtarget info for target " << TripleName << "\n";
730 return;
731 }
732
Ahmed Charles56440fd2014-03-06 05:51:42 +0000733 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000734 if (!MII) {
735 errs() << "error: no instruction info for target " << TripleName << "\n";
736 return;
737 }
738
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000739 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
740 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
741
742 std::unique_ptr<MCDisassembler> DisAsm(
743 TheTarget->createMCDisassembler(*STI, Ctx));
744
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000745 if (!DisAsm) {
746 errs() << "error: no disassembler for target " << TripleName << "\n";
747 return;
748 }
749
Ahmed Charles56440fd2014-03-06 05:51:42 +0000750 std::unique_ptr<const MCInstrAnalysis> MIA(
751 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000752
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000753 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000754 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000755 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000756 if (!IP) {
757 errs() << "error: no instruction printer for target " << TripleName
758 << '\n';
759 return;
760 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000761 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000762 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000763
Greg Fitzgerald18432272014-03-20 22:55:15 +0000764 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
765 "\t\t\t%08" PRIx64 ": ";
766
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000767 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
768 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000769 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000770 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
771 for (const SectionRef &Section : Obj->sections()) {
772 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000773 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000774 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000775 }
776
Alexey Samsonov48803e52014-03-13 14:37:36 +0000777 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000778 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000779 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000780
Rafael Espindola80291272014-10-08 15:28:58 +0000781 uint64_t SectionAddr = Section.getAddress();
782 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000783 if (!SectSize)
784 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000785
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000786 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000787 std::vector<std::pair<uint64_t, StringRef>> Symbols;
788 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000789 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000790 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000791 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000792 break;
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000793 if (Address == UnknownAddress)
Mark Seaborneb03ac52014-01-25 00:32:01 +0000794 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000795 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000796 if (Address >= SectSize)
797 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000798
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000799 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000800 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000801 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000802 Symbols.push_back(std::make_pair(Address, Name));
803 }
804 }
805
806 // Sort the symbols by address, just in case they didn't come in that way.
807 array_pod_sort(Symbols.begin(), Symbols.end());
808
Michael J. Spencer51862b32011-10-13 22:17:18 +0000809 // Make a list of all the relocations for this section.
810 std::vector<RelocationRef> Rels;
811 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000812 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
813 for (const RelocationRef &Reloc : RelocSec.relocations()) {
814 Rels.push_back(Reloc);
815 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000816 }
817 }
818
819 // Sort relocations by address.
820 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
821
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000822 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000823 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000824 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000825 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000826 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000827 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000828 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000829 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000830 outs() << "Disassembly of section ";
831 if (!SegmentName.empty())
832 outs() << SegmentName << ",";
833 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000834
Rafael Espindola7884c952015-06-04 15:01:05 +0000835 // If the section has no symbol at the start, just insert a dummy one.
836 if (Symbols.empty() || Symbols[0].first != 0)
837 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000838
839 SmallString<40> Comments;
840 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000841
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000842 StringRef BytesStr;
843 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000844 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000845 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
846 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000847
Michael J. Spencer2670c252011-01-20 06:39:06 +0000848 uint64_t Size;
849 uint64_t Index;
850
Michael J. Spencer51862b32011-10-13 22:17:18 +0000851 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
852 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000853 // Disassemble symbol by symbol.
854 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000855
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000856 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000857 // The end is either the section end or the beginning of the next symbol.
858 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
859 // If this symbol has the same address as the next symbol, then skip it.
860 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000861 continue;
862
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000863 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000864
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000865#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000866 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000867#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000868 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000869#endif
870
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000871 for (Index = Start; Index < End; Index += Size) {
872 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000873
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000874 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
875 SectionAddr + Index, DebugOut,
876 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000877 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000878 Bytes.slice(Index, Size),
879 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000880 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000881 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000882 outs() << "\n";
883 } else {
884 errs() << ToolName << ": warning: invalid instruction encoding\n";
885 if (Size == 0)
886 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000887 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000888
889 // Print relocation for instruction.
890 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000891 bool hidden = false;
Rafael Espindola96d071c2015-06-29 23:29:12 +0000892 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000893 SmallString<16> name;
894 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000895
896 // If this relocation is hidden, skip it.
897 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
898 if (hidden) goto skip_print_rel;
899
Michael J. Spencer51862b32011-10-13 22:17:18 +0000900 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000901 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000902 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
Rafael Espindola37070a52015-06-03 04:48:06 +0000903 if (error(getRelocationValueString(*rel_cur, val)))
904 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000905 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000906 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000907
908 skip_print_rel:
909 ++rel_cur;
910 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000911 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000912 }
913 }
914}
915
Kevin Enderby98da6132015-01-20 21:47:46 +0000916void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000917 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
918 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000919 // Regular objdump doesn't print relocations in non-relocatable object
920 // files.
921 if (!Obj->isRelocatableObject())
922 return;
923
Alexey Samsonov48803e52014-03-13 14:37:36 +0000924 for (const SectionRef &Section : Obj->sections()) {
925 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000926 continue;
927 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000928 if (error(Section.getName(secname)))
929 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000930 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000931 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000932 bool hidden;
Rafael Espindola96d071c2015-06-29 23:29:12 +0000933 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000934 SmallString<32> relocname;
935 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000936 if (error(Reloc.getHidden(hidden)))
937 continue;
938 if (hidden)
939 continue;
940 if (error(Reloc.getTypeName(relocname)))
941 continue;
Rafael Espindola37070a52015-06-03 04:48:06 +0000942 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000943 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000944 outs() << format(Fmt.data(), address) << " " << relocname << " "
945 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000946 }
947 outs() << "\n";
948 }
949}
950
Kevin Enderby98da6132015-01-20 21:47:46 +0000951void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000952 outs() << "Sections:\n"
953 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000954 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000955 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000956 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000957 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000958 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000959 uint64_t Address = Section.getAddress();
960 uint64_t Size = Section.getSize();
961 bool Text = Section.isText();
962 bool Data = Section.isData();
963 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000964 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000965 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000966 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
967 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000968 ++i;
969 }
970}
971
Kevin Enderby98da6132015-01-20 21:47:46 +0000972void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000973 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000974 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000975 StringRef Name;
976 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000977 if (error(Section.getName(Name)))
978 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000979 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +0000980 uint64_t Size = Section.getSize();
981 if (!Size)
982 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000983
984 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +0000985 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +0000986 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000987 ", %04" PRIx64 ")>\n",
988 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000989 continue;
990 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000991
David Majnemer8f6b04c2014-07-14 16:20:14 +0000992 if (error(Section.getContents(Contents)))
993 continue;
994
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000995 // Dump out the content as hex and printable ascii characters.
996 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +0000997 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000998 // Dump line of hex.
999 for (std::size_t i = 0; i < 16; ++i) {
1000 if (i != 0 && i % 4 == 0)
1001 outs() << ' ';
1002 if (addr + i < end)
1003 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1004 << hexdigit(Contents[addr + i] & 0xF, true);
1005 else
1006 outs() << " ";
1007 }
1008 // Print ascii.
1009 outs() << " ";
1010 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001011 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001012 outs() << Contents[addr + i];
1013 else
1014 outs() << ".";
1015 }
1016 outs() << "\n";
1017 }
1018 }
1019}
1020
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001021static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001022 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1023 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001024 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001025 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001026 return;
1027
David Majnemer44f51e52014-09-10 12:51:52 +00001028 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001029 return;
1030
1031 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001032 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001033 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001034 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1035 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1036 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1037 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001038 << Name << "\n";
1039
David Majnemer44f51e52014-09-10 12:51:52 +00001040 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001041 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001042 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001043 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001044 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001045
David Majnemer4d571592014-09-15 19:42:42 +00001046 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1047
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001048 outs() << "AUX "
1049 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1050 , unsigned(asd->Length)
1051 , unsigned(asd->NumberOfRelocations)
1052 , unsigned(asd->NumberOfLinenumbers)
1053 , unsigned(asd->CheckSum))
1054 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001055 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001056 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001057 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001058 const char *FileName;
1059 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001060 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001061
David Majnemer44f51e52014-09-10 12:51:52 +00001062 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1063 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001064 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001065
David Majnemer44f51e52014-09-10 12:51:52 +00001066 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001067 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001068 } else {
1069 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001070 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001071 }
1072 }
1073}
1074
Kevin Enderby98da6132015-01-20 21:47:46 +00001075void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001076 outs() << "SYMBOL TABLE:\n";
1077
Rui Ueyama4e39f712014-03-18 18:58:51 +00001078 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001079 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001080 return;
1081 }
1082 for (const SymbolRef &Symbol : o->symbols()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001083 uint64_t Address;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001084 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001085 uint32_t Flags = Symbol.getFlags();
1086 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001087 if (error(Symbol.getAddress(Address)))
1088 continue;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001089 if (error(Symbol.getSection(Section)))
1090 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001091 StringRef Name;
1092 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1093 Section->getName(Name);
1094 } else if (error(Symbol.getName(Name))) {
1095 continue;
1096 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001097
Rui Ueyama4e39f712014-03-18 18:58:51 +00001098 bool Global = Flags & SymbolRef::SF_Global;
1099 bool Weak = Flags & SymbolRef::SF_Weak;
1100 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001101 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001102 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001103
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001104 if (Common)
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001105 Address = Symbol.getCommonSize();
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001106
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001107 if (Address == UnknownAddress)
Rui Ueyama4e39f712014-03-18 18:58:51 +00001108 Address = 0;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001109 char GlobLoc = ' ';
1110 if (Type != SymbolRef::ST_Unknown)
1111 GlobLoc = Global ? 'g' : 'l';
1112 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1113 ? 'd' : ' ';
1114 char FileFunc = ' ';
1115 if (Type == SymbolRef::ST_File)
1116 FileFunc = 'f';
1117 else if (Type == SymbolRef::ST_Function)
1118 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001119
Rui Ueyama4e39f712014-03-18 18:58:51 +00001120 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1121 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001122
Rui Ueyama4e39f712014-03-18 18:58:51 +00001123 outs() << format(Fmt, Address) << " "
1124 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1125 << (Weak ? 'w' : ' ') // Weak?
1126 << ' ' // Constructor. Not supported yet.
1127 << ' ' // Warning. Not supported yet.
1128 << ' ' // Indirect reference to another symbol.
1129 << Debug // Debugging (d) or dynamic (D) symbol.
1130 << FileFunc // Name of function (F), file (f) or object (O).
1131 << ' ';
1132 if (Absolute) {
1133 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001134 } else if (Common) {
1135 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001136 } else if (Section == o->section_end()) {
1137 outs() << "*UND*";
1138 } else {
1139 if (const MachOObjectFile *MachO =
1140 dyn_cast<const MachOObjectFile>(o)) {
1141 DataRefImpl DR = Section->getRawDataRefImpl();
1142 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1143 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001144 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001145 StringRef SectionName;
1146 if (error(Section->getName(SectionName)))
1147 SectionName = "";
1148 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001149 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001150
1151 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001152 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001153 uint64_t Val =
1154 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001155 outs() << format("\t %08" PRIx64 " ", Val);
1156 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001157
Davide Italianocd2514d2015-04-30 23:08:53 +00001158 if (Hidden) {
1159 outs() << ".hidden ";
1160 }
1161 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001162 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001163 }
1164}
1165
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001166static void PrintUnwindInfo(const ObjectFile *o) {
1167 outs() << "Unwind info:\n\n";
1168
1169 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1170 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001171 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1172 printMachOUnwindInfo(MachO);
1173 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001174 // TODO: Extract DWARF dump tool to objdump.
1175 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001176 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001177 return;
1178 }
1179}
1180
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001181void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001182 outs() << "Exports trie:\n";
1183 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1184 printMachOExportsTrie(MachO);
1185 else {
1186 errs() << "This operation is only currently supported "
1187 "for Mach-O executable files.\n";
1188 return;
1189 }
1190}
1191
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001192void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001193 outs() << "Rebase table:\n";
1194 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1195 printMachORebaseTable(MachO);
1196 else {
1197 errs() << "This operation is only currently supported "
1198 "for Mach-O executable files.\n";
1199 return;
1200 }
1201}
1202
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001203void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001204 outs() << "Bind table:\n";
1205 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1206 printMachOBindTable(MachO);
1207 else {
1208 errs() << "This operation is only currently supported "
1209 "for Mach-O executable files.\n";
1210 return;
1211 }
1212}
1213
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001214void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001215 outs() << "Lazy bind table:\n";
1216 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1217 printMachOLazyBindTable(MachO);
1218 else {
1219 errs() << "This operation is only currently supported "
1220 "for Mach-O executable files.\n";
1221 return;
1222 }
1223}
1224
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001225void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001226 outs() << "Weak bind table:\n";
1227 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1228 printMachOWeakBindTable(MachO);
1229 else {
1230 errs() << "This operation is only currently supported "
1231 "for Mach-O executable files.\n";
1232 return;
1233 }
1234}
Nick Kledzikac431442014-09-12 21:34:15 +00001235
Sanjoy Das6f567a42015-06-22 18:03:02 +00001236static void printFaultMaps(const ObjectFile *Obj) {
1237 const char *FaultMapSectionName = nullptr;
1238
1239 if (isa<ELFObjectFileBase>(Obj)) {
1240 FaultMapSectionName = ".llvm_faultmaps";
1241 } else if (isa<MachOObjectFile>(Obj)) {
1242 FaultMapSectionName = "__llvm_faultmaps";
1243 } else {
1244 errs() << "This operation is only currently supported "
1245 "for ELF and Mach-O executable files.\n";
1246 return;
1247 }
1248
1249 Optional<object::SectionRef> FaultMapSection;
1250
1251 for (auto Sec : Obj->sections()) {
1252 StringRef Name;
1253 Sec.getName(Name);
1254 if (Name == FaultMapSectionName) {
1255 FaultMapSection = Sec;
1256 break;
1257 }
1258 }
1259
1260 outs() << "FaultMap table:\n";
1261
1262 if (!FaultMapSection.hasValue()) {
1263 outs() << "<not found>\n";
1264 return;
1265 }
1266
1267 StringRef FaultMapContents;
1268 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1269 errs() << "Could not read the " << FaultMapContents << " section!\n";
1270 return;
1271 }
1272
1273 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1274 FaultMapContents.bytes_end());
1275
1276 outs() << FMP;
1277}
1278
Rui Ueyamac2bed422013-09-27 21:04:00 +00001279static void printPrivateFileHeader(const ObjectFile *o) {
1280 if (o->isELF()) {
1281 printELFFileHeader(o);
1282 } else if (o->isCOFF()) {
1283 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001284 } else if (o->isMachO()) {
1285 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001286 }
1287}
1288
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001289static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001290 outs() << '\n';
1291 outs() << o->getFileName()
1292 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1293
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001294 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001295 DisassembleObject(o, Relocations);
1296 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001297 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001298 if (SectionHeaders)
1299 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001300 if (SectionContents)
1301 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001302 if (SymbolTable)
1303 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001304 if (UnwindInfo)
1305 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001306 if (PrivateHeaders)
1307 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001308 if (ExportsTrie)
1309 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001310 if (Rebase)
1311 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001312 if (Bind)
1313 printBindTable(o);
1314 if (LazyBind)
1315 printLazyBindTable(o);
1316 if (WeakBind)
1317 printWeakBindTable(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001318 if (PrintFaultMaps)
1319 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001320}
1321
1322/// @brief Dump each object file in \a a;
1323static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001324 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1325 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001326 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1327 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001328 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001329 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001330 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001331 continue;
1332 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001333 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001334 DumpObject(o);
1335 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001336 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001337 }
1338}
1339
1340/// @brief Open file and figure out how to dump it.
1341static void DumpInput(StringRef file) {
1342 // If file isn't stdin, check that it exists.
1343 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001344 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001345 return;
1346 }
1347
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001348 // If we are using the Mach-O specific object file parser, then let it parse
1349 // the file and process the command line options. So the -arch flags can
1350 // be used to select specific slices, etc.
1351 if (MachOOpt) {
1352 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001353 return;
1354 }
1355
1356 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001357 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001358 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001359 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001360 return;
1361 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001362 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001363
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001364 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001365 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001366 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001367 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001368 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001369 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001370}
1371
Michael J. Spencer2670c252011-01-20 06:39:06 +00001372int main(int argc, char **argv) {
1373 // Print a stack trace if we signal out.
1374 sys::PrintStackTraceOnErrorSignal();
1375 PrettyStackTraceProgram X(argc, argv);
1376 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1377
1378 // Initialize targets and assembly printers/parsers.
1379 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001380 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001381 llvm::InitializeAllAsmParsers();
1382 llvm::InitializeAllDisassemblers();
1383
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001384 // Register the target printer for --version.
1385 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1386
Michael J. Spencer2670c252011-01-20 06:39:06 +00001387 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1388 TripleName = Triple::normalize(TripleName);
1389
1390 ToolName = argv[0];
1391
1392 // Defaults to a.out if no filenames specified.
1393 if (InputFilenames.size() == 0)
1394 InputFilenames.push_back("a.out");
1395
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001396 if (!Disassemble
1397 && !Relocations
1398 && !SectionHeaders
1399 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001400 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001401 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001402 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001403 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001404 && !Rebase
1405 && !Bind
1406 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001407 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001408 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001409 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001410 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001411 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001412 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001413 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001414 && !(DylibsUsed && MachOOpt)
1415 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001416 && !(ObjcMetaData && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001417 && !(DumpSections.size() != 0 && MachOOpt)
1418 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001419 cl::PrintHelpMessage();
1420 return 2;
1421 }
1422
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001423 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1424 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001425
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001426 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001427}