blob: 43a9a7aaaccc50e6312da2cb0016bd28d8320672 [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:"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000191 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000192
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000193cl::opt<bool> PrintSource(
194 "source",
195 cl::desc(
196 "Display source inlined with disassembly. Implies disassmble object"));
197
198cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
199 cl::aliasopt(PrintSource));
200
201cl::opt<bool> PrintLines("line-numbers",
202 cl::desc("Display source line numbers with "
203 "disassembly. Implies disassemble object"));
204
205cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
206 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000207
208cl::opt<unsigned long long>
209 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
210 cl::value_desc("address"), cl::init(0));
211cl::opt<unsigned long long>
212 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
213 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000214static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000215
Colin LeMahieu77804be2015-07-29 15:45:39 +0000216namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000217typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000218
219class SectionFilterIterator {
220public:
221 SectionFilterIterator(FilterPredicate P,
222 llvm::object::section_iterator const &I,
223 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000224 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000225 ScanPredicate();
226 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000227 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000228 SectionFilterIterator &operator++() {
229 ++Iterator;
230 ScanPredicate();
231 return *this;
232 }
233 bool operator!=(SectionFilterIterator const &Other) const {
234 return Iterator != Other.Iterator;
235 }
236
237private:
238 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000239 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000240 ++Iterator;
241 }
242 }
243 FilterPredicate Predicate;
244 llvm::object::section_iterator Iterator;
245 llvm::object::section_iterator End;
246};
247
248class SectionFilter {
249public:
250 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000251 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000252 SectionFilterIterator begin() {
253 return SectionFilterIterator(Predicate, Object.section_begin(),
254 Object.section_end());
255 }
256 SectionFilterIterator end() {
257 return SectionFilterIterator(Predicate, Object.section_end(),
258 Object.section_end());
259 }
260
261private:
262 FilterPredicate Predicate;
263 llvm::object::ObjectFile const &Object;
264};
265SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000266 return SectionFilter(
267 [](llvm::object::SectionRef const &S) {
268 if (FilterSections.empty())
269 return true;
270 llvm::StringRef String;
271 std::error_code error = S.getName(String);
272 if (error)
273 return false;
274 return is_contained(FilterSections, String);
275 },
276 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000277}
278}
279
Davide Italianoccd53fe2015-08-05 07:18:31 +0000280void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000281 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000282 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000283
Davide Italiano140af642015-12-25 18:16:45 +0000284 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
285 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000286 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000287}
288
Kevin Enderby42398052016-06-28 23:16:13 +0000289LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
290 errs() << ToolName << ": " << Message << ".\n";
291 errs().flush();
292 exit(1);
293}
294
Davide Italianoed9d95b2015-12-29 13:41:02 +0000295LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
296 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000297 assert(EC);
298 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000299 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000300}
301
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000302LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
303 llvm::Error E) {
304 assert(E);
305 std::string Buf;
306 raw_string_ostream OS(Buf);
307 logAllUnhandledErrors(std::move(E), OS, "");
308 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000309 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000310 exit(1);
311}
312
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000313LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
314 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000315 llvm::Error E,
316 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000317 assert(E);
318 errs() << ToolName << ": ";
319 if (ArchiveName != "")
320 errs() << ArchiveName << "(" << FileName << ")";
321 else
322 errs() << FileName;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000323 if (!ArchitectureName.empty())
324 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000325 std::string Buf;
326 raw_string_ostream OS(Buf);
327 logAllUnhandledErrors(std::move(E), OS, "");
328 OS.flush();
329 errs() << " " << Buf;
330 exit(1);
331}
332
333LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
334 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000335 llvm::Error E,
336 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000337 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000338 // TODO: if we have a error getting the name then it would be nice to print
339 // the index of which archive member this is and or its offset in the
340 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000341 if (!NameOrErr) {
342 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000343 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000344 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000345 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
346 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000347}
348
Craig Toppere6cb63e2014-04-25 04:24:47 +0000349static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000350 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000351 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000352 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000353 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000354 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000355 // TheTriple defaults to ELF, and COFF doesn't have an environment:
356 // the best we can do here is indicate that it is mach-o.
357 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000358 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000359
360 if (Obj->isCOFF()) {
361 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
362 if (COFFObj->getArch() == Triple::thumb)
363 TheTriple.setTriple("thumbv7-windows");
364 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000365 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000366 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000367 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000368
369 // Get the target specific parser.
370 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000371 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
372 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000373 if (!TheTarget)
374 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000375
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000376 // Update the triple name and return the found target.
377 TripleName = TheTriple.getTriple();
378 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000379}
380
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000381bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000382 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000383}
384
Colin LeMahieufb76b002015-05-28 19:07:14 +0000385namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000386class SourcePrinter {
387protected:
388 DILineInfo OldLineInfo;
389 const ObjectFile *Obj;
390 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
391 // File name to file contents of source
392 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
393 // Mark the line endings of the cached source
394 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
395
396private:
397 bool cacheSource(std::string File);
398
399public:
400 virtual ~SourcePrinter() {}
401 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
402 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
403 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
404 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
405 DefaultArch);
406 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
407 }
408 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
409 StringRef Delimiter = "; ");
410};
411
412bool SourcePrinter::cacheSource(std::string File) {
413 auto BufferOrError = MemoryBuffer::getFile(File);
414 if (!BufferOrError)
415 return false;
416 // Chomp the file to get lines
417 size_t BufferSize = (*BufferOrError)->getBufferSize();
418 const char *BufferStart = (*BufferOrError)->getBufferStart();
419 for (const char *Start = BufferStart, *End = BufferStart;
420 End < BufferStart + BufferSize; End++)
421 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
422 (*End == '\r' && *(End + 1) == '\n')) {
423 LineCache[File].push_back(StringRef(Start, End - Start));
424 if (*End == '\r')
425 End++;
426 Start = End + 1;
427 }
428 SourceCache[File] = std::move(*BufferOrError);
429 return true;
430}
431
432void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
433 StringRef Delimiter) {
434 if (!Symbolizer)
435 return;
436 DILineInfo LineInfo = DILineInfo();
437 auto ExpectecLineInfo =
438 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
439 if (!ExpectecLineInfo)
440 consumeError(ExpectecLineInfo.takeError());
441 else
442 LineInfo = *ExpectecLineInfo;
443
444 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
445 LineInfo.Line == 0)
446 return;
447
448 if (PrintLines)
449 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
450 if (PrintSource) {
451 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
452 if (!cacheSource(LineInfo.FileName))
453 return;
454 auto FileBuffer = SourceCache.find(LineInfo.FileName);
455 if (FileBuffer != SourceCache.end()) {
456 auto LineBuffer = LineCache.find(LineInfo.FileName);
457 if (LineBuffer != LineCache.end())
458 // Vector begins at 0, line numbers are non-zero
459 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
460 << "\n";
461 }
462 }
463 OldLineInfo = LineInfo;
464}
465
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000466static bool isArmElf(const ObjectFile *Obj) {
467 return (Obj->isELF() &&
468 (Obj->getArch() == Triple::aarch64 ||
469 Obj->getArch() == Triple::aarch64_be ||
470 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
471 Obj->getArch() == Triple::thumb ||
472 Obj->getArch() == Triple::thumbeb));
473}
474
Colin LeMahieufb76b002015-05-28 19:07:14 +0000475class PrettyPrinter {
476public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000477 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000478 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000479 ArrayRef<uint8_t> Bytes, uint64_t Address,
480 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000481 MCSubtargetInfo const &STI, SourcePrinter *SP) {
482 if (SP && (PrintSource || PrintLines))
483 SP->printSourceLine(OS, Address);
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000484 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000485 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000486 OS << "\t";
487 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000488 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000489 if (MI)
490 IP.printInst(MI, OS, "", STI);
491 else
492 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000493 }
494};
495PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000496class HexagonPrettyPrinter : public PrettyPrinter {
497public:
498 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
499 raw_ostream &OS) {
500 uint32_t opcode =
501 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
502 OS << format("%8" PRIx64 ":", Address);
503 if (!NoShowRawInsn) {
504 OS << "\t";
505 dumpBytes(Bytes.slice(0, 4), OS);
506 OS << format("%08" PRIx32, opcode);
507 }
508 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000509 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
510 uint64_t Address, raw_ostream &OS, StringRef Annot,
511 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000512 if (SP && (PrintSource || PrintLines))
513 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000514 if (!MI) {
515 printLead(Bytes, Address, OS);
516 OS << " <unknown>";
517 return;
518 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000519 std::string Buffer;
520 {
521 raw_string_ostream TempStream(Buffer);
522 IP.printInst(MI, TempStream, "", STI);
523 }
524 StringRef Contents(Buffer);
525 // Split off bundle attributes
526 auto PacketBundle = Contents.rsplit('\n');
527 // Split off first instruction from the rest
528 auto HeadTail = PacketBundle.first.split('\n');
529 auto Preamble = " { ";
530 auto Separator = "";
531 while(!HeadTail.first.empty()) {
532 OS << Separator;
533 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000534 if (SP && (PrintSource || PrintLines))
535 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000536 printLead(Bytes, Address, OS);
537 OS << Preamble;
538 Preamble = " ";
539 StringRef Inst;
540 auto Duplex = HeadTail.first.split('\v');
541 if(!Duplex.second.empty()){
542 OS << Duplex.first;
543 OS << "; ";
544 Inst = Duplex.second;
545 }
546 else
547 Inst = HeadTail.first;
548 OS << Inst;
549 Bytes = Bytes.slice(4);
550 Address += 4;
551 HeadTail = HeadTail.second.split('\n');
552 }
553 OS << " } " << PacketBundle.second;
554 }
555};
556HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000557
558class AMDGCNPrettyPrinter : public PrettyPrinter {
559public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000560 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
561 uint64_t Address, raw_ostream &OS, StringRef Annot,
562 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000563 if (!MI) {
564 OS << " <unknown>";
565 return;
566 }
567
Valery Pykhtinde048052016-04-07 07:24:01 +0000568 SmallString<40> InstStr;
569 raw_svector_ostream IS(InstStr);
570
571 IP.printInst(MI, IS, "", STI);
572
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000573 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000574 typedef support::ulittle32_t U32;
575 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
576 Bytes.size() / sizeof(U32)))
577 // D should be explicitly casted to uint32_t here as it is passed
578 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000579 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000580
581 if (!Annot.empty())
582 OS << "// " << Annot;
583 }
584};
585AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
586
Colin LeMahieu35436a22015-05-29 14:48:25 +0000587PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000588 switch(Triple.getArch()) {
589 default:
590 return PrettyPrinterInst;
591 case Triple::hexagon:
592 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000593 case Triple::amdgcn:
594 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000595 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000596}
597}
598
Rafael Espindola37070a52015-06-03 04:48:06 +0000599template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000600static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000601 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000602 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000603 DataRefImpl Rel = RelRef.getRawDataRefImpl();
604
Rafael Espindola37070a52015-06-03 04:48:06 +0000605 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
606 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000607 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
608
Rafael Espindola37070a52015-06-03 04:48:06 +0000609 const ELFFile<ELFT> &EF = *Obj->getELFFile();
610
Rafael Espindola6def3042015-07-01 12:56:27 +0000611 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
612 if (std::error_code EC = SecOrErr.getError())
613 return EC;
614 const Elf_Shdr *Sec = *SecOrErr;
615 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
616 if (std::error_code EC = SymTabOrErr.getError())
617 return EC;
618 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000619 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
620 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000621 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
622 if (std::error_code EC = StrTabSec.getError())
623 return EC;
624 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000625 if (std::error_code EC = StrTabOrErr.getError())
626 return EC;
627 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000628 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000629 StringRef res;
630 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000631 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000632 default:
633 return object_error::parse_failed;
634 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000635 // TODO: Read implicit addend from section data.
636 break;
637 }
638 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000639 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000640 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000641 break;
642 }
643 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000644 symbol_iterator SI = RelRef.getSymbol();
645 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000646 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000647 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000648 Expected<section_iterator> SymSI = SI->getSection();
649 if (!SymSI)
650 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000651 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
652 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000653 if (std::error_code EC = SecName.getError())
654 return EC;
655 Target = *SecName;
656 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000657 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000658 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000659 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000660 Target = *SymName;
661 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000662 switch (EF.getHeader()->e_machine) {
663 case ELF::EM_X86_64:
664 switch (type) {
665 case ELF::R_X86_64_PC8:
666 case ELF::R_X86_64_PC16:
667 case ELF::R_X86_64_PC32: {
668 std::string fmtbuf;
669 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000670 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000671 fmt.flush();
672 Result.append(fmtbuf.begin(), fmtbuf.end());
673 } break;
674 case ELF::R_X86_64_8:
675 case ELF::R_X86_64_16:
676 case ELF::R_X86_64_32:
677 case ELF::R_X86_64_32S:
678 case ELF::R_X86_64_64: {
679 std::string fmtbuf;
680 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000681 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000682 fmt.flush();
683 Result.append(fmtbuf.begin(), fmtbuf.end());
684 } break;
685 default:
686 res = "Unknown";
687 }
688 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000689 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000690 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000691 case ELF::EM_AARCH64: {
692 std::string fmtbuf;
693 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000694 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000695 if (addend != 0)
696 fmt << (addend < 0 ? "" : "+") << addend;
697 fmt.flush();
698 Result.append(fmtbuf.begin(), fmtbuf.end());
699 break;
700 }
701 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000702 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000703 case ELF::EM_ARM:
704 case ELF::EM_HEXAGON:
705 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000706 case ELF::EM_BPF:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000707 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000708 break;
Dan Gohman46350172016-01-12 20:56:01 +0000709 case ELF::EM_WEBASSEMBLY:
710 switch (type) {
711 case ELF::R_WEBASSEMBLY_DATA: {
712 std::string fmtbuf;
713 raw_string_ostream fmt(fmtbuf);
714 fmt << Target << (addend < 0 ? "" : "+") << addend;
715 fmt.flush();
716 Result.append(fmtbuf.begin(), fmtbuf.end());
717 break;
718 }
719 case ELF::R_WEBASSEMBLY_FUNCTION:
720 res = Target;
721 break;
722 default:
723 res = "Unknown";
724 }
725 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000726 default:
727 res = "Unknown";
728 }
729 if (Result.empty())
730 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000731 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000732}
733
734static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000735 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000736 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000737 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
738 return getRelocationValueString(ELF32LE, Rel, Result);
739 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
740 return getRelocationValueString(ELF64LE, Rel, Result);
741 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
742 return getRelocationValueString(ELF32BE, Rel, Result);
743 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
744 return getRelocationValueString(ELF64BE, Rel, Result);
745}
746
747static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
748 const RelocationRef &Rel,
749 SmallVectorImpl<char> &Result) {
750 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000751 Expected<StringRef> SymNameOrErr = SymI->getName();
752 if (!SymNameOrErr)
753 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000754 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000755 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000756 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000757}
758
759static void printRelocationTargetName(const MachOObjectFile *O,
760 const MachO::any_relocation_info &RE,
761 raw_string_ostream &fmt) {
762 bool IsScattered = O->isRelocationScattered(RE);
763
764 // Target of a scattered relocation is an address. In the interest of
765 // generating pretty output, scan through the symbol table looking for a
766 // symbol that aligns with that address. If we find one, print it.
767 // Otherwise, we just print the hex address of the target.
768 if (IsScattered) {
769 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
770
771 for (const SymbolRef &Symbol : O->symbols()) {
772 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000773 Expected<uint64_t> Addr = Symbol.getAddress();
774 if (!Addr) {
775 std::string Buf;
776 raw_string_ostream OS(Buf);
777 logAllUnhandledErrors(Addr.takeError(), OS, "");
778 OS.flush();
779 report_fatal_error(Buf);
780 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000781 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000782 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000783 Expected<StringRef> Name = Symbol.getName();
784 if (!Name) {
785 std::string Buf;
786 raw_string_ostream OS(Buf);
787 logAllUnhandledErrors(Name.takeError(), OS, "");
788 OS.flush();
789 report_fatal_error(Buf);
790 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000791 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000792 return;
793 }
794
795 // If we couldn't find a symbol that this relocation refers to, try
796 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000797 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000798 std::error_code ec;
799
800 StringRef Name;
801 uint64_t Addr = Section.getAddress();
802 if (Addr != Val)
803 continue;
804 if ((ec = Section.getName(Name)))
805 report_fatal_error(ec.message());
806 fmt << Name;
807 return;
808 }
809
810 fmt << format("0x%x", Val);
811 return;
812 }
813
814 StringRef S;
815 bool isExtern = O->getPlainRelocationExternal(RE);
816 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
817
818 if (isExtern) {
819 symbol_iterator SI = O->symbol_begin();
820 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000821 Expected<StringRef> SOrErr = SI->getName();
822 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000823 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000824 } else {
825 section_iterator SI = O->section_begin();
826 // Adjust for the fact that sections are 1-indexed.
827 advance(SI, Val - 1);
828 SI->getName(S);
829 }
830
831 fmt << S;
832}
833
834static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
835 const RelocationRef &RelRef,
836 SmallVectorImpl<char> &Result) {
837 DataRefImpl Rel = RelRef.getRawDataRefImpl();
838 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
839
840 unsigned Arch = Obj->getArch();
841
842 std::string fmtbuf;
843 raw_string_ostream fmt(fmtbuf);
844 unsigned Type = Obj->getAnyRelocationType(RE);
845 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
846
847 // Determine any addends that should be displayed with the relocation.
848 // These require decoding the relocation type, which is triple-specific.
849
850 // X86_64 has entirely custom relocation types.
851 if (Arch == Triple::x86_64) {
852 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
853
854 switch (Type) {
855 case MachO::X86_64_RELOC_GOT_LOAD:
856 case MachO::X86_64_RELOC_GOT: {
857 printRelocationTargetName(Obj, RE, fmt);
858 fmt << "@GOT";
859 if (isPCRel)
860 fmt << "PCREL";
861 break;
862 }
863 case MachO::X86_64_RELOC_SUBTRACTOR: {
864 DataRefImpl RelNext = Rel;
865 Obj->moveRelocationNext(RelNext);
866 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
867
868 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
869 // X86_64_RELOC_UNSIGNED.
870 // NOTE: Scattered relocations don't exist on x86_64.
871 unsigned RType = Obj->getAnyRelocationType(RENext);
872 if (RType != MachO::X86_64_RELOC_UNSIGNED)
873 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
874 "X86_64_RELOC_SUBTRACTOR.");
875
876 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
877 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
878 printRelocationTargetName(Obj, RENext, fmt);
879 fmt << "-";
880 printRelocationTargetName(Obj, RE, fmt);
881 break;
882 }
883 case MachO::X86_64_RELOC_TLV:
884 printRelocationTargetName(Obj, RE, fmt);
885 fmt << "@TLV";
886 if (isPCRel)
887 fmt << "P";
888 break;
889 case MachO::X86_64_RELOC_SIGNED_1:
890 printRelocationTargetName(Obj, RE, fmt);
891 fmt << "-1";
892 break;
893 case MachO::X86_64_RELOC_SIGNED_2:
894 printRelocationTargetName(Obj, RE, fmt);
895 fmt << "-2";
896 break;
897 case MachO::X86_64_RELOC_SIGNED_4:
898 printRelocationTargetName(Obj, RE, fmt);
899 fmt << "-4";
900 break;
901 default:
902 printRelocationTargetName(Obj, RE, fmt);
903 break;
904 }
905 // X86 and ARM share some relocation types in common.
906 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
907 Arch == Triple::ppc) {
908 // Generic relocation types...
909 switch (Type) {
910 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000911 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000912 case MachO::GENERIC_RELOC_SECTDIFF: {
913 DataRefImpl RelNext = Rel;
914 Obj->moveRelocationNext(RelNext);
915 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
916
917 // X86 sect diff's must be followed by a relocation of type
918 // GENERIC_RELOC_PAIR.
919 unsigned RType = Obj->getAnyRelocationType(RENext);
920
921 if (RType != MachO::GENERIC_RELOC_PAIR)
922 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
923 "GENERIC_RELOC_SECTDIFF.");
924
925 printRelocationTargetName(Obj, RE, fmt);
926 fmt << "-";
927 printRelocationTargetName(Obj, RENext, fmt);
928 break;
929 }
930 }
931
932 if (Arch == Triple::x86 || Arch == Triple::ppc) {
933 switch (Type) {
934 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
935 DataRefImpl RelNext = Rel;
936 Obj->moveRelocationNext(RelNext);
937 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
938
939 // X86 sect diff's must be followed by a relocation of type
940 // GENERIC_RELOC_PAIR.
941 unsigned RType = Obj->getAnyRelocationType(RENext);
942 if (RType != MachO::GENERIC_RELOC_PAIR)
943 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
944 "GENERIC_RELOC_LOCAL_SECTDIFF.");
945
946 printRelocationTargetName(Obj, RE, fmt);
947 fmt << "-";
948 printRelocationTargetName(Obj, RENext, fmt);
949 break;
950 }
951 case MachO::GENERIC_RELOC_TLV: {
952 printRelocationTargetName(Obj, RE, fmt);
953 fmt << "@TLV";
954 if (IsPCRel)
955 fmt << "P";
956 break;
957 }
958 default:
959 printRelocationTargetName(Obj, RE, fmt);
960 }
961 } else { // ARM-specific relocations
962 switch (Type) {
963 case MachO::ARM_RELOC_HALF:
964 case MachO::ARM_RELOC_HALF_SECTDIFF: {
965 // Half relocations steal a bit from the length field to encode
966 // whether this is an upper16 or a lower16 relocation.
967 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
968
969 if (isUpper)
970 fmt << ":upper16:(";
971 else
972 fmt << ":lower16:(";
973 printRelocationTargetName(Obj, RE, fmt);
974
975 DataRefImpl RelNext = Rel;
976 Obj->moveRelocationNext(RelNext);
977 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
978
979 // ARM half relocs must be followed by a relocation of type
980 // ARM_RELOC_PAIR.
981 unsigned RType = Obj->getAnyRelocationType(RENext);
982 if (RType != MachO::ARM_RELOC_PAIR)
983 report_fatal_error("Expected ARM_RELOC_PAIR after "
984 "ARM_RELOC_HALF");
985
986 // NOTE: The half of the target virtual address is stashed in the
987 // address field of the secondary relocation, but we can't reverse
988 // engineer the constant offset from it without decoding the movw/movt
989 // instruction to find the other half in its immediate field.
990
991 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
992 // symbol/section pointer of the follow-on relocation.
993 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
994 fmt << "-";
995 printRelocationTargetName(Obj, RENext, fmt);
996 }
997
998 fmt << ")";
999 break;
1000 }
1001 default: { printRelocationTargetName(Obj, RE, fmt); }
1002 }
1003 }
1004 } else
1005 printRelocationTargetName(Obj, RE, fmt);
1006
1007 fmt.flush();
1008 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001009 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001010}
1011
1012static std::error_code getRelocationValueString(const RelocationRef &Rel,
1013 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001014 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001015 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1016 return getRelocationValueString(ELF, Rel, Result);
1017 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1018 return getRelocationValueString(COFF, Rel, Result);
1019 auto *MachO = cast<MachOObjectFile>(Obj);
1020 return getRelocationValueString(MachO, Rel, Result);
1021}
1022
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001023/// @brief Indicates whether this relocation should hidden when listing
1024/// relocations, usually because it is the trailing part of a multipart
1025/// relocation that will be printed as part of the leading relocation.
1026static bool getHidden(RelocationRef RelRef) {
1027 const ObjectFile *Obj = RelRef.getObject();
1028 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1029 if (!MachO)
1030 return false;
1031
1032 unsigned Arch = MachO->getArch();
1033 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1034 uint64_t Type = MachO->getRelocationType(Rel);
1035
1036 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1037 // is always hidden.
1038 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1039 if (Type == MachO::GENERIC_RELOC_PAIR)
1040 return true;
1041 } else if (Arch == Triple::x86_64) {
1042 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1043 // an X86_64_RELOC_SUBTRACTOR.
1044 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1045 DataRefImpl RelPrev = Rel;
1046 RelPrev.d.a--;
1047 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1048 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1049 return true;
1050 }
1051 }
1052
1053 return false;
1054}
1055
Sam Koltonc05d7782016-08-17 10:17:57 +00001056static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1057 assert(Obj->isELF());
1058 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1059 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1060 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1061 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1062 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1063 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1064 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1065 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1066 llvm_unreachable("Unsupported binary format");
1067}
1068
Michael J. Spencer51862b32011-10-13 22:17:18 +00001069static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001070 if (StartAddress > StopAddress)
1071 error("Start address should be less than stop address");
1072
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001073 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001074
Jack Carter551efd72012-08-28 19:24:49 +00001075 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001076 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001077 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001078 for (unsigned i = 0; i != MAttrs.size(); ++i)
1079 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001080 }
1081
Ahmed Charles56440fd2014-03-06 05:51:42 +00001082 std::unique_ptr<const MCRegisterInfo> MRI(
1083 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001084 if (!MRI)
1085 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001086
1087 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001088 std::unique_ptr<const MCAsmInfo> AsmInfo(
1089 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001090 if (!AsmInfo)
1091 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001092 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001093 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001094 if (!STI)
1095 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001096 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001097 if (!MII)
1098 report_fatal_error("error: no instruction info for target " + TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001099 MCObjectFileInfo MOFI;
1100 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1101 // FIXME: for now initialize MCObjectFileInfo with default values
1102 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, CodeModel::Default, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001103
1104 std::unique_ptr<MCDisassembler> DisAsm(
1105 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001106 if (!DisAsm)
1107 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001108
Ahmed Charles56440fd2014-03-06 05:51:42 +00001109 std::unique_ptr<const MCInstrAnalysis> MIA(
1110 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001111
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001112 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001113 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1114 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001115 if (!IP)
1116 report_fatal_error("error: no instruction printer for target " +
1117 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001118 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001119 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001120
Greg Fitzgerald18432272014-03-20 22:55:15 +00001121 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1122 "\t\t\t%08" PRIx64 ": ";
1123
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001124 SourcePrinter SP(Obj, TheTarget->getName());
1125
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001126 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1127 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001128 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001129 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001130 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001131 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001132 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001133 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001134 }
1135
David Majnemer81afca62015-07-07 22:06:59 +00001136 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001137 // pretty print the symbols while disassembling.
Sam Koltonc05d7782016-08-17 10:17:57 +00001138 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001139 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1140 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001141 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1142 error(errorToErrorCode(AddressOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001143 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001144
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001145 Expected<StringRef> Name = Symbol.getName();
1146 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001147 if (Name->empty())
1148 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001149
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001150 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1151 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001152 section_iterator SecI = *SectionOrErr;
1153 if (SecI == Obj->section_end())
1154 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001155
Sam Koltonc05d7782016-08-17 10:17:57 +00001156 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001157 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001158 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001159
Sam Koltonc05d7782016-08-17 10:17:57 +00001160 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1161
David Majnemer81afca62015-07-07 22:06:59 +00001162 }
1163
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001164 // Create a mapping from virtual address to section.
1165 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1166 for (SectionRef Sec : Obj->sections())
1167 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1168 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1169
1170 // Linked executables (.exe and .dll files) typically don't include a real
1171 // symbol table but they might contain an export table.
1172 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1173 for (const auto &ExportEntry : COFFObj->export_directories()) {
1174 StringRef Name;
1175 error(ExportEntry.getSymbolName(Name));
1176 if (Name.empty())
1177 continue;
1178 uint32_t RVA;
1179 error(ExportEntry.getExportRVA(RVA));
1180
1181 uint64_t VA = COFFObj->getImageBase() + RVA;
1182 auto Sec = std::upper_bound(
1183 SectionAddresses.begin(), SectionAddresses.end(), VA,
1184 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1185 return LHS < RHS.first;
1186 });
1187 if (Sec != SectionAddresses.begin())
1188 --Sec;
1189 else
1190 Sec = SectionAddresses.end();
1191
1192 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001193 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001194 }
1195 }
1196
1197 // Sort all the symbols, this allows us to use a simple binary search to find
1198 // a symbol near an address.
1199 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1200 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1201
Colin LeMahieu77804be2015-07-29 15:45:39 +00001202 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001203 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001204 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001205
Rafael Espindola80291272014-10-08 15:28:58 +00001206 uint64_t SectionAddr = Section.getAddress();
1207 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001208 if (!SectSize)
1209 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001210
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001211 // Get the list of all the symbols in this section.
1212 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001213 std::vector<uint64_t> DataMappingSymsAddr;
1214 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001215 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001216 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001217 uint64_t Address = std::get<0>(Symb);
1218 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001219 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001220 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001221 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001222 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001223 if (Name.startswith("$a"))
1224 TextMappingSymsAddr.push_back(Address - SectionAddr);
1225 if (Name.startswith("$t"))
1226 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001227 }
1228 }
1229
Davide Italianof0706882015-10-01 21:57:09 +00001230 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1231 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001232
Sam Kolton3381d7a2016-10-06 13:46:08 +00001233 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1234 // AMDGPU disassembler uses symbolizer for printing labels
1235 std::unique_ptr<MCRelocationInfo> RelInfo(
1236 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1237 if (RelInfo) {
1238 std::unique_ptr<MCSymbolizer> Symbolizer(
1239 TheTarget->createMCSymbolizer(
1240 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1241 DisAsm->setSymbolizer(std::move(Symbolizer));
1242 }
1243 }
1244
Michael J. Spencer51862b32011-10-13 22:17:18 +00001245 // Make a list of all the relocations for this section.
1246 std::vector<RelocationRef> Rels;
1247 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001248 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1249 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1250 Rels.push_back(Reloc);
1251 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001252 }
1253 }
1254
1255 // Sort relocations by address.
1256 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1257
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001258 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001259 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001260 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001261 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001262 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001263 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001264 error(Section.getName(name));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001265
1266 if ((SectionAddr <= StopAddress) &&
1267 (SectionAddr + SectSize) >= StartAddress) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001268 outs() << "Disassembly of section ";
1269 if (!SegmentName.empty())
1270 outs() << SegmentName << ",";
1271 outs() << name << ':';
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001272 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001273
Rafael Espindola7884c952015-06-04 15:01:05 +00001274 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001275 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001276 Symbols.insert(Symbols.begin(),
1277 std::make_tuple(SectionAddr, name, Section.isText()
1278 ? ELF::STT_FUNC
1279 : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001280 }
Alp Tokere69170a2014-06-26 22:52:05 +00001281
1282 SmallString<40> Comments;
1283 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001284
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001285 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001286 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001287 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1288 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001289
Michael J. Spencer2670c252011-01-20 06:39:06 +00001290 uint64_t Size;
1291 uint64_t Index;
1292
Michael J. Spencer51862b32011-10-13 22:17:18 +00001293 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1294 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001295 // Disassemble symbol by symbol.
1296 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001297 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001298 // The end is either the section end or the beginning of the next
1299 // symbol.
1300 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001301 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001302 // Don't try to disassemble beyond the end of section contents.
1303 if (End > SectSize)
1304 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001305 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001306 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001307 continue;
1308
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001309 // Check if we need to skip symbol
1310 // Skip if the symbol's data is not between StartAddress and StopAddress
1311 if (End + SectionAddr < StartAddress ||
1312 Start + SectionAddr > StopAddress) {
1313 continue;
1314 }
1315
1316 // Stop disassembly at the stop address specified
1317 if (End + SectionAddr > StopAddress)
1318 End = StopAddress - SectionAddr;
1319
Valery Pykhtinde048052016-04-07 07:24:01 +00001320 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1321 // make size 4 bytes folded
1322 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001323 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1324 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1325 Start += 256;
1326 }
1327 if (si == se - 1 ||
1328 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1329 // cut trailing zeroes at the end of kernel
1330 // cut up to 256 bytes
1331 const uint64_t EndAlign = 256;
1332 const auto Limit = End - (std::min)(EndAlign, End - Start);
1333 while (End > Limit &&
1334 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1335 End -= 4;
1336 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001337 }
1338
Sam Koltonc05d7782016-08-17 10:17:57 +00001339 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001340
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001341#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001342 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001343#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001344 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001345#endif
1346
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001347 for (Index = Start; Index < End; Index += Size) {
1348 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001349
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001350 if (Index + SectionAddr < StartAddress ||
1351 Index + SectionAddr > StopAddress) {
1352 // skip byte by byte till StartAddress is reached
1353 Size = 1;
1354 continue;
1355 }
Davide Italianof0706882015-10-01 21:57:09 +00001356 // AArch64 ELF binaries can interleave data and text in the
1357 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001358 // understand what we need to dump. If the data marker is within a
1359 // function, it is denoted as a word/short etc
1360 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1361 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001362 uint64_t Stride = 0;
1363
1364 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1365 DataMappingSymsAddr.end(), Index);
1366 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1367 // Switch to data.
1368 while (Index < End) {
1369 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1370 outs() << "\t";
1371 if (Index + 4 <= End) {
1372 Stride = 4;
1373 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001374 outs() << "\t.word\t";
1375 uint32_t Data = 0;
1376 if (Obj->isLittleEndian()) {
1377 const auto Word =
1378 reinterpret_cast<const support::ulittle32_t *>(
1379 Bytes.data() + Index);
1380 Data = *Word;
1381 } else {
1382 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1383 Bytes.data() + Index);
1384 Data = *Word;
1385 }
1386 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001387 } else if (Index + 2 <= End) {
1388 Stride = 2;
1389 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001390 outs() << "\t\t.short\t";
1391 uint16_t Data = 0;
1392 if (Obj->isLittleEndian()) {
1393 const auto Short =
1394 reinterpret_cast<const support::ulittle16_t *>(
1395 Bytes.data() + Index);
1396 Data = *Short;
1397 } else {
1398 const auto Short =
1399 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1400 Index);
1401 Data = *Short;
1402 }
1403 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001404 } else {
1405 Stride = 1;
1406 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001407 outs() << "\t\t.byte\t";
1408 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001409 }
1410 Index += Stride;
1411 outs() << "\n";
1412 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1413 TextMappingSymsAddr.end(), Index);
1414 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1415 break;
1416 }
1417 }
1418 }
1419
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001420 // If there is a data symbol inside an ELF text section and we are only
1421 // disassembling text (applicable all architectures),
1422 // we are in a situation where we must print the data and not
1423 // disassemble it.
1424 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1425 !DisassembleAll && Section.isText()) {
1426 // print out data up to 8 bytes at a time in hex and ascii
1427 uint8_t AsciiData[9] = {'\0'};
1428 uint8_t Byte;
1429 int NumBytes = 0;
1430
1431 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001432 if (((SectionAddr + Index) < StartAddress) ||
1433 ((SectionAddr + Index) > StopAddress))
1434 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001435 if (NumBytes == 0) {
1436 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1437 outs() << "\t";
1438 }
1439 Byte = Bytes.slice(Index)[0];
1440 outs() << format(" %02x", Byte);
1441 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1442
1443 uint8_t IndentOffset = 0;
1444 NumBytes++;
1445 if (Index == End - 1 || NumBytes > 8) {
1446 // Indent the space for less than 8 bytes data.
1447 // 2 spaces for byte and one for space between bytes
1448 IndentOffset = 3 * (8 - NumBytes);
1449 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1450 AsciiData[Excess] = '\0';
1451 NumBytes = 8;
1452 }
1453 if (NumBytes == 8) {
1454 AsciiData[8] = '\0';
1455 outs() << std::string(IndentOffset, ' ') << " ";
1456 outs() << reinterpret_cast<char *>(AsciiData);
1457 outs() << '\n';
1458 NumBytes = 0;
1459 }
1460 }
1461 }
Davide Italianof0706882015-10-01 21:57:09 +00001462 if (Index >= End)
1463 break;
1464
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001465 // Disassemble a real instruction or a data when disassemble all is
1466 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001467 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1468 SectionAddr + Index, DebugOut,
1469 CommentStream);
1470 if (Size == 0)
1471 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001472
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001473 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001474 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1475 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001476 outs() << CommentStream.str();
1477 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001478
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001479 // Try to resolve the target of a call, tail call, etc. to a specific
1480 // symbol.
1481 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1482 MIA->isConditionalBranch(Inst))) {
1483 uint64_t Target;
1484 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1485 // In a relocatable object, the target's section must reside in
1486 // the same section as the call instruction or it is accessed
1487 // through a relocation.
1488 //
1489 // In a non-relocatable object, the target may be in any section.
1490 //
1491 // N.B. We don't walk the relocations in the relocatable case yet.
1492 auto *TargetSectionSymbols = &Symbols;
1493 if (!Obj->isRelocatableObject()) {
1494 auto SectionAddress = std::upper_bound(
1495 SectionAddresses.begin(), SectionAddresses.end(), Target,
1496 [](uint64_t LHS,
1497 const std::pair<uint64_t, SectionRef> &RHS) {
1498 return LHS < RHS.first;
1499 });
1500 if (SectionAddress != SectionAddresses.begin()) {
1501 --SectionAddress;
1502 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1503 } else {
1504 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001505 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001506 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001507
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001508 // Find the first symbol in the section whose offset is less than
1509 // or equal to the target.
1510 if (TargetSectionSymbols) {
1511 auto TargetSym = std::upper_bound(
1512 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1513 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001514 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1515 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001516 });
1517 if (TargetSym != TargetSectionSymbols->begin()) {
1518 --TargetSym;
1519 uint64_t TargetAddress = std::get<0>(*TargetSym);
1520 StringRef TargetName = std::get<1>(*TargetSym);
1521 outs() << " <" << TargetName;
1522 uint64_t Disp = Target - TargetAddress;
1523 if (Disp)
1524 outs() << "+0x" << utohexstr(Disp);
1525 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001526 }
1527 }
1528 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001529 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001530 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001531
1532 // Print relocation for instruction.
1533 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001534 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001535 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001536 SmallString<16> name;
1537 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001538
1539 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001540 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1541 ++rel_cur;
1542 continue;
1543 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001544
Michael J. Spencer51862b32011-10-13 22:17:18 +00001545 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001546 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001547 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001548 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001549 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001550 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001551 ++rel_cur;
1552 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001553 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001554 }
1555 }
1556}
1557
Kevin Enderby98da6132015-01-20 21:47:46 +00001558void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001559 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1560 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001561 // Regular objdump doesn't print relocations in non-relocatable object
1562 // files.
1563 if (!Obj->isRelocatableObject())
1564 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001565
Colin LeMahieu77804be2015-07-29 15:45:39 +00001566 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001567 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001568 continue;
1569 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001570 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001571 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001572 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001573 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001574 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001575 SmallString<32> relocname;
1576 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001577 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001578 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001579 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001580 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001581 outs() << format(Fmt.data(), address) << " " << relocname << " "
1582 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001583 }
1584 outs() << "\n";
1585 }
1586}
1587
Kevin Enderby98da6132015-01-20 21:47:46 +00001588void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001589 outs() << "Sections:\n"
1590 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001591 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001592 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001593 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001594 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001595 uint64_t Address = Section.getAddress();
1596 uint64_t Size = Section.getSize();
1597 bool Text = Section.isText();
1598 bool Data = Section.isData();
1599 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001600 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001601 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001602 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1603 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001604 ++i;
1605 }
1606}
1607
Kevin Enderby98da6132015-01-20 21:47:46 +00001608void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001609 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001610 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001611 StringRef Name;
1612 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001613 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001614 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001615 uint64_t Size = Section.getSize();
1616 if (!Size)
1617 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001618
1619 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001620 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001621 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001622 ", %04" PRIx64 ")>\n",
1623 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001624 continue;
1625 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001626
Davide Italianoccd53fe2015-08-05 07:18:31 +00001627 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001628
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001629 // Dump out the content as hex and printable ascii characters.
1630 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001631 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001632 // Dump line of hex.
1633 for (std::size_t i = 0; i < 16; ++i) {
1634 if (i != 0 && i % 4 == 0)
1635 outs() << ' ';
1636 if (addr + i < end)
1637 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1638 << hexdigit(Contents[addr + i] & 0xF, true);
1639 else
1640 outs() << " ";
1641 }
1642 // Print ascii.
1643 outs() << " ";
1644 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001645 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001646 outs() << Contents[addr + i];
1647 else
1648 outs() << ".";
1649 }
1650 outs() << "\n";
1651 }
1652 }
1653}
1654
Kevin Enderby9acb1092016-05-31 20:35:34 +00001655void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1656 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001657 outs() << "SYMBOL TABLE:\n";
1658
Rui Ueyama4e39f712014-03-18 18:58:51 +00001659 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001660 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001661 return;
1662 }
1663 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001664 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1665 if (!AddressOrError)
1666 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001667 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001668 if ((Address < StartAddress) || (Address > StopAddress))
1669 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001670 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1671 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001672 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001673 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001674 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001675 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1676 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001677 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001678 StringRef Name;
1679 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1680 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001681 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001682 Expected<StringRef> NameOrErr = Symbol.getName();
1683 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001684 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1685 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001686 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001687 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001688
Rui Ueyama4e39f712014-03-18 18:58:51 +00001689 bool Global = Flags & SymbolRef::SF_Global;
1690 bool Weak = Flags & SymbolRef::SF_Weak;
1691 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001692 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001693 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001694
Rui Ueyama4e39f712014-03-18 18:58:51 +00001695 char GlobLoc = ' ';
1696 if (Type != SymbolRef::ST_Unknown)
1697 GlobLoc = Global ? 'g' : 'l';
1698 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1699 ? 'd' : ' ';
1700 char FileFunc = ' ';
1701 if (Type == SymbolRef::ST_File)
1702 FileFunc = 'f';
1703 else if (Type == SymbolRef::ST_Function)
1704 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001705
Rui Ueyama4e39f712014-03-18 18:58:51 +00001706 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1707 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001708
Rui Ueyama4e39f712014-03-18 18:58:51 +00001709 outs() << format(Fmt, Address) << " "
1710 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1711 << (Weak ? 'w' : ' ') // Weak?
1712 << ' ' // Constructor. Not supported yet.
1713 << ' ' // Warning. Not supported yet.
1714 << ' ' // Indirect reference to another symbol.
1715 << Debug // Debugging (d) or dynamic (D) symbol.
1716 << FileFunc // Name of function (F), file (f) or object (O).
1717 << ' ';
1718 if (Absolute) {
1719 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001720 } else if (Common) {
1721 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001722 } else if (Section == o->section_end()) {
1723 outs() << "*UND*";
1724 } else {
1725 if (const MachOObjectFile *MachO =
1726 dyn_cast<const MachOObjectFile>(o)) {
1727 DataRefImpl DR = Section->getRawDataRefImpl();
1728 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1729 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001730 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001731 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001732 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001733 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001734 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001735
1736 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001737 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001738 uint64_t Val =
1739 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001740 outs() << format("\t %08" PRIx64 " ", Val);
1741 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001742
Davide Italianocd2514d2015-04-30 23:08:53 +00001743 if (Hidden) {
1744 outs() << ".hidden ";
1745 }
1746 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001747 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001748 }
1749}
1750
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001751static void PrintUnwindInfo(const ObjectFile *o) {
1752 outs() << "Unwind info:\n\n";
1753
1754 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1755 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001756 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1757 printMachOUnwindInfo(MachO);
1758 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001759 // TODO: Extract DWARF dump tool to objdump.
1760 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001761 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001762 return;
1763 }
1764}
1765
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001766void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001767 outs() << "Exports trie:\n";
1768 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1769 printMachOExportsTrie(MachO);
1770 else {
1771 errs() << "This operation is only currently supported "
1772 "for Mach-O executable files.\n";
1773 return;
1774 }
1775}
1776
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001777void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001778 outs() << "Rebase table:\n";
1779 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1780 printMachORebaseTable(MachO);
1781 else {
1782 errs() << "This operation is only currently supported "
1783 "for Mach-O executable files.\n";
1784 return;
1785 }
1786}
1787
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001788void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001789 outs() << "Bind table:\n";
1790 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1791 printMachOBindTable(MachO);
1792 else {
1793 errs() << "This operation is only currently supported "
1794 "for Mach-O executable files.\n";
1795 return;
1796 }
1797}
1798
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001799void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001800 outs() << "Lazy bind table:\n";
1801 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1802 printMachOLazyBindTable(MachO);
1803 else {
1804 errs() << "This operation is only currently supported "
1805 "for Mach-O executable files.\n";
1806 return;
1807 }
1808}
1809
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001810void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001811 outs() << "Weak bind table:\n";
1812 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1813 printMachOWeakBindTable(MachO);
1814 else {
1815 errs() << "This operation is only currently supported "
1816 "for Mach-O executable files.\n";
1817 return;
1818 }
1819}
Nick Kledzikac431442014-09-12 21:34:15 +00001820
Adrian Prantl437105a2015-07-08 02:04:15 +00001821/// Dump the raw contents of the __clangast section so the output can be piped
1822/// into llvm-bcanalyzer.
1823void llvm::printRawClangAST(const ObjectFile *Obj) {
1824 if (outs().is_displayed()) {
1825 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1826 "the clang ast section.\n"
1827 "Please redirect the output to a file or another program such as "
1828 "llvm-bcanalyzer.\n";
1829 return;
1830 }
1831
1832 StringRef ClangASTSectionName("__clangast");
1833 if (isa<COFFObjectFile>(Obj)) {
1834 ClangASTSectionName = "clangast";
1835 }
1836
1837 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001838 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001839 StringRef Name;
1840 Sec.getName(Name);
1841 if (Name == ClangASTSectionName) {
1842 ClangASTSection = Sec;
1843 break;
1844 }
1845 }
1846 if (!ClangASTSection)
1847 return;
1848
1849 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001850 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001851 outs().write(ClangASTContents.data(), ClangASTContents.size());
1852}
1853
Sanjoy Das6f567a42015-06-22 18:03:02 +00001854static void printFaultMaps(const ObjectFile *Obj) {
1855 const char *FaultMapSectionName = nullptr;
1856
1857 if (isa<ELFObjectFileBase>(Obj)) {
1858 FaultMapSectionName = ".llvm_faultmaps";
1859 } else if (isa<MachOObjectFile>(Obj)) {
1860 FaultMapSectionName = "__llvm_faultmaps";
1861 } else {
1862 errs() << "This operation is only currently supported "
1863 "for ELF and Mach-O executable files.\n";
1864 return;
1865 }
1866
1867 Optional<object::SectionRef> FaultMapSection;
1868
Colin LeMahieu77804be2015-07-29 15:45:39 +00001869 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001870 StringRef Name;
1871 Sec.getName(Name);
1872 if (Name == FaultMapSectionName) {
1873 FaultMapSection = Sec;
1874 break;
1875 }
1876 }
1877
1878 outs() << "FaultMap table:\n";
1879
1880 if (!FaultMapSection.hasValue()) {
1881 outs() << "<not found>\n";
1882 return;
1883 }
1884
1885 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001886 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001887
1888 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1889 FaultMapContents.bytes_end());
1890
1891 outs() << FMP;
1892}
1893
Davide Italiano1bdaa202016-09-18 04:39:15 +00001894static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001895 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00001896 return printELFFileHeader(o);
1897 if (o->isCOFF())
1898 return printCOFFFileHeader(o);
1899 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001900 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001901 if (!onlyFirst)
1902 printMachOLoadCommands(o);
1903 return;
1904 }
1905 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001906}
1907
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001908static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1909 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001910 // Avoid other output when using a raw option.
1911 if (!RawClangAST) {
1912 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001913 if (a)
1914 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1915 else
1916 outs() << o->getFileName();
1917 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001918 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001919
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001920 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001921 DisassembleObject(o, Relocations);
1922 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001923 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001924 if (SectionHeaders)
1925 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001926 if (SectionContents)
1927 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001928 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001929 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001930 if (UnwindInfo)
1931 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001932 if (PrivateHeaders || FirstPrivateHeader)
1933 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001934 if (ExportsTrie)
1935 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001936 if (Rebase)
1937 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001938 if (Bind)
1939 printBindTable(o);
1940 if (LazyBind)
1941 printLazyBindTable(o);
1942 if (WeakBind)
1943 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001944 if (RawClangAST)
1945 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001946 if (PrintFaultMaps)
1947 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001948 if (DwarfDumpType != DIDT_Null) {
1949 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1950 // Dump the complete DWARF structure.
1951 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1952 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001953}
1954
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001955static void DumpObject(const COFFImportFile *I, const Archive *A) {
1956 StringRef ArchiveName = A ? A->getFileName() : "";
1957
1958 // Avoid other output when using a raw option.
1959 if (!RawClangAST)
1960 outs() << '\n'
1961 << ArchiveName << "(" << I->getFileName() << ")"
1962 << ":\tfile format COFF-import-file"
1963 << "\n\n";
1964
1965 if (SymbolTable)
1966 printCOFFSymbolTable(I);
1967}
1968
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001969/// @brief Dump each object file in \a a;
1970static void DumpArchive(const Archive *a) {
Lang Hamesfc209622016-07-14 02:24:01 +00001971 Error Err;
1972 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001973 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1974 if (!ChildOrErr) {
1975 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1976 report_error(a->getFileName(), C, std::move(E));
1977 continue;
1978 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001979 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001980 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001981 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
1982 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001983 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001984 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001985 }
Lang Hamesfc209622016-07-14 02:24:01 +00001986 if (Err)
1987 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001988}
1989
1990/// @brief Open file and figure out how to dump it.
1991static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001992
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001993 // If we are using the Mach-O specific object file parser, then let it parse
1994 // the file and process the command line options. So the -arch flags can
1995 // be used to select specific slices, etc.
1996 if (MachOOpt) {
1997 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001998 return;
1999 }
2000
2001 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002002 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2003 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002004 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002005 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002006
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002007 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002008 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002009 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002010 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002011 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002012 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002013}
2014
Michael J. Spencer2670c252011-01-20 06:39:06 +00002015int main(int argc, char **argv) {
2016 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00002017 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002018 PrettyStackTraceProgram X(argc, argv);
2019 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2020
2021 // Initialize targets and assembly printers/parsers.
2022 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002023 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002024 llvm::InitializeAllDisassemblers();
2025
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002026 // Register the target printer for --version.
2027 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2028
Michael J. Spencer2670c252011-01-20 06:39:06 +00002029 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2030 TripleName = Triple::normalize(TripleName);
2031
2032 ToolName = argv[0];
2033
2034 // Defaults to a.out if no filenames specified.
2035 if (InputFilenames.size() == 0)
2036 InputFilenames.push_back("a.out");
2037
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002038 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002039 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002040 if (!Disassemble
2041 && !Relocations
2042 && !SectionHeaders
2043 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002044 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002045 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002046 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002047 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002048 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002049 && !Rebase
2050 && !Bind
2051 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002052 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002053 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002054 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002055 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002056 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002057 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002058 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002059 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002060 && !(DylibsUsed && MachOOpt)
2061 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002062 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002063 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002064 && !PrintFaultMaps
2065 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002066 cl::PrintHelpMessage();
2067 return 2;
2068 }
2069
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002070 std::for_each(InputFilenames.begin(), InputFilenames.end(),
2071 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002072
Davide Italianoccd53fe2015-08-05 07:18:31 +00002073 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00002074}