blob: c0965d8843dc4b03b72ff3cbdc2f7100b8a924bb [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 Espindola704cd842015-07-06 15:47:43 +0000215 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000216}
217
Colin LeMahieufb76b002015-05-28 19:07:14 +0000218namespace {
219class PrettyPrinter {
220public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000221 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000222 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000223 ArrayRef<uint8_t> Bytes, uint64_t Address,
224 raw_ostream &OS, StringRef Annot,
225 MCSubtargetInfo const &STI) {
226 outs() << format("%8" PRIx64 ":", Address);
227 if (!NoShowRawInsn) {
228 outs() << "\t";
229 dumpBytes(Bytes, outs());
230 }
231 IP.printInst(MI, outs(), "", STI);
232 }
233};
234PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000235class HexagonPrettyPrinter : public PrettyPrinter {
236public:
237 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
238 raw_ostream &OS) {
239 uint32_t opcode =
240 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
241 OS << format("%8" PRIx64 ":", Address);
242 if (!NoShowRawInsn) {
243 OS << "\t";
244 dumpBytes(Bytes.slice(0, 4), OS);
245 OS << format("%08" PRIx32, opcode);
246 }
247 }
248 void printInst(MCInstPrinter &IP, const MCInst *MI,
249 ArrayRef<uint8_t> Bytes, uint64_t Address,
250 raw_ostream &OS, StringRef Annot,
251 MCSubtargetInfo const &STI) override {
252 std::string Buffer;
253 {
254 raw_string_ostream TempStream(Buffer);
255 IP.printInst(MI, TempStream, "", STI);
256 }
257 StringRef Contents(Buffer);
258 // Split off bundle attributes
259 auto PacketBundle = Contents.rsplit('\n');
260 // Split off first instruction from the rest
261 auto HeadTail = PacketBundle.first.split('\n');
262 auto Preamble = " { ";
263 auto Separator = "";
264 while(!HeadTail.first.empty()) {
265 OS << Separator;
266 Separator = "\n";
267 printLead(Bytes, Address, OS);
268 OS << Preamble;
269 Preamble = " ";
270 StringRef Inst;
271 auto Duplex = HeadTail.first.split('\v');
272 if(!Duplex.second.empty()){
273 OS << Duplex.first;
274 OS << "; ";
275 Inst = Duplex.second;
276 }
277 else
278 Inst = HeadTail.first;
279 OS << Inst;
280 Bytes = Bytes.slice(4);
281 Address += 4;
282 HeadTail = HeadTail.second.split('\n');
283 }
284 OS << " } " << PacketBundle.second;
285 }
286};
287HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000288PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000289 switch(Triple.getArch()) {
290 default:
291 return PrettyPrinterInst;
292 case Triple::hexagon:
293 return HexagonPrettyPrinterInst;
294 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000295}
296}
297
Rafael Espindola37070a52015-06-03 04:48:06 +0000298template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000299static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
300 DataRefImpl Rel,
301 SmallVectorImpl<char> &Result) {
302 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
303 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000304 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
305 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
306
Rafael Espindola37070a52015-06-03 04:48:06 +0000307 const ELFFile<ELFT> &EF = *Obj->getELFFile();
308
Rafael Espindola6def3042015-07-01 12:56:27 +0000309 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
310 if (std::error_code EC = SecOrErr.getError())
311 return EC;
312 const Elf_Shdr *Sec = *SecOrErr;
313 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
314 if (std::error_code EC = SymTabOrErr.getError())
315 return EC;
316 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000317 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
318 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000319 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
320 if (std::error_code EC = StrTabSec.getError())
321 return EC;
322 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000323 if (std::error_code EC = StrTabOrErr.getError())
324 return EC;
325 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000326 uint8_t type;
327 StringRef res;
328 int64_t addend = 0;
329 uint16_t symbol_index = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000330 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000331 default:
332 return object_error::parse_failed;
333 case ELF::SHT_REL: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000334 const Elf_Rel *ERel = Obj->getRel(Rel);
335 type = ERel->getType(EF.isMips64EL());
336 symbol_index = ERel->getSymbol(EF.isMips64EL());
Rafael Espindola37070a52015-06-03 04:48:06 +0000337 // TODO: Read implicit addend from section data.
338 break;
339 }
340 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000341 const Elf_Rela *ERela = Obj->getRela(Rel);
342 type = ERela->getType(EF.isMips64EL());
343 symbol_index = ERela->getSymbol(EF.isMips64EL());
344 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000345 break;
346 }
347 }
348 const Elf_Sym *symb =
Rafael Espindola6def3042015-07-01 12:56:27 +0000349 EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000350 StringRef Target;
Rafael Espindola6def3042015-07-01 12:56:27 +0000351 ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
352 if (std::error_code EC = SymSec.getError())
353 return EC;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000354 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindola6def3042015-07-01 12:56:27 +0000355 ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000356 if (std::error_code EC = SecName.getError())
357 return EC;
358 Target = *SecName;
359 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000360 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000361 if (!SymName)
362 return SymName.getError();
363 Target = *SymName;
364 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000365 switch (EF.getHeader()->e_machine) {
366 case ELF::EM_X86_64:
367 switch (type) {
368 case ELF::R_X86_64_PC8:
369 case ELF::R_X86_64_PC16:
370 case ELF::R_X86_64_PC32: {
371 std::string fmtbuf;
372 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000373 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000374 fmt.flush();
375 Result.append(fmtbuf.begin(), fmtbuf.end());
376 } break;
377 case ELF::R_X86_64_8:
378 case ELF::R_X86_64_16:
379 case ELF::R_X86_64_32:
380 case ELF::R_X86_64_32S:
381 case ELF::R_X86_64_64: {
382 std::string fmtbuf;
383 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000384 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000385 fmt.flush();
386 Result.append(fmtbuf.begin(), fmtbuf.end());
387 } break;
388 default:
389 res = "Unknown";
390 }
391 break;
392 case ELF::EM_AARCH64: {
393 std::string fmtbuf;
394 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000395 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000396 if (addend != 0)
397 fmt << (addend < 0 ? "" : "+") << addend;
398 fmt.flush();
399 Result.append(fmtbuf.begin(), fmtbuf.end());
400 break;
401 }
402 case ELF::EM_386:
403 case ELF::EM_ARM:
404 case ELF::EM_HEXAGON:
405 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000406 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000407 break;
408 default:
409 res = "Unknown";
410 }
411 if (Result.empty())
412 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000413 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000414}
415
416static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
417 const RelocationRef &RelRef,
418 SmallVectorImpl<char> &Result) {
419 DataRefImpl Rel = RelRef.getRawDataRefImpl();
420 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
421 return getRelocationValueString(ELF32LE, Rel, Result);
422 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
423 return getRelocationValueString(ELF64LE, Rel, Result);
424 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
425 return getRelocationValueString(ELF32BE, Rel, Result);
426 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
427 return getRelocationValueString(ELF64BE, Rel, Result);
428}
429
430static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
431 const RelocationRef &Rel,
432 SmallVectorImpl<char> &Result) {
433 symbol_iterator SymI = Rel.getSymbol();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000434 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
435 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000436 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000437 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000438 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;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000456 ErrorOr<uint64_t> Addr = Symbol.getAddress();
457 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000458 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000459 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000460 continue;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000461 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000462 if (std::error_code EC = Name.getError())
463 report_fatal_error(EC.message());
464 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000465 return;
466 }
467
468 // If we couldn't find a symbol that this relocation refers to, try
469 // to find a section beginning instead.
470 for (const SectionRef &Section : O->sections()) {
471 std::error_code ec;
472
473 StringRef Name;
474 uint64_t Addr = Section.getAddress();
475 if (Addr != Val)
476 continue;
477 if ((ec = Section.getName(Name)))
478 report_fatal_error(ec.message());
479 fmt << Name;
480 return;
481 }
482
483 fmt << format("0x%x", Val);
484 return;
485 }
486
487 StringRef S;
488 bool isExtern = O->getPlainRelocationExternal(RE);
489 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
490
491 if (isExtern) {
492 symbol_iterator SI = O->symbol_begin();
493 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000494 ErrorOr<StringRef> SOrErr = SI->getName();
495 if (!error(SOrErr.getError()))
496 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000497 } 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
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000696/// @brief Indicates whether this relocation should hidden when listing
697/// relocations, usually because it is the trailing part of a multipart
698/// relocation that will be printed as part of the leading relocation.
699static bool getHidden(RelocationRef RelRef) {
700 const ObjectFile *Obj = RelRef.getObject();
701 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
702 if (!MachO)
703 return false;
704
705 unsigned Arch = MachO->getArch();
706 DataRefImpl Rel = RelRef.getRawDataRefImpl();
707 uint64_t Type = MachO->getRelocationType(Rel);
708
709 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
710 // is always hidden.
711 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
712 if (Type == MachO::GENERIC_RELOC_PAIR)
713 return true;
714 } else if (Arch == Triple::x86_64) {
715 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
716 // an X86_64_RELOC_SUBTRACTOR.
717 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
718 DataRefImpl RelPrev = Rel;
719 RelPrev.d.a--;
720 uint64_t PrevType = MachO->getRelocationType(RelPrev);
721 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
722 return true;
723 }
724 }
725
726 return false;
727}
728
Michael J. Spencer51862b32011-10-13 22:17:18 +0000729static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000730 const Target *TheTarget = getTarget(Obj);
731 // getTarget() will have already issued a diagnostic if necessary, so
732 // just bail here if it failed.
733 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000734 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000735
Jack Carter551efd72012-08-28 19:24:49 +0000736 // Package up features to be passed to target/subtarget
737 std::string FeaturesStr;
738 if (MAttrs.size()) {
739 SubtargetFeatures Features;
740 for (unsigned i = 0; i != MAttrs.size(); ++i)
741 Features.AddFeature(MAttrs[i]);
742 FeaturesStr = Features.getString();
743 }
744
Ahmed Charles56440fd2014-03-06 05:51:42 +0000745 std::unique_ptr<const MCRegisterInfo> MRI(
746 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000747 if (!MRI) {
748 errs() << "error: no register info for target " << TripleName << "\n";
749 return;
750 }
751
752 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000753 std::unique_ptr<const MCAsmInfo> AsmInfo(
754 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000755 if (!AsmInfo) {
756 errs() << "error: no assembly info for target " << TripleName << "\n";
757 return;
758 }
759
Ahmed Charles56440fd2014-03-06 05:51:42 +0000760 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000761 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000762 if (!STI) {
763 errs() << "error: no subtarget info for target " << TripleName << "\n";
764 return;
765 }
766
Ahmed Charles56440fd2014-03-06 05:51:42 +0000767 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000768 if (!MII) {
769 errs() << "error: no instruction info for target " << TripleName << "\n";
770 return;
771 }
772
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000773 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
774 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
775
776 std::unique_ptr<MCDisassembler> DisAsm(
777 TheTarget->createMCDisassembler(*STI, Ctx));
778
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000779 if (!DisAsm) {
780 errs() << "error: no disassembler for target " << TripleName << "\n";
781 return;
782 }
783
Ahmed Charles56440fd2014-03-06 05:51:42 +0000784 std::unique_ptr<const MCInstrAnalysis> MIA(
785 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000786
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000787 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000788 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000789 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000790 if (!IP) {
791 errs() << "error: no instruction printer for target " << TripleName
792 << '\n';
793 return;
794 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000795 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000796 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000797
Greg Fitzgerald18432272014-03-20 22:55:15 +0000798 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
799 "\t\t\t%08" PRIx64 ": ";
800
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000801 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
802 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000803 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000804 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
805 for (const SectionRef &Section : Obj->sections()) {
806 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000807 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000808 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000809 }
810
David Majnemer81afca62015-07-07 22:06:59 +0000811 // Create a mapping from virtual address to symbol name. This is used to
812 // pretty print the target of a call.
813 std::vector<std::pair<uint64_t, StringRef>> AllSymbols;
814 if (MIA) {
815 for (const SymbolRef &Symbol : Obj->symbols()) {
816 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
817 if (error(AddressOrErr.getError()))
818 break;
819 uint64_t Address = *AddressOrErr;
820
821 ErrorOr<StringRef> Name = Symbol.getName();
822 if (error(Name.getError()))
823 break;
824 if (Name->empty())
825 continue;
826 AllSymbols.push_back(std::make_pair(Address, *Name));
827 }
828
829 array_pod_sort(AllSymbols.begin(), AllSymbols.end());
830 }
831
Alexey Samsonov48803e52014-03-13 14:37:36 +0000832 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000833 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000834 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000835
Rafael Espindola80291272014-10-08 15:28:58 +0000836 uint64_t SectionAddr = Section.getAddress();
837 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000838 if (!SectSize)
839 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000840
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000841 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000842 std::vector<std::pair<uint64_t, StringRef>> Symbols;
843 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000844 if (Section.containsSymbol(Symbol)) {
Rafael Espindolaed067c42015-07-03 18:19:00 +0000845 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
846 if (error(AddressOrErr.getError()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000847 break;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000848 uint64_t Address = *AddressOrErr;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000849 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000850 if (Address >= SectSize)
851 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000852
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000853 ErrorOr<StringRef> Name = Symbol.getName();
854 if (error(Name.getError()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000855 break;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000856 Symbols.push_back(std::make_pair(Address, *Name));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000857 }
858 }
859
860 // Sort the symbols by address, just in case they didn't come in that way.
861 array_pod_sort(Symbols.begin(), Symbols.end());
862
Michael J. Spencer51862b32011-10-13 22:17:18 +0000863 // Make a list of all the relocations for this section.
864 std::vector<RelocationRef> Rels;
865 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000866 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
867 for (const RelocationRef &Reloc : RelocSec.relocations()) {
868 Rels.push_back(Reloc);
869 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000870 }
871 }
872
873 // Sort relocations by address.
874 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
875
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000876 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000877 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000878 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000879 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000880 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000881 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000882 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000883 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000884 outs() << "Disassembly of section ";
885 if (!SegmentName.empty())
886 outs() << SegmentName << ",";
887 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000888
Rafael Espindola7884c952015-06-04 15:01:05 +0000889 // If the section has no symbol at the start, just insert a dummy one.
890 if (Symbols.empty() || Symbols[0].first != 0)
891 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000892
893 SmallString<40> Comments;
894 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000895
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000896 StringRef BytesStr;
897 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000898 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000899 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
900 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000901
Michael J. Spencer2670c252011-01-20 06:39:06 +0000902 uint64_t Size;
903 uint64_t Index;
904
Michael J. Spencer51862b32011-10-13 22:17:18 +0000905 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
906 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000907 // Disassemble symbol by symbol.
908 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000909
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000910 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000911 // The end is either the section end or the beginning of the next symbol.
912 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
913 // If this symbol has the same address as the next symbol, then skip it.
914 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000915 continue;
916
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000917 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000918
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000919#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000920 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000921#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000922 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000923#endif
924
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000925 for (Index = Start; Index < End; Index += Size) {
926 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000927
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000928 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
929 SectionAddr + Index, DebugOut,
930 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000931 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000932 Bytes.slice(Index, Size),
933 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000934 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000935 Comments.clear();
David Majnemer81afca62015-07-07 22:06:59 +0000936 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst))) {
937 uint64_t Target;
938 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
939 const auto &TargetSym =
940 std::lower_bound(AllSymbols.begin(), AllSymbols.end(),
941 std::make_pair(Target, StringRef()));
942 if (TargetSym != AllSymbols.end()) {
943 outs() << " <" << TargetSym->second;
944 uint64_t Disp = TargetSym->first - Target;
945 if (Disp)
946 outs() << '-' << Disp;
947 outs() << '>';
948 }
949 }
950 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000951 outs() << "\n";
952 } else {
953 errs() << ToolName << ": warning: invalid instruction encoding\n";
954 if (Size == 0)
955 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000956 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000957
958 // Print relocation for instruction.
959 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000960 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +0000961 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000962 SmallString<16> name;
963 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000964
965 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +0000966 if (hidden) goto skip_print_rel;
967
Michael J. Spencer51862b32011-10-13 22:17:18 +0000968 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000969 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +0000970 rel_cur->getTypeName(name);
Rafael Espindola37070a52015-06-03 04:48:06 +0000971 if (error(getRelocationValueString(*rel_cur, val)))
972 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000973 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000974 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000975
976 skip_print_rel:
977 ++rel_cur;
978 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000979 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000980 }
981 }
982}
983
Kevin Enderby98da6132015-01-20 21:47:46 +0000984void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000985 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
986 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000987 // Regular objdump doesn't print relocations in non-relocatable object
988 // files.
989 if (!Obj->isRelocatableObject())
990 return;
991
Alexey Samsonov48803e52014-03-13 14:37:36 +0000992 for (const SectionRef &Section : Obj->sections()) {
993 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000994 continue;
995 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000996 if (error(Section.getName(secname)))
997 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000998 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000999 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001000 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001001 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001002 SmallString<32> relocname;
1003 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001004 if (hidden)
1005 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001006 Reloc.getTypeName(relocname);
Rafael Espindola37070a52015-06-03 04:48:06 +00001007 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001008 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +00001009 outs() << format(Fmt.data(), address) << " " << relocname << " "
1010 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001011 }
1012 outs() << "\n";
1013 }
1014}
1015
Kevin Enderby98da6132015-01-20 21:47:46 +00001016void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001017 outs() << "Sections:\n"
1018 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001019 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001020 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001021 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001022 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001023 return;
Rafael Espindola80291272014-10-08 15:28:58 +00001024 uint64_t Address = Section.getAddress();
1025 uint64_t Size = Section.getSize();
1026 bool Text = Section.isText();
1027 bool Data = Section.isData();
1028 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001029 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001030 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001031 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1032 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001033 ++i;
1034 }
1035}
1036
Kevin Enderby98da6132015-01-20 21:47:46 +00001037void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001038 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001039 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001040 StringRef Name;
1041 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001042 if (error(Section.getName(Name)))
1043 continue;
Rafael Espindola80291272014-10-08 15:28:58 +00001044 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001045 uint64_t Size = Section.getSize();
1046 if (!Size)
1047 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001048
1049 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001050 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001051 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001052 ", %04" PRIx64 ")>\n",
1053 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001054 continue;
1055 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001056
David Majnemer8f6b04c2014-07-14 16:20:14 +00001057 if (error(Section.getContents(Contents)))
1058 continue;
1059
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001060 // Dump out the content as hex and printable ascii characters.
1061 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001062 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001063 // Dump line of hex.
1064 for (std::size_t i = 0; i < 16; ++i) {
1065 if (i != 0 && i % 4 == 0)
1066 outs() << ' ';
1067 if (addr + i < end)
1068 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1069 << hexdigit(Contents[addr + i] & 0xF, true);
1070 else
1071 outs() << " ";
1072 }
1073 // Print ascii.
1074 outs() << " ";
1075 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001076 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001077 outs() << Contents[addr + i];
1078 else
1079 outs() << ".";
1080 }
1081 outs() << "\n";
1082 }
1083 }
1084}
1085
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001086static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001087 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1088 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001089 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001090 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001091 return;
1092
David Majnemer44f51e52014-09-10 12:51:52 +00001093 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001094 return;
1095
1096 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001097 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001098 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001099 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1100 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1101 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1102 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001103 << Name << "\n";
1104
David Majnemer44f51e52014-09-10 12:51:52 +00001105 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001106 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001107 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001108 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001109 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001110
David Majnemer4d571592014-09-15 19:42:42 +00001111 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1112
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001113 outs() << "AUX "
1114 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1115 , unsigned(asd->Length)
1116 , unsigned(asd->NumberOfRelocations)
1117 , unsigned(asd->NumberOfLinenumbers)
1118 , unsigned(asd->CheckSum))
1119 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001120 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001121 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001122 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001123 const char *FileName;
1124 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001125 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001126
David Majnemer44f51e52014-09-10 12:51:52 +00001127 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1128 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001129 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001130
David Majnemer44f51e52014-09-10 12:51:52 +00001131 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001132 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001133 } else {
1134 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001135 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001136 }
1137 }
1138}
1139
Kevin Enderby98da6132015-01-20 21:47:46 +00001140void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001141 outs() << "SYMBOL TABLE:\n";
1142
Rui Ueyama4e39f712014-03-18 18:58:51 +00001143 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001144 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001145 return;
1146 }
1147 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001148 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1149 if (error(AddressOrError.getError()))
1150 continue;
1151 uint64_t Address = *AddressOrError;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001152 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001153 uint32_t Flags = Symbol.getFlags();
1154 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001155 if (error(Symbol.getSection(Section)))
1156 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001157 StringRef Name;
1158 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1159 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001160 } else {
1161 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1162 if (error(NameOrErr.getError()))
1163 continue;
1164 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001165 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001166
Rui Ueyama4e39f712014-03-18 18:58:51 +00001167 bool Global = Flags & SymbolRef::SF_Global;
1168 bool Weak = Flags & SymbolRef::SF_Weak;
1169 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001170 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001171 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001172
Rui Ueyama4e39f712014-03-18 18:58:51 +00001173 char GlobLoc = ' ';
1174 if (Type != SymbolRef::ST_Unknown)
1175 GlobLoc = Global ? 'g' : 'l';
1176 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1177 ? 'd' : ' ';
1178 char FileFunc = ' ';
1179 if (Type == SymbolRef::ST_File)
1180 FileFunc = 'f';
1181 else if (Type == SymbolRef::ST_Function)
1182 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001183
Rui Ueyama4e39f712014-03-18 18:58:51 +00001184 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1185 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001186
Rui Ueyama4e39f712014-03-18 18:58:51 +00001187 outs() << format(Fmt, Address) << " "
1188 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1189 << (Weak ? 'w' : ' ') // Weak?
1190 << ' ' // Constructor. Not supported yet.
1191 << ' ' // Warning. Not supported yet.
1192 << ' ' // Indirect reference to another symbol.
1193 << Debug // Debugging (d) or dynamic (D) symbol.
1194 << FileFunc // Name of function (F), file (f) or object (O).
1195 << ' ';
1196 if (Absolute) {
1197 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001198 } else if (Common) {
1199 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001200 } else if (Section == o->section_end()) {
1201 outs() << "*UND*";
1202 } else {
1203 if (const MachOObjectFile *MachO =
1204 dyn_cast<const MachOObjectFile>(o)) {
1205 DataRefImpl DR = Section->getRawDataRefImpl();
1206 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1207 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001208 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001209 StringRef SectionName;
1210 if (error(Section->getName(SectionName)))
1211 SectionName = "";
1212 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001213 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001214
1215 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001216 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001217 uint64_t Val =
1218 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001219 outs() << format("\t %08" PRIx64 " ", Val);
1220 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001221
Davide Italianocd2514d2015-04-30 23:08:53 +00001222 if (Hidden) {
1223 outs() << ".hidden ";
1224 }
1225 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001226 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001227 }
1228}
1229
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001230static void PrintUnwindInfo(const ObjectFile *o) {
1231 outs() << "Unwind info:\n\n";
1232
1233 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1234 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001235 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1236 printMachOUnwindInfo(MachO);
1237 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001238 // TODO: Extract DWARF dump tool to objdump.
1239 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001240 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001241 return;
1242 }
1243}
1244
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001245void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001246 outs() << "Exports trie:\n";
1247 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1248 printMachOExportsTrie(MachO);
1249 else {
1250 errs() << "This operation is only currently supported "
1251 "for Mach-O executable files.\n";
1252 return;
1253 }
1254}
1255
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001256void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001257 outs() << "Rebase table:\n";
1258 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1259 printMachORebaseTable(MachO);
1260 else {
1261 errs() << "This operation is only currently supported "
1262 "for Mach-O executable files.\n";
1263 return;
1264 }
1265}
1266
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001267void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001268 outs() << "Bind table:\n";
1269 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1270 printMachOBindTable(MachO);
1271 else {
1272 errs() << "This operation is only currently supported "
1273 "for Mach-O executable files.\n";
1274 return;
1275 }
1276}
1277
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001278void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001279 outs() << "Lazy bind table:\n";
1280 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1281 printMachOLazyBindTable(MachO);
1282 else {
1283 errs() << "This operation is only currently supported "
1284 "for Mach-O executable files.\n";
1285 return;
1286 }
1287}
1288
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001289void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001290 outs() << "Weak bind table:\n";
1291 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1292 printMachOWeakBindTable(MachO);
1293 else {
1294 errs() << "This operation is only currently supported "
1295 "for Mach-O executable files.\n";
1296 return;
1297 }
1298}
Nick Kledzikac431442014-09-12 21:34:15 +00001299
Sanjoy Das6f567a42015-06-22 18:03:02 +00001300static void printFaultMaps(const ObjectFile *Obj) {
1301 const char *FaultMapSectionName = nullptr;
1302
1303 if (isa<ELFObjectFileBase>(Obj)) {
1304 FaultMapSectionName = ".llvm_faultmaps";
1305 } else if (isa<MachOObjectFile>(Obj)) {
1306 FaultMapSectionName = "__llvm_faultmaps";
1307 } else {
1308 errs() << "This operation is only currently supported "
1309 "for ELF and Mach-O executable files.\n";
1310 return;
1311 }
1312
1313 Optional<object::SectionRef> FaultMapSection;
1314
1315 for (auto Sec : Obj->sections()) {
1316 StringRef Name;
1317 Sec.getName(Name);
1318 if (Name == FaultMapSectionName) {
1319 FaultMapSection = Sec;
1320 break;
1321 }
1322 }
1323
1324 outs() << "FaultMap table:\n";
1325
1326 if (!FaultMapSection.hasValue()) {
1327 outs() << "<not found>\n";
1328 return;
1329 }
1330
1331 StringRef FaultMapContents;
1332 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1333 errs() << "Could not read the " << FaultMapContents << " section!\n";
1334 return;
1335 }
1336
1337 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1338 FaultMapContents.bytes_end());
1339
1340 outs() << FMP;
1341}
1342
Rui Ueyamac2bed422013-09-27 21:04:00 +00001343static void printPrivateFileHeader(const ObjectFile *o) {
1344 if (o->isELF()) {
1345 printELFFileHeader(o);
1346 } else if (o->isCOFF()) {
1347 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001348 } else if (o->isMachO()) {
1349 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001350 }
1351}
1352
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001353static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001354 outs() << '\n';
1355 outs() << o->getFileName()
1356 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1357
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001358 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001359 DisassembleObject(o, Relocations);
1360 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001361 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001362 if (SectionHeaders)
1363 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001364 if (SectionContents)
1365 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001366 if (SymbolTable)
1367 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001368 if (UnwindInfo)
1369 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001370 if (PrivateHeaders)
1371 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001372 if (ExportsTrie)
1373 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001374 if (Rebase)
1375 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001376 if (Bind)
1377 printBindTable(o);
1378 if (LazyBind)
1379 printLazyBindTable(o);
1380 if (WeakBind)
1381 printWeakBindTable(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001382 if (PrintFaultMaps)
1383 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001384}
1385
1386/// @brief Dump each object file in \a a;
1387static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001388 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1389 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001390 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1391 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001392 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001393 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001394 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001395 continue;
1396 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001397 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001398 DumpObject(o);
1399 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001400 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001401 }
1402}
1403
1404/// @brief Open file and figure out how to dump it.
1405static void DumpInput(StringRef file) {
1406 // If file isn't stdin, check that it exists.
1407 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001408 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001409 return;
1410 }
1411
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001412 // If we are using the Mach-O specific object file parser, then let it parse
1413 // the file and process the command line options. So the -arch flags can
1414 // be used to select specific slices, etc.
1415 if (MachOOpt) {
1416 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001417 return;
1418 }
1419
1420 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001421 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001422 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001423 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001424 return;
1425 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001426 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001427
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001428 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001429 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001430 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001431 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001432 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001433 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001434}
1435
Michael J. Spencer2670c252011-01-20 06:39:06 +00001436int main(int argc, char **argv) {
1437 // Print a stack trace if we signal out.
1438 sys::PrintStackTraceOnErrorSignal();
1439 PrettyStackTraceProgram X(argc, argv);
1440 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1441
1442 // Initialize targets and assembly printers/parsers.
1443 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001444 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001445 llvm::InitializeAllAsmParsers();
1446 llvm::InitializeAllDisassemblers();
1447
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001448 // Register the target printer for --version.
1449 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1450
Michael J. Spencer2670c252011-01-20 06:39:06 +00001451 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1452 TripleName = Triple::normalize(TripleName);
1453
1454 ToolName = argv[0];
1455
1456 // Defaults to a.out if no filenames specified.
1457 if (InputFilenames.size() == 0)
1458 InputFilenames.push_back("a.out");
1459
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001460 if (!Disassemble
1461 && !Relocations
1462 && !SectionHeaders
1463 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001464 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001465 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001466 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001467 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001468 && !Rebase
1469 && !Bind
1470 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001471 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001472 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001473 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001474 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001475 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001476 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001477 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001478 && !(DylibsUsed && MachOOpt)
1479 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001480 && !(ObjcMetaData && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001481 && !(DumpSections.size() != 0 && MachOOpt)
1482 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001483 cl::PrintHelpMessage();
1484 return 2;
1485 }
1486
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001487 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1488 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001489
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001490 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001491}