blob: bb171ec3fc3183763994ea851daadaac80d262ec [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"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000026#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000027#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000028#include "llvm/MC/MCDisassembler/MCDisassembler.h"
29#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000030#include "llvm/MC/MCInst.h"
31#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000032#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000033#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000034#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000035#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000036#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Object/Archive.h"
38#include "llvm/Object/COFF.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000039#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000040#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000042#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000043#include "llvm/Support/CommandLine.h"
44#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000045#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000046#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000047#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000048#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Host.h"
50#include "llvm/Support/ManagedStatic.h"
51#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/PrettyStackTrace.h"
53#include "llvm/Support/Signals.h"
54#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000055#include "llvm/Support/TargetRegistry.h"
56#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000059#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000062#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000063
Michael J. Spencer2670c252011-01-20 06:39:06 +000064using namespace llvm;
65using namespace object;
66
Benjamin Kramer43a772e2011-09-19 17:56:04 +000067static cl::list<std::string>
68InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000069
Kevin Enderbye2297dd2015-01-07 21:02:18 +000070cl::opt<bool>
71llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000072 cl::desc("Display assembler mnemonics for the machine instructions"));
73static cl::alias
74Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000075 cl::aliasopt(Disassemble));
76
77cl::opt<bool>
78llvm::DisassembleAll("disassemble-all",
79 cl::desc("Display assembler mnemonics for the machine instructions"));
80static cl::alias
81DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000082 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000083
Kevin Enderby98da6132015-01-20 21:47:46 +000084cl::opt<bool>
85llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000086
Kevin Enderby98da6132015-01-20 21:47:46 +000087cl::opt<bool>
88llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000089
Kevin Enderby98da6132015-01-20 21:47:46 +000090cl::opt<bool>
91llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000092
Kevin Enderbye2297dd2015-01-07 21:02:18 +000093cl::opt<bool>
94llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000095
Kevin Enderbye2297dd2015-01-07 21:02:18 +000096cl::opt<bool>
97llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +000098
Kevin Enderbye2297dd2015-01-07 21:02:18 +000099cl::opt<bool>
100llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000101
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000102cl::opt<bool>
103llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000104
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000105cl::opt<bool>
106llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000107
Adrian Prantl437105a2015-07-08 02:04:15 +0000108cl::opt<bool>
109llvm::RawClangAST("raw-clang-ast",
110 cl::desc("Dump the raw binary contents of the clang AST section"));
111
Nick Kledzik56ebef42014-09-16 01:41:51 +0000112static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000113MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000114static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000115MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000116
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000117cl::opt<std::string>
118llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
119 "see -version for available targets"));
120
121cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000122llvm::MCPU("mcpu",
123 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
124 cl::value_desc("cpu-name"),
125 cl::init(""));
126
127cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000128llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000129 "see -version for available targets"));
130
Kevin Enderby98da6132015-01-20 21:47:46 +0000131cl::opt<bool>
132llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
133 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000134static cl::alias
135SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
136 cl::aliasopt(SectionHeaders));
137static cl::alias
138SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
139 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000140
Colin LeMahieu77804be2015-07-29 15:45:39 +0000141cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000142llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
143 "With -macho dump segment,section"));
144cl::alias
145static FilterSectionsj("j", cl::desc("Alias for --section"),
146 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000147
Kevin Enderbyc9595622014-08-06 23:24:41 +0000148cl::list<std::string>
149llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000150 cl::CommaSeparated,
151 cl::desc("Target specific attributes"),
152 cl::value_desc("a1,+a2,-a3,..."));
153
Kevin Enderbybf246f52014-09-24 23:08:22 +0000154cl::opt<bool>
155llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
156 "instructions, do not print "
157 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000158
Kevin Enderby98da6132015-01-20 21:47:46 +0000159cl::opt<bool>
160llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000161
162static cl::alias
163UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
164 cl::aliasopt(UnwindInfo));
165
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000166cl::opt<bool>
167llvm::PrivateHeaders("private-headers",
168 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000169
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000170cl::opt<bool>
171llvm::FirstPrivateHeader("private-header",
172 cl::desc("Display only the first format specific file "
173 "header"));
174
Michael J. Spencer209565db2013-01-06 03:56:49 +0000175static cl::alias
176PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
177 cl::aliasopt(PrivateHeaders));
178
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000179cl::opt<bool>
180 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000181 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000182
Sanjoy Das6f567a42015-06-22 18:03:02 +0000183cl::opt<bool> PrintFaultMaps("fault-map-section",
184 cl::desc("Display contents of faultmap section"));
185
Igor Laevsky03a670c2016-01-26 15:09:42 +0000186cl::opt<DIDumpType> llvm::DwarfDumpType(
187 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
188 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
189 clEnumValEnd));
190
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000191static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000192
Colin LeMahieu77804be2015-07-29 15:45:39 +0000193namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000194typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000195
196class SectionFilterIterator {
197public:
198 SectionFilterIterator(FilterPredicate P,
199 llvm::object::section_iterator const &I,
200 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000201 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000202 ScanPredicate();
203 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000204 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000205 SectionFilterIterator &operator++() {
206 ++Iterator;
207 ScanPredicate();
208 return *this;
209 }
210 bool operator!=(SectionFilterIterator const &Other) const {
211 return Iterator != Other.Iterator;
212 }
213
214private:
215 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000216 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000217 ++Iterator;
218 }
219 }
220 FilterPredicate Predicate;
221 llvm::object::section_iterator Iterator;
222 llvm::object::section_iterator End;
223};
224
225class SectionFilter {
226public:
227 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000228 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000229 SectionFilterIterator begin() {
230 return SectionFilterIterator(Predicate, Object.section_begin(),
231 Object.section_end());
232 }
233 SectionFilterIterator end() {
234 return SectionFilterIterator(Predicate, Object.section_end(),
235 Object.section_end());
236 }
237
238private:
239 FilterPredicate Predicate;
240 llvm::object::ObjectFile const &Object;
241};
242SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000243 return SectionFilter([](llvm::object::SectionRef const &S) {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000244 if(FilterSections.empty())
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000245 return true;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000246 llvm::StringRef String;
247 std::error_code error = S.getName(String);
Colin LeMahieufcc32762015-07-29 19:08:10 +0000248 if (error)
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000249 return false;
Colin LeMahieufcc32762015-07-29 19:08:10 +0000250 return std::find(FilterSections.begin(),
251 FilterSections.end(),
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000252 String) != FilterSections.end();
Colin LeMahieu77804be2015-07-29 15:45:39 +0000253 },
254 O);
255}
256}
257
Davide Italianoccd53fe2015-08-05 07:18:31 +0000258void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000259 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000260 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000261
Davide Italiano140af642015-12-25 18:16:45 +0000262 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
263 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000264 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000265}
266
Kevin Enderby42398052016-06-28 23:16:13 +0000267LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
268 errs() << ToolName << ": " << Message << ".\n";
269 errs().flush();
270 exit(1);
271}
272
Davide Italianoed9d95b2015-12-29 13:41:02 +0000273LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
274 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000275 assert(EC);
276 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000277 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000278}
279
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000280LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
281 llvm::Error E) {
282 assert(E);
283 std::string Buf;
284 raw_string_ostream OS(Buf);
285 logAllUnhandledErrors(std::move(E), OS, "");
286 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000287 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000288 exit(1);
289}
290
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000291LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
292 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000293 llvm::Error E,
294 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000295 assert(E);
296 errs() << ToolName << ": ";
297 if (ArchiveName != "")
298 errs() << ArchiveName << "(" << FileName << ")";
299 else
300 errs() << FileName;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000301 if (!ArchitectureName.empty())
302 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000303 std::string Buf;
304 raw_string_ostream OS(Buf);
305 logAllUnhandledErrors(std::move(E), OS, "");
306 OS.flush();
307 errs() << " " << Buf;
308 exit(1);
309}
310
311LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
312 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000313 llvm::Error E,
314 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000315 ErrorOr<StringRef> NameOrErr = C.getName();
316 // TODO: if we have a error getting the name then it would be nice to print
317 // the index of which archive member this is and or its offset in the
318 // archive instead of "???" as the name.
319 if (NameOrErr.getError())
Kevin Enderby9acb1092016-05-31 20:35:34 +0000320 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000321 else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000322 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
323 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000324}
325
Craig Toppere6cb63e2014-04-25 04:24:47 +0000326static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000327 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000328 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000329 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000330 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000331 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000332 // TheTriple defaults to ELF, and COFF doesn't have an environment:
333 // the best we can do here is indicate that it is mach-o.
334 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000335 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000336
337 if (Obj->isCOFF()) {
338 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
339 if (COFFObj->getArch() == Triple::thumb)
340 TheTriple.setTriple("thumbv7-windows");
341 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000342 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000343 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000344 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000345
346 // Get the target specific parser.
347 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000348 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
349 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000350 if (!TheTarget)
351 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000352
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000353 // Update the triple name and return the found target.
354 TripleName = TheTriple.getTriple();
355 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000356}
357
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000358bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000359 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000360}
361
Colin LeMahieufb76b002015-05-28 19:07:14 +0000362namespace {
363class PrettyPrinter {
364public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000365 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000366 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000367 ArrayRef<uint8_t> Bytes, uint64_t Address,
368 raw_ostream &OS, StringRef Annot,
369 MCSubtargetInfo const &STI) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000370 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000371 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000372 OS << "\t";
373 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000374 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000375 if (MI)
376 IP.printInst(MI, OS, "", STI);
377 else
378 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000379 }
380};
381PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000382class HexagonPrettyPrinter : public PrettyPrinter {
383public:
384 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
385 raw_ostream &OS) {
386 uint32_t opcode =
387 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
388 OS << format("%8" PRIx64 ":", Address);
389 if (!NoShowRawInsn) {
390 OS << "\t";
391 dumpBytes(Bytes.slice(0, 4), OS);
392 OS << format("%08" PRIx32, opcode);
393 }
394 }
395 void printInst(MCInstPrinter &IP, const MCInst *MI,
396 ArrayRef<uint8_t> Bytes, uint64_t Address,
397 raw_ostream &OS, StringRef Annot,
398 MCSubtargetInfo const &STI) override {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000399 if (!MI) {
400 printLead(Bytes, Address, OS);
401 OS << " <unknown>";
402 return;
403 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000404 std::string Buffer;
405 {
406 raw_string_ostream TempStream(Buffer);
407 IP.printInst(MI, TempStream, "", STI);
408 }
409 StringRef Contents(Buffer);
410 // Split off bundle attributes
411 auto PacketBundle = Contents.rsplit('\n');
412 // Split off first instruction from the rest
413 auto HeadTail = PacketBundle.first.split('\n');
414 auto Preamble = " { ";
415 auto Separator = "";
416 while(!HeadTail.first.empty()) {
417 OS << Separator;
418 Separator = "\n";
419 printLead(Bytes, Address, OS);
420 OS << Preamble;
421 Preamble = " ";
422 StringRef Inst;
423 auto Duplex = HeadTail.first.split('\v');
424 if(!Duplex.second.empty()){
425 OS << Duplex.first;
426 OS << "; ";
427 Inst = Duplex.second;
428 }
429 else
430 Inst = HeadTail.first;
431 OS << Inst;
432 Bytes = Bytes.slice(4);
433 Address += 4;
434 HeadTail = HeadTail.second.split('\n');
435 }
436 OS << " } " << PacketBundle.second;
437 }
438};
439HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000440
441class AMDGCNPrettyPrinter : public PrettyPrinter {
442public:
443 void printInst(MCInstPrinter &IP,
444 const MCInst *MI,
445 ArrayRef<uint8_t> Bytes,
446 uint64_t Address,
447 raw_ostream &OS,
448 StringRef Annot,
449 MCSubtargetInfo const &STI) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000450 if (!MI) {
451 OS << " <unknown>";
452 return;
453 }
454
Valery Pykhtinde048052016-04-07 07:24:01 +0000455 SmallString<40> InstStr;
456 raw_svector_ostream IS(InstStr);
457
458 IP.printInst(MI, IS, "", STI);
459
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000460 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000461 typedef support::ulittle32_t U32;
462 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
463 Bytes.size() / sizeof(U32)))
464 // D should be explicitly casted to uint32_t here as it is passed
465 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000466 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000467
468 if (!Annot.empty())
469 OS << "// " << Annot;
470 }
471};
472AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
473
Colin LeMahieu35436a22015-05-29 14:48:25 +0000474PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000475 switch(Triple.getArch()) {
476 default:
477 return PrettyPrinterInst;
478 case Triple::hexagon:
479 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000480 case Triple::amdgcn:
481 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000482 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000483}
484}
485
Rafael Espindola37070a52015-06-03 04:48:06 +0000486template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000487static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000488 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000489 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000490 DataRefImpl Rel = RelRef.getRawDataRefImpl();
491
Rafael Espindola37070a52015-06-03 04:48:06 +0000492 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
493 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000494 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
495
Rafael Espindola37070a52015-06-03 04:48:06 +0000496 const ELFFile<ELFT> &EF = *Obj->getELFFile();
497
Rafael Espindola6def3042015-07-01 12:56:27 +0000498 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
499 if (std::error_code EC = SecOrErr.getError())
500 return EC;
501 const Elf_Shdr *Sec = *SecOrErr;
502 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
503 if (std::error_code EC = SymTabOrErr.getError())
504 return EC;
505 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000506 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
507 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000508 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
509 if (std::error_code EC = StrTabSec.getError())
510 return EC;
511 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000512 if (std::error_code EC = StrTabOrErr.getError())
513 return EC;
514 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000515 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000516 StringRef res;
517 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000518 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000519 default:
520 return object_error::parse_failed;
521 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000522 // TODO: Read implicit addend from section data.
523 break;
524 }
525 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000526 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000527 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000528 break;
529 }
530 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000531 symbol_iterator SI = RelRef.getSymbol();
532 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000533 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000534 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000535 Expected<section_iterator> SymSI = SI->getSection();
536 if (!SymSI)
537 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000538 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
539 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000540 if (std::error_code EC = SecName.getError())
541 return EC;
542 Target = *SecName;
543 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000544 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000545 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000546 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000547 Target = *SymName;
548 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000549 switch (EF.getHeader()->e_machine) {
550 case ELF::EM_X86_64:
551 switch (type) {
552 case ELF::R_X86_64_PC8:
553 case ELF::R_X86_64_PC16:
554 case ELF::R_X86_64_PC32: {
555 std::string fmtbuf;
556 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000557 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000558 fmt.flush();
559 Result.append(fmtbuf.begin(), fmtbuf.end());
560 } break;
561 case ELF::R_X86_64_8:
562 case ELF::R_X86_64_16:
563 case ELF::R_X86_64_32:
564 case ELF::R_X86_64_32S:
565 case ELF::R_X86_64_64: {
566 std::string fmtbuf;
567 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000568 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000569 fmt.flush();
570 Result.append(fmtbuf.begin(), fmtbuf.end());
571 } break;
572 default:
573 res = "Unknown";
574 }
575 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000576 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000577 case ELF::EM_AARCH64: {
578 std::string fmtbuf;
579 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000580 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000581 if (addend != 0)
582 fmt << (addend < 0 ? "" : "+") << addend;
583 fmt.flush();
584 Result.append(fmtbuf.begin(), fmtbuf.end());
585 break;
586 }
587 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000588 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000589 case ELF::EM_ARM:
590 case ELF::EM_HEXAGON:
591 case ELF::EM_MIPS:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000592 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000593 break;
Dan Gohman46350172016-01-12 20:56:01 +0000594 case ELF::EM_WEBASSEMBLY:
595 switch (type) {
596 case ELF::R_WEBASSEMBLY_DATA: {
597 std::string fmtbuf;
598 raw_string_ostream fmt(fmtbuf);
599 fmt << Target << (addend < 0 ? "" : "+") << addend;
600 fmt.flush();
601 Result.append(fmtbuf.begin(), fmtbuf.end());
602 break;
603 }
604 case ELF::R_WEBASSEMBLY_FUNCTION:
605 res = Target;
606 break;
607 default:
608 res = "Unknown";
609 }
610 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000611 default:
612 res = "Unknown";
613 }
614 if (Result.empty())
615 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000616 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000617}
618
619static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000620 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000621 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000622 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
623 return getRelocationValueString(ELF32LE, Rel, Result);
624 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
625 return getRelocationValueString(ELF64LE, Rel, Result);
626 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
627 return getRelocationValueString(ELF32BE, Rel, Result);
628 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
629 return getRelocationValueString(ELF64BE, Rel, Result);
630}
631
632static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
633 const RelocationRef &Rel,
634 SmallVectorImpl<char> &Result) {
635 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000636 Expected<StringRef> SymNameOrErr = SymI->getName();
637 if (!SymNameOrErr)
638 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000639 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000640 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000641 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000642}
643
644static void printRelocationTargetName(const MachOObjectFile *O,
645 const MachO::any_relocation_info &RE,
646 raw_string_ostream &fmt) {
647 bool IsScattered = O->isRelocationScattered(RE);
648
649 // Target of a scattered relocation is an address. In the interest of
650 // generating pretty output, scan through the symbol table looking for a
651 // symbol that aligns with that address. If we find one, print it.
652 // Otherwise, we just print the hex address of the target.
653 if (IsScattered) {
654 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
655
656 for (const SymbolRef &Symbol : O->symbols()) {
657 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000658 Expected<uint64_t> Addr = Symbol.getAddress();
659 if (!Addr) {
660 std::string Buf;
661 raw_string_ostream OS(Buf);
662 logAllUnhandledErrors(Addr.takeError(), OS, "");
663 OS.flush();
664 report_fatal_error(Buf);
665 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000666 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000667 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000668 Expected<StringRef> Name = Symbol.getName();
669 if (!Name) {
670 std::string Buf;
671 raw_string_ostream OS(Buf);
672 logAllUnhandledErrors(Name.takeError(), OS, "");
673 OS.flush();
674 report_fatal_error(Buf);
675 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000676 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000677 return;
678 }
679
680 // If we couldn't find a symbol that this relocation refers to, try
681 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000682 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000683 std::error_code ec;
684
685 StringRef Name;
686 uint64_t Addr = Section.getAddress();
687 if (Addr != Val)
688 continue;
689 if ((ec = Section.getName(Name)))
690 report_fatal_error(ec.message());
691 fmt << Name;
692 return;
693 }
694
695 fmt << format("0x%x", Val);
696 return;
697 }
698
699 StringRef S;
700 bool isExtern = O->getPlainRelocationExternal(RE);
701 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
702
703 if (isExtern) {
704 symbol_iterator SI = O->symbol_begin();
705 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000706 Expected<StringRef> SOrErr = SI->getName();
707 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000708 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000709 } else {
710 section_iterator SI = O->section_begin();
711 // Adjust for the fact that sections are 1-indexed.
712 advance(SI, Val - 1);
713 SI->getName(S);
714 }
715
716 fmt << S;
717}
718
719static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
720 const RelocationRef &RelRef,
721 SmallVectorImpl<char> &Result) {
722 DataRefImpl Rel = RelRef.getRawDataRefImpl();
723 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
724
725 unsigned Arch = Obj->getArch();
726
727 std::string fmtbuf;
728 raw_string_ostream fmt(fmtbuf);
729 unsigned Type = Obj->getAnyRelocationType(RE);
730 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
731
732 // Determine any addends that should be displayed with the relocation.
733 // These require decoding the relocation type, which is triple-specific.
734
735 // X86_64 has entirely custom relocation types.
736 if (Arch == Triple::x86_64) {
737 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
738
739 switch (Type) {
740 case MachO::X86_64_RELOC_GOT_LOAD:
741 case MachO::X86_64_RELOC_GOT: {
742 printRelocationTargetName(Obj, RE, fmt);
743 fmt << "@GOT";
744 if (isPCRel)
745 fmt << "PCREL";
746 break;
747 }
748 case MachO::X86_64_RELOC_SUBTRACTOR: {
749 DataRefImpl RelNext = Rel;
750 Obj->moveRelocationNext(RelNext);
751 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
752
753 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
754 // X86_64_RELOC_UNSIGNED.
755 // NOTE: Scattered relocations don't exist on x86_64.
756 unsigned RType = Obj->getAnyRelocationType(RENext);
757 if (RType != MachO::X86_64_RELOC_UNSIGNED)
758 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
759 "X86_64_RELOC_SUBTRACTOR.");
760
761 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
762 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
763 printRelocationTargetName(Obj, RENext, fmt);
764 fmt << "-";
765 printRelocationTargetName(Obj, RE, fmt);
766 break;
767 }
768 case MachO::X86_64_RELOC_TLV:
769 printRelocationTargetName(Obj, RE, fmt);
770 fmt << "@TLV";
771 if (isPCRel)
772 fmt << "P";
773 break;
774 case MachO::X86_64_RELOC_SIGNED_1:
775 printRelocationTargetName(Obj, RE, fmt);
776 fmt << "-1";
777 break;
778 case MachO::X86_64_RELOC_SIGNED_2:
779 printRelocationTargetName(Obj, RE, fmt);
780 fmt << "-2";
781 break;
782 case MachO::X86_64_RELOC_SIGNED_4:
783 printRelocationTargetName(Obj, RE, fmt);
784 fmt << "-4";
785 break;
786 default:
787 printRelocationTargetName(Obj, RE, fmt);
788 break;
789 }
790 // X86 and ARM share some relocation types in common.
791 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
792 Arch == Triple::ppc) {
793 // Generic relocation types...
794 switch (Type) {
795 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000796 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000797 case MachO::GENERIC_RELOC_SECTDIFF: {
798 DataRefImpl RelNext = Rel;
799 Obj->moveRelocationNext(RelNext);
800 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
801
802 // X86 sect diff's must be followed by a relocation of type
803 // GENERIC_RELOC_PAIR.
804 unsigned RType = Obj->getAnyRelocationType(RENext);
805
806 if (RType != MachO::GENERIC_RELOC_PAIR)
807 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
808 "GENERIC_RELOC_SECTDIFF.");
809
810 printRelocationTargetName(Obj, RE, fmt);
811 fmt << "-";
812 printRelocationTargetName(Obj, RENext, fmt);
813 break;
814 }
815 }
816
817 if (Arch == Triple::x86 || Arch == Triple::ppc) {
818 switch (Type) {
819 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
820 DataRefImpl RelNext = Rel;
821 Obj->moveRelocationNext(RelNext);
822 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
823
824 // X86 sect diff's must be followed by a relocation of type
825 // GENERIC_RELOC_PAIR.
826 unsigned RType = Obj->getAnyRelocationType(RENext);
827 if (RType != MachO::GENERIC_RELOC_PAIR)
828 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
829 "GENERIC_RELOC_LOCAL_SECTDIFF.");
830
831 printRelocationTargetName(Obj, RE, fmt);
832 fmt << "-";
833 printRelocationTargetName(Obj, RENext, fmt);
834 break;
835 }
836 case MachO::GENERIC_RELOC_TLV: {
837 printRelocationTargetName(Obj, RE, fmt);
838 fmt << "@TLV";
839 if (IsPCRel)
840 fmt << "P";
841 break;
842 }
843 default:
844 printRelocationTargetName(Obj, RE, fmt);
845 }
846 } else { // ARM-specific relocations
847 switch (Type) {
848 case MachO::ARM_RELOC_HALF:
849 case MachO::ARM_RELOC_HALF_SECTDIFF: {
850 // Half relocations steal a bit from the length field to encode
851 // whether this is an upper16 or a lower16 relocation.
852 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
853
854 if (isUpper)
855 fmt << ":upper16:(";
856 else
857 fmt << ":lower16:(";
858 printRelocationTargetName(Obj, RE, fmt);
859
860 DataRefImpl RelNext = Rel;
861 Obj->moveRelocationNext(RelNext);
862 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
863
864 // ARM half relocs must be followed by a relocation of type
865 // ARM_RELOC_PAIR.
866 unsigned RType = Obj->getAnyRelocationType(RENext);
867 if (RType != MachO::ARM_RELOC_PAIR)
868 report_fatal_error("Expected ARM_RELOC_PAIR after "
869 "ARM_RELOC_HALF");
870
871 // NOTE: The half of the target virtual address is stashed in the
872 // address field of the secondary relocation, but we can't reverse
873 // engineer the constant offset from it without decoding the movw/movt
874 // instruction to find the other half in its immediate field.
875
876 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
877 // symbol/section pointer of the follow-on relocation.
878 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
879 fmt << "-";
880 printRelocationTargetName(Obj, RENext, fmt);
881 }
882
883 fmt << ")";
884 break;
885 }
886 default: { printRelocationTargetName(Obj, RE, fmt); }
887 }
888 }
889 } else
890 printRelocationTargetName(Obj, RE, fmt);
891
892 fmt.flush();
893 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000894 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000895}
896
897static std::error_code getRelocationValueString(const RelocationRef &Rel,
898 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000899 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000900 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
901 return getRelocationValueString(ELF, Rel, Result);
902 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
903 return getRelocationValueString(COFF, Rel, Result);
904 auto *MachO = cast<MachOObjectFile>(Obj);
905 return getRelocationValueString(MachO, Rel, Result);
906}
907
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000908/// @brief Indicates whether this relocation should hidden when listing
909/// relocations, usually because it is the trailing part of a multipart
910/// relocation that will be printed as part of the leading relocation.
911static bool getHidden(RelocationRef RelRef) {
912 const ObjectFile *Obj = RelRef.getObject();
913 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
914 if (!MachO)
915 return false;
916
917 unsigned Arch = MachO->getArch();
918 DataRefImpl Rel = RelRef.getRawDataRefImpl();
919 uint64_t Type = MachO->getRelocationType(Rel);
920
921 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
922 // is always hidden.
923 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
924 if (Type == MachO::GENERIC_RELOC_PAIR)
925 return true;
926 } else if (Arch == Triple::x86_64) {
927 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
928 // an X86_64_RELOC_SUBTRACTOR.
929 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
930 DataRefImpl RelPrev = Rel;
931 RelPrev.d.a--;
932 uint64_t PrevType = MachO->getRelocationType(RelPrev);
933 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
934 return true;
935 }
936 }
937
938 return false;
939}
940
Michael J. Spencer51862b32011-10-13 22:17:18 +0000941static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +0000942 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000943
Jack Carter551efd72012-08-28 19:24:49 +0000944 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +0000945 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +0000946 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +0000947 for (unsigned i = 0; i != MAttrs.size(); ++i)
948 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +0000949 }
950
Ahmed Charles56440fd2014-03-06 05:51:42 +0000951 std::unique_ptr<const MCRegisterInfo> MRI(
952 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000953 if (!MRI)
954 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000955
956 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000957 std::unique_ptr<const MCAsmInfo> AsmInfo(
958 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +0000959 if (!AsmInfo)
960 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000961 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +0000962 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +0000963 if (!STI)
964 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000965 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +0000966 if (!MII)
967 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +0000968 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
969 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
970
971 std::unique_ptr<MCDisassembler> DisAsm(
972 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +0000973 if (!DisAsm)
974 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000975
Ahmed Charles56440fd2014-03-06 05:51:42 +0000976 std::unique_ptr<const MCInstrAnalysis> MIA(
977 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000978
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000979 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +0000980 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
981 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +0000982 if (!IP)
983 report_fatal_error("error: no instruction printer for target " +
984 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000985 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +0000986 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +0000987
Greg Fitzgerald18432272014-03-20 22:55:15 +0000988 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
989 "\t\t\t%08" PRIx64 ": ";
990
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000991 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
992 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +0000993 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000994 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000995 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +0000996 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +0000997 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +0000998 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000999 }
1000
David Majnemer81afca62015-07-07 22:06:59 +00001001 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001002 // pretty print the symbols while disassembling.
1003 typedef std::vector<std::pair<uint64_t, StringRef>> SectionSymbolsTy;
1004 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1005 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001006 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1007 error(errorToErrorCode(AddressOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001008 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001009
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001010 Expected<StringRef> Name = Symbol.getName();
1011 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001012 if (Name->empty())
1013 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001014
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001015 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1016 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001017 section_iterator SecI = *SectionOrErr;
1018 if (SecI == Obj->section_end())
1019 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001020
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001021 AllSymbols[*SecI].emplace_back(Address, *Name);
David Majnemer81afca62015-07-07 22:06:59 +00001022 }
1023
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001024 // Create a mapping from virtual address to section.
1025 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1026 for (SectionRef Sec : Obj->sections())
1027 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1028 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1029
1030 // Linked executables (.exe and .dll files) typically don't include a real
1031 // symbol table but they might contain an export table.
1032 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1033 for (const auto &ExportEntry : COFFObj->export_directories()) {
1034 StringRef Name;
1035 error(ExportEntry.getSymbolName(Name));
1036 if (Name.empty())
1037 continue;
1038 uint32_t RVA;
1039 error(ExportEntry.getExportRVA(RVA));
1040
1041 uint64_t VA = COFFObj->getImageBase() + RVA;
1042 auto Sec = std::upper_bound(
1043 SectionAddresses.begin(), SectionAddresses.end(), VA,
1044 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1045 return LHS < RHS.first;
1046 });
1047 if (Sec != SectionAddresses.begin())
1048 --Sec;
1049 else
1050 Sec = SectionAddresses.end();
1051
1052 if (Sec != SectionAddresses.end())
1053 AllSymbols[Sec->second].emplace_back(VA, Name);
1054 }
1055 }
1056
1057 // Sort all the symbols, this allows us to use a simple binary search to find
1058 // a symbol near an address.
1059 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1060 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1061
Colin LeMahieu77804be2015-07-29 15:45:39 +00001062 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001063 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001064 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001065
Rafael Espindola80291272014-10-08 15:28:58 +00001066 uint64_t SectionAddr = Section.getAddress();
1067 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001068 if (!SectSize)
1069 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001070
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001071 // Get the list of all the symbols in this section.
1072 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001073 std::vector<uint64_t> DataMappingSymsAddr;
1074 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001075 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1076 for (const auto &Symb : Symbols) {
1077 uint64_t Address = Symb.first;
1078 StringRef Name = Symb.second;
1079 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001080 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001081 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001082 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001083 }
1084 }
1085
Davide Italianof0706882015-10-01 21:57:09 +00001086 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1087 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001088
Michael J. Spencer51862b32011-10-13 22:17:18 +00001089 // Make a list of all the relocations for this section.
1090 std::vector<RelocationRef> Rels;
1091 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001092 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1093 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1094 Rels.push_back(Reloc);
1095 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001096 }
1097 }
1098
1099 // Sort relocations by address.
1100 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1101
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001102 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001103 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001104 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001105 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001106 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001107 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001108 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001109 outs() << "Disassembly of section ";
1110 if (!SegmentName.empty())
1111 outs() << SegmentName << ",";
1112 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001113
Rafael Espindola7884c952015-06-04 15:01:05 +00001114 // If the section has no symbol at the start, just insert a dummy one.
1115 if (Symbols.empty() || Symbols[0].first != 0)
David Majnemer153722d2015-11-18 04:35:32 +00001116 Symbols.insert(Symbols.begin(), std::make_pair(SectionAddr, name));
Alp Tokere69170a2014-06-26 22:52:05 +00001117
1118 SmallString<40> Comments;
1119 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001120
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001121 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001122 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001123 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1124 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001125
Michael J. Spencer2670c252011-01-20 06:39:06 +00001126 uint64_t Size;
1127 uint64_t Index;
1128
Michael J. Spencer51862b32011-10-13 22:17:18 +00001129 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1130 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001131 // Disassemble symbol by symbol.
1132 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Rafael Espindolae45c7402014-08-17 16:31:39 +00001133
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001134 uint64_t Start = Symbols[si].first - SectionAddr;
1135 // The end is either the section end or the beginning of the next
1136 // symbol.
1137 uint64_t End =
1138 (si == se - 1) ? SectSize : Symbols[si + 1].first - SectionAddr;
1139 // Don't try to disassemble beyond the end of section contents.
1140 if (End > SectSize)
1141 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001142 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001143 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001144 continue;
1145
Valery Pykhtinde048052016-04-07 07:24:01 +00001146 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1147 // make size 4 bytes folded
1148 End = Start + ((End - Start) & ~0x3ull);
1149 Start += 256; // add sizeof(amd_kernel_code_t)
1150 // cut trailing zeroes - up to 256 bytes (align)
1151 const uint64_t EndAlign = 256;
1152 const auto Limit = End - (std::min)(EndAlign, End - Start);
1153 while (End > Limit &&
1154 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1155 End -= 4;
1156 }
1157
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001158 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001159
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001160#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001161 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001162#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001163 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001164#endif
1165
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001166 for (Index = Start; Index < End; Index += Size) {
1167 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001168
Davide Italianof0706882015-10-01 21:57:09 +00001169 // AArch64 ELF binaries can interleave data and text in the
1170 // same section. We rely on the markers introduced to
1171 // understand what we need to dump.
1172 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1173 uint64_t Stride = 0;
1174
1175 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1176 DataMappingSymsAddr.end(), Index);
1177 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1178 // Switch to data.
1179 while (Index < End) {
1180 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1181 outs() << "\t";
1182 if (Index + 4 <= End) {
1183 Stride = 4;
1184 dumpBytes(Bytes.slice(Index, 4), outs());
1185 outs() << "\t.word";
1186 } else if (Index + 2 <= End) {
1187 Stride = 2;
1188 dumpBytes(Bytes.slice(Index, 2), outs());
1189 outs() << "\t.short";
1190 } else {
1191 Stride = 1;
1192 dumpBytes(Bytes.slice(Index, 1), outs());
1193 outs() << "\t.byte";
1194 }
1195 Index += Stride;
1196 outs() << "\n";
1197 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1198 TextMappingSymsAddr.end(), Index);
1199 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1200 break;
1201 }
1202 }
1203 }
1204
1205 if (Index >= End)
1206 break;
1207
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001208 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1209 SectionAddr + Index, DebugOut,
1210 CommentStream);
1211 if (Size == 0)
1212 Size = 1;
1213 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1214 Bytes.slice(Index, Size),
1215 SectionAddr + Index, outs(), "", *STI);
1216 outs() << CommentStream.str();
1217 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001218
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001219 // Try to resolve the target of a call, tail call, etc. to a specific
1220 // symbol.
1221 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1222 MIA->isConditionalBranch(Inst))) {
1223 uint64_t Target;
1224 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1225 // In a relocatable object, the target's section must reside in
1226 // the same section as the call instruction or it is accessed
1227 // through a relocation.
1228 //
1229 // In a non-relocatable object, the target may be in any section.
1230 //
1231 // N.B. We don't walk the relocations in the relocatable case yet.
1232 auto *TargetSectionSymbols = &Symbols;
1233 if (!Obj->isRelocatableObject()) {
1234 auto SectionAddress = std::upper_bound(
1235 SectionAddresses.begin(), SectionAddresses.end(), Target,
1236 [](uint64_t LHS,
1237 const std::pair<uint64_t, SectionRef> &RHS) {
1238 return LHS < RHS.first;
1239 });
1240 if (SectionAddress != SectionAddresses.begin()) {
1241 --SectionAddress;
1242 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1243 } else {
1244 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001245 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001246 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001247
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001248 // Find the first symbol in the section whose offset is less than
1249 // or equal to the target.
1250 if (TargetSectionSymbols) {
1251 auto TargetSym = std::upper_bound(
1252 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1253 Target, [](uint64_t LHS,
1254 const std::pair<uint64_t, StringRef> &RHS) {
1255 return LHS < RHS.first;
1256 });
1257 if (TargetSym != TargetSectionSymbols->begin()) {
1258 --TargetSym;
1259 uint64_t TargetAddress = std::get<0>(*TargetSym);
1260 StringRef TargetName = std::get<1>(*TargetSym);
1261 outs() << " <" << TargetName;
1262 uint64_t Disp = Target - TargetAddress;
1263 if (Disp)
1264 outs() << "+0x" << utohexstr(Disp);
1265 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001266 }
1267 }
1268 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001269 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001270 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001271
1272 // Print relocation for instruction.
1273 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001274 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001275 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001276 SmallString<16> name;
1277 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001278
1279 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001280 if (hidden) goto skip_print_rel;
1281
Michael J. Spencer51862b32011-10-13 22:17:18 +00001282 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001283 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001284 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001285 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001286 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001287 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001288
1289 skip_print_rel:
1290 ++rel_cur;
1291 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001292 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001293 }
1294 }
1295}
1296
Kevin Enderby98da6132015-01-20 21:47:46 +00001297void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001298 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1299 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001300 // Regular objdump doesn't print relocations in non-relocatable object
1301 // files.
1302 if (!Obj->isRelocatableObject())
1303 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001304
Colin LeMahieu77804be2015-07-29 15:45:39 +00001305 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001306 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001307 continue;
1308 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001309 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001310 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001311 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001312 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001313 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001314 SmallString<32> relocname;
1315 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001316 if (hidden)
1317 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001318 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001319 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001320 outs() << format(Fmt.data(), address) << " " << relocname << " "
1321 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001322 }
1323 outs() << "\n";
1324 }
1325}
1326
Kevin Enderby98da6132015-01-20 21:47:46 +00001327void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001328 outs() << "Sections:\n"
1329 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001330 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001331 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001332 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001333 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001334 uint64_t Address = Section.getAddress();
1335 uint64_t Size = Section.getSize();
1336 bool Text = Section.isText();
1337 bool Data = Section.isData();
1338 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001339 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001340 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001341 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1342 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001343 ++i;
1344 }
1345}
1346
Kevin Enderby98da6132015-01-20 21:47:46 +00001347void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001348 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001349 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001350 StringRef Name;
1351 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001352 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001353 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001354 uint64_t Size = Section.getSize();
1355 if (!Size)
1356 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001357
1358 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001359 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001360 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001361 ", %04" PRIx64 ")>\n",
1362 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001363 continue;
1364 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001365
Davide Italianoccd53fe2015-08-05 07:18:31 +00001366 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001367
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001368 // Dump out the content as hex and printable ascii characters.
1369 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001370 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001371 // Dump line of hex.
1372 for (std::size_t i = 0; i < 16; ++i) {
1373 if (i != 0 && i % 4 == 0)
1374 outs() << ' ';
1375 if (addr + i < end)
1376 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1377 << hexdigit(Contents[addr + i] & 0xF, true);
1378 else
1379 outs() << " ";
1380 }
1381 // Print ascii.
1382 outs() << " ";
1383 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001384 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001385 outs() << Contents[addr + i];
1386 else
1387 outs() << ".";
1388 }
1389 outs() << "\n";
1390 }
1391 }
1392}
1393
Kevin Enderby9acb1092016-05-31 20:35:34 +00001394void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1395 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001396 outs() << "SYMBOL TABLE:\n";
1397
Rui Ueyama4e39f712014-03-18 18:58:51 +00001398 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001399 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001400 return;
1401 }
1402 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001403 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1404 if (!AddressOrError)
1405 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001406 uint64_t Address = *AddressOrError;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001407 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1408 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001409 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001410 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001411 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001412 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1413 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001414 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001415 StringRef Name;
1416 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1417 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001418 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001419 Expected<StringRef> NameOrErr = Symbol.getName();
1420 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001421 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1422 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001423 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001424 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001425
Rui Ueyama4e39f712014-03-18 18:58:51 +00001426 bool Global = Flags & SymbolRef::SF_Global;
1427 bool Weak = Flags & SymbolRef::SF_Weak;
1428 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001429 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001430 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001431
Rui Ueyama4e39f712014-03-18 18:58:51 +00001432 char GlobLoc = ' ';
1433 if (Type != SymbolRef::ST_Unknown)
1434 GlobLoc = Global ? 'g' : 'l';
1435 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1436 ? 'd' : ' ';
1437 char FileFunc = ' ';
1438 if (Type == SymbolRef::ST_File)
1439 FileFunc = 'f';
1440 else if (Type == SymbolRef::ST_Function)
1441 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001442
Rui Ueyama4e39f712014-03-18 18:58:51 +00001443 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1444 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001445
Rui Ueyama4e39f712014-03-18 18:58:51 +00001446 outs() << format(Fmt, Address) << " "
1447 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1448 << (Weak ? 'w' : ' ') // Weak?
1449 << ' ' // Constructor. Not supported yet.
1450 << ' ' // Warning. Not supported yet.
1451 << ' ' // Indirect reference to another symbol.
1452 << Debug // Debugging (d) or dynamic (D) symbol.
1453 << FileFunc // Name of function (F), file (f) or object (O).
1454 << ' ';
1455 if (Absolute) {
1456 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001457 } else if (Common) {
1458 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001459 } else if (Section == o->section_end()) {
1460 outs() << "*UND*";
1461 } else {
1462 if (const MachOObjectFile *MachO =
1463 dyn_cast<const MachOObjectFile>(o)) {
1464 DataRefImpl DR = Section->getRawDataRefImpl();
1465 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1466 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001467 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001468 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001469 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001470 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001471 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001472
1473 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001474 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001475 uint64_t Val =
1476 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001477 outs() << format("\t %08" PRIx64 " ", Val);
1478 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001479
Davide Italianocd2514d2015-04-30 23:08:53 +00001480 if (Hidden) {
1481 outs() << ".hidden ";
1482 }
1483 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001484 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001485 }
1486}
1487
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001488static void PrintUnwindInfo(const ObjectFile *o) {
1489 outs() << "Unwind info:\n\n";
1490
1491 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1492 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001493 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1494 printMachOUnwindInfo(MachO);
1495 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001496 // TODO: Extract DWARF dump tool to objdump.
1497 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001498 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001499 return;
1500 }
1501}
1502
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001503void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001504 outs() << "Exports trie:\n";
1505 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1506 printMachOExportsTrie(MachO);
1507 else {
1508 errs() << "This operation is only currently supported "
1509 "for Mach-O executable files.\n";
1510 return;
1511 }
1512}
1513
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001514void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001515 outs() << "Rebase table:\n";
1516 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1517 printMachORebaseTable(MachO);
1518 else {
1519 errs() << "This operation is only currently supported "
1520 "for Mach-O executable files.\n";
1521 return;
1522 }
1523}
1524
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001525void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001526 outs() << "Bind table:\n";
1527 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1528 printMachOBindTable(MachO);
1529 else {
1530 errs() << "This operation is only currently supported "
1531 "for Mach-O executable files.\n";
1532 return;
1533 }
1534}
1535
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001536void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001537 outs() << "Lazy bind table:\n";
1538 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1539 printMachOLazyBindTable(MachO);
1540 else {
1541 errs() << "This operation is only currently supported "
1542 "for Mach-O executable files.\n";
1543 return;
1544 }
1545}
1546
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001547void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001548 outs() << "Weak bind table:\n";
1549 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1550 printMachOWeakBindTable(MachO);
1551 else {
1552 errs() << "This operation is only currently supported "
1553 "for Mach-O executable files.\n";
1554 return;
1555 }
1556}
Nick Kledzikac431442014-09-12 21:34:15 +00001557
Adrian Prantl437105a2015-07-08 02:04:15 +00001558/// Dump the raw contents of the __clangast section so the output can be piped
1559/// into llvm-bcanalyzer.
1560void llvm::printRawClangAST(const ObjectFile *Obj) {
1561 if (outs().is_displayed()) {
1562 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1563 "the clang ast section.\n"
1564 "Please redirect the output to a file or another program such as "
1565 "llvm-bcanalyzer.\n";
1566 return;
1567 }
1568
1569 StringRef ClangASTSectionName("__clangast");
1570 if (isa<COFFObjectFile>(Obj)) {
1571 ClangASTSectionName = "clangast";
1572 }
1573
1574 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001575 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001576 StringRef Name;
1577 Sec.getName(Name);
1578 if (Name == ClangASTSectionName) {
1579 ClangASTSection = Sec;
1580 break;
1581 }
1582 }
1583 if (!ClangASTSection)
1584 return;
1585
1586 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001587 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001588 outs().write(ClangASTContents.data(), ClangASTContents.size());
1589}
1590
Sanjoy Das6f567a42015-06-22 18:03:02 +00001591static void printFaultMaps(const ObjectFile *Obj) {
1592 const char *FaultMapSectionName = nullptr;
1593
1594 if (isa<ELFObjectFileBase>(Obj)) {
1595 FaultMapSectionName = ".llvm_faultmaps";
1596 } else if (isa<MachOObjectFile>(Obj)) {
1597 FaultMapSectionName = "__llvm_faultmaps";
1598 } else {
1599 errs() << "This operation is only currently supported "
1600 "for ELF and Mach-O executable files.\n";
1601 return;
1602 }
1603
1604 Optional<object::SectionRef> FaultMapSection;
1605
Colin LeMahieu77804be2015-07-29 15:45:39 +00001606 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001607 StringRef Name;
1608 Sec.getName(Name);
1609 if (Name == FaultMapSectionName) {
1610 FaultMapSection = Sec;
1611 break;
1612 }
1613 }
1614
1615 outs() << "FaultMap table:\n";
1616
1617 if (!FaultMapSection.hasValue()) {
1618 outs() << "<not found>\n";
1619 return;
1620 }
1621
1622 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001623 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001624
1625 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1626 FaultMapContents.bytes_end());
1627
1628 outs() << FMP;
1629}
1630
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001631static void printPrivateFileHeaders(const ObjectFile *o) {
1632 if (o->isELF())
1633 printELFFileHeader(o);
1634 else if (o->isCOFF())
1635 printCOFFFileHeader(o);
1636 else if (o->isMachO()) {
1637 printMachOFileHeader(o);
1638 printMachOLoadCommands(o);
1639 } else
1640 report_fatal_error("Invalid/Unsupported object file format");
1641}
1642
1643static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001644 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001645 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001646 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001647 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001648 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001649 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001650 else
1651 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001652}
1653
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001654static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1655 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001656 // Avoid other output when using a raw option.
1657 if (!RawClangAST) {
1658 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001659 if (a)
1660 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1661 else
1662 outs() << o->getFileName();
1663 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001664 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001665
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001666 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001667 DisassembleObject(o, Relocations);
1668 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001669 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001670 if (SectionHeaders)
1671 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001672 if (SectionContents)
1673 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001674 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001675 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001676 if (UnwindInfo)
1677 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001678 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001679 printPrivateFileHeaders(o);
1680 if (FirstPrivateHeader)
1681 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001682 if (ExportsTrie)
1683 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001684 if (Rebase)
1685 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001686 if (Bind)
1687 printBindTable(o);
1688 if (LazyBind)
1689 printLazyBindTable(o);
1690 if (WeakBind)
1691 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001692 if (RawClangAST)
1693 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001694 if (PrintFaultMaps)
1695 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001696 if (DwarfDumpType != DIDT_Null) {
1697 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1698 // Dump the complete DWARF structure.
1699 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1700 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001701}
1702
1703/// @brief Dump each object file in \a a;
1704static void DumpArchive(const Archive *a) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001705 for (auto &ErrorOrChild : a->children()) {
1706 if (std::error_code EC = ErrorOrChild.getError())
1707 report_error(a->getFileName(), EC);
1708 const Archive::Child &C = *ErrorOrChild;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001709 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1710 if (!ChildOrErr) {
1711 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1712 report_error(a->getFileName(), C, std::move(E));
1713 continue;
1714 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001715 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001716 DumpObject(o, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001717 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001718 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001719 }
1720}
1721
1722/// @brief Open file and figure out how to dump it.
1723static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001724
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001725 // If we are using the Mach-O specific object file parser, then let it parse
1726 // the file and process the command line options. So the -arch flags can
1727 // be used to select specific slices, etc.
1728 if (MachOOpt) {
1729 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001730 return;
1731 }
1732
1733 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001734 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1735 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00001736 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00001737 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001738
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001739 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001740 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001741 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001742 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001743 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001744 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001745}
1746
Michael J. Spencer2670c252011-01-20 06:39:06 +00001747int main(int argc, char **argv) {
1748 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00001749 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001750 PrettyStackTraceProgram X(argc, argv);
1751 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1752
1753 // Initialize targets and assembly printers/parsers.
1754 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001755 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001756 llvm::InitializeAllDisassemblers();
1757
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001758 // Register the target printer for --version.
1759 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1760
Michael J. Spencer2670c252011-01-20 06:39:06 +00001761 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1762 TripleName = Triple::normalize(TripleName);
1763
1764 ToolName = argv[0];
1765
1766 // Defaults to a.out if no filenames specified.
1767 if (InputFilenames.size() == 0)
1768 InputFilenames.push_back("a.out");
1769
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001770 if (DisassembleAll)
1771 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001772 if (!Disassemble
1773 && !Relocations
1774 && !SectionHeaders
1775 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001776 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001777 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001778 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001779 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001780 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001781 && !Rebase
1782 && !Bind
1783 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001784 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001785 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001786 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001787 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001788 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001789 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001790 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001791 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001792 && !(DylibsUsed && MachOOpt)
1793 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001794 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001795 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001796 && !PrintFaultMaps
1797 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001798 cl::PrintHelpMessage();
1799 return 2;
1800 }
1801
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001802 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1803 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001804
Davide Italianoccd53fe2015-08-05 07:18:31 +00001805 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001806}