blob: 3bcf1651b7497942916c9e157ef8308d08cdb944 [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"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000026#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000028#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000029#include "llvm/MC/MCDisassembler/MCDisassembler.h"
30#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000031#include "llvm/MC/MCInst.h"
32#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000033#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000034#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000035#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000036#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000037#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/Archive.h"
39#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000040#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000041#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000042#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000044#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000047#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000048#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000050#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000051#include "llvm/Support/Host.h"
52#include "llvm/Support/ManagedStatic.h"
53#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include "llvm/Support/PrettyStackTrace.h"
55#include "llvm/Support/Signals.h"
56#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000057#include "llvm/Support/TargetRegistry.h"
58#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000061#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000063#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000064#include <utility>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000065#include <unordered_map>
Ahmed Bougacha17926472013-08-21 07:29:02 +000066
Michael J. Spencer2670c252011-01-20 06:39:06 +000067using namespace llvm;
68using namespace object;
69
Benjamin Kramer43a772e2011-09-19 17:56:04 +000070static cl::list<std::string>
71InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000072
Kevin Enderbye2297dd2015-01-07 21:02:18 +000073cl::opt<bool>
74llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000075 cl::desc("Display assembler mnemonics for the machine instructions"));
76static cl::alias
77Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000078 cl::aliasopt(Disassemble));
79
80cl::opt<bool>
81llvm::DisassembleAll("disassemble-all",
82 cl::desc("Display assembler mnemonics for the machine instructions"));
83static cl::alias
84DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000085 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000086
Kevin Enderby98da6132015-01-20 21:47:46 +000087cl::opt<bool>
88llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000089
Kevin Enderby98da6132015-01-20 21:47:46 +000090cl::opt<bool>
91llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000092
Kevin Enderby98da6132015-01-20 21:47:46 +000093cl::opt<bool>
94llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000095
Kevin Enderbye2297dd2015-01-07 21:02:18 +000096cl::opt<bool>
97llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000098
Kevin Enderbye2297dd2015-01-07 21:02:18 +000099cl::opt<bool>
100llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000101
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000102cl::opt<bool>
103llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000104
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000105cl::opt<bool>
106llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000107
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000108cl::opt<bool>
109llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000110
Adrian Prantl437105a2015-07-08 02:04:15 +0000111cl::opt<bool>
112llvm::RawClangAST("raw-clang-ast",
113 cl::desc("Dump the raw binary contents of the clang AST section"));
114
Nick Kledzik56ebef42014-09-16 01:41:51 +0000115static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000116MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000117static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000118MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000119
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000120cl::opt<std::string>
121llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
122 "see -version for available targets"));
123
124cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000125llvm::MCPU("mcpu",
126 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
127 cl::value_desc("cpu-name"),
128 cl::init(""));
129
130cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000131llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000132 "see -version for available targets"));
133
Kevin Enderby98da6132015-01-20 21:47:46 +0000134cl::opt<bool>
135llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
136 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000137static cl::alias
138SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
139 cl::aliasopt(SectionHeaders));
140static cl::alias
141SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
142 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000143
Colin LeMahieu77804be2015-07-29 15:45:39 +0000144cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000145llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
146 "With -macho dump segment,section"));
147cl::alias
148static FilterSectionsj("j", cl::desc("Alias for --section"),
149 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000150
Kevin Enderbyc9595622014-08-06 23:24:41 +0000151cl::list<std::string>
152llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000153 cl::CommaSeparated,
154 cl::desc("Target specific attributes"),
155 cl::value_desc("a1,+a2,-a3,..."));
156
Kevin Enderbybf246f52014-09-24 23:08:22 +0000157cl::opt<bool>
158llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
159 "instructions, do not print "
160 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000161
Kevin Enderby98da6132015-01-20 21:47:46 +0000162cl::opt<bool>
163llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000164
165static cl::alias
166UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
167 cl::aliasopt(UnwindInfo));
168
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000169cl::opt<bool>
170llvm::PrivateHeaders("private-headers",
171 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000172
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000173cl::opt<bool>
174llvm::FirstPrivateHeader("private-header",
175 cl::desc("Display only the first format specific file "
176 "header"));
177
Michael J. Spencer209565db2013-01-06 03:56:49 +0000178static cl::alias
179PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
180 cl::aliasopt(PrivateHeaders));
181
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000182cl::opt<bool>
183 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000184 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000185
Sanjoy Das6f567a42015-06-22 18:03:02 +0000186cl::opt<bool> PrintFaultMaps("fault-map-section",
187 cl::desc("Display contents of faultmap section"));
188
Igor Laevsky03a670c2016-01-26 15:09:42 +0000189cl::opt<DIDumpType> llvm::DwarfDumpType(
190 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
191 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
192 clEnumValEnd));
193
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000194cl::opt<bool> PrintSource(
195 "source",
196 cl::desc(
197 "Display source inlined with disassembly. Implies disassmble object"));
198
199cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
200 cl::aliasopt(PrintSource));
201
202cl::opt<bool> PrintLines("line-numbers",
203 cl::desc("Display source line numbers with "
204 "disassembly. Implies disassemble object"));
205
206cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
207 cl::aliasopt(PrintLines));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000208static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000209
Colin LeMahieu77804be2015-07-29 15:45:39 +0000210namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000211typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000212
213class SectionFilterIterator {
214public:
215 SectionFilterIterator(FilterPredicate P,
216 llvm::object::section_iterator const &I,
217 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000218 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000219 ScanPredicate();
220 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000221 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000222 SectionFilterIterator &operator++() {
223 ++Iterator;
224 ScanPredicate();
225 return *this;
226 }
227 bool operator!=(SectionFilterIterator const &Other) const {
228 return Iterator != Other.Iterator;
229 }
230
231private:
232 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000233 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000234 ++Iterator;
235 }
236 }
237 FilterPredicate Predicate;
238 llvm::object::section_iterator Iterator;
239 llvm::object::section_iterator End;
240};
241
242class SectionFilter {
243public:
244 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000245 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000246 SectionFilterIterator begin() {
247 return SectionFilterIterator(Predicate, Object.section_begin(),
248 Object.section_end());
249 }
250 SectionFilterIterator end() {
251 return SectionFilterIterator(Predicate, Object.section_end(),
252 Object.section_end());
253 }
254
255private:
256 FilterPredicate Predicate;
257 llvm::object::ObjectFile const &Object;
258};
259SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000260 return SectionFilter(
261 [](llvm::object::SectionRef const &S) {
262 if (FilterSections.empty())
263 return true;
264 llvm::StringRef String;
265 std::error_code error = S.getName(String);
266 if (error)
267 return false;
268 return is_contained(FilterSections, String);
269 },
270 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000271}
272}
273
Davide Italianoccd53fe2015-08-05 07:18:31 +0000274void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000275 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000276 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000277
Davide Italiano140af642015-12-25 18:16:45 +0000278 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
279 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000280 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000281}
282
Kevin Enderby42398052016-06-28 23:16:13 +0000283LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
284 errs() << ToolName << ": " << Message << ".\n";
285 errs().flush();
286 exit(1);
287}
288
Davide Italianoed9d95b2015-12-29 13:41:02 +0000289LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
290 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000291 assert(EC);
292 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000293 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000294}
295
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000296LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
297 llvm::Error E) {
298 assert(E);
299 std::string Buf;
300 raw_string_ostream OS(Buf);
301 logAllUnhandledErrors(std::move(E), OS, "");
302 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000303 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000304 exit(1);
305}
306
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000307LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
308 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000309 llvm::Error E,
310 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000311 assert(E);
312 errs() << ToolName << ": ";
313 if (ArchiveName != "")
314 errs() << ArchiveName << "(" << FileName << ")";
315 else
316 errs() << FileName;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000317 if (!ArchitectureName.empty())
318 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000319 std::string Buf;
320 raw_string_ostream OS(Buf);
321 logAllUnhandledErrors(std::move(E), OS, "");
322 OS.flush();
323 errs() << " " << Buf;
324 exit(1);
325}
326
327LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
328 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000329 llvm::Error E,
330 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000331 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000332 // TODO: if we have a error getting the name then it would be nice to print
333 // the index of which archive member this is and or its offset in the
334 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000335 if (!NameOrErr) {
336 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000337 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000338 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000339 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
340 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000341}
342
Craig Toppere6cb63e2014-04-25 04:24:47 +0000343static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000344 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000345 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000346 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000347 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000348 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000349 // TheTriple defaults to ELF, and COFF doesn't have an environment:
350 // the best we can do here is indicate that it is mach-o.
351 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000352 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000353
354 if (Obj->isCOFF()) {
355 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
356 if (COFFObj->getArch() == Triple::thumb)
357 TheTriple.setTriple("thumbv7-windows");
358 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000359 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000360 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000361 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000362
363 // Get the target specific parser.
364 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000365 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
366 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000367 if (!TheTarget)
368 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000369
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000370 // Update the triple name and return the found target.
371 TripleName = TheTriple.getTriple();
372 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000373}
374
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000375bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000376 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000377}
378
Colin LeMahieufb76b002015-05-28 19:07:14 +0000379namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000380class SourcePrinter {
381protected:
382 DILineInfo OldLineInfo;
383 const ObjectFile *Obj;
384 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
385 // File name to file contents of source
386 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
387 // Mark the line endings of the cached source
388 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
389
390private:
391 bool cacheSource(std::string File);
392
393public:
394 virtual ~SourcePrinter() {}
395 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
396 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
397 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
398 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
399 DefaultArch);
400 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
401 }
402 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
403 StringRef Delimiter = "; ");
404};
405
406bool SourcePrinter::cacheSource(std::string File) {
407 auto BufferOrError = MemoryBuffer::getFile(File);
408 if (!BufferOrError)
409 return false;
410 // Chomp the file to get lines
411 size_t BufferSize = (*BufferOrError)->getBufferSize();
412 const char *BufferStart = (*BufferOrError)->getBufferStart();
413 for (const char *Start = BufferStart, *End = BufferStart;
414 End < BufferStart + BufferSize; End++)
415 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
416 (*End == '\r' && *(End + 1) == '\n')) {
417 LineCache[File].push_back(StringRef(Start, End - Start));
418 if (*End == '\r')
419 End++;
420 Start = End + 1;
421 }
422 SourceCache[File] = std::move(*BufferOrError);
423 return true;
424}
425
426void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
427 StringRef Delimiter) {
428 if (!Symbolizer)
429 return;
430 DILineInfo LineInfo = DILineInfo();
431 auto ExpectecLineInfo =
432 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
433 if (!ExpectecLineInfo)
434 consumeError(ExpectecLineInfo.takeError());
435 else
436 LineInfo = *ExpectecLineInfo;
437
438 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
439 LineInfo.Line == 0)
440 return;
441
442 if (PrintLines)
443 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
444 if (PrintSource) {
445 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
446 if (!cacheSource(LineInfo.FileName))
447 return;
448 auto FileBuffer = SourceCache.find(LineInfo.FileName);
449 if (FileBuffer != SourceCache.end()) {
450 auto LineBuffer = LineCache.find(LineInfo.FileName);
451 if (LineBuffer != LineCache.end())
452 // Vector begins at 0, line numbers are non-zero
453 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
454 << "\n";
455 }
456 }
457 OldLineInfo = LineInfo;
458}
459
Colin LeMahieufb76b002015-05-28 19:07:14 +0000460class PrettyPrinter {
461public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000462 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000463 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000464 ArrayRef<uint8_t> Bytes, uint64_t Address,
465 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000466 MCSubtargetInfo const &STI, SourcePrinter *SP) {
467 if (SP && (PrintSource || PrintLines))
468 SP->printSourceLine(OS, Address);
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000469 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000470 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000471 OS << "\t";
472 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000473 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000474 if (MI)
475 IP.printInst(MI, OS, "", STI);
476 else
477 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000478 }
479};
480PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000481class HexagonPrettyPrinter : public PrettyPrinter {
482public:
483 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
484 raw_ostream &OS) {
485 uint32_t opcode =
486 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
487 OS << format("%8" PRIx64 ":", Address);
488 if (!NoShowRawInsn) {
489 OS << "\t";
490 dumpBytes(Bytes.slice(0, 4), OS);
491 OS << format("%08" PRIx32, opcode);
492 }
493 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000494 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
495 uint64_t Address, raw_ostream &OS, StringRef Annot,
496 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000497 if (SP && (PrintSource || PrintLines))
498 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000499 if (!MI) {
500 printLead(Bytes, Address, OS);
501 OS << " <unknown>";
502 return;
503 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000504 std::string Buffer;
505 {
506 raw_string_ostream TempStream(Buffer);
507 IP.printInst(MI, TempStream, "", STI);
508 }
509 StringRef Contents(Buffer);
510 // Split off bundle attributes
511 auto PacketBundle = Contents.rsplit('\n');
512 // Split off first instruction from the rest
513 auto HeadTail = PacketBundle.first.split('\n');
514 auto Preamble = " { ";
515 auto Separator = "";
516 while(!HeadTail.first.empty()) {
517 OS << Separator;
518 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000519 if (SP && (PrintSource || PrintLines))
520 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000521 printLead(Bytes, Address, OS);
522 OS << Preamble;
523 Preamble = " ";
524 StringRef Inst;
525 auto Duplex = HeadTail.first.split('\v');
526 if(!Duplex.second.empty()){
527 OS << Duplex.first;
528 OS << "; ";
529 Inst = Duplex.second;
530 }
531 else
532 Inst = HeadTail.first;
533 OS << Inst;
534 Bytes = Bytes.slice(4);
535 Address += 4;
536 HeadTail = HeadTail.second.split('\n');
537 }
538 OS << " } " << PacketBundle.second;
539 }
540};
541HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000542
543class AMDGCNPrettyPrinter : public PrettyPrinter {
544public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000545 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
546 uint64_t Address, raw_ostream &OS, StringRef Annot,
547 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000548 if (!MI) {
549 OS << " <unknown>";
550 return;
551 }
552
Valery Pykhtinde048052016-04-07 07:24:01 +0000553 SmallString<40> InstStr;
554 raw_svector_ostream IS(InstStr);
555
556 IP.printInst(MI, IS, "", STI);
557
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000558 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000559 typedef support::ulittle32_t U32;
560 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
561 Bytes.size() / sizeof(U32)))
562 // D should be explicitly casted to uint32_t here as it is passed
563 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000564 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000565
566 if (!Annot.empty())
567 OS << "// " << Annot;
568 }
569};
570AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
571
Colin LeMahieu35436a22015-05-29 14:48:25 +0000572PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000573 switch(Triple.getArch()) {
574 default:
575 return PrettyPrinterInst;
576 case Triple::hexagon:
577 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000578 case Triple::amdgcn:
579 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000580 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000581}
582}
583
Rafael Espindola37070a52015-06-03 04:48:06 +0000584template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000585static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000586 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000587 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000588 DataRefImpl Rel = RelRef.getRawDataRefImpl();
589
Rafael Espindola37070a52015-06-03 04:48:06 +0000590 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
591 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000592 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
593
Rafael Espindola37070a52015-06-03 04:48:06 +0000594 const ELFFile<ELFT> &EF = *Obj->getELFFile();
595
Rafael Espindola6def3042015-07-01 12:56:27 +0000596 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
597 if (std::error_code EC = SecOrErr.getError())
598 return EC;
599 const Elf_Shdr *Sec = *SecOrErr;
600 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
601 if (std::error_code EC = SymTabOrErr.getError())
602 return EC;
603 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000604 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
605 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000606 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
607 if (std::error_code EC = StrTabSec.getError())
608 return EC;
609 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000610 if (std::error_code EC = StrTabOrErr.getError())
611 return EC;
612 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000613 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000614 StringRef res;
615 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000616 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000617 default:
618 return object_error::parse_failed;
619 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000620 // TODO: Read implicit addend from section data.
621 break;
622 }
623 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000624 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000625 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000626 break;
627 }
628 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000629 symbol_iterator SI = RelRef.getSymbol();
630 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000631 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000632 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000633 Expected<section_iterator> SymSI = SI->getSection();
634 if (!SymSI)
635 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000636 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
637 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000638 if (std::error_code EC = SecName.getError())
639 return EC;
640 Target = *SecName;
641 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000642 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000643 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000644 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000645 Target = *SymName;
646 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000647 switch (EF.getHeader()->e_machine) {
648 case ELF::EM_X86_64:
649 switch (type) {
650 case ELF::R_X86_64_PC8:
651 case ELF::R_X86_64_PC16:
652 case ELF::R_X86_64_PC32: {
653 std::string fmtbuf;
654 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000655 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000656 fmt.flush();
657 Result.append(fmtbuf.begin(), fmtbuf.end());
658 } break;
659 case ELF::R_X86_64_8:
660 case ELF::R_X86_64_16:
661 case ELF::R_X86_64_32:
662 case ELF::R_X86_64_32S:
663 case ELF::R_X86_64_64: {
664 std::string fmtbuf;
665 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000666 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000667 fmt.flush();
668 Result.append(fmtbuf.begin(), fmtbuf.end());
669 } break;
670 default:
671 res = "Unknown";
672 }
673 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000674 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000675 case ELF::EM_AARCH64: {
676 std::string fmtbuf;
677 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000678 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000679 if (addend != 0)
680 fmt << (addend < 0 ? "" : "+") << addend;
681 fmt.flush();
682 Result.append(fmtbuf.begin(), fmtbuf.end());
683 break;
684 }
685 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000686 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000687 case ELF::EM_ARM:
688 case ELF::EM_HEXAGON:
689 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000690 case ELF::EM_BPF:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000691 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000692 break;
Dan Gohman46350172016-01-12 20:56:01 +0000693 case ELF::EM_WEBASSEMBLY:
694 switch (type) {
695 case ELF::R_WEBASSEMBLY_DATA: {
696 std::string fmtbuf;
697 raw_string_ostream fmt(fmtbuf);
698 fmt << Target << (addend < 0 ? "" : "+") << addend;
699 fmt.flush();
700 Result.append(fmtbuf.begin(), fmtbuf.end());
701 break;
702 }
703 case ELF::R_WEBASSEMBLY_FUNCTION:
704 res = Target;
705 break;
706 default:
707 res = "Unknown";
708 }
709 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000710 default:
711 res = "Unknown";
712 }
713 if (Result.empty())
714 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000715 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000716}
717
718static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000719 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000720 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000721 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
722 return getRelocationValueString(ELF32LE, Rel, Result);
723 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
724 return getRelocationValueString(ELF64LE, Rel, Result);
725 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
726 return getRelocationValueString(ELF32BE, Rel, Result);
727 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
728 return getRelocationValueString(ELF64BE, Rel, Result);
729}
730
731static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
732 const RelocationRef &Rel,
733 SmallVectorImpl<char> &Result) {
734 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000735 Expected<StringRef> SymNameOrErr = SymI->getName();
736 if (!SymNameOrErr)
737 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000738 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000739 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000740 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000741}
742
743static void printRelocationTargetName(const MachOObjectFile *O,
744 const MachO::any_relocation_info &RE,
745 raw_string_ostream &fmt) {
746 bool IsScattered = O->isRelocationScattered(RE);
747
748 // Target of a scattered relocation is an address. In the interest of
749 // generating pretty output, scan through the symbol table looking for a
750 // symbol that aligns with that address. If we find one, print it.
751 // Otherwise, we just print the hex address of the target.
752 if (IsScattered) {
753 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
754
755 for (const SymbolRef &Symbol : O->symbols()) {
756 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000757 Expected<uint64_t> Addr = Symbol.getAddress();
758 if (!Addr) {
759 std::string Buf;
760 raw_string_ostream OS(Buf);
761 logAllUnhandledErrors(Addr.takeError(), OS, "");
762 OS.flush();
763 report_fatal_error(Buf);
764 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000765 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000766 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000767 Expected<StringRef> Name = Symbol.getName();
768 if (!Name) {
769 std::string Buf;
770 raw_string_ostream OS(Buf);
771 logAllUnhandledErrors(Name.takeError(), OS, "");
772 OS.flush();
773 report_fatal_error(Buf);
774 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000775 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000776 return;
777 }
778
779 // If we couldn't find a symbol that this relocation refers to, try
780 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000781 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000782 std::error_code ec;
783
784 StringRef Name;
785 uint64_t Addr = Section.getAddress();
786 if (Addr != Val)
787 continue;
788 if ((ec = Section.getName(Name)))
789 report_fatal_error(ec.message());
790 fmt << Name;
791 return;
792 }
793
794 fmt << format("0x%x", Val);
795 return;
796 }
797
798 StringRef S;
799 bool isExtern = O->getPlainRelocationExternal(RE);
800 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
801
802 if (isExtern) {
803 symbol_iterator SI = O->symbol_begin();
804 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000805 Expected<StringRef> SOrErr = SI->getName();
806 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000807 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000808 } else {
809 section_iterator SI = O->section_begin();
810 // Adjust for the fact that sections are 1-indexed.
811 advance(SI, Val - 1);
812 SI->getName(S);
813 }
814
815 fmt << S;
816}
817
818static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
819 const RelocationRef &RelRef,
820 SmallVectorImpl<char> &Result) {
821 DataRefImpl Rel = RelRef.getRawDataRefImpl();
822 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
823
824 unsigned Arch = Obj->getArch();
825
826 std::string fmtbuf;
827 raw_string_ostream fmt(fmtbuf);
828 unsigned Type = Obj->getAnyRelocationType(RE);
829 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
830
831 // Determine any addends that should be displayed with the relocation.
832 // These require decoding the relocation type, which is triple-specific.
833
834 // X86_64 has entirely custom relocation types.
835 if (Arch == Triple::x86_64) {
836 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
837
838 switch (Type) {
839 case MachO::X86_64_RELOC_GOT_LOAD:
840 case MachO::X86_64_RELOC_GOT: {
841 printRelocationTargetName(Obj, RE, fmt);
842 fmt << "@GOT";
843 if (isPCRel)
844 fmt << "PCREL";
845 break;
846 }
847 case MachO::X86_64_RELOC_SUBTRACTOR: {
848 DataRefImpl RelNext = Rel;
849 Obj->moveRelocationNext(RelNext);
850 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
851
852 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
853 // X86_64_RELOC_UNSIGNED.
854 // NOTE: Scattered relocations don't exist on x86_64.
855 unsigned RType = Obj->getAnyRelocationType(RENext);
856 if (RType != MachO::X86_64_RELOC_UNSIGNED)
857 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
858 "X86_64_RELOC_SUBTRACTOR.");
859
860 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
861 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
862 printRelocationTargetName(Obj, RENext, fmt);
863 fmt << "-";
864 printRelocationTargetName(Obj, RE, fmt);
865 break;
866 }
867 case MachO::X86_64_RELOC_TLV:
868 printRelocationTargetName(Obj, RE, fmt);
869 fmt << "@TLV";
870 if (isPCRel)
871 fmt << "P";
872 break;
873 case MachO::X86_64_RELOC_SIGNED_1:
874 printRelocationTargetName(Obj, RE, fmt);
875 fmt << "-1";
876 break;
877 case MachO::X86_64_RELOC_SIGNED_2:
878 printRelocationTargetName(Obj, RE, fmt);
879 fmt << "-2";
880 break;
881 case MachO::X86_64_RELOC_SIGNED_4:
882 printRelocationTargetName(Obj, RE, fmt);
883 fmt << "-4";
884 break;
885 default:
886 printRelocationTargetName(Obj, RE, fmt);
887 break;
888 }
889 // X86 and ARM share some relocation types in common.
890 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
891 Arch == Triple::ppc) {
892 // Generic relocation types...
893 switch (Type) {
894 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000895 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000896 case MachO::GENERIC_RELOC_SECTDIFF: {
897 DataRefImpl RelNext = Rel;
898 Obj->moveRelocationNext(RelNext);
899 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
900
901 // X86 sect diff's must be followed by a relocation of type
902 // GENERIC_RELOC_PAIR.
903 unsigned RType = Obj->getAnyRelocationType(RENext);
904
905 if (RType != MachO::GENERIC_RELOC_PAIR)
906 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
907 "GENERIC_RELOC_SECTDIFF.");
908
909 printRelocationTargetName(Obj, RE, fmt);
910 fmt << "-";
911 printRelocationTargetName(Obj, RENext, fmt);
912 break;
913 }
914 }
915
916 if (Arch == Triple::x86 || Arch == Triple::ppc) {
917 switch (Type) {
918 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
919 DataRefImpl RelNext = Rel;
920 Obj->moveRelocationNext(RelNext);
921 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
922
923 // X86 sect diff's must be followed by a relocation of type
924 // GENERIC_RELOC_PAIR.
925 unsigned RType = Obj->getAnyRelocationType(RENext);
926 if (RType != MachO::GENERIC_RELOC_PAIR)
927 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
928 "GENERIC_RELOC_LOCAL_SECTDIFF.");
929
930 printRelocationTargetName(Obj, RE, fmt);
931 fmt << "-";
932 printRelocationTargetName(Obj, RENext, fmt);
933 break;
934 }
935 case MachO::GENERIC_RELOC_TLV: {
936 printRelocationTargetName(Obj, RE, fmt);
937 fmt << "@TLV";
938 if (IsPCRel)
939 fmt << "P";
940 break;
941 }
942 default:
943 printRelocationTargetName(Obj, RE, fmt);
944 }
945 } else { // ARM-specific relocations
946 switch (Type) {
947 case MachO::ARM_RELOC_HALF:
948 case MachO::ARM_RELOC_HALF_SECTDIFF: {
949 // Half relocations steal a bit from the length field to encode
950 // whether this is an upper16 or a lower16 relocation.
951 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
952
953 if (isUpper)
954 fmt << ":upper16:(";
955 else
956 fmt << ":lower16:(";
957 printRelocationTargetName(Obj, RE, fmt);
958
959 DataRefImpl RelNext = Rel;
960 Obj->moveRelocationNext(RelNext);
961 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
962
963 // ARM half relocs must be followed by a relocation of type
964 // ARM_RELOC_PAIR.
965 unsigned RType = Obj->getAnyRelocationType(RENext);
966 if (RType != MachO::ARM_RELOC_PAIR)
967 report_fatal_error("Expected ARM_RELOC_PAIR after "
968 "ARM_RELOC_HALF");
969
970 // NOTE: The half of the target virtual address is stashed in the
971 // address field of the secondary relocation, but we can't reverse
972 // engineer the constant offset from it without decoding the movw/movt
973 // instruction to find the other half in its immediate field.
974
975 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
976 // symbol/section pointer of the follow-on relocation.
977 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
978 fmt << "-";
979 printRelocationTargetName(Obj, RENext, fmt);
980 }
981
982 fmt << ")";
983 break;
984 }
985 default: { printRelocationTargetName(Obj, RE, fmt); }
986 }
987 }
988 } else
989 printRelocationTargetName(Obj, RE, fmt);
990
991 fmt.flush();
992 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000993 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000994}
995
996static std::error_code getRelocationValueString(const RelocationRef &Rel,
997 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000998 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000999 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1000 return getRelocationValueString(ELF, Rel, Result);
1001 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1002 return getRelocationValueString(COFF, Rel, Result);
1003 auto *MachO = cast<MachOObjectFile>(Obj);
1004 return getRelocationValueString(MachO, Rel, Result);
1005}
1006
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001007/// @brief Indicates whether this relocation should hidden when listing
1008/// relocations, usually because it is the trailing part of a multipart
1009/// relocation that will be printed as part of the leading relocation.
1010static bool getHidden(RelocationRef RelRef) {
1011 const ObjectFile *Obj = RelRef.getObject();
1012 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1013 if (!MachO)
1014 return false;
1015
1016 unsigned Arch = MachO->getArch();
1017 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1018 uint64_t Type = MachO->getRelocationType(Rel);
1019
1020 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1021 // is always hidden.
1022 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1023 if (Type == MachO::GENERIC_RELOC_PAIR)
1024 return true;
1025 } else if (Arch == Triple::x86_64) {
1026 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1027 // an X86_64_RELOC_SUBTRACTOR.
1028 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1029 DataRefImpl RelPrev = Rel;
1030 RelPrev.d.a--;
1031 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1032 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1033 return true;
1034 }
1035 }
1036
1037 return false;
1038}
1039
Sam Koltonc05d7782016-08-17 10:17:57 +00001040static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1041 assert(Obj->isELF());
1042 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1043 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1044 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1045 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1046 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1047 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1048 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1049 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1050 llvm_unreachable("Unsupported binary format");
1051}
1052
Michael J. Spencer51862b32011-10-13 22:17:18 +00001053static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001054 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001055
Jack Carter551efd72012-08-28 19:24:49 +00001056 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001057 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001058 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001059 for (unsigned i = 0; i != MAttrs.size(); ++i)
1060 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001061 }
1062
Ahmed Charles56440fd2014-03-06 05:51:42 +00001063 std::unique_ptr<const MCRegisterInfo> MRI(
1064 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001065 if (!MRI)
1066 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001067
1068 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001069 std::unique_ptr<const MCAsmInfo> AsmInfo(
1070 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001071 if (!AsmInfo)
1072 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001073 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001074 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001075 if (!STI)
1076 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001077 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001078 if (!MII)
1079 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001080 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
1081 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
1082
1083 std::unique_ptr<MCDisassembler> DisAsm(
1084 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001085 if (!DisAsm)
1086 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001087
Ahmed Charles56440fd2014-03-06 05:51:42 +00001088 std::unique_ptr<const MCInstrAnalysis> MIA(
1089 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001090
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001091 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001092 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1093 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001094 if (!IP)
1095 report_fatal_error("error: no instruction printer for target " +
1096 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001097 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001098 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001099
Greg Fitzgerald18432272014-03-20 22:55:15 +00001100 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1101 "\t\t\t%08" PRIx64 ": ";
1102
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001103 SourcePrinter SP(Obj, TheTarget->getName());
1104
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001105 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1106 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001107 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001108 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001109 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001110 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001111 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001112 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001113 }
1114
David Majnemer81afca62015-07-07 22:06:59 +00001115 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001116 // pretty print the symbols while disassembling.
Sam Koltonc05d7782016-08-17 10:17:57 +00001117 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001118 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1119 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001120 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1121 error(errorToErrorCode(AddressOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001122 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001123
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001124 Expected<StringRef> Name = Symbol.getName();
1125 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001126 if (Name->empty())
1127 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001128
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001129 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1130 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001131 section_iterator SecI = *SectionOrErr;
1132 if (SecI == Obj->section_end())
1133 continue;
Sam Koltonc05d7782016-08-17 10:17:57 +00001134
1135 // For AMDGPU we need to track symbol types
1136 uint8_t SymbolType = ELF::STT_NOTYPE;
1137 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1138 SymbolType = getElfSymbolType(Obj, Symbol);
1139 }
David Majnemer81afca62015-07-07 22:06:59 +00001140
Sam Koltonc05d7782016-08-17 10:17:57 +00001141 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1142
David Majnemer81afca62015-07-07 22:06:59 +00001143 }
1144
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001145 // Create a mapping from virtual address to section.
1146 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1147 for (SectionRef Sec : Obj->sections())
1148 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1149 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1150
1151 // Linked executables (.exe and .dll files) typically don't include a real
1152 // symbol table but they might contain an export table.
1153 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1154 for (const auto &ExportEntry : COFFObj->export_directories()) {
1155 StringRef Name;
1156 error(ExportEntry.getSymbolName(Name));
1157 if (Name.empty())
1158 continue;
1159 uint32_t RVA;
1160 error(ExportEntry.getExportRVA(RVA));
1161
1162 uint64_t VA = COFFObj->getImageBase() + RVA;
1163 auto Sec = std::upper_bound(
1164 SectionAddresses.begin(), SectionAddresses.end(), VA,
1165 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1166 return LHS < RHS.first;
1167 });
1168 if (Sec != SectionAddresses.begin())
1169 --Sec;
1170 else
1171 Sec = SectionAddresses.end();
1172
1173 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001174 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001175 }
1176 }
1177
1178 // Sort all the symbols, this allows us to use a simple binary search to find
1179 // a symbol near an address.
1180 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1181 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1182
Colin LeMahieu77804be2015-07-29 15:45:39 +00001183 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001184 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001185 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001186
Rafael Espindola80291272014-10-08 15:28:58 +00001187 uint64_t SectionAddr = Section.getAddress();
1188 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001189 if (!SectSize)
1190 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001191
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001192 // Get the list of all the symbols in this section.
1193 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001194 std::vector<uint64_t> DataMappingSymsAddr;
1195 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001196 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1197 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001198 uint64_t Address = std::get<0>(Symb);
1199 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001200 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001201 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001202 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001203 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001204 }
1205 }
1206
Davide Italianof0706882015-10-01 21:57:09 +00001207 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1208 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001209
Michael J. Spencer51862b32011-10-13 22:17:18 +00001210 // Make a list of all the relocations for this section.
1211 std::vector<RelocationRef> Rels;
1212 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001213 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1214 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1215 Rels.push_back(Reloc);
1216 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001217 }
1218 }
1219
1220 // Sort relocations by address.
1221 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1222
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001223 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001224 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001225 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001226 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001227 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001228 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001229 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001230 outs() << "Disassembly of section ";
1231 if (!SegmentName.empty())
1232 outs() << SegmentName << ",";
1233 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001234
Rafael Espindola7884c952015-06-04 15:01:05 +00001235 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001236 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1237 Symbols.insert(Symbols.begin(), std::make_tuple(SectionAddr, name, ELF::STT_NOTYPE));
1238 }
Alp Tokere69170a2014-06-26 22:52:05 +00001239
1240 SmallString<40> Comments;
1241 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001242
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001243 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001244 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001245 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1246 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001247
Michael J. Spencer2670c252011-01-20 06:39:06 +00001248 uint64_t Size;
1249 uint64_t Index;
1250
Michael J. Spencer51862b32011-10-13 22:17:18 +00001251 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1252 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001253 // Disassemble symbol by symbol.
1254 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001255 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001256 // The end is either the section end or the beginning of the next
1257 // symbol.
1258 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001259 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001260 // Don't try to disassemble beyond the end of section contents.
1261 if (End > SectSize)
1262 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001263 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001264 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001265 continue;
1266
Valery Pykhtinde048052016-04-07 07:24:01 +00001267 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1268 // make size 4 bytes folded
1269 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001270 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1271 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1272 Start += 256;
1273 }
1274 if (si == se - 1 ||
1275 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1276 // cut trailing zeroes at the end of kernel
1277 // cut up to 256 bytes
1278 const uint64_t EndAlign = 256;
1279 const auto Limit = End - (std::min)(EndAlign, End - Start);
1280 while (End > Limit &&
1281 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1282 End -= 4;
1283 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001284 }
1285
Sam Koltonc05d7782016-08-17 10:17:57 +00001286 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001287
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001288#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001289 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001290#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001291 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001292#endif
1293
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001294 for (Index = Start; Index < End; Index += Size) {
1295 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001296
Davide Italianof0706882015-10-01 21:57:09 +00001297 // AArch64 ELF binaries can interleave data and text in the
1298 // same section. We rely on the markers introduced to
1299 // understand what we need to dump.
1300 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1301 uint64_t Stride = 0;
1302
1303 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1304 DataMappingSymsAddr.end(), Index);
1305 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1306 // Switch to data.
1307 while (Index < End) {
1308 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1309 outs() << "\t";
1310 if (Index + 4 <= End) {
1311 Stride = 4;
1312 dumpBytes(Bytes.slice(Index, 4), outs());
1313 outs() << "\t.word";
1314 } else if (Index + 2 <= End) {
1315 Stride = 2;
1316 dumpBytes(Bytes.slice(Index, 2), outs());
1317 outs() << "\t.short";
1318 } else {
1319 Stride = 1;
1320 dumpBytes(Bytes.slice(Index, 1), outs());
1321 outs() << "\t.byte";
1322 }
1323 Index += Stride;
1324 outs() << "\n";
1325 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1326 TextMappingSymsAddr.end(), Index);
1327 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1328 break;
1329 }
1330 }
1331 }
1332
1333 if (Index >= End)
1334 break;
1335
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001336 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1337 SectionAddr + Index, DebugOut,
1338 CommentStream);
1339 if (Size == 0)
1340 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001341
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001342 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001343 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1344 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001345 outs() << CommentStream.str();
1346 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001347
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001348 // Try to resolve the target of a call, tail call, etc. to a specific
1349 // symbol.
1350 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1351 MIA->isConditionalBranch(Inst))) {
1352 uint64_t Target;
1353 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1354 // In a relocatable object, the target's section must reside in
1355 // the same section as the call instruction or it is accessed
1356 // through a relocation.
1357 //
1358 // In a non-relocatable object, the target may be in any section.
1359 //
1360 // N.B. We don't walk the relocations in the relocatable case yet.
1361 auto *TargetSectionSymbols = &Symbols;
1362 if (!Obj->isRelocatableObject()) {
1363 auto SectionAddress = std::upper_bound(
1364 SectionAddresses.begin(), SectionAddresses.end(), Target,
1365 [](uint64_t LHS,
1366 const std::pair<uint64_t, SectionRef> &RHS) {
1367 return LHS < RHS.first;
1368 });
1369 if (SectionAddress != SectionAddresses.begin()) {
1370 --SectionAddress;
1371 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1372 } else {
1373 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001374 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001375 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001376
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001377 // Find the first symbol in the section whose offset is less than
1378 // or equal to the target.
1379 if (TargetSectionSymbols) {
1380 auto TargetSym = std::upper_bound(
1381 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1382 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001383 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1384 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001385 });
1386 if (TargetSym != TargetSectionSymbols->begin()) {
1387 --TargetSym;
1388 uint64_t TargetAddress = std::get<0>(*TargetSym);
1389 StringRef TargetName = std::get<1>(*TargetSym);
1390 outs() << " <" << TargetName;
1391 uint64_t Disp = Target - TargetAddress;
1392 if (Disp)
1393 outs() << "+0x" << utohexstr(Disp);
1394 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001395 }
1396 }
1397 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001398 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001399 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001400
1401 // Print relocation for instruction.
1402 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001403 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001404 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001405 SmallString<16> name;
1406 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001407
1408 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001409 if (hidden) goto skip_print_rel;
1410
Michael J. Spencer51862b32011-10-13 22:17:18 +00001411 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001412 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001413 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001414 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001415 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001416 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001417
1418 skip_print_rel:
1419 ++rel_cur;
1420 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001421 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001422 }
1423 }
1424}
1425
Kevin Enderby98da6132015-01-20 21:47:46 +00001426void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001427 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1428 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001429 // Regular objdump doesn't print relocations in non-relocatable object
1430 // files.
1431 if (!Obj->isRelocatableObject())
1432 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001433
Colin LeMahieu77804be2015-07-29 15:45:39 +00001434 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001435 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001436 continue;
1437 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001438 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001439 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001440 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001441 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001442 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001443 SmallString<32> relocname;
1444 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001445 if (hidden)
1446 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001447 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001448 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001449 outs() << format(Fmt.data(), address) << " " << relocname << " "
1450 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001451 }
1452 outs() << "\n";
1453 }
1454}
1455
Kevin Enderby98da6132015-01-20 21:47:46 +00001456void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001457 outs() << "Sections:\n"
1458 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001459 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001460 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001461 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001462 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001463 uint64_t Address = Section.getAddress();
1464 uint64_t Size = Section.getSize();
1465 bool Text = Section.isText();
1466 bool Data = Section.isData();
1467 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001468 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001469 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001470 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1471 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001472 ++i;
1473 }
1474}
1475
Kevin Enderby98da6132015-01-20 21:47:46 +00001476void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001477 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001478 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001479 StringRef Name;
1480 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001481 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001482 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001483 uint64_t Size = Section.getSize();
1484 if (!Size)
1485 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001486
1487 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001488 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001489 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001490 ", %04" PRIx64 ")>\n",
1491 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001492 continue;
1493 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001494
Davide Italianoccd53fe2015-08-05 07:18:31 +00001495 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001496
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001497 // Dump out the content as hex and printable ascii characters.
1498 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001499 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001500 // Dump line of hex.
1501 for (std::size_t i = 0; i < 16; ++i) {
1502 if (i != 0 && i % 4 == 0)
1503 outs() << ' ';
1504 if (addr + i < end)
1505 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1506 << hexdigit(Contents[addr + i] & 0xF, true);
1507 else
1508 outs() << " ";
1509 }
1510 // Print ascii.
1511 outs() << " ";
1512 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001513 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001514 outs() << Contents[addr + i];
1515 else
1516 outs() << ".";
1517 }
1518 outs() << "\n";
1519 }
1520 }
1521}
1522
Kevin Enderby9acb1092016-05-31 20:35:34 +00001523void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1524 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001525 outs() << "SYMBOL TABLE:\n";
1526
Rui Ueyama4e39f712014-03-18 18:58:51 +00001527 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001528 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001529 return;
1530 }
1531 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001532 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1533 if (!AddressOrError)
1534 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001535 uint64_t Address = *AddressOrError;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001536 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1537 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001538 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001539 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001540 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001541 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1542 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001543 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001544 StringRef Name;
1545 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1546 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001547 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001548 Expected<StringRef> NameOrErr = Symbol.getName();
1549 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001550 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1551 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001552 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001553 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001554
Rui Ueyama4e39f712014-03-18 18:58:51 +00001555 bool Global = Flags & SymbolRef::SF_Global;
1556 bool Weak = Flags & SymbolRef::SF_Weak;
1557 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001558 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001559 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001560
Rui Ueyama4e39f712014-03-18 18:58:51 +00001561 char GlobLoc = ' ';
1562 if (Type != SymbolRef::ST_Unknown)
1563 GlobLoc = Global ? 'g' : 'l';
1564 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1565 ? 'd' : ' ';
1566 char FileFunc = ' ';
1567 if (Type == SymbolRef::ST_File)
1568 FileFunc = 'f';
1569 else if (Type == SymbolRef::ST_Function)
1570 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001571
Rui Ueyama4e39f712014-03-18 18:58:51 +00001572 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1573 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001574
Rui Ueyama4e39f712014-03-18 18:58:51 +00001575 outs() << format(Fmt, Address) << " "
1576 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1577 << (Weak ? 'w' : ' ') // Weak?
1578 << ' ' // Constructor. Not supported yet.
1579 << ' ' // Warning. Not supported yet.
1580 << ' ' // Indirect reference to another symbol.
1581 << Debug // Debugging (d) or dynamic (D) symbol.
1582 << FileFunc // Name of function (F), file (f) or object (O).
1583 << ' ';
1584 if (Absolute) {
1585 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001586 } else if (Common) {
1587 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001588 } else if (Section == o->section_end()) {
1589 outs() << "*UND*";
1590 } else {
1591 if (const MachOObjectFile *MachO =
1592 dyn_cast<const MachOObjectFile>(o)) {
1593 DataRefImpl DR = Section->getRawDataRefImpl();
1594 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1595 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001596 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001597 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001598 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001599 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001600 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001601
1602 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001603 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001604 uint64_t Val =
1605 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001606 outs() << format("\t %08" PRIx64 " ", Val);
1607 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001608
Davide Italianocd2514d2015-04-30 23:08:53 +00001609 if (Hidden) {
1610 outs() << ".hidden ";
1611 }
1612 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001613 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001614 }
1615}
1616
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001617static void PrintUnwindInfo(const ObjectFile *o) {
1618 outs() << "Unwind info:\n\n";
1619
1620 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1621 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001622 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1623 printMachOUnwindInfo(MachO);
1624 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001625 // TODO: Extract DWARF dump tool to objdump.
1626 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001627 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001628 return;
1629 }
1630}
1631
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001632void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001633 outs() << "Exports trie:\n";
1634 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1635 printMachOExportsTrie(MachO);
1636 else {
1637 errs() << "This operation is only currently supported "
1638 "for Mach-O executable files.\n";
1639 return;
1640 }
1641}
1642
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001643void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001644 outs() << "Rebase table:\n";
1645 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1646 printMachORebaseTable(MachO);
1647 else {
1648 errs() << "This operation is only currently supported "
1649 "for Mach-O executable files.\n";
1650 return;
1651 }
1652}
1653
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001655 outs() << "Bind table:\n";
1656 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1657 printMachOBindTable(MachO);
1658 else {
1659 errs() << "This operation is only currently supported "
1660 "for Mach-O executable files.\n";
1661 return;
1662 }
1663}
1664
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001665void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001666 outs() << "Lazy bind table:\n";
1667 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1668 printMachOLazyBindTable(MachO);
1669 else {
1670 errs() << "This operation is only currently supported "
1671 "for Mach-O executable files.\n";
1672 return;
1673 }
1674}
1675
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001676void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001677 outs() << "Weak bind table:\n";
1678 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1679 printMachOWeakBindTable(MachO);
1680 else {
1681 errs() << "This operation is only currently supported "
1682 "for Mach-O executable files.\n";
1683 return;
1684 }
1685}
Nick Kledzikac431442014-09-12 21:34:15 +00001686
Adrian Prantl437105a2015-07-08 02:04:15 +00001687/// Dump the raw contents of the __clangast section so the output can be piped
1688/// into llvm-bcanalyzer.
1689void llvm::printRawClangAST(const ObjectFile *Obj) {
1690 if (outs().is_displayed()) {
1691 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1692 "the clang ast section.\n"
1693 "Please redirect the output to a file or another program such as "
1694 "llvm-bcanalyzer.\n";
1695 return;
1696 }
1697
1698 StringRef ClangASTSectionName("__clangast");
1699 if (isa<COFFObjectFile>(Obj)) {
1700 ClangASTSectionName = "clangast";
1701 }
1702
1703 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001704 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001705 StringRef Name;
1706 Sec.getName(Name);
1707 if (Name == ClangASTSectionName) {
1708 ClangASTSection = Sec;
1709 break;
1710 }
1711 }
1712 if (!ClangASTSection)
1713 return;
1714
1715 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001716 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001717 outs().write(ClangASTContents.data(), ClangASTContents.size());
1718}
1719
Sanjoy Das6f567a42015-06-22 18:03:02 +00001720static void printFaultMaps(const ObjectFile *Obj) {
1721 const char *FaultMapSectionName = nullptr;
1722
1723 if (isa<ELFObjectFileBase>(Obj)) {
1724 FaultMapSectionName = ".llvm_faultmaps";
1725 } else if (isa<MachOObjectFile>(Obj)) {
1726 FaultMapSectionName = "__llvm_faultmaps";
1727 } else {
1728 errs() << "This operation is only currently supported "
1729 "for ELF and Mach-O executable files.\n";
1730 return;
1731 }
1732
1733 Optional<object::SectionRef> FaultMapSection;
1734
Colin LeMahieu77804be2015-07-29 15:45:39 +00001735 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001736 StringRef Name;
1737 Sec.getName(Name);
1738 if (Name == FaultMapSectionName) {
1739 FaultMapSection = Sec;
1740 break;
1741 }
1742 }
1743
1744 outs() << "FaultMap table:\n";
1745
1746 if (!FaultMapSection.hasValue()) {
1747 outs() << "<not found>\n";
1748 return;
1749 }
1750
1751 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001752 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001753
1754 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1755 FaultMapContents.bytes_end());
1756
1757 outs() << FMP;
1758}
1759
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001760static void printPrivateFileHeaders(const ObjectFile *o) {
1761 if (o->isELF())
1762 printELFFileHeader(o);
1763 else if (o->isCOFF())
1764 printCOFFFileHeader(o);
1765 else if (o->isMachO()) {
1766 printMachOFileHeader(o);
1767 printMachOLoadCommands(o);
1768 } else
1769 report_fatal_error("Invalid/Unsupported object file format");
1770}
1771
1772static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001773 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001774 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001775 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001776 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001777 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001778 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001779 else
1780 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001781}
1782
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001783static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1784 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001785 // Avoid other output when using a raw option.
1786 if (!RawClangAST) {
1787 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001788 if (a)
1789 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1790 else
1791 outs() << o->getFileName();
1792 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001793 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001794
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001795 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001796 DisassembleObject(o, Relocations);
1797 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001798 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001799 if (SectionHeaders)
1800 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001801 if (SectionContents)
1802 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001803 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001804 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001805 if (UnwindInfo)
1806 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001807 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001808 printPrivateFileHeaders(o);
1809 if (FirstPrivateHeader)
1810 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001811 if (ExportsTrie)
1812 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001813 if (Rebase)
1814 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001815 if (Bind)
1816 printBindTable(o);
1817 if (LazyBind)
1818 printLazyBindTable(o);
1819 if (WeakBind)
1820 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001821 if (RawClangAST)
1822 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001823 if (PrintFaultMaps)
1824 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001825 if (DwarfDumpType != DIDT_Null) {
1826 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1827 // Dump the complete DWARF structure.
1828 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1829 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001830}
1831
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001832static void DumpObject(const COFFImportFile *I, const Archive *A) {
1833 StringRef ArchiveName = A ? A->getFileName() : "";
1834
1835 // Avoid other output when using a raw option.
1836 if (!RawClangAST)
1837 outs() << '\n'
1838 << ArchiveName << "(" << I->getFileName() << ")"
1839 << ":\tfile format COFF-import-file"
1840 << "\n\n";
1841
1842 if (SymbolTable)
1843 printCOFFSymbolTable(I);
1844}
1845
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001846/// @brief Dump each object file in \a a;
1847static void DumpArchive(const Archive *a) {
Lang Hamesfc209622016-07-14 02:24:01 +00001848 Error Err;
1849 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001850 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1851 if (!ChildOrErr) {
1852 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1853 report_error(a->getFileName(), C, std::move(E));
1854 continue;
1855 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001856 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001857 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001858 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
1859 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001860 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001861 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001862 }
Lang Hamesfc209622016-07-14 02:24:01 +00001863 if (Err)
1864 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001865}
1866
1867/// @brief Open file and figure out how to dump it.
1868static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001869
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001870 // If we are using the Mach-O specific object file parser, then let it parse
1871 // the file and process the command line options. So the -arch flags can
1872 // be used to select specific slices, etc.
1873 if (MachOOpt) {
1874 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001875 return;
1876 }
1877
1878 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001879 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1880 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00001881 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00001882 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001883
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001884 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001885 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001886 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001887 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001888 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001889 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001890}
1891
Michael J. Spencer2670c252011-01-20 06:39:06 +00001892int main(int argc, char **argv) {
1893 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00001894 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001895 PrettyStackTraceProgram X(argc, argv);
1896 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1897
1898 // Initialize targets and assembly printers/parsers.
1899 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001900 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001901 llvm::InitializeAllDisassemblers();
1902
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001903 // Register the target printer for --version.
1904 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1905
Michael J. Spencer2670c252011-01-20 06:39:06 +00001906 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1907 TripleName = Triple::normalize(TripleName);
1908
1909 ToolName = argv[0];
1910
1911 // Defaults to a.out if no filenames specified.
1912 if (InputFilenames.size() == 0)
1913 InputFilenames.push_back("a.out");
1914
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001915 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001916 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001917 if (!Disassemble
1918 && !Relocations
1919 && !SectionHeaders
1920 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001921 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001922 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001923 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001924 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001925 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001926 && !Rebase
1927 && !Bind
1928 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001929 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001930 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001931 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001932 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001933 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001934 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001935 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001936 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001937 && !(DylibsUsed && MachOOpt)
1938 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001939 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001940 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001941 && !PrintFaultMaps
1942 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001943 cl::PrintHelpMessage();
1944 return 2;
1945 }
1946
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001947 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1948 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001949
Davide Italianoccd53fe2015-08-05 07:18:31 +00001950 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001951}