blob: 796a79eb5c2b5db25c55fc9ceb8821b25928a6a2 [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);
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000324 const Elf_Shdr *SymTab = EF.getSection(sec->sh_link);
325 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
326 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000327 const Elf_Shdr *StrTabSec = EF.getSection(SymTab->sh_link);
328 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(StrTabSec);
329 if (std::error_code EC = StrTabOrErr.getError())
330 return EC;
331 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000332 uint8_t type;
333 StringRef res;
334 int64_t addend = 0;
335 uint16_t symbol_index = 0;
336 switch (sec->sh_type) {
337 default:
338 return object_error::parse_failed;
339 case ELF::SHT_REL: {
340 type = getRel(EF, Rel)->getType(EF.isMips64EL());
341 symbol_index = getRel(EF, Rel)->getSymbol(EF.isMips64EL());
342 // TODO: Read implicit addend from section data.
343 break;
344 }
345 case ELF::SHT_RELA: {
346 type = getRela(EF, Rel)->getType(EF.isMips64EL());
347 symbol_index = getRela(EF, Rel)->getSymbol(EF.isMips64EL());
348 addend = getRela(EF, Rel)->r_addend;
349 break;
350 }
351 }
352 const Elf_Sym *symb =
353 EF.template getEntry<Elf_Sym>(sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000354 StringRef Target;
355 const Elf_Shdr *SymSec = EF.getSection(symb);
356 if (symb->getType() == ELF::STT_SECTION) {
357 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
358 if (std::error_code EC = SecName.getError())
359 return EC;
360 Target = *SecName;
361 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000362 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000363 if (!SymName)
364 return SymName.getError();
365 Target = *SymName;
366 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000367 switch (EF.getHeader()->e_machine) {
368 case ELF::EM_X86_64:
369 switch (type) {
370 case ELF::R_X86_64_PC8:
371 case ELF::R_X86_64_PC16:
372 case ELF::R_X86_64_PC32: {
373 std::string fmtbuf;
374 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000375 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000376 fmt.flush();
377 Result.append(fmtbuf.begin(), fmtbuf.end());
378 } break;
379 case ELF::R_X86_64_8:
380 case ELF::R_X86_64_16:
381 case ELF::R_X86_64_32:
382 case ELF::R_X86_64_32S:
383 case ELF::R_X86_64_64: {
384 std::string fmtbuf;
385 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000386 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000387 fmt.flush();
388 Result.append(fmtbuf.begin(), fmtbuf.end());
389 } break;
390 default:
391 res = "Unknown";
392 }
393 break;
394 case ELF::EM_AARCH64: {
395 std::string fmtbuf;
396 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000397 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000398 if (addend != 0)
399 fmt << (addend < 0 ? "" : "+") << addend;
400 fmt.flush();
401 Result.append(fmtbuf.begin(), fmtbuf.end());
402 break;
403 }
404 case ELF::EM_386:
405 case ELF::EM_ARM:
406 case ELF::EM_HEXAGON:
407 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000408 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000409 break;
410 default:
411 res = "Unknown";
412 }
413 if (Result.empty())
414 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000415 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000416}
417
418static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
419 const RelocationRef &RelRef,
420 SmallVectorImpl<char> &Result) {
421 DataRefImpl Rel = RelRef.getRawDataRefImpl();
422 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
423 return getRelocationValueString(ELF32LE, Rel, Result);
424 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
425 return getRelocationValueString(ELF64LE, Rel, Result);
426 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
427 return getRelocationValueString(ELF32BE, Rel, Result);
428 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
429 return getRelocationValueString(ELF64BE, Rel, Result);
430}
431
432static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
433 const RelocationRef &Rel,
434 SmallVectorImpl<char> &Result) {
435 symbol_iterator SymI = Rel.getSymbol();
436 StringRef SymName;
437 if (std::error_code EC = SymI->getName(SymName))
438 return EC;
439 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000440 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000441}
442
443static void printRelocationTargetName(const MachOObjectFile *O,
444 const MachO::any_relocation_info &RE,
445 raw_string_ostream &fmt) {
446 bool IsScattered = O->isRelocationScattered(RE);
447
448 // Target of a scattered relocation is an address. In the interest of
449 // generating pretty output, scan through the symbol table looking for a
450 // symbol that aligns with that address. If we find one, print it.
451 // Otherwise, we just print the hex address of the target.
452 if (IsScattered) {
453 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
454
455 for (const SymbolRef &Symbol : O->symbols()) {
456 std::error_code ec;
457 uint64_t Addr;
458 StringRef Name;
459
460 if ((ec = Symbol.getAddress(Addr)))
461 report_fatal_error(ec.message());
462 if (Addr != Val)
463 continue;
464 if ((ec = Symbol.getName(Name)))
465 report_fatal_error(ec.message());
466 fmt << Name;
467 return;
468 }
469
470 // If we couldn't find a symbol that this relocation refers to, try
471 // to find a section beginning instead.
472 for (const SectionRef &Section : O->sections()) {
473 std::error_code ec;
474
475 StringRef Name;
476 uint64_t Addr = Section.getAddress();
477 if (Addr != Val)
478 continue;
479 if ((ec = Section.getName(Name)))
480 report_fatal_error(ec.message());
481 fmt << Name;
482 return;
483 }
484
485 fmt << format("0x%x", Val);
486 return;
487 }
488
489 StringRef S;
490 bool isExtern = O->getPlainRelocationExternal(RE);
491 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
492
493 if (isExtern) {
494 symbol_iterator SI = O->symbol_begin();
495 advance(SI, Val);
496 SI->getName(S);
497 } else {
498 section_iterator SI = O->section_begin();
499 // Adjust for the fact that sections are 1-indexed.
500 advance(SI, Val - 1);
501 SI->getName(S);
502 }
503
504 fmt << S;
505}
506
507static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
508 const RelocationRef &RelRef,
509 SmallVectorImpl<char> &Result) {
510 DataRefImpl Rel = RelRef.getRawDataRefImpl();
511 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
512
513 unsigned Arch = Obj->getArch();
514
515 std::string fmtbuf;
516 raw_string_ostream fmt(fmtbuf);
517 unsigned Type = Obj->getAnyRelocationType(RE);
518 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
519
520 // Determine any addends that should be displayed with the relocation.
521 // These require decoding the relocation type, which is triple-specific.
522
523 // X86_64 has entirely custom relocation types.
524 if (Arch == Triple::x86_64) {
525 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
526
527 switch (Type) {
528 case MachO::X86_64_RELOC_GOT_LOAD:
529 case MachO::X86_64_RELOC_GOT: {
530 printRelocationTargetName(Obj, RE, fmt);
531 fmt << "@GOT";
532 if (isPCRel)
533 fmt << "PCREL";
534 break;
535 }
536 case MachO::X86_64_RELOC_SUBTRACTOR: {
537 DataRefImpl RelNext = Rel;
538 Obj->moveRelocationNext(RelNext);
539 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
540
541 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
542 // X86_64_RELOC_UNSIGNED.
543 // NOTE: Scattered relocations don't exist on x86_64.
544 unsigned RType = Obj->getAnyRelocationType(RENext);
545 if (RType != MachO::X86_64_RELOC_UNSIGNED)
546 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
547 "X86_64_RELOC_SUBTRACTOR.");
548
549 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
550 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
551 printRelocationTargetName(Obj, RENext, fmt);
552 fmt << "-";
553 printRelocationTargetName(Obj, RE, fmt);
554 break;
555 }
556 case MachO::X86_64_RELOC_TLV:
557 printRelocationTargetName(Obj, RE, fmt);
558 fmt << "@TLV";
559 if (isPCRel)
560 fmt << "P";
561 break;
562 case MachO::X86_64_RELOC_SIGNED_1:
563 printRelocationTargetName(Obj, RE, fmt);
564 fmt << "-1";
565 break;
566 case MachO::X86_64_RELOC_SIGNED_2:
567 printRelocationTargetName(Obj, RE, fmt);
568 fmt << "-2";
569 break;
570 case MachO::X86_64_RELOC_SIGNED_4:
571 printRelocationTargetName(Obj, RE, fmt);
572 fmt << "-4";
573 break;
574 default:
575 printRelocationTargetName(Obj, RE, fmt);
576 break;
577 }
578 // X86 and ARM share some relocation types in common.
579 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
580 Arch == Triple::ppc) {
581 // Generic relocation types...
582 switch (Type) {
583 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000584 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000585 case MachO::GENERIC_RELOC_SECTDIFF: {
586 DataRefImpl RelNext = Rel;
587 Obj->moveRelocationNext(RelNext);
588 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
589
590 // X86 sect diff's must be followed by a relocation of type
591 // GENERIC_RELOC_PAIR.
592 unsigned RType = Obj->getAnyRelocationType(RENext);
593
594 if (RType != MachO::GENERIC_RELOC_PAIR)
595 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
596 "GENERIC_RELOC_SECTDIFF.");
597
598 printRelocationTargetName(Obj, RE, fmt);
599 fmt << "-";
600 printRelocationTargetName(Obj, RENext, fmt);
601 break;
602 }
603 }
604
605 if (Arch == Triple::x86 || Arch == Triple::ppc) {
606 switch (Type) {
607 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
608 DataRefImpl RelNext = Rel;
609 Obj->moveRelocationNext(RelNext);
610 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
611
612 // X86 sect diff's must be followed by a relocation of type
613 // GENERIC_RELOC_PAIR.
614 unsigned RType = Obj->getAnyRelocationType(RENext);
615 if (RType != MachO::GENERIC_RELOC_PAIR)
616 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
617 "GENERIC_RELOC_LOCAL_SECTDIFF.");
618
619 printRelocationTargetName(Obj, RE, fmt);
620 fmt << "-";
621 printRelocationTargetName(Obj, RENext, fmt);
622 break;
623 }
624 case MachO::GENERIC_RELOC_TLV: {
625 printRelocationTargetName(Obj, RE, fmt);
626 fmt << "@TLV";
627 if (IsPCRel)
628 fmt << "P";
629 break;
630 }
631 default:
632 printRelocationTargetName(Obj, RE, fmt);
633 }
634 } else { // ARM-specific relocations
635 switch (Type) {
636 case MachO::ARM_RELOC_HALF:
637 case MachO::ARM_RELOC_HALF_SECTDIFF: {
638 // Half relocations steal a bit from the length field to encode
639 // whether this is an upper16 or a lower16 relocation.
640 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
641
642 if (isUpper)
643 fmt << ":upper16:(";
644 else
645 fmt << ":lower16:(";
646 printRelocationTargetName(Obj, RE, fmt);
647
648 DataRefImpl RelNext = Rel;
649 Obj->moveRelocationNext(RelNext);
650 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
651
652 // ARM half relocs must be followed by a relocation of type
653 // ARM_RELOC_PAIR.
654 unsigned RType = Obj->getAnyRelocationType(RENext);
655 if (RType != MachO::ARM_RELOC_PAIR)
656 report_fatal_error("Expected ARM_RELOC_PAIR after "
657 "ARM_RELOC_HALF");
658
659 // NOTE: The half of the target virtual address is stashed in the
660 // address field of the secondary relocation, but we can't reverse
661 // engineer the constant offset from it without decoding the movw/movt
662 // instruction to find the other half in its immediate field.
663
664 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
665 // symbol/section pointer of the follow-on relocation.
666 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
667 fmt << "-";
668 printRelocationTargetName(Obj, RENext, fmt);
669 }
670
671 fmt << ")";
672 break;
673 }
674 default: { printRelocationTargetName(Obj, RE, fmt); }
675 }
676 }
677 } else
678 printRelocationTargetName(Obj, RE, fmt);
679
680 fmt.flush();
681 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000682 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000683}
684
685static std::error_code getRelocationValueString(const RelocationRef &Rel,
686 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000687 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000688 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
689 return getRelocationValueString(ELF, Rel, Result);
690 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
691 return getRelocationValueString(COFF, Rel, Result);
692 auto *MachO = cast<MachOObjectFile>(Obj);
693 return getRelocationValueString(MachO, Rel, Result);
694}
695
Michael J. Spencer51862b32011-10-13 22:17:18 +0000696static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000697 const Target *TheTarget = getTarget(Obj);
698 // getTarget() will have already issued a diagnostic if necessary, so
699 // just bail here if it failed.
700 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000701 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000702
Jack Carter551efd72012-08-28 19:24:49 +0000703 // Package up features to be passed to target/subtarget
704 std::string FeaturesStr;
705 if (MAttrs.size()) {
706 SubtargetFeatures Features;
707 for (unsigned i = 0; i != MAttrs.size(); ++i)
708 Features.AddFeature(MAttrs[i]);
709 FeaturesStr = Features.getString();
710 }
711
Ahmed Charles56440fd2014-03-06 05:51:42 +0000712 std::unique_ptr<const MCRegisterInfo> MRI(
713 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000714 if (!MRI) {
715 errs() << "error: no register info for target " << TripleName << "\n";
716 return;
717 }
718
719 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000720 std::unique_ptr<const MCAsmInfo> AsmInfo(
721 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000722 if (!AsmInfo) {
723 errs() << "error: no assembly info for target " << TripleName << "\n";
724 return;
725 }
726
Ahmed Charles56440fd2014-03-06 05:51:42 +0000727 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000728 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000729 if (!STI) {
730 errs() << "error: no subtarget info for target " << TripleName << "\n";
731 return;
732 }
733
Ahmed Charles56440fd2014-03-06 05:51:42 +0000734 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000735 if (!MII) {
736 errs() << "error: no instruction info for target " << TripleName << "\n";
737 return;
738 }
739
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000740 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
741 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
742
743 std::unique_ptr<MCDisassembler> DisAsm(
744 TheTarget->createMCDisassembler(*STI, Ctx));
745
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000746 if (!DisAsm) {
747 errs() << "error: no disassembler for target " << TripleName << "\n";
748 return;
749 }
750
Ahmed Charles56440fd2014-03-06 05:51:42 +0000751 std::unique_ptr<const MCInstrAnalysis> MIA(
752 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000753
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000754 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000755 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000756 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000757 if (!IP) {
758 errs() << "error: no instruction printer for target " << TripleName
759 << '\n';
760 return;
761 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000762 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000763 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000764
Greg Fitzgerald18432272014-03-20 22:55:15 +0000765 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
766 "\t\t\t%08" PRIx64 ": ";
767
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000768 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
769 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000770 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000771 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
772 for (const SectionRef &Section : Obj->sections()) {
773 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000774 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000775 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000776 }
777
Alexey Samsonov48803e52014-03-13 14:37:36 +0000778 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000779 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000780 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000781
Rafael Espindola80291272014-10-08 15:28:58 +0000782 uint64_t SectionAddr = Section.getAddress();
783 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000784 if (!SectSize)
785 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000786
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000787 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000788 std::vector<std::pair<uint64_t, StringRef>> Symbols;
789 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000790 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000791 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000792 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000793 break;
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000794 if (Address == UnknownAddress)
Mark Seaborneb03ac52014-01-25 00:32:01 +0000795 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000796 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000797 if (Address >= SectSize)
798 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000799
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000800 StringRef Name;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000801 if (error(Symbol.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000802 break;
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000803 Symbols.push_back(std::make_pair(Address, Name));
804 }
805 }
806
807 // Sort the symbols by address, just in case they didn't come in that way.
808 array_pod_sort(Symbols.begin(), Symbols.end());
809
Michael J. Spencer51862b32011-10-13 22:17:18 +0000810 // Make a list of all the relocations for this section.
811 std::vector<RelocationRef> Rels;
812 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000813 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
814 for (const RelocationRef &Reloc : RelocSec.relocations()) {
815 Rels.push_back(Reloc);
816 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000817 }
818 }
819
820 // Sort relocations by address.
821 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
822
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000823 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000824 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000825 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000826 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000827 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000828 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000829 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000830 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000831 outs() << "Disassembly of section ";
832 if (!SegmentName.empty())
833 outs() << SegmentName << ",";
834 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000835
Rafael Espindola7884c952015-06-04 15:01:05 +0000836 // If the section has no symbol at the start, just insert a dummy one.
837 if (Symbols.empty() || Symbols[0].first != 0)
838 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000839
840 SmallString<40> Comments;
841 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000842
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000843 StringRef BytesStr;
844 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000845 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000846 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
847 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000848
Michael J. Spencer2670c252011-01-20 06:39:06 +0000849 uint64_t Size;
850 uint64_t Index;
851
Michael J. Spencer51862b32011-10-13 22:17:18 +0000852 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
853 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000854 // Disassemble symbol by symbol.
855 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000856
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000857 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000858 // The end is either the section end or the beginning of the next symbol.
859 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
860 // If this symbol has the same address as the next symbol, then skip it.
861 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000862 continue;
863
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000864 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000865
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000866#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000867 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000868#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000869 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000870#endif
871
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000872 for (Index = Start; Index < End; Index += Size) {
873 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000874
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000875 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
876 SectionAddr + Index, DebugOut,
877 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000878 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000879 Bytes.slice(Index, Size),
880 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000881 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000882 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000883 outs() << "\n";
884 } else {
885 errs() << ToolName << ": warning: invalid instruction encoding\n";
886 if (Size == 0)
887 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000888 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000889
890 // Print relocation for instruction.
891 while (rel_cur != rel_end) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000892 bool hidden = false;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000893 uint64_t addr;
894 SmallString<16> name;
895 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000896
897 // If this relocation is hidden, skip it.
898 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
899 if (hidden) goto skip_print_rel;
900
Rafael Espindola1e483872013-04-25 12:28:45 +0000901 if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000902 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000903 if (addr >= Index + Size) break;
Michael J. Spencer51862b32011-10-13 22:17:18 +0000904 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
Rafael Espindola37070a52015-06-03 04:48:06 +0000905 if (error(getRelocationValueString(*rel_cur, val)))
906 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000907 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000908 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000909
910 skip_print_rel:
911 ++rel_cur;
912 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000913 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000914 }
915 }
916}
917
Kevin Enderby98da6132015-01-20 21:47:46 +0000918void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000919 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
920 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000921 // Regular objdump doesn't print relocations in non-relocatable object
922 // files.
923 if (!Obj->isRelocatableObject())
924 return;
925
Alexey Samsonov48803e52014-03-13 14:37:36 +0000926 for (const SectionRef &Section : Obj->sections()) {
927 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000928 continue;
929 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000930 if (error(Section.getName(secname)))
931 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000932 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000933 for (const RelocationRef &Reloc : Section.relocations()) {
Owen Andersonfa3e5202011-10-25 20:35:53 +0000934 bool hidden;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000935 uint64_t address;
936 SmallString<32> relocname;
937 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000938 if (error(Reloc.getHidden(hidden)))
939 continue;
940 if (hidden)
941 continue;
942 if (error(Reloc.getTypeName(relocname)))
943 continue;
944 if (error(Reloc.getOffset(address)))
945 continue;
Rafael Espindola37070a52015-06-03 04:48:06 +0000946 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000947 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000948 outs() << format(Fmt.data(), address) << " " << relocname << " "
949 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000950 }
951 outs() << "\n";
952 }
953}
954
Kevin Enderby98da6132015-01-20 21:47:46 +0000955void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000956 outs() << "Sections:\n"
957 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000958 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000959 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000960 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000961 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000962 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000963 uint64_t Address = Section.getAddress();
964 uint64_t Size = Section.getSize();
965 bool Text = Section.isText();
966 bool Data = Section.isData();
967 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000968 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000969 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000970 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
971 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000972 ++i;
973 }
974}
975
Kevin Enderby98da6132015-01-20 21:47:46 +0000976void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +0000977 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000978 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000979 StringRef Name;
980 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000981 if (error(Section.getName(Name)))
982 continue;
Rafael Espindola80291272014-10-08 15:28:58 +0000983 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +0000984 uint64_t Size = Section.getSize();
985 if (!Size)
986 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000987
988 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +0000989 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +0000990 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +0000991 ", %04" PRIx64 ")>\n",
992 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +0000993 continue;
994 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000995
David Majnemer8f6b04c2014-07-14 16:20:14 +0000996 if (error(Section.getContents(Contents)))
997 continue;
998
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000999 // Dump out the content as hex and printable ascii characters.
1000 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001001 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001002 // Dump line of hex.
1003 for (std::size_t i = 0; i < 16; ++i) {
1004 if (i != 0 && i % 4 == 0)
1005 outs() << ' ';
1006 if (addr + i < end)
1007 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1008 << hexdigit(Contents[addr + i] & 0xF, true);
1009 else
1010 outs() << " ";
1011 }
1012 // Print ascii.
1013 outs() << " ";
1014 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001015 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001016 outs() << Contents[addr + i];
1017 else
1018 outs() << ".";
1019 }
1020 outs() << "\n";
1021 }
1022 }
1023}
1024
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001025static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001026 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1027 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001028 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001029 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001030 return;
1031
David Majnemer44f51e52014-09-10 12:51:52 +00001032 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001033 return;
1034
1035 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001036 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001037 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001038 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1039 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1040 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1041 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001042 << Name << "\n";
1043
David Majnemer44f51e52014-09-10 12:51:52 +00001044 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001045 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001046 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001047 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001048 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001049
David Majnemer4d571592014-09-15 19:42:42 +00001050 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1051
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001052 outs() << "AUX "
1053 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1054 , unsigned(asd->Length)
1055 , unsigned(asd->NumberOfRelocations)
1056 , unsigned(asd->NumberOfLinenumbers)
1057 , unsigned(asd->CheckSum))
1058 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001059 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001060 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001061 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001062 const char *FileName;
1063 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001064 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001065
David Majnemer44f51e52014-09-10 12:51:52 +00001066 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1067 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001068 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001069
David Majnemer44f51e52014-09-10 12:51:52 +00001070 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001071 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001072 } else {
1073 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001074 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001075 }
1076 }
1077}
1078
Kevin Enderby98da6132015-01-20 21:47:46 +00001079void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001080 outs() << "SYMBOL TABLE:\n";
1081
Rui Ueyama4e39f712014-03-18 18:58:51 +00001082 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001083 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001084 return;
1085 }
1086 for (const SymbolRef &Symbol : o->symbols()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001087 uint64_t Address;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001088 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001089 uint32_t Flags = Symbol.getFlags();
1090 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001091 if (error(Symbol.getAddress(Address)))
1092 continue;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001093 if (error(Symbol.getSection(Section)))
1094 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001095 StringRef Name;
1096 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1097 Section->getName(Name);
1098 } else if (error(Symbol.getName(Name))) {
1099 continue;
1100 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001101
Rui Ueyama4e39f712014-03-18 18:58:51 +00001102 bool Global = Flags & SymbolRef::SF_Global;
1103 bool Weak = Flags & SymbolRef::SF_Weak;
1104 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001105 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001106 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001107
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001108 if (Common)
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001109 Address = Symbol.getCommonSize();
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001110
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001111 if (Address == UnknownAddress)
Rui Ueyama4e39f712014-03-18 18:58:51 +00001112 Address = 0;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001113 char GlobLoc = ' ';
1114 if (Type != SymbolRef::ST_Unknown)
1115 GlobLoc = Global ? 'g' : 'l';
1116 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1117 ? 'd' : ' ';
1118 char FileFunc = ' ';
1119 if (Type == SymbolRef::ST_File)
1120 FileFunc = 'f';
1121 else if (Type == SymbolRef::ST_Function)
1122 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001123
Rui Ueyama4e39f712014-03-18 18:58:51 +00001124 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1125 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001126
Rui Ueyama4e39f712014-03-18 18:58:51 +00001127 outs() << format(Fmt, Address) << " "
1128 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1129 << (Weak ? 'w' : ' ') // Weak?
1130 << ' ' // Constructor. Not supported yet.
1131 << ' ' // Warning. Not supported yet.
1132 << ' ' // Indirect reference to another symbol.
1133 << Debug // Debugging (d) or dynamic (D) symbol.
1134 << FileFunc // Name of function (F), file (f) or object (O).
1135 << ' ';
1136 if (Absolute) {
1137 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001138 } else if (Common) {
1139 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001140 } else if (Section == o->section_end()) {
1141 outs() << "*UND*";
1142 } else {
1143 if (const MachOObjectFile *MachO =
1144 dyn_cast<const MachOObjectFile>(o)) {
1145 DataRefImpl DR = Section->getRawDataRefImpl();
1146 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1147 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001148 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001149 StringRef SectionName;
1150 if (error(Section->getName(SectionName)))
1151 SectionName = "";
1152 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001153 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001154
1155 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001156 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001157 uint64_t Val =
1158 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001159 outs() << format("\t %08" PRIx64 " ", Val);
1160 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001161
Davide Italianocd2514d2015-04-30 23:08:53 +00001162 if (Hidden) {
1163 outs() << ".hidden ";
1164 }
1165 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001166 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001167 }
1168}
1169
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001170static void PrintUnwindInfo(const ObjectFile *o) {
1171 outs() << "Unwind info:\n\n";
1172
1173 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1174 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001175 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1176 printMachOUnwindInfo(MachO);
1177 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001178 // TODO: Extract DWARF dump tool to objdump.
1179 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001180 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001181 return;
1182 }
1183}
1184
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001185void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001186 outs() << "Exports trie:\n";
1187 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1188 printMachOExportsTrie(MachO);
1189 else {
1190 errs() << "This operation is only currently supported "
1191 "for Mach-O executable files.\n";
1192 return;
1193 }
1194}
1195
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001196void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001197 outs() << "Rebase table:\n";
1198 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1199 printMachORebaseTable(MachO);
1200 else {
1201 errs() << "This operation is only currently supported "
1202 "for Mach-O executable files.\n";
1203 return;
1204 }
1205}
1206
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001207void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001208 outs() << "Bind table:\n";
1209 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1210 printMachOBindTable(MachO);
1211 else {
1212 errs() << "This operation is only currently supported "
1213 "for Mach-O executable files.\n";
1214 return;
1215 }
1216}
1217
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001218void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001219 outs() << "Lazy bind table:\n";
1220 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1221 printMachOLazyBindTable(MachO);
1222 else {
1223 errs() << "This operation is only currently supported "
1224 "for Mach-O executable files.\n";
1225 return;
1226 }
1227}
1228
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001229void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001230 outs() << "Weak bind table:\n";
1231 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1232 printMachOWeakBindTable(MachO);
1233 else {
1234 errs() << "This operation is only currently supported "
1235 "for Mach-O executable files.\n";
1236 return;
1237 }
1238}
Nick Kledzikac431442014-09-12 21:34:15 +00001239
Sanjoy Das6f567a42015-06-22 18:03:02 +00001240static void printFaultMaps(const ObjectFile *Obj) {
1241 const char *FaultMapSectionName = nullptr;
1242
1243 if (isa<ELFObjectFileBase>(Obj)) {
1244 FaultMapSectionName = ".llvm_faultmaps";
1245 } else if (isa<MachOObjectFile>(Obj)) {
1246 FaultMapSectionName = "__llvm_faultmaps";
1247 } else {
1248 errs() << "This operation is only currently supported "
1249 "for ELF and Mach-O executable files.\n";
1250 return;
1251 }
1252
1253 Optional<object::SectionRef> FaultMapSection;
1254
1255 for (auto Sec : Obj->sections()) {
1256 StringRef Name;
1257 Sec.getName(Name);
1258 if (Name == FaultMapSectionName) {
1259 FaultMapSection = Sec;
1260 break;
1261 }
1262 }
1263
1264 outs() << "FaultMap table:\n";
1265
1266 if (!FaultMapSection.hasValue()) {
1267 outs() << "<not found>\n";
1268 return;
1269 }
1270
1271 StringRef FaultMapContents;
1272 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1273 errs() << "Could not read the " << FaultMapContents << " section!\n";
1274 return;
1275 }
1276
1277 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1278 FaultMapContents.bytes_end());
1279
1280 outs() << FMP;
1281}
1282
Rui Ueyamac2bed422013-09-27 21:04:00 +00001283static void printPrivateFileHeader(const ObjectFile *o) {
1284 if (o->isELF()) {
1285 printELFFileHeader(o);
1286 } else if (o->isCOFF()) {
1287 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001288 } else if (o->isMachO()) {
1289 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001290 }
1291}
1292
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001293static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001294 outs() << '\n';
1295 outs() << o->getFileName()
1296 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1297
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001298 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001299 DisassembleObject(o, Relocations);
1300 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001301 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001302 if (SectionHeaders)
1303 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001304 if (SectionContents)
1305 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001306 if (SymbolTable)
1307 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001308 if (UnwindInfo)
1309 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001310 if (PrivateHeaders)
1311 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001312 if (ExportsTrie)
1313 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001314 if (Rebase)
1315 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001316 if (Bind)
1317 printBindTable(o);
1318 if (LazyBind)
1319 printLazyBindTable(o);
1320 if (WeakBind)
1321 printWeakBindTable(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001322 if (PrintFaultMaps)
1323 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001324}
1325
1326/// @brief Dump each object file in \a a;
1327static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001328 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1329 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001330 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1331 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001332 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001333 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001334 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001335 continue;
1336 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001337 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001338 DumpObject(o);
1339 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001340 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001341 }
1342}
1343
1344/// @brief Open file and figure out how to dump it.
1345static void DumpInput(StringRef file) {
1346 // If file isn't stdin, check that it exists.
1347 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001348 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001349 return;
1350 }
1351
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001352 // If we are using the Mach-O specific object file parser, then let it parse
1353 // the file and process the command line options. So the -arch flags can
1354 // be used to select specific slices, etc.
1355 if (MachOOpt) {
1356 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001357 return;
1358 }
1359
1360 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001361 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001362 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001363 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001364 return;
1365 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001366 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001367
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001368 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001369 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001370 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001371 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001372 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001373 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001374}
1375
Michael J. Spencer2670c252011-01-20 06:39:06 +00001376int main(int argc, char **argv) {
1377 // Print a stack trace if we signal out.
1378 sys::PrintStackTraceOnErrorSignal();
1379 PrettyStackTraceProgram X(argc, argv);
1380 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1381
1382 // Initialize targets and assembly printers/parsers.
1383 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001384 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001385 llvm::InitializeAllAsmParsers();
1386 llvm::InitializeAllDisassemblers();
1387
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001388 // Register the target printer for --version.
1389 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1390
Michael J. Spencer2670c252011-01-20 06:39:06 +00001391 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1392 TripleName = Triple::normalize(TripleName);
1393
1394 ToolName = argv[0];
1395
1396 // Defaults to a.out if no filenames specified.
1397 if (InputFilenames.size() == 0)
1398 InputFilenames.push_back("a.out");
1399
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001400 if (!Disassemble
1401 && !Relocations
1402 && !SectionHeaders
1403 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001404 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001405 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001406 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001407 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001408 && !Rebase
1409 && !Bind
1410 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001411 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001412 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001413 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001414 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001415 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001416 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001417 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001418 && !(DylibsUsed && MachOOpt)
1419 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001420 && !(ObjcMetaData && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001421 && !(DumpSections.size() != 0 && MachOOpt)
1422 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001423 cl::PrintHelpMessage();
1424 return 2;
1425 }
1426
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001427 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1428 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001429
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001430 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001431}