blob: c61bd98e9ebdfd389f79b207787fd301f830a011 [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
Adrian Prantl437105a2015-07-08 02:04:15 +000099cl::opt<bool>
100llvm::RawClangAST("raw-clang-ast",
101 cl::desc("Dump the raw binary contents of the clang AST section"));
102
Nick Kledzik56ebef42014-09-16 01:41:51 +0000103static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000104MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000105static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000106MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000107
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000108cl::opt<std::string>
109llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
110 "see -version for available targets"));
111
112cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000113llvm::MCPU("mcpu",
114 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
115 cl::value_desc("cpu-name"),
116 cl::init(""));
117
118cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000119llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000120 "see -version for available targets"));
121
Kevin Enderby98da6132015-01-20 21:47:46 +0000122cl::opt<bool>
123llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
124 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000125static cl::alias
126SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
127 cl::aliasopt(SectionHeaders));
128static cl::alias
129SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
130 cl::aliasopt(SectionHeaders));
131
Kevin Enderbyc9595622014-08-06 23:24:41 +0000132cl::list<std::string>
133llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000134 cl::CommaSeparated,
135 cl::desc("Target specific attributes"),
136 cl::value_desc("a1,+a2,-a3,..."));
137
Kevin Enderbybf246f52014-09-24 23:08:22 +0000138cl::opt<bool>
139llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
140 "instructions, do not print "
141 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000142
Kevin Enderby98da6132015-01-20 21:47:46 +0000143cl::opt<bool>
144llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000145
146static cl::alias
147UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
148 cl::aliasopt(UnwindInfo));
149
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000150cl::opt<bool>
151llvm::PrivateHeaders("private-headers",
152 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000153
154static cl::alias
155PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
156 cl::aliasopt(PrivateHeaders));
157
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000158cl::opt<bool>
159 llvm::PrintImmHex("print-imm-hex",
160 cl::desc("Use hex format for immediate values"));
161
Sanjoy Das6f567a42015-06-22 18:03:02 +0000162cl::opt<bool> PrintFaultMaps("fault-map-section",
163 cl::desc("Display contents of faultmap section"));
164
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000165static StringRef ToolName;
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000166static int ReturnValue = EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000167
Rafael Espindola4453e42942014-06-13 03:07:50 +0000168bool llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000169 if (!EC)
170 return false;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000171
Mark Seaborneb03ac52014-01-25 00:32:01 +0000172 outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000173 outs().flush();
Rui Ueyama98fe58a2014-11-26 22:17:25 +0000174 ReturnValue = EXIT_FAILURE;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000175 return true;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000176}
177
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000178static void report_error(StringRef File, std::error_code EC) {
179 assert(EC);
180 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
181 ReturnValue = EXIT_FAILURE;
182}
183
Craig Toppere6cb63e2014-04-25 04:24:47 +0000184static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000185 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000186 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000187 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000188 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000189 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000190 // TheTriple defaults to ELF, and COFF doesn't have an environment:
191 // the best we can do here is indicate that it is mach-o.
192 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000193 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000194
195 if (Obj->isCOFF()) {
196 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
197 if (COFFObj->getArch() == Triple::thumb)
198 TheTriple.setTriple("thumbv7-windows");
199 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000200 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000201 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000202 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000203
204 // Get the target specific parser.
205 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000206 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
207 Error);
208 if (!TheTarget) {
209 errs() << ToolName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000210 return nullptr;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000211 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000212
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000213 // Update the triple name and return the found target.
214 TripleName = TheTriple.getTriple();
215 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000216}
217
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000218bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000219 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000220}
221
Colin LeMahieufb76b002015-05-28 19:07:14 +0000222namespace {
223class PrettyPrinter {
224public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000225 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000226 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000227 ArrayRef<uint8_t> Bytes, uint64_t Address,
228 raw_ostream &OS, StringRef Annot,
229 MCSubtargetInfo const &STI) {
230 outs() << format("%8" PRIx64 ":", Address);
231 if (!NoShowRawInsn) {
232 outs() << "\t";
233 dumpBytes(Bytes, outs());
234 }
235 IP.printInst(MI, outs(), "", STI);
236 }
237};
238PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000239class HexagonPrettyPrinter : public PrettyPrinter {
240public:
241 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
242 raw_ostream &OS) {
243 uint32_t opcode =
244 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
245 OS << format("%8" PRIx64 ":", Address);
246 if (!NoShowRawInsn) {
247 OS << "\t";
248 dumpBytes(Bytes.slice(0, 4), OS);
249 OS << format("%08" PRIx32, opcode);
250 }
251 }
252 void printInst(MCInstPrinter &IP, const MCInst *MI,
253 ArrayRef<uint8_t> Bytes, uint64_t Address,
254 raw_ostream &OS, StringRef Annot,
255 MCSubtargetInfo const &STI) override {
256 std::string Buffer;
257 {
258 raw_string_ostream TempStream(Buffer);
259 IP.printInst(MI, TempStream, "", STI);
260 }
261 StringRef Contents(Buffer);
262 // Split off bundle attributes
263 auto PacketBundle = Contents.rsplit('\n');
264 // Split off first instruction from the rest
265 auto HeadTail = PacketBundle.first.split('\n');
266 auto Preamble = " { ";
267 auto Separator = "";
268 while(!HeadTail.first.empty()) {
269 OS << Separator;
270 Separator = "\n";
271 printLead(Bytes, Address, OS);
272 OS << Preamble;
273 Preamble = " ";
274 StringRef Inst;
275 auto Duplex = HeadTail.first.split('\v');
276 if(!Duplex.second.empty()){
277 OS << Duplex.first;
278 OS << "; ";
279 Inst = Duplex.second;
280 }
281 else
282 Inst = HeadTail.first;
283 OS << Inst;
284 Bytes = Bytes.slice(4);
285 Address += 4;
286 HeadTail = HeadTail.second.split('\n');
287 }
288 OS << " } " << PacketBundle.second;
289 }
290};
291HexagonPrettyPrinter HexagonPrettyPrinterInst;
Colin LeMahieu35436a22015-05-29 14:48:25 +0000292PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000293 switch(Triple.getArch()) {
294 default:
295 return PrettyPrinterInst;
296 case Triple::hexagon:
297 return HexagonPrettyPrinterInst;
298 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000299}
300}
301
Rafael Espindola37070a52015-06-03 04:48:06 +0000302template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000303static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
304 DataRefImpl Rel,
305 SmallVectorImpl<char> &Result) {
306 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
307 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000308 typedef typename ELFObjectFile<ELFT>::Elf_Rel Elf_Rel;
309 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
310
Rafael Espindola37070a52015-06-03 04:48:06 +0000311 const ELFFile<ELFT> &EF = *Obj->getELFFile();
312
Rafael Espindola6def3042015-07-01 12:56:27 +0000313 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
314 if (std::error_code EC = SecOrErr.getError())
315 return EC;
316 const Elf_Shdr *Sec = *SecOrErr;
317 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
318 if (std::error_code EC = SymTabOrErr.getError())
319 return EC;
320 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000321 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
322 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000323 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
324 if (std::error_code EC = StrTabSec.getError())
325 return EC;
326 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000327 if (std::error_code EC = StrTabOrErr.getError())
328 return EC;
329 StringRef StrTab = *StrTabOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000330 uint8_t type;
331 StringRef res;
332 int64_t addend = 0;
333 uint16_t symbol_index = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000334 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000335 default:
336 return object_error::parse_failed;
337 case ELF::SHT_REL: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000338 const Elf_Rel *ERel = Obj->getRel(Rel);
339 type = ERel->getType(EF.isMips64EL());
340 symbol_index = ERel->getSymbol(EF.isMips64EL());
Rafael Espindola37070a52015-06-03 04:48:06 +0000341 // TODO: Read implicit addend from section data.
342 break;
343 }
344 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000345 const Elf_Rela *ERela = Obj->getRela(Rel);
346 type = ERela->getType(EF.isMips64EL());
347 symbol_index = ERela->getSymbol(EF.isMips64EL());
348 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000349 break;
350 }
351 }
352 const Elf_Sym *symb =
Rafael Espindola6def3042015-07-01 12:56:27 +0000353 EF.template getEntry<Elf_Sym>(Sec->sh_link, symbol_index);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000354 StringRef Target;
Rafael Espindola6def3042015-07-01 12:56:27 +0000355 ErrorOr<const Elf_Shdr *> SymSec = EF.getSection(symb);
356 if (std::error_code EC = SymSec.getError())
357 return EC;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000358 if (symb->getType() == ELF::STT_SECTION) {
Rafael Espindola6def3042015-07-01 12:56:27 +0000359 ErrorOr<StringRef> SecName = EF.getSectionName(*SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000360 if (std::error_code EC = SecName.getError())
361 return EC;
362 Target = *SecName;
363 } else {
Rafael Espindola44c28712015-06-29 21:24:55 +0000364 ErrorOr<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000365 if (!SymName)
366 return SymName.getError();
367 Target = *SymName;
368 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000369 switch (EF.getHeader()->e_machine) {
370 case ELF::EM_X86_64:
371 switch (type) {
372 case ELF::R_X86_64_PC8:
373 case ELF::R_X86_64_PC16:
374 case ELF::R_X86_64_PC32: {
375 std::string fmtbuf;
376 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000377 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000378 fmt.flush();
379 Result.append(fmtbuf.begin(), fmtbuf.end());
380 } break;
381 case ELF::R_X86_64_8:
382 case ELF::R_X86_64_16:
383 case ELF::R_X86_64_32:
384 case ELF::R_X86_64_32S:
385 case ELF::R_X86_64_64: {
386 std::string fmtbuf;
387 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000388 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000389 fmt.flush();
390 Result.append(fmtbuf.begin(), fmtbuf.end());
391 } break;
392 default:
393 res = "Unknown";
394 }
395 break;
396 case ELF::EM_AARCH64: {
397 std::string fmtbuf;
398 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000399 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000400 if (addend != 0)
401 fmt << (addend < 0 ? "" : "+") << addend;
402 fmt.flush();
403 Result.append(fmtbuf.begin(), fmtbuf.end());
404 break;
405 }
406 case ELF::EM_386:
407 case ELF::EM_ARM:
408 case ELF::EM_HEXAGON:
409 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000410 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000411 break;
412 default:
413 res = "Unknown";
414 }
415 if (Result.empty())
416 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000417 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000418}
419
420static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
421 const RelocationRef &RelRef,
422 SmallVectorImpl<char> &Result) {
423 DataRefImpl Rel = RelRef.getRawDataRefImpl();
424 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
425 return getRelocationValueString(ELF32LE, Rel, Result);
426 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
427 return getRelocationValueString(ELF64LE, Rel, Result);
428 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
429 return getRelocationValueString(ELF32BE, Rel, Result);
430 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
431 return getRelocationValueString(ELF64BE, Rel, Result);
432}
433
434static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
435 const RelocationRef &Rel,
436 SmallVectorImpl<char> &Result) {
437 symbol_iterator SymI = Rel.getSymbol();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000438 ErrorOr<StringRef> SymNameOrErr = SymI->getName();
439 if (std::error_code EC = SymNameOrErr.getError())
Rafael Espindola37070a52015-06-03 04:48:06 +0000440 return EC;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000441 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000442 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000443 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000444}
445
446static void printRelocationTargetName(const MachOObjectFile *O,
447 const MachO::any_relocation_info &RE,
448 raw_string_ostream &fmt) {
449 bool IsScattered = O->isRelocationScattered(RE);
450
451 // Target of a scattered relocation is an address. In the interest of
452 // generating pretty output, scan through the symbol table looking for a
453 // symbol that aligns with that address. If we find one, print it.
454 // Otherwise, we just print the hex address of the target.
455 if (IsScattered) {
456 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
457
458 for (const SymbolRef &Symbol : O->symbols()) {
459 std::error_code ec;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000460 ErrorOr<uint64_t> Addr = Symbol.getAddress();
461 if ((ec = Addr.getError()))
Rafael Espindola37070a52015-06-03 04:48:06 +0000462 report_fatal_error(ec.message());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000463 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000464 continue;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000465 ErrorOr<StringRef> Name = Symbol.getName();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000466 if (std::error_code EC = Name.getError())
467 report_fatal_error(EC.message());
468 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000469 return;
470 }
471
472 // If we couldn't find a symbol that this relocation refers to, try
473 // to find a section beginning instead.
474 for (const SectionRef &Section : O->sections()) {
475 std::error_code ec;
476
477 StringRef Name;
478 uint64_t Addr = Section.getAddress();
479 if (Addr != Val)
480 continue;
481 if ((ec = Section.getName(Name)))
482 report_fatal_error(ec.message());
483 fmt << Name;
484 return;
485 }
486
487 fmt << format("0x%x", Val);
488 return;
489 }
490
491 StringRef S;
492 bool isExtern = O->getPlainRelocationExternal(RE);
493 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
494
495 if (isExtern) {
496 symbol_iterator SI = O->symbol_begin();
497 advance(SI, Val);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000498 ErrorOr<StringRef> SOrErr = SI->getName();
499 if (!error(SOrErr.getError()))
500 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000501 } else {
502 section_iterator SI = O->section_begin();
503 // Adjust for the fact that sections are 1-indexed.
504 advance(SI, Val - 1);
505 SI->getName(S);
506 }
507
508 fmt << S;
509}
510
511static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
512 const RelocationRef &RelRef,
513 SmallVectorImpl<char> &Result) {
514 DataRefImpl Rel = RelRef.getRawDataRefImpl();
515 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
516
517 unsigned Arch = Obj->getArch();
518
519 std::string fmtbuf;
520 raw_string_ostream fmt(fmtbuf);
521 unsigned Type = Obj->getAnyRelocationType(RE);
522 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
523
524 // Determine any addends that should be displayed with the relocation.
525 // These require decoding the relocation type, which is triple-specific.
526
527 // X86_64 has entirely custom relocation types.
528 if (Arch == Triple::x86_64) {
529 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
530
531 switch (Type) {
532 case MachO::X86_64_RELOC_GOT_LOAD:
533 case MachO::X86_64_RELOC_GOT: {
534 printRelocationTargetName(Obj, RE, fmt);
535 fmt << "@GOT";
536 if (isPCRel)
537 fmt << "PCREL";
538 break;
539 }
540 case MachO::X86_64_RELOC_SUBTRACTOR: {
541 DataRefImpl RelNext = Rel;
542 Obj->moveRelocationNext(RelNext);
543 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
544
545 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
546 // X86_64_RELOC_UNSIGNED.
547 // NOTE: Scattered relocations don't exist on x86_64.
548 unsigned RType = Obj->getAnyRelocationType(RENext);
549 if (RType != MachO::X86_64_RELOC_UNSIGNED)
550 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
551 "X86_64_RELOC_SUBTRACTOR.");
552
553 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
554 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
555 printRelocationTargetName(Obj, RENext, fmt);
556 fmt << "-";
557 printRelocationTargetName(Obj, RE, fmt);
558 break;
559 }
560 case MachO::X86_64_RELOC_TLV:
561 printRelocationTargetName(Obj, RE, fmt);
562 fmt << "@TLV";
563 if (isPCRel)
564 fmt << "P";
565 break;
566 case MachO::X86_64_RELOC_SIGNED_1:
567 printRelocationTargetName(Obj, RE, fmt);
568 fmt << "-1";
569 break;
570 case MachO::X86_64_RELOC_SIGNED_2:
571 printRelocationTargetName(Obj, RE, fmt);
572 fmt << "-2";
573 break;
574 case MachO::X86_64_RELOC_SIGNED_4:
575 printRelocationTargetName(Obj, RE, fmt);
576 fmt << "-4";
577 break;
578 default:
579 printRelocationTargetName(Obj, RE, fmt);
580 break;
581 }
582 // X86 and ARM share some relocation types in common.
583 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
584 Arch == Triple::ppc) {
585 // Generic relocation types...
586 switch (Type) {
587 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000588 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000589 case MachO::GENERIC_RELOC_SECTDIFF: {
590 DataRefImpl RelNext = Rel;
591 Obj->moveRelocationNext(RelNext);
592 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
593
594 // X86 sect diff's must be followed by a relocation of type
595 // GENERIC_RELOC_PAIR.
596 unsigned RType = Obj->getAnyRelocationType(RENext);
597
598 if (RType != MachO::GENERIC_RELOC_PAIR)
599 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
600 "GENERIC_RELOC_SECTDIFF.");
601
602 printRelocationTargetName(Obj, RE, fmt);
603 fmt << "-";
604 printRelocationTargetName(Obj, RENext, fmt);
605 break;
606 }
607 }
608
609 if (Arch == Triple::x86 || Arch == Triple::ppc) {
610 switch (Type) {
611 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
612 DataRefImpl RelNext = Rel;
613 Obj->moveRelocationNext(RelNext);
614 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
615
616 // X86 sect diff's must be followed by a relocation of type
617 // GENERIC_RELOC_PAIR.
618 unsigned RType = Obj->getAnyRelocationType(RENext);
619 if (RType != MachO::GENERIC_RELOC_PAIR)
620 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
621 "GENERIC_RELOC_LOCAL_SECTDIFF.");
622
623 printRelocationTargetName(Obj, RE, fmt);
624 fmt << "-";
625 printRelocationTargetName(Obj, RENext, fmt);
626 break;
627 }
628 case MachO::GENERIC_RELOC_TLV: {
629 printRelocationTargetName(Obj, RE, fmt);
630 fmt << "@TLV";
631 if (IsPCRel)
632 fmt << "P";
633 break;
634 }
635 default:
636 printRelocationTargetName(Obj, RE, fmt);
637 }
638 } else { // ARM-specific relocations
639 switch (Type) {
640 case MachO::ARM_RELOC_HALF:
641 case MachO::ARM_RELOC_HALF_SECTDIFF: {
642 // Half relocations steal a bit from the length field to encode
643 // whether this is an upper16 or a lower16 relocation.
644 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
645
646 if (isUpper)
647 fmt << ":upper16:(";
648 else
649 fmt << ":lower16:(";
650 printRelocationTargetName(Obj, RE, fmt);
651
652 DataRefImpl RelNext = Rel;
653 Obj->moveRelocationNext(RelNext);
654 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
655
656 // ARM half relocs must be followed by a relocation of type
657 // ARM_RELOC_PAIR.
658 unsigned RType = Obj->getAnyRelocationType(RENext);
659 if (RType != MachO::ARM_RELOC_PAIR)
660 report_fatal_error("Expected ARM_RELOC_PAIR after "
661 "ARM_RELOC_HALF");
662
663 // NOTE: The half of the target virtual address is stashed in the
664 // address field of the secondary relocation, but we can't reverse
665 // engineer the constant offset from it without decoding the movw/movt
666 // instruction to find the other half in its immediate field.
667
668 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
669 // symbol/section pointer of the follow-on relocation.
670 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
671 fmt << "-";
672 printRelocationTargetName(Obj, RENext, fmt);
673 }
674
675 fmt << ")";
676 break;
677 }
678 default: { printRelocationTargetName(Obj, RE, fmt); }
679 }
680 }
681 } else
682 printRelocationTargetName(Obj, RE, fmt);
683
684 fmt.flush();
685 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000686 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000687}
688
689static std::error_code getRelocationValueString(const RelocationRef &Rel,
690 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000691 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000692 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
693 return getRelocationValueString(ELF, Rel, Result);
694 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
695 return getRelocationValueString(COFF, Rel, Result);
696 auto *MachO = cast<MachOObjectFile>(Obj);
697 return getRelocationValueString(MachO, Rel, Result);
698}
699
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000700/// @brief Indicates whether this relocation should hidden when listing
701/// relocations, usually because it is the trailing part of a multipart
702/// relocation that will be printed as part of the leading relocation.
703static bool getHidden(RelocationRef RelRef) {
704 const ObjectFile *Obj = RelRef.getObject();
705 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
706 if (!MachO)
707 return false;
708
709 unsigned Arch = MachO->getArch();
710 DataRefImpl Rel = RelRef.getRawDataRefImpl();
711 uint64_t Type = MachO->getRelocationType(Rel);
712
713 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
714 // is always hidden.
715 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
716 if (Type == MachO::GENERIC_RELOC_PAIR)
717 return true;
718 } else if (Arch == Triple::x86_64) {
719 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
720 // an X86_64_RELOC_SUBTRACTOR.
721 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
722 DataRefImpl RelPrev = Rel;
723 RelPrev.d.a--;
724 uint64_t PrevType = MachO->getRelocationType(RelPrev);
725 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
726 return true;
727 }
728 }
729
730 return false;
731}
732
Michael J. Spencer51862b32011-10-13 22:17:18 +0000733static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000734 const Target *TheTarget = getTarget(Obj);
735 // getTarget() will have already issued a diagnostic if necessary, so
736 // just bail here if it failed.
737 if (!TheTarget)
Michael J. Spencer2670c252011-01-20 06:39:06 +0000738 return;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000739
Jack Carter551efd72012-08-28 19:24:49 +0000740 // Package up features to be passed to target/subtarget
741 std::string FeaturesStr;
742 if (MAttrs.size()) {
743 SubtargetFeatures Features;
744 for (unsigned i = 0; i != MAttrs.size(); ++i)
745 Features.AddFeature(MAttrs[i]);
746 FeaturesStr = Features.getString();
747 }
748
Ahmed Charles56440fd2014-03-06 05:51:42 +0000749 std::unique_ptr<const MCRegisterInfo> MRI(
750 TheTarget->createMCRegInfo(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000751 if (!MRI) {
752 errs() << "error: no register info for target " << TripleName << "\n";
753 return;
754 }
755
756 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000757 std::unique_ptr<const MCAsmInfo> AsmInfo(
758 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000759 if (!AsmInfo) {
760 errs() << "error: no assembly info for target " << TripleName << "\n";
761 return;
762 }
763
Ahmed Charles56440fd2014-03-06 05:51:42 +0000764 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000765 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000766 if (!STI) {
767 errs() << "error: no subtarget info for target " << TripleName << "\n";
768 return;
769 }
770
Ahmed Charles56440fd2014-03-06 05:51:42 +0000771 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000772 if (!MII) {
773 errs() << "error: no instruction info for target " << TripleName << "\n";
774 return;
775 }
776
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000777 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
778 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
779
780 std::unique_ptr<MCDisassembler> DisAsm(
781 TheTarget->createMCDisassembler(*STI, Ctx));
782
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000783 if (!DisAsm) {
784 errs() << "error: no disassembler for target " << TripleName << "\n";
785 return;
786 }
787
Ahmed Charles56440fd2014-03-06 05:51:42 +0000788 std::unique_ptr<const MCInstrAnalysis> MIA(
789 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000790
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000791 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000792 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Eric Christopherf8019402015-03-31 00:10:04 +0000793 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000794 if (!IP) {
795 errs() << "error: no instruction printer for target " << TripleName
796 << '\n';
797 return;
798 }
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000799 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000800 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000801
Greg Fitzgerald18432272014-03-20 22:55:15 +0000802 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
803 "\t\t\t%08" PRIx64 ": ";
804
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000805 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
806 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000807 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000808 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
809 for (const SectionRef &Section : Obj->sections()) {
810 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000811 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000812 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000813 }
814
David Majnemer81afca62015-07-07 22:06:59 +0000815 // Create a mapping from virtual address to symbol name. This is used to
816 // pretty print the target of a call.
817 std::vector<std::pair<uint64_t, StringRef>> AllSymbols;
818 if (MIA) {
819 for (const SymbolRef &Symbol : Obj->symbols()) {
820 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
821 if (error(AddressOrErr.getError()))
822 break;
823 uint64_t Address = *AddressOrErr;
824
825 ErrorOr<StringRef> Name = Symbol.getName();
826 if (error(Name.getError()))
827 break;
828 if (Name->empty())
829 continue;
830 AllSymbols.push_back(std::make_pair(Address, *Name));
831 }
832
833 array_pod_sort(AllSymbols.begin(), AllSymbols.end());
834 }
835
Alexey Samsonov48803e52014-03-13 14:37:36 +0000836 for (const SectionRef &Section : Obj->sections()) {
David Majnemer236b0ca2014-11-17 11:17:17 +0000837 if (!Section.isText() || Section.isVirtual())
Mark Seaborneb03ac52014-01-25 00:32:01 +0000838 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000839
Rafael Espindola80291272014-10-08 15:28:58 +0000840 uint64_t SectionAddr = Section.getAddress();
841 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +0000842 if (!SectSize)
843 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000844
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000845 // Make a list of all the symbols in this section.
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000846 std::vector<std::pair<uint64_t, StringRef>> Symbols;
847 for (const SymbolRef &Symbol : Obj->symbols()) {
Rafael Espindola80291272014-10-08 15:28:58 +0000848 if (Section.containsSymbol(Symbol)) {
Rafael Espindolaed067c42015-07-03 18:19:00 +0000849 ErrorOr<uint64_t> AddressOrErr = Symbol.getAddress();
850 if (error(AddressOrErr.getError()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000851 break;
Rafael Espindolaed067c42015-07-03 18:19:00 +0000852 uint64_t Address = *AddressOrErr;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000853 Address -= SectionAddr;
Simon Atanasyan2b614e12014-02-24 22:12:11 +0000854 if (Address >= SectSize)
855 continue;
Cameron Zwarich07f0f772012-02-03 04:13:37 +0000856
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000857 ErrorOr<StringRef> Name = Symbol.getName();
858 if (error(Name.getError()))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000859 break;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000860 Symbols.push_back(std::make_pair(Address, *Name));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000861 }
862 }
863
864 // Sort the symbols by address, just in case they didn't come in that way.
865 array_pod_sort(Symbols.begin(), Symbols.end());
866
Michael J. Spencer51862b32011-10-13 22:17:18 +0000867 // Make a list of all the relocations for this section.
868 std::vector<RelocationRef> Rels;
869 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000870 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
871 for (const RelocationRef &Reloc : RelocSec.relocations()) {
872 Rels.push_back(Reloc);
873 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000874 }
875 }
876
877 // Sort relocations by address.
878 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
879
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000880 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +0000881 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000882 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +0000883 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000884 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000885 StringRef name;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000886 if (error(Section.getName(name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000887 break;
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000888 outs() << "Disassembly of section ";
889 if (!SegmentName.empty())
890 outs() << SegmentName << ",";
891 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000892
Rafael Espindola7884c952015-06-04 15:01:05 +0000893 // If the section has no symbol at the start, just insert a dummy one.
894 if (Symbols.empty() || Symbols[0].first != 0)
895 Symbols.insert(Symbols.begin(), std::make_pair(0, name));
Alp Tokere69170a2014-06-26 22:52:05 +0000896
897 SmallString<40> Comments;
898 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000899
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000900 StringRef BytesStr;
901 if (error(Section.getContents(BytesStr)))
Mark Seaborneb03ac52014-01-25 00:32:01 +0000902 break;
Aaron Ballman106fd7b2014-11-12 14:01:17 +0000903 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
904 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000905
Michael J. Spencer2670c252011-01-20 06:39:06 +0000906 uint64_t Size;
907 uint64_t Index;
908
Michael J. Spencer51862b32011-10-13 22:17:18 +0000909 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
910 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000911 // Disassemble symbol by symbol.
912 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +0000913
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000914 uint64_t Start = Symbols[si].first;
Rafael Espindolae45c7402014-08-17 16:31:39 +0000915 // The end is either the section end or the beginning of the next symbol.
916 uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
917 // If this symbol has the same address as the next symbol, then skip it.
918 if (Start == End)
Michael J. Spenceree84f642011-10-13 20:37:08 +0000919 continue;
920
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000921 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +0000922
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000923#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +0000924 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000925#else
Mark Seaborneb03ac52014-01-25 00:32:01 +0000926 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000927#endif
928
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000929 for (Index = Start; Index < End; Index += Size) {
930 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +0000931
Rafael Espindola7fc5b872014-11-12 02:04:27 +0000932 if (DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
933 SectionAddr + Index, DebugOut,
934 CommentStream)) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000935 PIP.printInst(*IP, &Inst,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000936 Bytes.slice(Index, Size),
937 SectionAddr + Index, outs(), "", *STI);
Alp Tokere69170a2014-06-26 22:52:05 +0000938 outs() << CommentStream.str();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000939 Comments.clear();
David Majnemer81afca62015-07-07 22:06:59 +0000940 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst))) {
941 uint64_t Target;
942 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
943 const auto &TargetSym =
944 std::lower_bound(AllSymbols.begin(), AllSymbols.end(),
945 std::make_pair(Target, StringRef()));
946 if (TargetSym != AllSymbols.end()) {
947 outs() << " <" << TargetSym->second;
948 uint64_t Disp = TargetSym->first - Target;
949 if (Disp)
950 outs() << '-' << Disp;
951 outs() << '>';
952 }
953 }
954 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000955 outs() << "\n";
956 } else {
957 errs() << ToolName << ": warning: invalid instruction encoding\n";
958 if (Size == 0)
959 Size = 1; // skip illegible bytes
Benjamin Kramere0dda9c2011-07-15 18:39:24 +0000960 }
Michael J. Spencer51862b32011-10-13 22:17:18 +0000961
962 // Print relocation for instruction.
963 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000964 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +0000965 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000966 SmallString<16> name;
967 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +0000968
969 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +0000970 if (hidden) goto skip_print_rel;
971
Michael J. Spencer51862b32011-10-13 22:17:18 +0000972 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +0000973 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +0000974 rel_cur->getTypeName(name);
Rafael Espindola37070a52015-06-03 04:48:06 +0000975 if (error(getRelocationValueString(*rel_cur, val)))
976 goto skip_print_rel;
Greg Fitzgerald18432272014-03-20 22:55:15 +0000977 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +0000978 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +0000979
980 skip_print_rel:
981 ++rel_cur;
982 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000983 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000984 }
985 }
986}
987
Kevin Enderby98da6132015-01-20 21:47:46 +0000988void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +0000989 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
990 "%08" PRIx64;
Rafael Espindolac66d7612014-08-17 19:09:37 +0000991 // Regular objdump doesn't print relocations in non-relocatable object
992 // files.
993 if (!Obj->isRelocatableObject())
994 return;
995
Alexey Samsonov48803e52014-03-13 14:37:36 +0000996 for (const SectionRef &Section : Obj->sections()) {
997 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000998 continue;
999 StringRef secname;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001000 if (error(Section.getName(secname)))
1001 continue;
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001002 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001003 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001004 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001005 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001006 SmallString<32> relocname;
1007 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001008 if (hidden)
1009 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001010 Reloc.getTypeName(relocname);
Rafael Espindola37070a52015-06-03 04:48:06 +00001011 if (error(getRelocationValueString(Reloc, valuestr)))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001012 continue;
Greg Fitzgerald18432272014-03-20 22:55:15 +00001013 outs() << format(Fmt.data(), address) << " " << relocname << " "
1014 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001015 }
1016 outs() << "\n";
1017 }
1018}
1019
Kevin Enderby98da6132015-01-20 21:47:46 +00001020void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001021 outs() << "Sections:\n"
1022 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001023 unsigned i = 0;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001024 for (const SectionRef &Section : Obj->sections()) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001025 StringRef Name;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001026 if (error(Section.getName(Name)))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001027 return;
Rafael Espindola80291272014-10-08 15:28:58 +00001028 uint64_t Address = Section.getAddress();
1029 uint64_t Size = Section.getSize();
1030 bool Text = Section.isText();
1031 bool Data = Section.isData();
1032 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001033 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001034 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001035 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1036 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001037 ++i;
1038 }
1039}
1040
Kevin Enderby98da6132015-01-20 21:47:46 +00001041void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001042 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001043 for (const SectionRef &Section : Obj->sections()) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001044 StringRef Name;
1045 StringRef Contents;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001046 if (error(Section.getName(Name)))
1047 continue;
Rafael Espindola80291272014-10-08 15:28:58 +00001048 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001049 uint64_t Size = Section.getSize();
1050 if (!Size)
1051 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001052
1053 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001054 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001055 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001056 ", %04" PRIx64 ")>\n",
1057 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001058 continue;
1059 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001060
David Majnemer8f6b04c2014-07-14 16:20:14 +00001061 if (error(Section.getContents(Contents)))
1062 continue;
1063
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001064 // Dump out the content as hex and printable ascii characters.
1065 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001066 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001067 // Dump line of hex.
1068 for (std::size_t i = 0; i < 16; ++i) {
1069 if (i != 0 && i % 4 == 0)
1070 outs() << ' ';
1071 if (addr + i < end)
1072 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1073 << hexdigit(Contents[addr + i] & 0xF, true);
1074 else
1075 outs() << " ";
1076 }
1077 // Print ascii.
1078 outs() << " ";
1079 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001080 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001081 outs() << Contents[addr + i];
1082 else
1083 outs() << ".";
1084 }
1085 outs() << "\n";
1086 }
1087 }
1088}
1089
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001090static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
David Majnemer44f51e52014-09-10 12:51:52 +00001091 for (unsigned SI = 0, SE = coff->getNumberOfSymbols(); SI != SE; ++SI) {
1092 ErrorOr<COFFSymbolRef> Symbol = coff->getSymbol(SI);
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001093 StringRef Name;
David Majnemer44f51e52014-09-10 12:51:52 +00001094 if (error(Symbol.getError()))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001095 return;
1096
David Majnemer44f51e52014-09-10 12:51:52 +00001097 if (error(coff->getSymbolName(*Symbol, Name)))
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001098 return;
1099
1100 outs() << "[" << format("%2d", SI) << "]"
David Majnemer44f51e52014-09-10 12:51:52 +00001101 << "(sec " << format("%2d", int(Symbol->getSectionNumber())) << ")"
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001102 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
David Majnemer44f51e52014-09-10 12:51:52 +00001103 << "(ty " << format("%3x", unsigned(Symbol->getType())) << ")"
1104 << "(scl " << format("%3x", unsigned(Symbol->getStorageClass())) << ") "
1105 << "(nx " << unsigned(Symbol->getNumberOfAuxSymbols()) << ") "
1106 << "0x" << format("%08x", unsigned(Symbol->getValue())) << " "
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001107 << Name << "\n";
1108
David Majnemer44f51e52014-09-10 12:51:52 +00001109 for (unsigned AI = 0, AE = Symbol->getNumberOfAuxSymbols(); AI < AE; ++AI, ++SI) {
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001110 if (Symbol->isSectionDefinition()) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001111 const coff_aux_section_definition *asd;
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001112 if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001113 return;
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001114
David Majnemer4d571592014-09-15 19:42:42 +00001115 int32_t AuxNumber = asd->getNumber(Symbol->isBigObj());
1116
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001117 outs() << "AUX "
1118 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
1119 , unsigned(asd->Length)
1120 , unsigned(asd->NumberOfRelocations)
1121 , unsigned(asd->NumberOfLinenumbers)
1122 , unsigned(asd->CheckSum))
1123 << format("assoc %d comdat %d\n"
David Majnemer4d571592014-09-15 19:42:42 +00001124 , unsigned(AuxNumber)
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001125 , unsigned(asd->Selection));
Saleem Abdulrasool7050eed2014-04-14 02:37:28 +00001126 } else if (Symbol->isFileRecord()) {
David Majnemer44f51e52014-09-10 12:51:52 +00001127 const char *FileName;
1128 if (error(coff->getAuxSymbol<char>(SI + 1, FileName)))
Saleem Abdulrasool63a0dd62014-04-13 22:54:11 +00001129 return;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001130
David Majnemer44f51e52014-09-10 12:51:52 +00001131 StringRef Name(FileName, Symbol->getNumberOfAuxSymbols() *
1132 coff->getSymbolTableEntrySize());
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001133 outs() << "AUX " << Name.rtrim(StringRef("\0", 1)) << '\n';
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001134
David Majnemer44f51e52014-09-10 12:51:52 +00001135 SI = SI + Symbol->getNumberOfAuxSymbols();
Saleem Abdulrasool13a3f692014-04-14 16:38:25 +00001136 break;
Saleem Abdulrasoold38c6b12014-04-14 02:37:23 +00001137 } else {
1138 outs() << "AUX Unknown\n";
Saleem Abdulrasool9ede5c72014-04-13 03:11:08 +00001139 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001140 }
1141 }
1142}
1143
Kevin Enderby98da6132015-01-20 21:47:46 +00001144void llvm::PrintSymbolTable(const ObjectFile *o) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001145 outs() << "SYMBOL TABLE:\n";
1146
Rui Ueyama4e39f712014-03-18 18:58:51 +00001147 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001148 PrintCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001149 return;
1150 }
1151 for (const SymbolRef &Symbol : o->symbols()) {
Rafael Espindolaed067c42015-07-03 18:19:00 +00001152 ErrorOr<uint64_t> AddressOrError = Symbol.getAddress();
1153 if (error(AddressOrError.getError()))
1154 continue;
1155 uint64_t Address = *AddressOrError;
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00001156 SymbolRef::Type Type = Symbol.getType();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001157 uint32_t Flags = Symbol.getFlags();
1158 section_iterator Section = o->section_end();
Rui Ueyama4e39f712014-03-18 18:58:51 +00001159 if (error(Symbol.getSection(Section)))
1160 continue;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001161 StringRef Name;
1162 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1163 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001164 } else {
1165 ErrorOr<StringRef> NameOrErr = Symbol.getName();
1166 if (error(NameOrErr.getError()))
1167 continue;
1168 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001169 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001170
Rui Ueyama4e39f712014-03-18 18:58:51 +00001171 bool Global = Flags & SymbolRef::SF_Global;
1172 bool Weak = Flags & SymbolRef::SF_Weak;
1173 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001174 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001175 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001176
Rui Ueyama4e39f712014-03-18 18:58:51 +00001177 char GlobLoc = ' ';
1178 if (Type != SymbolRef::ST_Unknown)
1179 GlobLoc = Global ? 'g' : 'l';
1180 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1181 ? 'd' : ' ';
1182 char FileFunc = ' ';
1183 if (Type == SymbolRef::ST_File)
1184 FileFunc = 'f';
1185 else if (Type == SymbolRef::ST_Function)
1186 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001187
Rui Ueyama4e39f712014-03-18 18:58:51 +00001188 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1189 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001190
Rui Ueyama4e39f712014-03-18 18:58:51 +00001191 outs() << format(Fmt, Address) << " "
1192 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1193 << (Weak ? 'w' : ' ') // Weak?
1194 << ' ' // Constructor. Not supported yet.
1195 << ' ' // Warning. Not supported yet.
1196 << ' ' // Indirect reference to another symbol.
1197 << Debug // Debugging (d) or dynamic (D) symbol.
1198 << FileFunc // Name of function (F), file (f) or object (O).
1199 << ' ';
1200 if (Absolute) {
1201 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001202 } else if (Common) {
1203 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001204 } else if (Section == o->section_end()) {
1205 outs() << "*UND*";
1206 } else {
1207 if (const MachOObjectFile *MachO =
1208 dyn_cast<const MachOObjectFile>(o)) {
1209 DataRefImpl DR = Section->getRawDataRefImpl();
1210 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1211 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001212 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001213 StringRef SectionName;
1214 if (error(Section->getName(SectionName)))
1215 SectionName = "";
1216 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001217 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001218
1219 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001220 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001221 uint64_t Val =
1222 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001223 outs() << format("\t %08" PRIx64 " ", Val);
1224 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001225
Davide Italianocd2514d2015-04-30 23:08:53 +00001226 if (Hidden) {
1227 outs() << ".hidden ";
1228 }
1229 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001230 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001231 }
1232}
1233
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001234static void PrintUnwindInfo(const ObjectFile *o) {
1235 outs() << "Unwind info:\n\n";
1236
1237 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1238 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001239 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1240 printMachOUnwindInfo(MachO);
1241 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001242 // TODO: Extract DWARF dump tool to objdump.
1243 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001244 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001245 return;
1246 }
1247}
1248
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001249void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001250 outs() << "Exports trie:\n";
1251 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1252 printMachOExportsTrie(MachO);
1253 else {
1254 errs() << "This operation is only currently supported "
1255 "for Mach-O executable files.\n";
1256 return;
1257 }
1258}
1259
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001260void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001261 outs() << "Rebase table:\n";
1262 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1263 printMachORebaseTable(MachO);
1264 else {
1265 errs() << "This operation is only currently supported "
1266 "for Mach-O executable files.\n";
1267 return;
1268 }
1269}
1270
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001271void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001272 outs() << "Bind table:\n";
1273 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1274 printMachOBindTable(MachO);
1275 else {
1276 errs() << "This operation is only currently supported "
1277 "for Mach-O executable files.\n";
1278 return;
1279 }
1280}
1281
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001282void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001283 outs() << "Lazy bind table:\n";
1284 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1285 printMachOLazyBindTable(MachO);
1286 else {
1287 errs() << "This operation is only currently supported "
1288 "for Mach-O executable files.\n";
1289 return;
1290 }
1291}
1292
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001293void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001294 outs() << "Weak bind table:\n";
1295 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1296 printMachOWeakBindTable(MachO);
1297 else {
1298 errs() << "This operation is only currently supported "
1299 "for Mach-O executable files.\n";
1300 return;
1301 }
1302}
Nick Kledzikac431442014-09-12 21:34:15 +00001303
Adrian Prantl437105a2015-07-08 02:04:15 +00001304/// Dump the raw contents of the __clangast section so the output can be piped
1305/// into llvm-bcanalyzer.
1306void llvm::printRawClangAST(const ObjectFile *Obj) {
1307 if (outs().is_displayed()) {
1308 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1309 "the clang ast section.\n"
1310 "Please redirect the output to a file or another program such as "
1311 "llvm-bcanalyzer.\n";
1312 return;
1313 }
1314
1315 StringRef ClangASTSectionName("__clangast");
1316 if (isa<COFFObjectFile>(Obj)) {
1317 ClangASTSectionName = "clangast";
1318 }
1319
1320 Optional<object::SectionRef> ClangASTSection;
1321 for (auto Sec : Obj->sections()) {
1322 StringRef Name;
1323 Sec.getName(Name);
1324 if (Name == ClangASTSectionName) {
1325 ClangASTSection = Sec;
1326 break;
1327 }
1328 }
1329 if (!ClangASTSection)
1330 return;
1331
1332 StringRef ClangASTContents;
1333 if (error(ClangASTSection.getValue().getContents(ClangASTContents))) {
1334 errs() << "Could not read the " << ClangASTSectionName << " section!\n";
1335 return;
1336 }
1337
1338 outs().write(ClangASTContents.data(), ClangASTContents.size());
1339}
1340
Sanjoy Das6f567a42015-06-22 18:03:02 +00001341static void printFaultMaps(const ObjectFile *Obj) {
1342 const char *FaultMapSectionName = nullptr;
1343
1344 if (isa<ELFObjectFileBase>(Obj)) {
1345 FaultMapSectionName = ".llvm_faultmaps";
1346 } else if (isa<MachOObjectFile>(Obj)) {
1347 FaultMapSectionName = "__llvm_faultmaps";
1348 } else {
1349 errs() << "This operation is only currently supported "
1350 "for ELF and Mach-O executable files.\n";
1351 return;
1352 }
1353
1354 Optional<object::SectionRef> FaultMapSection;
1355
1356 for (auto Sec : Obj->sections()) {
1357 StringRef Name;
1358 Sec.getName(Name);
1359 if (Name == FaultMapSectionName) {
1360 FaultMapSection = Sec;
1361 break;
1362 }
1363 }
1364
1365 outs() << "FaultMap table:\n";
1366
1367 if (!FaultMapSection.hasValue()) {
1368 outs() << "<not found>\n";
1369 return;
1370 }
1371
1372 StringRef FaultMapContents;
1373 if (error(FaultMapSection.getValue().getContents(FaultMapContents))) {
1374 errs() << "Could not read the " << FaultMapContents << " section!\n";
1375 return;
1376 }
1377
1378 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1379 FaultMapContents.bytes_end());
1380
1381 outs() << FMP;
1382}
1383
Rui Ueyamac2bed422013-09-27 21:04:00 +00001384static void printPrivateFileHeader(const ObjectFile *o) {
1385 if (o->isELF()) {
1386 printELFFileHeader(o);
1387 } else if (o->isCOFF()) {
1388 printCOFFFileHeader(o);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001389 } else if (o->isMachO()) {
1390 printMachOFileHeader(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001391 }
1392}
1393
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001394static void DumpObject(const ObjectFile *o) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001395 // Avoid other output when using a raw option.
1396 if (!RawClangAST) {
1397 outs() << '\n';
1398 outs() << o->getFileName()
1399 << ":\tfile format " << o->getFileFormatName() << "\n\n";
1400 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001401
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001402 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001403 DisassembleObject(o, Relocations);
1404 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001405 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001406 if (SectionHeaders)
1407 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001408 if (SectionContents)
1409 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001410 if (SymbolTable)
1411 PrintSymbolTable(o);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001412 if (UnwindInfo)
1413 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001414 if (PrivateHeaders)
1415 printPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001416 if (ExportsTrie)
1417 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001418 if (Rebase)
1419 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001420 if (Bind)
1421 printBindTable(o);
1422 if (LazyBind)
1423 printLazyBindTable(o);
1424 if (WeakBind)
1425 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001426 if (RawClangAST)
1427 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001428 if (PrintFaultMaps)
1429 printFaultMaps(o);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001430}
1431
1432/// @brief Dump each object file in \a a;
1433static void DumpArchive(const Archive *a) {
Mark Seaborneb03ac52014-01-25 00:32:01 +00001434 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
1435 ++i) {
Rafael Espindolaae460022014-06-16 16:08:36 +00001436 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
1437 if (std::error_code EC = ChildOrErr.getError()) {
Michael J. Spencer53723de2011-11-16 01:24:41 +00001438 // Ignore non-object files.
Mark Seaborneb03ac52014-01-25 00:32:01 +00001439 if (EC != object_error::invalid_file_type)
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001440 report_error(a->getFileName(), EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001441 continue;
1442 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001443 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001444 DumpObject(o);
1445 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001446 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001447 }
1448}
1449
1450/// @brief Open file and figure out how to dump it.
1451static void DumpInput(StringRef file) {
1452 // If file isn't stdin, check that it exists.
1453 if (file != "-" && !sys::fs::exists(file)) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001454 report_error(file, errc::no_such_file_or_directory);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001455 return;
1456 }
1457
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001458 // If we are using the Mach-O specific object file parser, then let it parse
1459 // the file and process the command line options. So the -arch flags can
1460 // be used to select specific slices, etc.
1461 if (MachOOpt) {
1462 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001463 return;
1464 }
1465
1466 // Attempt to open the binary.
Rafael Espindola48af1c22014-08-19 18:44:46 +00001467 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
Rafael Espindola4453e42942014-06-13 03:07:50 +00001468 if (std::error_code EC = BinaryOrErr.getError()) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001469 report_error(file, EC);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001470 return;
1471 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001472 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001473
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001474 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001475 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001476 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001477 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001478 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001479 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001480}
1481
Michael J. Spencer2670c252011-01-20 06:39:06 +00001482int main(int argc, char **argv) {
1483 // Print a stack trace if we signal out.
1484 sys::PrintStackTraceOnErrorSignal();
1485 PrettyStackTraceProgram X(argc, argv);
1486 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1487
1488 // Initialize targets and assembly printers/parsers.
1489 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001490 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001491 llvm::InitializeAllAsmParsers();
1492 llvm::InitializeAllDisassemblers();
1493
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001494 // Register the target printer for --version.
1495 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1496
Michael J. Spencer2670c252011-01-20 06:39:06 +00001497 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1498 TripleName = Triple::normalize(TripleName);
1499
1500 ToolName = argv[0];
1501
1502 // Defaults to a.out if no filenames specified.
1503 if (InputFilenames.size() == 0)
1504 InputFilenames.push_back("a.out");
1505
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001506 if (!Disassemble
1507 && !Relocations
1508 && !SectionHeaders
1509 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001510 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001511 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001512 && !PrivateHeaders
Nick Kledzikac431442014-09-12 21:34:15 +00001513 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001514 && !Rebase
1515 && !Bind
1516 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001517 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001518 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001519 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001520 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001521 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001522 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001523 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001524 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001525 && !(DylibsUsed && MachOOpt)
1526 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001527 && !(ObjcMetaData && MachOOpt)
Sanjoy Das6f567a42015-06-22 18:03:02 +00001528 && !(DumpSections.size() != 0 && MachOOpt)
1529 && !PrintFaultMaps) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001530 cl::PrintHelpMessage();
1531 return 2;
1532 }
1533
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001534 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1535 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001536
Rui Ueyama98fe58a2014-11-26 22:17:25 +00001537 return ReturnValue;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001538}