blob: 7869818546098d4f783f98fe7f0050e976f11776 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000025#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000026#include "llvm/MC/MCContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCDisassembler.h"
28#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000030#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000031#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000032#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000033#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCRelocationInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Object/Archive.h"
Rafael Espindola37070a52015-06-03 04:48:06 +000037#include "llvm/Object/ELFObjectFile.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/COFF.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000039#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000041#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000044#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000045#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000047#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/Host.h"
49#include "llvm/Support/ManagedStatic.h"
50#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/PrettyStackTrace.h"
52#include "llvm/Support/Signals.h"
53#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000054#include "llvm/Support/TargetRegistry.h"
55#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000058#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Ahmed Bougacha17926472013-08-21 07:29:02 +000061
Michael J. Spencer2670c252011-01-20 06:39:06 +000062using namespace llvm;
63using namespace object;
64
Benjamin Kramer43a772e2011-09-19 17:56:04 +000065static cl::list<std::string>
66InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000067
Kevin Enderbye2297dd2015-01-07 21:02:18 +000068cl::opt<bool>
69llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000070 cl::desc("Display assembler mnemonics for the machine instructions"));
71static cl::alias
72Disassembled("d", cl::desc("Alias for --disassemble"),
73 cl::aliasopt(Disassemble));
Michael J. Spencer2670c252011-01-20 06:39:06 +000074
Kevin Enderby98da6132015-01-20 21:47:46 +000075cl::opt<bool>
76llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000077
Kevin Enderby98da6132015-01-20 21:47:46 +000078cl::opt<bool>
79llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000080
Kevin Enderby98da6132015-01-20 21:47:46 +000081cl::opt<bool>
82llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000083
Kevin Enderbye2297dd2015-01-07 21:02:18 +000084cl::opt<bool>
85llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000086
Kevin Enderbye2297dd2015-01-07 21:02:18 +000087cl::opt<bool>
88llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000089
Kevin Enderbye2297dd2015-01-07 21:02:18 +000090cl::opt<bool>
91llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000092
Kevin Enderbye2297dd2015-01-07 21:02:18 +000093cl::opt<bool>
94llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000095
Kevin Enderbye2297dd2015-01-07 21:02:18 +000096cl::opt<bool>
97llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +000098
99static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000100MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000101static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000102MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000103
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000104cl::opt<std::string>
105llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
106 "see -version for available targets"));
107
108cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000109llvm::MCPU("mcpu",
110 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111 cl::value_desc("cpu-name"),
112 cl::init(""));
113
114cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000115llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000116 "see -version for available targets"));
117
Kevin Enderby98da6132015-01-20 21:47:46 +0000118cl::opt<bool>
119llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
120 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000121static cl::alias
122SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
123 cl::aliasopt(SectionHeaders));
124static cl::alias
125SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
126 cl::aliasopt(SectionHeaders));
127
Kevin Enderbyc9595622014-08-06 23:24:41 +0000128cl::list<std::string>
129llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000130 cl::CommaSeparated,
131 cl::desc("Target specific attributes"),
132 cl::value_desc("a1,+a2,-a3,..."));
133
Kevin Enderbybf246f52014-09-24 23:08:22 +0000134cl::opt<bool>
135llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
136 "instructions, do not print "
137 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000138
Kevin Enderby98da6132015-01-20 21:47:46 +0000139cl::opt<bool>
140llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000141
142static cl::alias
143UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
144 cl::aliasopt(UnwindInfo));
145
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000146cl::opt<bool>
147llvm::PrivateHeaders("private-headers",
148 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000149
150static cl::alias
151PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
152 cl::aliasopt(PrivateHeaders));
153
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000154cl::opt<bool>
155 llvm::PrintImmHex("print-imm-hex",
156 cl::desc("Use hex format for immediate values"));
157
Sanjoy Das6f567a42015-06-22 18:03:02 +0000158cl::opt<bool> PrintFaultMaps("fault-map-section",
159 cl::desc("Display contents of faultmap section"));
160
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000161static StringRef ToolName;
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000162static int ReturnValue = EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000163
Rafael Espindola4453e42942014-06-13 03:07:50 +0000164bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000165 if (!EC)
166 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000167
Mark Seaborneb03ac52014-01-25 00:32:01 +0000168 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000169 outs().flush();
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000170 ReturnValue = EXIT_FAILURE;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000172}
173
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000174static void report_error(StringRef File, std::error_code EC) {
175 assert(EC);
176 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
177 ReturnValue = EXIT_FAILURE;
178}
179
Craig Toppere6cb63e2014-04-25 04:24:47 +0000180static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000181 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000182 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000183 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000184 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000185 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000186 // TheTriple defaults to ELF, and COFF doesn't have an environment:
187 // the best we can do here is indicate that it is mach-o.
188 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000189 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000190
191 if (Obj->isCOFF()) {
192 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
193 if (COFFObj->getArch() == Triple::thumb)
194 TheTriple.setTriple("thumbv7-windows");
195 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000196 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000197 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000198 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000199
200 // Get the target specific parser.
201 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000202 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
203 Error);
204 if (!TheTarget) {
205 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000206 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000207 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000208
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000209 // Update the triple name and return the found target.
210 TripleName = TheTriple.getTriple();
211 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000212}
213
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000214bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000215 uint64_t a_addr = a.getOffset();
216 uint64_t b_addr = b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000217 return a_addr < b_addr;
218}
219
Colin LeMahieufb76b002015-05-28 19:07:14 +0000220namespace {
221class PrettyPrinter {
222public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000223 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000224 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000225 ArrayRef<uint8_t> Bytes, uint64_t Address,
226 raw_ostream &OS, StringRef Annot,
227 MCSubtargetInfo const &STI) {
228 outs() << format("%8" PRIx64 ":", Address);
229 if (!NoShowRawInsn) {
230 outs() << "\t";
231 dumpBytes(Bytes, outs());
232 }
233 IP.printInst(MI, outs(), "", STI);
234 }
235};
236PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000237class HexagonPrettyPrinter : public PrettyPrinter {
238public:
239 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
240 raw_ostream &OS) {
241 uint32_t opcode =
242 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
243 OS << format("%8" PRIx64 ":", Address);
244 if (!NoShowRawInsn) {
245 OS << "\t";
246 dumpBytes(Bytes.slice(0, 4), OS);
247 OS << format("%08" PRIx32, opcode);
248 }
249 }
250 void printInst(MCInstPrinter &IP, const MCInst *MI,
251 ArrayRef<uint8_t> Bytes, uint64_t Address,
252 raw_ostream &OS, StringRef Annot,
253 MCSubtargetInfo const &STI) override {
254 std::string Buffer;
255 {
256 raw_string_ostream TempStream(Buffer);
257 IP.printInst(MI, TempStream, "", STI);
258 }
259 StringRef Contents(Buffer);
260 // Split off bundle attributes
261 auto PacketBundle = Contents.rsplit('\n');
262 // Split off first instruction from the rest
263 auto HeadTail = PacketBundle.first.split('\n');
264 auto Preamble = " { ";
265 auto Separator = "";
266 while(!HeadTail.first.empty()) {
267 OS << Separator;
268 Separator = "\n";
269 printLead(Bytes, Address, OS);
270 OS << Preamble;
271 Preamble = " ";
272 StringRef Inst;
273 auto Duplex = HeadTail.first.split('\v');
274 if(!Duplex.second.empty()){
275 OS << Duplex.first;
276 OS << "; ";
277 Inst = Duplex.second;
278 }
279 else
280 Inst = HeadTail.first;
281 OS << Inst;
282 Bytes = Bytes.slice(4);
283 Address += 4;
284 HeadTail = HeadTail.second.split('\n');
285 }
286 OS << " } " << PacketBundle.second;
287 }
288};
289HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000290PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000291 switch(Triple.getArch()) {
292 default:
293 return PrettyPrinterInst;
294 case Triple::hexagon:
295 return HexagonPrettyPrinterInst;
296 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000297}
298}
299
Rafael Espindola37070a52015-06-03 04:48:06 +0000300template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000301static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
302 DataRefImpl Rel,
303 SmallVectorImpl<char> &Result) {
304 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
305 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000306 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
307 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
308
Rafael Espindola37070a52015-06-03 04:48:06 +0000309 const ELFFile<ELFT> &EF = *Obj->getELFFile();
310
Rafael Espindola6def3042015-07-01 12:56:27 +0000311 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
312 if (std::error_code EC = SecOrErr.getError())
313 return EC;
314 const Elf_Shdr *Sec = *SecOrErr;
315 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
316 if (std::error_code EC = SymTabOrErr.getError())
317 return EC;
318 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000319 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
320 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000321 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
322 if (std::error_code EC = StrTabSec.getError())
323 return EC;
324 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000325 if (std::error_code EC = StrTabOrErr.getError())
326 return EC;
327 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000328 uint8_t type;
329 StringRef res;
330 int64_t addend = 0;
331 uint16_t symbol_index = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000332 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000333 default:
334 return object_error::parse_failed;
335 case ELF::SHT_REL: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000336 const Elf_Rel *ERel = Obj->getRel(Rel);
337 type = ERel->getType(EF.isMips64EL());
338 symbol_index = ERel->getSymbol(EF.isMips64EL());
Rafael Espindola37070a52015-06-03 04:48:06 +0000339 // TODO: Read implicit addend from section data.
340 break;
341 }
342 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000343 const Elf_Rela *ERela = Obj->getRela(Rel);
344 type = ERela->getType(EF.isMips64EL());
345 symbol_index = ERela->getSymbol(EF.isMips64EL());
346 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000347 break;
348 }
349 }
350 const Elf_Sym *symb =
Rafael Espindola6def3042015-07-01 12:56:27 +0000351 EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000352 StringRef Target;
Rafael Espindola6def3042015-07-01 12:56:27 +0000353 ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
354 if (std::error_code EC = SymSec.getError())
355 return EC;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000356 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindola6def3042015-07-01 12:56:27 +0000357 ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000358 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();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000436 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
437 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000438 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000439 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000440 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000441 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000442}
443
444static void printRelocationTargetName(const MachOObjectFile *O,
445 const MachO::any_relocation_info &RE,
446 raw_string_ostream &fmt) {
447 bool IsScattered = O->isRelocationScattered(RE);
448
449 // Target of a scattered relocation is an address. In the interest of
450 // generating pretty output, scan through the symbol table looking for a
451 // symbol that aligns with that address. If we find one, print it.
452 // Otherwise, we just print the hex address of the target.
453 if (IsScattered) {
454 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
455
456 for (const SymbolRef &Symbol : O->symbols()) {
457 std::error_code ec;
458 uint64_t Addr;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000459 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola37070a52015-06-03 04:48:06 +0000460
461 if ((ec = Symbol.getAddress(Addr)))
462 report_fatal_error(ec.message());
463 if (Addr != Val)
464 continue;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000465 if (std::error_code EC = Name.getError())
466 report_fatal_error(EC.message());
467 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000468 return;
469 }
470
471 // If we couldn't find a symbol that this relocation refers to, try
472 // to find a section beginning instead.
473 for (const SectionRef &Section : O->sections()) {
474 std::error_code ec;
475
476 StringRef Name;
477 uint64_t Addr = Section.getAddress();
478 if (Addr != Val)
479 continue;
480 if ((ec = Section.getName(Name)))
481 report_fatal_error(ec.message());
482 fmt << Name;
483 return;
484 }
485
486 fmt << format("0x%x", Val);
487 return;
488 }
489
490 StringRef S;
491 bool isExtern = O->getPlainRelocationExternal(RE);
492 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
493
494 if (isExtern) {
495 symbol_iterator SI = O->symbol_begin();
496 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000497 ErrorOr<StringRef> SOrErr = SI->getName();
498 if (!error(SOrErr.getError()))
499 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000500 } else {
501 section_iterator SI = O->section_begin();
502 // Adjust for the fact that sections are 1-indexed.
503 advance(SI, Val - 1);
504 SI->getName(S);
505 }
506
507 fmt << S;
508}
509
510static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
511 const RelocationRef &RelRef,
512 SmallVectorImpl<char> &Result) {
513 DataRefImpl Rel = RelRef.getRawDataRefImpl();
514 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
515
516 unsigned Arch = Obj->getArch();
517
518 std::string fmtbuf;
519 raw_string_ostream fmt(fmtbuf);
520 unsigned Type = Obj->getAnyRelocationType(RE);
521 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
522
523 // Determine any addends that should be displayed with the relocation.
524 // These require decoding the relocation type, which is triple-specific.
525
526 // X86_64 has entirely custom relocation types.
527 if (Arch == Triple::x86_64) {
528 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
529
530 switch (Type) {
531 case MachO::X86_64_RELOC_GOT_LOAD:
532 case MachO::X86_64_RELOC_GOT: {
533 printRelocationTargetName(Obj, RE, fmt);
534 fmt << "@GOT";
535 if (isPCRel)
536 fmt << "PCREL";
537 break;
538 }
539 case MachO::X86_64_RELOC_SUBTRACTOR: {
540 DataRefImpl RelNext = Rel;
541 Obj->moveRelocationNext(RelNext);
542 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
543
544 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
545 // X86_64_RELOC_UNSIGNED.
546 // NOTE: Scattered relocations don't exist on x86_64.
547 unsigned RType = Obj->getAnyRelocationType(RENext);
548 if (RType != MachO::X86_64_RELOC_UNSIGNED)
549 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
550 "X86_64_RELOC_SUBTRACTOR.");
551
552 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
553 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
554 printRelocationTargetName(Obj, RENext, fmt);
555 fmt << "-";
556 printRelocationTargetName(Obj, RE, fmt);
557 break;
558 }
559 case MachO::X86_64_RELOC_TLV:
560 printRelocationTargetName(Obj, RE, fmt);
561 fmt << "@TLV";
562 if (isPCRel)
563 fmt << "P";
564 break;
565 case MachO::X86_64_RELOC_SIGNED_1:
566 printRelocationTargetName(Obj, RE, fmt);
567 fmt << "-1";
568 break;
569 case MachO::X86_64_RELOC_SIGNED_2:
570 printRelocationTargetName(Obj, RE, fmt);
571 fmt << "-2";
572 break;
573 case MachO::X86_64_RELOC_SIGNED_4:
574 printRelocationTargetName(Obj, RE, fmt);
575 fmt << "-4";
576 break;
577 default:
578 printRelocationTargetName(Obj, RE, fmt);
579 break;
580 }
581 // X86 and ARM share some relocation types in common.
582 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
583 Arch == Triple::ppc) {
584 // Generic relocation types...
585 switch (Type) {
586 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000587 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000588 case MachO::GENERIC_RELOC_SECTDIFF: {
589 DataRefImpl RelNext = Rel;
590 Obj->moveRelocationNext(RelNext);
591 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
592
593 // X86 sect diff's must be followed by a relocation of type
594 // GENERIC_RELOC_PAIR.
595 unsigned RType = Obj->getAnyRelocationType(RENext);
596
597 if (RType != MachO::GENERIC_RELOC_PAIR)
598 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
599 "GENERIC_RELOC_SECTDIFF.");
600
601 printRelocationTargetName(Obj, RE, fmt);
602 fmt << "-";
603 printRelocationTargetName(Obj, RENext, fmt);
604 break;
605 }
606 }
607
608 if (Arch == Triple::x86 || Arch == Triple::ppc) {
609 switch (Type) {
610 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
611 DataRefImpl RelNext = Rel;
612 Obj->moveRelocationNext(RelNext);
613 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
614
615 // X86 sect diff's must be followed by a relocation of type
616 // GENERIC_RELOC_PAIR.
617 unsigned RType = Obj->getAnyRelocationType(RENext);
618 if (RType != MachO::GENERIC_RELOC_PAIR)
619 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
620 "GENERIC_RELOC_LOCAL_SECTDIFF.");
621
622 printRelocationTargetName(Obj, RE, fmt);
623 fmt << "-";
624 printRelocationTargetName(Obj, RENext, fmt);
625 break;
626 }
627 case MachO::GENERIC_RELOC_TLV: {
628 printRelocationTargetName(Obj, RE, fmt);
629 fmt << "@TLV";
630 if (IsPCRel)
631 fmt << "P";
632 break;
633 }
634 default:
635 printRelocationTargetName(Obj, RE, fmt);
636 }
637 } else { // ARM-specific relocations
638 switch (Type) {
639 case MachO::ARM_RELOC_HALF:
640 case MachO::ARM_RELOC_HALF_SECTDIFF: {
641 // Half relocations steal a bit from the length field to encode
642 // whether this is an upper16 or a lower16 relocation.
643 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
644
645 if (isUpper)
646 fmt << ":upper16:(";
647 else
648 fmt << ":lower16:(";
649 printRelocationTargetName(Obj, RE, fmt);
650
651 DataRefImpl RelNext = Rel;
652 Obj->moveRelocationNext(RelNext);
653 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
654
655 // ARM half relocs must be followed by a relocation of type
656 // ARM_RELOC_PAIR.
657 unsigned RType = Obj->getAnyRelocationType(RENext);
658 if (RType != MachO::ARM_RELOC_PAIR)
659 report_fatal_error("Expected ARM_RELOC_PAIR after "
660 "ARM_RELOC_HALF");
661
662 // NOTE: The half of the target virtual address is stashed in the
663 // address field of the secondary relocation, but we can't reverse
664 // engineer the constant offset from it without decoding the movw/movt
665 // instruction to find the other half in its immediate field.
666
667 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
668 // symbol/section pointer of the follow-on relocation.
669 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
670 fmt << "-";
671 printRelocationTargetName(Obj, RENext, fmt);
672 }
673
674 fmt << ")";
675 break;
676 }
677 default: { printRelocationTargetName(Obj, RE, fmt); }
678 }
679 }
680 } else
681 printRelocationTargetName(Obj, RE, fmt);
682
683 fmt.flush();
684 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000685 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000686}
687
688static std::error_code getRelocationValueString(const RelocationRef &Rel,
689 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000690 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000691 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
692 return getRelocationValueString(ELF, Rel, Result);
693 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
694 return getRelocationValueString(COFF, Rel, Result);
695 auto *MachO = cast<MachOObjectFile>(Obj);
696 return getRelocationValueString(MachO, Rel, Result);
697}
698
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000699/// @brief Indicates whether this relocation should hidden when listing
700/// relocations, usually because it is the trailing part of a multipart
701/// relocation that will be printed as part of the leading relocation.
702static bool getHidden(RelocationRef RelRef) {
703 const ObjectFile *Obj = RelRef.getObject();
704 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
705 if (!MachO)
706 return false;
707
708 unsigned Arch = MachO->getArch();
709 DataRefImpl Rel = RelRef.getRawDataRefImpl();
710 uint64_t Type = MachO->getRelocationType(Rel);
711
712 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
713 // is always hidden.
714 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
715 if (Type == MachO::GENERIC_RELOC_PAIR)
716 return true;
717 } else if (Arch == Triple::x86_64) {
718 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
719 // an X86_64_RELOC_SUBTRACTOR.
720 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
721 DataRefImpl RelPrev = Rel;
722 RelPrev.d.a--;
723 uint64_t PrevType = MachO->getRelocationType(RelPrev);
724 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
725 return true;
726 }
727 }
728
729 return false;
730}
731
Michael J. Spencer51862b32011-10-13 22:17:18 +0000732static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000733 const Target *TheTarget = getTarget(Obj);
734 // getTarget() will have already issued a diagnostic if necessary, so
735 // just bail here if it failed.
736 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000737 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000738
Jack Carter551efd72012-08-28 19:24:49 +0000739 // Package up features to be passed to target/subtarget
740 std::string FeaturesStr;
741 if (MAttrs.size()) {
742 SubtargetFeatures Features;
743 for (unsigned i = 0; i != MAttrs.size(); ++i)
744 Features.AddFeature(MAttrs[i]);
745 FeaturesStr = Features.getString();
746 }
747
Ahmed Charles56440fd2014-03-06 05:51:42 +0000748 std::unique_ptr<const MCRegisterInfo> MRI(
749 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000750 if (!MRI) {
751 errs() << "error: no register info for target " << TripleName << "\n";
752 return;
753 }
754
755 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000756 std::unique_ptr<const MCAsmInfo> AsmInfo(
757 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000758 if (!AsmInfo) {
759 errs() << "error: no assembly info for target " << TripleName << "\n";
760 return;
761 }
762
Ahmed Charles56440fd2014-03-06 05:51:42 +0000763 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000764 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000765 if (!STI) {
766 errs() << "error: no subtarget info for target " << TripleName << "\n";
767 return;
768 }
769
Ahmed Charles56440fd2014-03-06 05:51:42 +0000770 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000771 if (!MII) {
772 errs() << "error: no instruction info for target " << TripleName << "\n";
773 return;
774 }
775
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000776 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
777 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
778
779 std::unique_ptr<MCDisassembler> DisAsm(
780 TheTarget->createMCDisassembler(*STI, Ctx));
781
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000782 if (!DisAsm) {
783 errs() << "error: no disassembler for target " << TripleName << "\n";
784 return;
785 }
786
Ahmed Charles56440fd2014-03-06 05:51:42 +0000787 std::unique_ptr<const MCInstrAnalysis> MIA(
788 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000789
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000790 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000791 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000792 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000793 if (!IP) {
794 errs() << "error: no instruction printer for target " << TripleName
795 << '\n';
796 return;
797 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000798 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000799 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000800
Greg Fitzgerald18432272014-03-20 22:55:15 +0000801 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
802 "\t\t\t%08" PRIx64 ": ";
803
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000804 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
805 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000806 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000807 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
808 for (const SectionRef &Section : Obj->sections()) {
809 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000810 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000811 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000812 }
813
Alexey Samsonov48803e52014-03-13 14:37:36 +0000814 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000815 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000816 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000817
Rafael Espindola80291272014-10-08 15:28:58 +0000818 uint64_t SectionAddr = Section.getAddress();
819 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000820 if (!SectSize)
821 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000822
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000823 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000824 std::vector<std::pair<uint64_t, StringRef>> Symbols;
825 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000826 if (Section.containsSymbol(Symbol)) {
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000827 uint64_t Address;
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000828 if (error(Symbol.getAddress(Address)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000829 break;
Rafael Espindolad7a32ea2015-06-24 10:20:30 +0000830 if (Address == UnknownAddress)
Mark Seaborneb03ac52014-01-25 00:32:01 +0000831 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000832 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000833 if (Address >= SectSize)
834 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000835
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000836 ErrorOr<StringRef> Name = Symbol.getName();
837 if (error(Name.getError()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000838 break;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000839 Symbols.push_back(std::make_pair(Address, *Name));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000840 }
841 }
842
843 // Sort the symbols by address, just in case they didn't come in that way.
844 array_pod_sort(Symbols.begin(), Symbols.end());
845
Michael J. Spencer51862b32011-10-13 22:17:18 +0000846 // Make a list of all the relocations for this section.
847 std::vector<RelocationRef> Rels;
848 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000849 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
850 for (const RelocationRef &Reloc : RelocSec.relocations()) {
851 Rels.push_back(Reloc);
852 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000853 }
854 }
855
856 // Sort relocations by address.
857 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
858
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000859 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000860 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000861 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000862 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000863 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000864 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000865 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000866 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000867 outs() << "Disassembly of section ";
868 if (!SegmentName.empty())
869 outs() << SegmentName << ",";
870 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000871
Rafael Espindola7884c952015-06-04 15:01:05 +0000872 // If the section has no symbol at the start, just insert a dummy one.
873 if (Symbols.empty() || Symbols[0].first != 0)
874 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000875
876 SmallString<40> Comments;
877 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000878
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000879 StringRef BytesStr;
880 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000881 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000882 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
883 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000884
Michael J. Spencer2670c252011-01-20 06:39:06 +0000885 uint64_t Size;
886 uint64_t Index;
887
Michael J. Spencer51862b32011-10-13 22:17:18 +0000888 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
889 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000890 // Disassemble symbol by symbol.
891 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000892
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000893 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000894 // The end is either the section end or the beginning of the next symbol.
895 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
896 // If this symbol has the same address as the next symbol, then skip it.
897 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000898 continue;
899
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000900 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000901
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000902#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000903 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000904#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000905 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000906#endif
907
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000908 for (Index = Start; Index < End; Index += Size) {
909 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000910
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000911 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
912 SectionAddr + Index, DebugOut,
913 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000914 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000915 Bytes.slice(Index, Size),
916 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000917 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000918 Comments.clear();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000919 outs() << "\n";
920 } else {
921 errs() << ToolName << ": warning: invalid instruction encoding\n";
922 if (Size == 0)
923 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000924 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000925
926 // Print relocation for instruction.
927 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000928 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +0000929 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000930 SmallString<16> name;
931 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000932
933 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +0000934 if (hidden) goto skip_print_rel;
935
Michael J. Spencer51862b32011-10-13 22:17:18 +0000936 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000937 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +0000938 rel_cur->getTypeName(name);
Rafael Espindola37070a52015-06-03 04:48:06 +0000939 if (error(getRelocationValueString(*rel_cur, val)))
940 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000941 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000942 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000943
944 skip_print_rel:
945 ++rel_cur;
946 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000947 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000948 }
949 }
950}
951
Kevin Enderby98da6132015-01-20 21:47:46 +0000952void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000953 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
954 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000955 // Regular objdump doesn't print relocations in non-relocatable object
956 // files.
957 if (!Obj->isRelocatableObject())
958 return;
959
Alexey Samsonov48803e52014-03-13 14:37:36 +0000960 for (const SectionRef &Section : Obj->sections()) {
961 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000962 continue;
963 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000964 if (error(Section.getName(secname)))
965 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000966 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000967 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000968 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +0000969 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000970 SmallString<32> relocname;
971 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000972 if (hidden)
973 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +0000974 Reloc.getTypeName(relocname);
Rafael Espindola37070a52015-06-03 04:48:06 +0000975 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000976 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000977 outs() << format(Fmt.data(), address) << " " << relocname << " "
978 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000979 }
980 outs() << "\n";
981 }
982}
983
Kevin Enderby98da6132015-01-20 21:47:46 +0000984void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000985 outs() << "Sections:\n"
986 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000987 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000988 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000989 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000990 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000991 return;
Rafael Espindola80291272014-10-08 15:28:58 +0000992 uint64_t Address = Section.getAddress();
993 uint64_t Size = Section.getSize();
994 bool Text = Section.isText();
995 bool Data = Section.isData();
996 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000997 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +0000998 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +0000999 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1000 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001001 ++i;
1002 }
1003}
1004
Kevin Enderby98da6132015-01-20 21:47:46 +00001005void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001006 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001007 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001008 StringRef Name;
1009 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001010 if (error(Section.getName(Name)))
1011 continue;
Rafael Espindola80291272014-10-08 15:28:58 +00001012 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001013 uint64_t Size = Section.getSize();
1014 if (!Size)
1015 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001016
1017 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001018 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001019 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001020 ", %04" PRIx64 ")>\n",
1021 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001022 continue;
1023 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001024
David Majnemer8f6b04c2014-07-14 16:20:14 +00001025 if (error(Section.getContents(Contents)))
1026 continue;
1027
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001028 // Dump out the content as hex and printable ascii characters.
1029 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001030 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001031 // Dump line of hex.
1032 for (std::size_t i = 0; i < 16; ++i) {
1033 if (i != 0 && i % 4 == 0)
1034 outs() << ' ';
1035 if (addr + i < end)
1036 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1037 << hexdigit(Contents[addr + i] & 0xF, true);
1038 else
1039 outs() << " ";
1040 }
1041 // Print ascii.
1042 outs() << " ";
1043 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001044 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001045 outs() << Contents[addr + i];
1046 else
1047 outs() << ".";
1048 }
1049 outs() << "\n";
1050 }
1051 }
1052}
1053
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001054static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001055 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1056 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001057 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001058 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001059 return;
1060
David Majnemer44f51e52014-09-10 12:51:52 +00001061 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001062 return;
1063
1064 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001065 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001066 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001067 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1068 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1069 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1070 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001071 << Name << "\n";
1072
David Majnemer44f51e52014-09-10 12:51:52 +00001073 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001074 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001075 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001076 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001077 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001078
David Majnemer4d571592014-09-15 19:42:42 +00001079 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1080
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001081 outs() << "AUX "
1082 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1083 , unsigned(asd->Length)
1084 , unsigned(asd->NumberOfRelocations)
1085 , unsigned(asd->NumberOfLinenumbers)
1086 , unsigned(asd->CheckSum))
1087 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001088 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001089 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001090 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001091 const char *FileName;
1092 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001093 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001094
David Majnemer44f51e52014-09-10 12:51:52 +00001095 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1096 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001097 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001098
David Majnemer44f51e52014-09-10 12:51:52 +00001099 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001100 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001101 } else {
1102 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001103 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001104 }
1105 }
1106}
1107
Kevin Enderby98da6132015-01-20 21:47:46 +00001108void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001109 outs() << "SYMBOL TABLE:\n";
1110
Rui Ueyama4e39f712014-03-18 18:58:51 +00001111 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001112 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001113 return;
1114 }
1115 for (const SymbolRef &Symbol : o->symbols()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001116 uint64_t Address;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001117 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001118 uint32_t Flags = Symbol.getFlags();
1119 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001120 if (error(Symbol.getAddress(Address)))
1121 continue;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001122 if (error(Symbol.getSection(Section)))
1123 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001124 StringRef Name;
1125 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1126 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001127 } else {
1128 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1129 if (error(NameOrErr.getError()))
1130 continue;
1131 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001132 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001133
Rui Ueyama4e39f712014-03-18 18:58:51 +00001134 bool Global = Flags & SymbolRef::SF_Global;
1135 bool Weak = Flags & SymbolRef::SF_Weak;
1136 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001137 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001138 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001139
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001140 if (Common)
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001141 Address = Symbol.getCommonSize();
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001142
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00001143 if (Address == UnknownAddress)
Rui Ueyama4e39f712014-03-18 18:58:51 +00001144 Address = 0;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001145 char GlobLoc = ' ';
1146 if (Type != SymbolRef::ST_Unknown)
1147 GlobLoc = Global ? 'g' : 'l';
1148 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1149 ? 'd' : ' ';
1150 char FileFunc = ' ';
1151 if (Type == SymbolRef::ST_File)
1152 FileFunc = 'f';
1153 else if (Type == SymbolRef::ST_Function)
1154 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001155
Rui Ueyama4e39f712014-03-18 18:58:51 +00001156 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1157 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001158
Rui Ueyama4e39f712014-03-18 18:58:51 +00001159 outs() << format(Fmt, Address) << " "
1160 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1161 << (Weak ? 'w' : ' ') // Weak?
1162 << ' ' // Constructor. Not supported yet.
1163 << ' ' // Warning. Not supported yet.
1164 << ' ' // Indirect reference to another symbol.
1165 << Debug // Debugging (d) or dynamic (D) symbol.
1166 << FileFunc // Name of function (F), file (f) or object (O).
1167 << ' ';
1168 if (Absolute) {
1169 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001170 } else if (Common) {
1171 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001172 } else if (Section == o->section_end()) {
1173 outs() << "*UND*";
1174 } else {
1175 if (const MachOObjectFile *MachO =
1176 dyn_cast<const MachOObjectFile>(o)) {
1177 DataRefImpl DR = Section->getRawDataRefImpl();
1178 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1179 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001180 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001181 StringRef SectionName;
1182 if (error(Section->getName(SectionName)))
1183 SectionName = "";
1184 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001185 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001186
1187 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001188 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001189 uint64_t Val =
1190 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001191 outs() << format("\t %08" PRIx64 " ", Val);
1192 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001193
Davide Italianocd2514d2015-04-30 23:08:53 +00001194 if (Hidden) {
1195 outs() << ".hidden ";
1196 }
1197 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001198 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001199 }
1200}
1201
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001202static void PrintUnwindInfo(const ObjectFile *o) {
1203 outs() << "Unwind info:\n\n";
1204
1205 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1206 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001207 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1208 printMachOUnwindInfo(MachO);
1209 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001210 // TODO: Extract DWARF dump tool to objdump.
1211 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001212 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001213 return;
1214 }
1215}
1216
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001217void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001218 outs() << "Exports trie:\n";
1219 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1220 printMachOExportsTrie(MachO);
1221 else {
1222 errs() << "This operation is only currently supported "
1223 "for Mach-O executable files.\n";
1224 return;
1225 }
1226}
1227
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001228void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001229 outs() << "Rebase table:\n";
1230 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1231 printMachORebaseTable(MachO);
1232 else {
1233 errs() << "This operation is only currently supported "
1234 "for Mach-O executable files.\n";
1235 return;
1236 }
1237}
1238
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001239void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001240 outs() << "Bind table:\n";
1241 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1242 printMachOBindTable(MachO);
1243 else {
1244 errs() << "This operation is only currently supported "
1245 "for Mach-O executable files.\n";
1246 return;
1247 }
1248}
1249
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001250void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001251 outs() << "Lazy bind table:\n";
1252 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1253 printMachOLazyBindTable(MachO);
1254 else {
1255 errs() << "This operation is only currently supported "
1256 "for Mach-O executable files.\n";
1257 return;
1258 }
1259}
1260
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001261void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001262 outs() << "Weak bind table:\n";
1263 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1264 printMachOWeakBindTable(MachO);
1265 else {
1266 errs() << "This operation is only currently supported "
1267 "for Mach-O executable files.\n";
1268 return;
1269 }
1270}
Nick Kledzikac431442014-09-12 21:34:15 +00001271
Sanjoy Das6f567a42015-06-22 18:03:02 +00001272static void printFaultMaps(const ObjectFile *Obj) {
1273 const char *FaultMapSectionName = nullptr;
1274
1275 if (isa<ELFObjectFileBase>(Obj)) {
1276 FaultMapSectionName = ".llvm_faultmaps";
1277 } else if (isa<MachOObjectFile>(Obj)) {
1278 FaultMapSectionName = "__llvm_faultmaps";
1279 } else {
1280 errs() << "This operation is only currently supported "
1281 "for ELF and Mach-O executable files.\n";
1282 return;
1283 }
1284
1285 Optional<object::SectionRef> FaultMapSection;
1286
1287 for (auto Sec : Obj->sections()) {
1288 StringRef Name;
1289 Sec.getName(Name);
1290 if (Name == FaultMapSectionName) {
1291 FaultMapSection = Sec;
1292 break;
1293 }
1294 }
1295
1296 outs() << "FaultMap table:\n";
1297
1298 if (!FaultMapSection.hasValue()) {
1299 outs() << "<not found>\n";
1300 return;
1301 }
1302
1303 StringRef FaultMapContents;
1304 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1305 errs() << "Could not read the " << FaultMapContents << " section!\n";
1306 return;
1307 }
1308
1309 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1310 FaultMapContents.bytes_end());
1311
1312 outs() << FMP;
1313}
1314
Rui Ueyamac2bed422013-09-27 21:04:00 +00001315static void printPrivateFileHeader(const ObjectFile *o) {
1316 if (o->isELF()) {
1317 printELFFileHeader(o);
1318 } else if (o->isCOFF()) {
1319 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001320 } else if (o->isMachO()) {
1321 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001322 }
1323}
1324
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001325static void DumpObject(const ObjectFile *o) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001326 outs() << '\n';
1327 outs() << o->getFileName()
1328 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1329
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001330 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001331 DisassembleObject(o, Relocations);
1332 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001333 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001334 if (SectionHeaders)
1335 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001336 if (SectionContents)
1337 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001338 if (SymbolTable)
1339 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001340 if (UnwindInfo)
1341 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001342 if (PrivateHeaders)
1343 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001344 if (ExportsTrie)
1345 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001346 if (Rebase)
1347 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001348 if (Bind)
1349 printBindTable(o);
1350 if (LazyBind)
1351 printLazyBindTable(o);
1352 if (WeakBind)
1353 printWeakBindTable(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001354 if (PrintFaultMaps)
1355 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001356}
1357
1358/// @brief Dump each object file in \a a;
1359static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001360 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1361 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001362 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1363 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001364 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001365 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001366 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001367 continue;
1368 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001369 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001370 DumpObject(o);
1371 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001372 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001373 }
1374}
1375
1376/// @brief Open file and figure out how to dump it.
1377static void DumpInput(StringRef file) {
1378 // If file isn't stdin, check that it exists.
1379 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001380 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001381 return;
1382 }
1383
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001384 // If we are using the Mach-O specific object file parser, then let it parse
1385 // the file and process the command line options. So the -arch flags can
1386 // be used to select specific slices, etc.
1387 if (MachOOpt) {
1388 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001389 return;
1390 }
1391
1392 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001393 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001394 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001395 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001396 return;
1397 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001398 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001399
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001400 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001401 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001402 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001403 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001404 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001405 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001406}
1407
Michael J. Spencer2670c252011-01-20 06:39:06 +00001408int main(int argc, char **argv) {
1409 // Print a stack trace if we signal out.
1410 sys::PrintStackTraceOnErrorSignal();
1411 PrettyStackTraceProgram X(argc, argv);
1412 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1413
1414 // Initialize targets and assembly printers/parsers.
1415 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001416 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001417 llvm::InitializeAllAsmParsers();
1418 llvm::InitializeAllDisassemblers();
1419
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001420 // Register the target printer for --version.
1421 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1422
Michael J. Spencer2670c252011-01-20 06:39:06 +00001423 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1424 TripleName = Triple::normalize(TripleName);
1425
1426 ToolName = argv[0];
1427
1428 // Defaults to a.out if no filenames specified.
1429 if (InputFilenames.size() == 0)
1430 InputFilenames.push_back("a.out");
1431
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001432 if (!Disassemble
1433 && !Relocations
1434 && !SectionHeaders
1435 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001436 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001437 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001438 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001439 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001440 && !Rebase
1441 && !Bind
1442 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001443 && !WeakBind
Kevin Enderby13023a12015-01-15 23:19:11 +00001444 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001445 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001446 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001447 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001448 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001449 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001450 && !(DylibsUsed && MachOOpt)
1451 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001452 && !(ObjcMetaData && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001453 && !(DumpSections.size() != 0 && MachOOpt)
1454 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001455 cl::PrintHelpMessage();
1456 return 2;
1457 }
1458
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001459 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1460 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001461
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001462 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001463}