blob: 4fc4affa7f9905b63612f813201adfa6a09e23c0 [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"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000040#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000041#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Object/ObjectFile.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000043#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000046#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000047#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000049#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000050#include "llvm/Support/Host.h"
51#include "llvm/Support/ManagedStatic.h"
52#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/PrettyStackTrace.h"
54#include "llvm/Support/Signals.h"
55#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000056#include "llvm/Support/TargetRegistry.h"
57#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000059#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000060#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000061#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000062#include <system_error>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000063#include <utility>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000064#include <unordered_map>
Ahmed Bougacha17926472013-08-21 07:29:02 +000065
Michael J. Spencer2670c252011-01-20 06:39:06 +000066using namespace llvm;
67using namespace object;
68
Benjamin Kramer43a772e2011-09-19 17:56:04 +000069static cl::list<std::string>
70InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000071
Kevin Enderbye2297dd2015-01-07 21:02:18 +000072cl::opt<bool>
73llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000074 cl::desc("Display assembler mnemonics for the machine instructions"));
75static cl::alias
76Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000077 cl::aliasopt(Disassemble));
78
79cl::opt<bool>
80llvm::DisassembleAll("disassemble-all",
81 cl::desc("Display assembler mnemonics for the machine instructions"));
82static cl::alias
83DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000084 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000085
Kevin Enderby98da6132015-01-20 21:47:46 +000086cl::opt<bool>
87llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000088
Kevin Enderby98da6132015-01-20 21:47:46 +000089cl::opt<bool>
90llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000091
Kevin Enderby98da6132015-01-20 21:47:46 +000092cl::opt<bool>
93llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000094
Kevin Enderbye2297dd2015-01-07 21:02:18 +000095cl::opt<bool>
96llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000097
Kevin Enderbye2297dd2015-01-07 21:02:18 +000098cl::opt<bool>
99llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000100
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000101cl::opt<bool>
102llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000103
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000104cl::opt<bool>
105llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000106
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000107cl::opt<bool>
108llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000109
Adrian Prantl437105a2015-07-08 02:04:15 +0000110cl::opt<bool>
111llvm::RawClangAST("raw-clang-ast",
112 cl::desc("Dump the raw binary contents of the clang AST section"));
113
Nick Kledzik56ebef42014-09-16 01:41:51 +0000114static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000115MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000116static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000117MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000118
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000119cl::opt<std::string>
120llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
121 "see -version for available targets"));
122
123cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000124llvm::MCPU("mcpu",
125 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
126 cl::value_desc("cpu-name"),
127 cl::init(""));
128
129cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000130llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000131 "see -version for available targets"));
132
Kevin Enderby98da6132015-01-20 21:47:46 +0000133cl::opt<bool>
134llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
135 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000136static cl::alias
137SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
138 cl::aliasopt(SectionHeaders));
139static cl::alias
140SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
141 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000142
Colin LeMahieu77804be2015-07-29 15:45:39 +0000143cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000144llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
145 "With -macho dump segment,section"));
146cl::alias
147static FilterSectionsj("j", cl::desc("Alias for --section"),
148 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000149
Kevin Enderbyc9595622014-08-06 23:24:41 +0000150cl::list<std::string>
151llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000152 cl::CommaSeparated,
153 cl::desc("Target specific attributes"),
154 cl::value_desc("a1,+a2,-a3,..."));
155
Kevin Enderbybf246f52014-09-24 23:08:22 +0000156cl::opt<bool>
157llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
158 "instructions, do not print "
159 "the instruction bytes."));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000160
Kevin Enderby98da6132015-01-20 21:47:46 +0000161cl::opt<bool>
162llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000163
164static cl::alias
165UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
166 cl::aliasopt(UnwindInfo));
167
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000168cl::opt<bool>
169llvm::PrivateHeaders("private-headers",
170 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000171
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000172cl::opt<bool>
173llvm::FirstPrivateHeader("private-header",
174 cl::desc("Display only the first format specific file "
175 "header"));
176
Michael J. Spencer209565db2013-01-06 03:56:49 +0000177static cl::alias
178PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
179 cl::aliasopt(PrivateHeaders));
180
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000181cl::opt<bool>
182 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000183 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000184
Sanjoy Das6f567a42015-06-22 18:03:02 +0000185cl::opt<bool> PrintFaultMaps("fault-map-section",
186 cl::desc("Display contents of faultmap section"));
187
Igor Laevsky03a670c2016-01-26 15:09:42 +0000188cl::opt<DIDumpType> llvm::DwarfDumpType(
189 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
190 cl::values(clEnumValN(DIDT_Frames, "frames", ".debug_frame"),
191 clEnumValEnd));
192
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));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000207static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000208
Colin LeMahieu77804be2015-07-29 15:45:39 +0000209namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000210typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000211
212class SectionFilterIterator {
213public:
214 SectionFilterIterator(FilterPredicate P,
215 llvm::object::section_iterator const &I,
216 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000217 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000218 ScanPredicate();
219 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000220 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000221 SectionFilterIterator &operator++() {
222 ++Iterator;
223 ScanPredicate();
224 return *this;
225 }
226 bool operator!=(SectionFilterIterator const &Other) const {
227 return Iterator != Other.Iterator;
228 }
229
230private:
231 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000232 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000233 ++Iterator;
234 }
235 }
236 FilterPredicate Predicate;
237 llvm::object::section_iterator Iterator;
238 llvm::object::section_iterator End;
239};
240
241class SectionFilter {
242public:
243 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000244 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000245 SectionFilterIterator begin() {
246 return SectionFilterIterator(Predicate, Object.section_begin(),
247 Object.section_end());
248 }
249 SectionFilterIterator end() {
250 return SectionFilterIterator(Predicate, Object.section_end(),
251 Object.section_end());
252 }
253
254private:
255 FilterPredicate Predicate;
256 llvm::object::ObjectFile const &Object;
257};
258SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000259 return SectionFilter(
260 [](llvm::object::SectionRef const &S) {
261 if (FilterSections.empty())
262 return true;
263 llvm::StringRef String;
264 std::error_code error = S.getName(String);
265 if (error)
266 return false;
267 return is_contained(FilterSections, String);
268 },
269 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000270}
271}
272
Davide Italianoccd53fe2015-08-05 07:18:31 +0000273void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000274 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000275 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000276
Davide Italiano140af642015-12-25 18:16:45 +0000277 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
278 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000279 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000280}
281
Kevin Enderby42398052016-06-28 23:16:13 +0000282LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
283 errs() << ToolName << ": " << Message << ".\n";
284 errs().flush();
285 exit(1);
286}
287
Davide Italianoed9d95b2015-12-29 13:41:02 +0000288LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
289 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000290 assert(EC);
291 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000292 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000293}
294
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000295LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
296 llvm::Error E) {
297 assert(E);
298 std::string Buf;
299 raw_string_ostream OS(Buf);
300 logAllUnhandledErrors(std::move(E), OS, "");
301 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000302 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000303 exit(1);
304}
305
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000306LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
307 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000308 llvm::Error E,
309 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000310 assert(E);
311 errs() << ToolName << ": ";
312 if (ArchiveName != "")
313 errs() << ArchiveName << "(" << FileName << ")";
314 else
315 errs() << FileName;
Kevin Enderby9acb1092016-05-31 20:35:34 +0000316 if (!ArchitectureName.empty())
317 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000318 std::string Buf;
319 raw_string_ostream OS(Buf);
320 logAllUnhandledErrors(std::move(E), OS, "");
321 OS.flush();
322 errs() << " " << Buf;
323 exit(1);
324}
325
326LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
327 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000328 llvm::Error E,
329 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000330 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000331 // TODO: if we have a error getting the name then it would be nice to print
332 // the index of which archive member this is and or its offset in the
333 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000334 if (!NameOrErr) {
335 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000336 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000337 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000338 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
339 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000340}
341
Craig Toppere6cb63e2014-04-25 04:24:47 +0000342static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000343 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000344 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000345 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000346 if (Obj) {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000347 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000348 // TheTriple defaults to ELF, and COFF doesn't have an environment:
349 // the best we can do here is indicate that it is mach-o.
350 if (Obj->isMachO())
Saleem Abdulrasool35476332014-03-06 20:47:11 +0000351 TheTriple.setObjectFormat(Triple::MachO);
Saleem Abdulrasool98938f12014-04-17 06:17:23 +0000352
353 if (Obj->isCOFF()) {
354 const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
355 if (COFFObj->getArch() == Triple::thumb)
356 TheTriple.setTriple("thumbv7-windows");
357 }
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000358 }
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000359 } else
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000360 TheTriple.setTriple(Triple::normalize(TripleName));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000361
362 // Get the target specific parser.
363 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000364 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
365 Error);
Davide Italianobb599e32015-12-03 22:13:40 +0000366 if (!TheTarget)
367 report_fatal_error("can't find target: " + Error);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000368
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000369 // Update the triple name and return the found target.
370 TripleName = TheTriple.getTriple();
371 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000372}
373
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000374bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000375 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000376}
377
Colin LeMahieufb76b002015-05-28 19:07:14 +0000378namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000379class SourcePrinter {
380protected:
381 DILineInfo OldLineInfo;
382 const ObjectFile *Obj;
383 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
384 // File name to file contents of source
385 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
386 // Mark the line endings of the cached source
387 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
388
389private:
390 bool cacheSource(std::string File);
391
392public:
393 virtual ~SourcePrinter() {}
394 SourcePrinter() : Obj(nullptr), Symbolizer(nullptr) {}
395 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
396 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
397 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
398 DefaultArch);
399 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
400 }
401 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
402 StringRef Delimiter = "; ");
403};
404
405bool SourcePrinter::cacheSource(std::string File) {
406 auto BufferOrError = MemoryBuffer::getFile(File);
407 if (!BufferOrError)
408 return false;
409 // Chomp the file to get lines
410 size_t BufferSize = (*BufferOrError)->getBufferSize();
411 const char *BufferStart = (*BufferOrError)->getBufferStart();
412 for (const char *Start = BufferStart, *End = BufferStart;
413 End < BufferStart + BufferSize; End++)
414 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
415 (*End == '\r' && *(End + 1) == '\n')) {
416 LineCache[File].push_back(StringRef(Start, End - Start));
417 if (*End == '\r')
418 End++;
419 Start = End + 1;
420 }
421 SourceCache[File] = std::move(*BufferOrError);
422 return true;
423}
424
425void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
426 StringRef Delimiter) {
427 if (!Symbolizer)
428 return;
429 DILineInfo LineInfo = DILineInfo();
430 auto ExpectecLineInfo =
431 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
432 if (!ExpectecLineInfo)
433 consumeError(ExpectecLineInfo.takeError());
434 else
435 LineInfo = *ExpectecLineInfo;
436
437 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
438 LineInfo.Line == 0)
439 return;
440
441 if (PrintLines)
442 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
443 if (PrintSource) {
444 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
445 if (!cacheSource(LineInfo.FileName))
446 return;
447 auto FileBuffer = SourceCache.find(LineInfo.FileName);
448 if (FileBuffer != SourceCache.end()) {
449 auto LineBuffer = LineCache.find(LineInfo.FileName);
450 if (LineBuffer != LineCache.end())
451 // Vector begins at 0, line numbers are non-zero
452 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
453 << "\n";
454 }
455 }
456 OldLineInfo = LineInfo;
457}
458
Colin LeMahieufb76b002015-05-28 19:07:14 +0000459class PrettyPrinter {
460public:
Colin LeMahieu0b5890d2015-05-28 20:59:08 +0000461 virtual ~PrettyPrinter(){}
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000462 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000463 ArrayRef<uint8_t> Bytes, uint64_t Address,
464 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000465 MCSubtargetInfo const &STI, SourcePrinter *SP) {
466 if (SP && (PrintSource || PrintLines))
467 SP->printSourceLine(OS, Address);
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000468 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000469 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000470 OS << "\t";
471 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000472 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000473 if (MI)
474 IP.printInst(MI, OS, "", STI);
475 else
476 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000477 }
478};
479PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000480class HexagonPrettyPrinter : public PrettyPrinter {
481public:
482 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
483 raw_ostream &OS) {
484 uint32_t opcode =
485 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
486 OS << format("%8" PRIx64 ":", Address);
487 if (!NoShowRawInsn) {
488 OS << "\t";
489 dumpBytes(Bytes.slice(0, 4), OS);
490 OS << format("%08" PRIx32, opcode);
491 }
492 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000493 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
494 uint64_t Address, raw_ostream &OS, StringRef Annot,
495 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000496 if (!MI) {
497 printLead(Bytes, Address, OS);
498 OS << " <unknown>";
499 return;
500 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000501 std::string Buffer;
502 {
503 raw_string_ostream TempStream(Buffer);
504 IP.printInst(MI, TempStream, "", STI);
505 }
506 StringRef Contents(Buffer);
507 // Split off bundle attributes
508 auto PacketBundle = Contents.rsplit('\n');
509 // Split off first instruction from the rest
510 auto HeadTail = PacketBundle.first.split('\n');
511 auto Preamble = " { ";
512 auto Separator = "";
513 while(!HeadTail.first.empty()) {
514 OS << Separator;
515 Separator = "\n";
516 printLead(Bytes, Address, OS);
517 OS << Preamble;
518 Preamble = " ";
519 StringRef Inst;
520 auto Duplex = HeadTail.first.split('\v');
521 if(!Duplex.second.empty()){
522 OS << Duplex.first;
523 OS << "; ";
524 Inst = Duplex.second;
525 }
526 else
527 Inst = HeadTail.first;
528 OS << Inst;
529 Bytes = Bytes.slice(4);
530 Address += 4;
531 HeadTail = HeadTail.second.split('\n');
532 }
533 OS << " } " << PacketBundle.second;
534 }
535};
536HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000537
538class AMDGCNPrettyPrinter : public PrettyPrinter {
539public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000540 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
541 uint64_t Address, raw_ostream &OS, StringRef Annot,
542 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Matt Arsenault87d80db2016-04-22 21:23:41 +0000543 if (!MI) {
544 OS << " <unknown>";
545 return;
546 }
547
Valery Pykhtinde048052016-04-07 07:24:01 +0000548 SmallString<40> InstStr;
549 raw_svector_ostream IS(InstStr);
550
551 IP.printInst(MI, IS, "", STI);
552
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000553 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000554 typedef support::ulittle32_t U32;
555 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
556 Bytes.size() / sizeof(U32)))
557 // D should be explicitly casted to uint32_t here as it is passed
558 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000559 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000560
561 if (!Annot.empty())
562 OS << "// " << Annot;
563 }
564};
565AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
566
Colin LeMahieu35436a22015-05-29 14:48:25 +0000567PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000568 switch(Triple.getArch()) {
569 default:
570 return PrettyPrinterInst;
571 case Triple::hexagon:
572 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000573 case Triple::amdgcn:
574 return AMDGCNPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000575 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000576}
577}
578
Rafael Espindola37070a52015-06-03 04:48:06 +0000579template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000580static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000581 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000582 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000583 DataRefImpl Rel = RelRef.getRawDataRefImpl();
584
Rafael Espindola37070a52015-06-03 04:48:06 +0000585 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
586 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000587 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
588
Rafael Espindola37070a52015-06-03 04:48:06 +0000589 const ELFFile<ELFT> &EF = *Obj->getELFFile();
590
Rafael Espindola6def3042015-07-01 12:56:27 +0000591 ErrorOr<const Elf_Shdr *> SecOrErr = EF.getSection(Rel.d.a);
592 if (std::error_code EC = SecOrErr.getError())
593 return EC;
594 const Elf_Shdr *Sec = *SecOrErr;
595 ErrorOr<const Elf_Shdr *> SymTabOrErr = EF.getSection(Sec->sh_link);
596 if (std::error_code EC = SymTabOrErr.getError())
597 return EC;
598 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000599 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
600 SymTab->sh_type == ELF::SHT_DYNSYM);
Rafael Espindola6def3042015-07-01 12:56:27 +0000601 ErrorOr<const Elf_Shdr *> StrTabSec = EF.getSection(SymTab->sh_link);
602 if (std::error_code EC = StrTabSec.getError())
603 return EC;
604 ErrorOr<StringRef> StrTabOrErr = EF.getStringTable(*StrTabSec);
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000605 if (std::error_code EC = StrTabOrErr.getError())
606 return EC;
607 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000608 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000609 StringRef res;
610 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000611 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000612 default:
613 return object_error::parse_failed;
614 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000615 // TODO: Read implicit addend from section data.
616 break;
617 }
618 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000619 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000620 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000621 break;
622 }
623 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000624 symbol_iterator SI = RelRef.getSymbol();
625 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000626 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000627 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000628 Expected<section_iterator> SymSI = SI->getSection();
629 if (!SymSI)
630 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000631 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
632 ErrorOr<StringRef> SecName = EF.getSectionName(SymSec);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000633 if (std::error_code EC = SecName.getError())
634 return EC;
635 Target = *SecName;
636 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000637 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000638 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000639 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000640 Target = *SymName;
641 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000642 switch (EF.getHeader()->e_machine) {
643 case ELF::EM_X86_64:
644 switch (type) {
645 case ELF::R_X86_64_PC8:
646 case ELF::R_X86_64_PC16:
647 case ELF::R_X86_64_PC32: {
648 std::string fmtbuf;
649 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000650 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000651 fmt.flush();
652 Result.append(fmtbuf.begin(), fmtbuf.end());
653 } break;
654 case ELF::R_X86_64_8:
655 case ELF::R_X86_64_16:
656 case ELF::R_X86_64_32:
657 case ELF::R_X86_64_32S:
658 case ELF::R_X86_64_64: {
659 std::string fmtbuf;
660 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000661 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000662 fmt.flush();
663 Result.append(fmtbuf.begin(), fmtbuf.end());
664 } break;
665 default:
666 res = "Unknown";
667 }
668 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000669 case ELF::EM_LANAI:
Rafael Espindola37070a52015-06-03 04:48:06 +0000670 case ELF::EM_AARCH64: {
671 std::string fmtbuf;
672 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000673 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000674 if (addend != 0)
675 fmt << (addend < 0 ? "" : "+") << addend;
676 fmt.flush();
677 Result.append(fmtbuf.begin(), fmtbuf.end());
678 break;
679 }
680 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000681 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000682 case ELF::EM_ARM:
683 case ELF::EM_HEXAGON:
684 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000685 case ELF::EM_BPF:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000686 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000687 break;
Dan Gohman46350172016-01-12 20:56:01 +0000688 case ELF::EM_WEBASSEMBLY:
689 switch (type) {
690 case ELF::R_WEBASSEMBLY_DATA: {
691 std::string fmtbuf;
692 raw_string_ostream fmt(fmtbuf);
693 fmt << Target << (addend < 0 ? "" : "+") << addend;
694 fmt.flush();
695 Result.append(fmtbuf.begin(), fmtbuf.end());
696 break;
697 }
698 case ELF::R_WEBASSEMBLY_FUNCTION:
699 res = Target;
700 break;
701 default:
702 res = "Unknown";
703 }
704 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000705 default:
706 res = "Unknown";
707 }
708 if (Result.empty())
709 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000710 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000711}
712
713static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000714 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000715 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000716 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
717 return getRelocationValueString(ELF32LE, Rel, Result);
718 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
719 return getRelocationValueString(ELF64LE, Rel, Result);
720 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
721 return getRelocationValueString(ELF32BE, Rel, Result);
722 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
723 return getRelocationValueString(ELF64BE, Rel, Result);
724}
725
726static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
727 const RelocationRef &Rel,
728 SmallVectorImpl<char> &Result) {
729 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000730 Expected<StringRef> SymNameOrErr = SymI->getName();
731 if (!SymNameOrErr)
732 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000733 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000734 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000735 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000736}
737
738static void printRelocationTargetName(const MachOObjectFile *O,
739 const MachO::any_relocation_info &RE,
740 raw_string_ostream &fmt) {
741 bool IsScattered = O->isRelocationScattered(RE);
742
743 // Target of a scattered relocation is an address. In the interest of
744 // generating pretty output, scan through the symbol table looking for a
745 // symbol that aligns with that address. If we find one, print it.
746 // Otherwise, we just print the hex address of the target.
747 if (IsScattered) {
748 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
749
750 for (const SymbolRef &Symbol : O->symbols()) {
751 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000752 Expected<uint64_t> Addr = Symbol.getAddress();
753 if (!Addr) {
754 std::string Buf;
755 raw_string_ostream OS(Buf);
756 logAllUnhandledErrors(Addr.takeError(), OS, "");
757 OS.flush();
758 report_fatal_error(Buf);
759 }
Rafael Espindolaed067c42015-07-03 18:19:00 +0000760 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000761 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000762 Expected<StringRef> Name = Symbol.getName();
763 if (!Name) {
764 std::string Buf;
765 raw_string_ostream OS(Buf);
766 logAllUnhandledErrors(Name.takeError(), OS, "");
767 OS.flush();
768 report_fatal_error(Buf);
769 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000770 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000771 return;
772 }
773
774 // If we couldn't find a symbol that this relocation refers to, try
775 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000776 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000777 std::error_code ec;
778
779 StringRef Name;
780 uint64_t Addr = Section.getAddress();
781 if (Addr != Val)
782 continue;
783 if ((ec = Section.getName(Name)))
784 report_fatal_error(ec.message());
785 fmt << Name;
786 return;
787 }
788
789 fmt << format("0x%x", Val);
790 return;
791 }
792
793 StringRef S;
794 bool isExtern = O->getPlainRelocationExternal(RE);
795 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
796
797 if (isExtern) {
798 symbol_iterator SI = O->symbol_begin();
799 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000800 Expected<StringRef> SOrErr = SI->getName();
801 error(errorToErrorCode(SOrErr.takeError()));
Davide Italianoccd53fe2015-08-05 07:18:31 +0000802 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000803 } else {
804 section_iterator SI = O->section_begin();
805 // Adjust for the fact that sections are 1-indexed.
806 advance(SI, Val - 1);
807 SI->getName(S);
808 }
809
810 fmt << S;
811}
812
813static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
814 const RelocationRef &RelRef,
815 SmallVectorImpl<char> &Result) {
816 DataRefImpl Rel = RelRef.getRawDataRefImpl();
817 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
818
819 unsigned Arch = Obj->getArch();
820
821 std::string fmtbuf;
822 raw_string_ostream fmt(fmtbuf);
823 unsigned Type = Obj->getAnyRelocationType(RE);
824 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
825
826 // Determine any addends that should be displayed with the relocation.
827 // These require decoding the relocation type, which is triple-specific.
828
829 // X86_64 has entirely custom relocation types.
830 if (Arch == Triple::x86_64) {
831 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
832
833 switch (Type) {
834 case MachO::X86_64_RELOC_GOT_LOAD:
835 case MachO::X86_64_RELOC_GOT: {
836 printRelocationTargetName(Obj, RE, fmt);
837 fmt << "@GOT";
838 if (isPCRel)
839 fmt << "PCREL";
840 break;
841 }
842 case MachO::X86_64_RELOC_SUBTRACTOR: {
843 DataRefImpl RelNext = Rel;
844 Obj->moveRelocationNext(RelNext);
845 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
846
847 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
848 // X86_64_RELOC_UNSIGNED.
849 // NOTE: Scattered relocations don't exist on x86_64.
850 unsigned RType = Obj->getAnyRelocationType(RENext);
851 if (RType != MachO::X86_64_RELOC_UNSIGNED)
852 report_fatal_error("Expected X86_64_RELOC_UNSIGNED after "
853 "X86_64_RELOC_SUBTRACTOR.");
854
855 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
856 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
857 printRelocationTargetName(Obj, RENext, fmt);
858 fmt << "-";
859 printRelocationTargetName(Obj, RE, fmt);
860 break;
861 }
862 case MachO::X86_64_RELOC_TLV:
863 printRelocationTargetName(Obj, RE, fmt);
864 fmt << "@TLV";
865 if (isPCRel)
866 fmt << "P";
867 break;
868 case MachO::X86_64_RELOC_SIGNED_1:
869 printRelocationTargetName(Obj, RE, fmt);
870 fmt << "-1";
871 break;
872 case MachO::X86_64_RELOC_SIGNED_2:
873 printRelocationTargetName(Obj, RE, fmt);
874 fmt << "-2";
875 break;
876 case MachO::X86_64_RELOC_SIGNED_4:
877 printRelocationTargetName(Obj, RE, fmt);
878 fmt << "-4";
879 break;
880 default:
881 printRelocationTargetName(Obj, RE, fmt);
882 break;
883 }
884 // X86 and ARM share some relocation types in common.
885 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
886 Arch == Triple::ppc) {
887 // Generic relocation types...
888 switch (Type) {
889 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000890 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000891 case MachO::GENERIC_RELOC_SECTDIFF: {
892 DataRefImpl RelNext = Rel;
893 Obj->moveRelocationNext(RelNext);
894 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
895
896 // X86 sect diff's must be followed by a relocation of type
897 // GENERIC_RELOC_PAIR.
898 unsigned RType = Obj->getAnyRelocationType(RENext);
899
900 if (RType != MachO::GENERIC_RELOC_PAIR)
901 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
902 "GENERIC_RELOC_SECTDIFF.");
903
904 printRelocationTargetName(Obj, RE, fmt);
905 fmt << "-";
906 printRelocationTargetName(Obj, RENext, fmt);
907 break;
908 }
909 }
910
911 if (Arch == Triple::x86 || Arch == Triple::ppc) {
912 switch (Type) {
913 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
914 DataRefImpl RelNext = Rel;
915 Obj->moveRelocationNext(RelNext);
916 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
917
918 // X86 sect diff's must be followed by a relocation of type
919 // GENERIC_RELOC_PAIR.
920 unsigned RType = Obj->getAnyRelocationType(RENext);
921 if (RType != MachO::GENERIC_RELOC_PAIR)
922 report_fatal_error("Expected GENERIC_RELOC_PAIR after "
923 "GENERIC_RELOC_LOCAL_SECTDIFF.");
924
925 printRelocationTargetName(Obj, RE, fmt);
926 fmt << "-";
927 printRelocationTargetName(Obj, RENext, fmt);
928 break;
929 }
930 case MachO::GENERIC_RELOC_TLV: {
931 printRelocationTargetName(Obj, RE, fmt);
932 fmt << "@TLV";
933 if (IsPCRel)
934 fmt << "P";
935 break;
936 }
937 default:
938 printRelocationTargetName(Obj, RE, fmt);
939 }
940 } else { // ARM-specific relocations
941 switch (Type) {
942 case MachO::ARM_RELOC_HALF:
943 case MachO::ARM_RELOC_HALF_SECTDIFF: {
944 // Half relocations steal a bit from the length field to encode
945 // whether this is an upper16 or a lower16 relocation.
946 bool isUpper = Obj->getAnyRelocationLength(RE) >> 1;
947
948 if (isUpper)
949 fmt << ":upper16:(";
950 else
951 fmt << ":lower16:(";
952 printRelocationTargetName(Obj, RE, fmt);
953
954 DataRefImpl RelNext = Rel;
955 Obj->moveRelocationNext(RelNext);
956 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
957
958 // ARM half relocs must be followed by a relocation of type
959 // ARM_RELOC_PAIR.
960 unsigned RType = Obj->getAnyRelocationType(RENext);
961 if (RType != MachO::ARM_RELOC_PAIR)
962 report_fatal_error("Expected ARM_RELOC_PAIR after "
963 "ARM_RELOC_HALF");
964
965 // NOTE: The half of the target virtual address is stashed in the
966 // address field of the secondary relocation, but we can't reverse
967 // engineer the constant offset from it without decoding the movw/movt
968 // instruction to find the other half in its immediate field.
969
970 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
971 // symbol/section pointer of the follow-on relocation.
972 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
973 fmt << "-";
974 printRelocationTargetName(Obj, RENext, fmt);
975 }
976
977 fmt << ")";
978 break;
979 }
980 default: { printRelocationTargetName(Obj, RE, fmt); }
981 }
982 }
983 } else
984 printRelocationTargetName(Obj, RE, fmt);
985
986 fmt.flush();
987 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000988 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000989}
990
991static std::error_code getRelocationValueString(const RelocationRef &Rel,
992 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000993 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000994 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
995 return getRelocationValueString(ELF, Rel, Result);
996 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
997 return getRelocationValueString(COFF, Rel, Result);
998 auto *MachO = cast<MachOObjectFile>(Obj);
999 return getRelocationValueString(MachO, Rel, Result);
1000}
1001
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001002/// @brief Indicates whether this relocation should hidden when listing
1003/// relocations, usually because it is the trailing part of a multipart
1004/// relocation that will be printed as part of the leading relocation.
1005static bool getHidden(RelocationRef RelRef) {
1006 const ObjectFile *Obj = RelRef.getObject();
1007 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1008 if (!MachO)
1009 return false;
1010
1011 unsigned Arch = MachO->getArch();
1012 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1013 uint64_t Type = MachO->getRelocationType(Rel);
1014
1015 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1016 // is always hidden.
1017 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1018 if (Type == MachO::GENERIC_RELOC_PAIR)
1019 return true;
1020 } else if (Arch == Triple::x86_64) {
1021 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1022 // an X86_64_RELOC_SUBTRACTOR.
1023 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1024 DataRefImpl RelPrev = Rel;
1025 RelPrev.d.a--;
1026 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1027 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1028 return true;
1029 }
1030 }
1031
1032 return false;
1033}
1034
Sam Koltonc05d7782016-08-17 10:17:57 +00001035static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1036 assert(Obj->isELF());
1037 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1038 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1039 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1040 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1041 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1042 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1043 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1044 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1045 llvm_unreachable("Unsupported binary format");
1046}
1047
Michael J. Spencer51862b32011-10-13 22:17:18 +00001048static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001049 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001050
Jack Carter551efd72012-08-28 19:24:49 +00001051 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001052 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001053 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001054 for (unsigned i = 0; i != MAttrs.size(); ++i)
1055 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001056 }
1057
Ahmed Charles56440fd2014-03-06 05:51:42 +00001058 std::unique_ptr<const MCRegisterInfo> MRI(
1059 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001060 if (!MRI)
1061 report_fatal_error("error: no register info for target " + TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001062
1063 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001064 std::unique_ptr<const MCAsmInfo> AsmInfo(
1065 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001066 if (!AsmInfo)
1067 report_fatal_error("error: no assembly info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001068 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001069 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001070 if (!STI)
1071 report_fatal_error("error: no subtarget info for target " + TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001072 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001073 if (!MII)
1074 report_fatal_error("error: no instruction info for target " + TripleName);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001075 std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
1076 MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
1077
1078 std::unique_ptr<MCDisassembler> DisAsm(
1079 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001080 if (!DisAsm)
1081 report_fatal_error("error: no disassembler for target " + TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001082
Ahmed Charles56440fd2014-03-06 05:51:42 +00001083 std::unique_ptr<const MCInstrAnalysis> MIA(
1084 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001085
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001086 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001087 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1088 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001089 if (!IP)
1090 report_fatal_error("error: no instruction printer for target " +
1091 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001092 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001093 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001094
Greg Fitzgerald18432272014-03-20 22:55:15 +00001095 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1096 "\t\t\t%08" PRIx64 ": ";
1097
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001098 SourcePrinter SP(Obj, TheTarget->getName());
1099
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001100 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1101 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001102 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001103 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001104 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001105 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001106 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001107 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001108 }
1109
David Majnemer81afca62015-07-07 22:06:59 +00001110 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001111 // pretty print the symbols while disassembling.
Sam Koltonc05d7782016-08-17 10:17:57 +00001112 typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001113 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1114 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001115 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1116 error(errorToErrorCode(AddressOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001117 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001118
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001119 Expected<StringRef> Name = Symbol.getName();
1120 error(errorToErrorCode(Name.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001121 if (Name->empty())
1122 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001123
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001124 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1125 error(errorToErrorCode(SectionOrErr.takeError()));
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001126 section_iterator SecI = *SectionOrErr;
1127 if (SecI == Obj->section_end())
1128 continue;
Sam Koltonc05d7782016-08-17 10:17:57 +00001129
1130 // For AMDGPU we need to track symbol types
1131 uint8_t SymbolType = ELF::STT_NOTYPE;
1132 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1133 SymbolType = getElfSymbolType(Obj, Symbol);
1134 }
David Majnemer81afca62015-07-07 22:06:59 +00001135
Sam Koltonc05d7782016-08-17 10:17:57 +00001136 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1137
David Majnemer81afca62015-07-07 22:06:59 +00001138 }
1139
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001140 // Create a mapping from virtual address to section.
1141 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1142 for (SectionRef Sec : Obj->sections())
1143 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1144 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1145
1146 // Linked executables (.exe and .dll files) typically don't include a real
1147 // symbol table but they might contain an export table.
1148 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1149 for (const auto &ExportEntry : COFFObj->export_directories()) {
1150 StringRef Name;
1151 error(ExportEntry.getSymbolName(Name));
1152 if (Name.empty())
1153 continue;
1154 uint32_t RVA;
1155 error(ExportEntry.getExportRVA(RVA));
1156
1157 uint64_t VA = COFFObj->getImageBase() + RVA;
1158 auto Sec = std::upper_bound(
1159 SectionAddresses.begin(), SectionAddresses.end(), VA,
1160 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1161 return LHS < RHS.first;
1162 });
1163 if (Sec != SectionAddresses.begin())
1164 --Sec;
1165 else
1166 Sec = SectionAddresses.end();
1167
1168 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001169 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001170 }
1171 }
1172
1173 // Sort all the symbols, this allows us to use a simple binary search to find
1174 // a symbol near an address.
1175 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1176 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1177
Colin LeMahieu77804be2015-07-29 15:45:39 +00001178 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001179 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001180 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001181
Rafael Espindola80291272014-10-08 15:28:58 +00001182 uint64_t SectionAddr = Section.getAddress();
1183 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001184 if (!SectSize)
1185 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001186
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001187 // Get the list of all the symbols in this section.
1188 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001189 std::vector<uint64_t> DataMappingSymsAddr;
1190 std::vector<uint64_t> TextMappingSymsAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001191 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1192 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001193 uint64_t Address = std::get<0>(Symb);
1194 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001195 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001196 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001197 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001198 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001199 }
1200 }
1201
Davide Italianof0706882015-10-01 21:57:09 +00001202 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1203 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001204
Michael J. Spencer51862b32011-10-13 22:17:18 +00001205 // Make a list of all the relocations for this section.
1206 std::vector<RelocationRef> Rels;
1207 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001208 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1209 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1210 Rels.push_back(Reloc);
1211 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001212 }
1213 }
1214
1215 // Sort relocations by address.
1216 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1217
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001218 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001219 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001220 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001221 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001222 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001223 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001224 error(Section.getName(name));
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001225 outs() << "Disassembly of section ";
1226 if (!SegmentName.empty())
1227 outs() << SegmentName << ",";
1228 outs() << name << ':';
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001229
Rafael Espindola7884c952015-06-04 15:01:05 +00001230 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001231 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1232 Symbols.insert(Symbols.begin(), std::make_tuple(SectionAddr, name, ELF::STT_NOTYPE));
1233 }
Alp Tokere69170a2014-06-26 22:52:05 +00001234
1235 SmallString<40> Comments;
1236 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001237
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001238 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001239 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001240 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1241 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001242
Michael J. Spencer2670c252011-01-20 06:39:06 +00001243 uint64_t Size;
1244 uint64_t Index;
1245
Michael J. Spencer51862b32011-10-13 22:17:18 +00001246 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1247 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001248 // Disassemble symbol by symbol.
1249 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001250 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001251 // The end is either the section end or the beginning of the next
1252 // symbol.
1253 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001254 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001255 // Don't try to disassemble beyond the end of section contents.
1256 if (End > SectSize)
1257 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001258 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001259 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001260 continue;
1261
Valery Pykhtinde048052016-04-07 07:24:01 +00001262 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1263 // make size 4 bytes folded
1264 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001265 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1266 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1267 Start += 256;
1268 }
1269 if (si == se - 1 ||
1270 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1271 // cut trailing zeroes at the end of kernel
1272 // cut up to 256 bytes
1273 const uint64_t EndAlign = 256;
1274 const auto Limit = End - (std::min)(EndAlign, End - Start);
1275 while (End > Limit &&
1276 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1277 End -= 4;
1278 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001279 }
1280
Sam Koltonc05d7782016-08-17 10:17:57 +00001281 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001282
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001283#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001284 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001285#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001286 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001287#endif
1288
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001289 for (Index = Start; Index < End; Index += Size) {
1290 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001291
Davide Italianof0706882015-10-01 21:57:09 +00001292 // AArch64 ELF binaries can interleave data and text in the
1293 // same section. We rely on the markers introduced to
1294 // understand what we need to dump.
1295 if (Obj->isELF() && Obj->getArch() == Triple::aarch64) {
1296 uint64_t Stride = 0;
1297
1298 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1299 DataMappingSymsAddr.end(), Index);
1300 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1301 // Switch to data.
1302 while (Index < End) {
1303 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1304 outs() << "\t";
1305 if (Index + 4 <= End) {
1306 Stride = 4;
1307 dumpBytes(Bytes.slice(Index, 4), outs());
1308 outs() << "\t.word";
1309 } else if (Index + 2 <= End) {
1310 Stride = 2;
1311 dumpBytes(Bytes.slice(Index, 2), outs());
1312 outs() << "\t.short";
1313 } else {
1314 Stride = 1;
1315 dumpBytes(Bytes.slice(Index, 1), outs());
1316 outs() << "\t.byte";
1317 }
1318 Index += Stride;
1319 outs() << "\n";
1320 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1321 TextMappingSymsAddr.end(), Index);
1322 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1323 break;
1324 }
1325 }
1326 }
1327
1328 if (Index >= End)
1329 break;
1330
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001331 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1332 SectionAddr + Index, DebugOut,
1333 CommentStream);
1334 if (Size == 0)
1335 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001336
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001337 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001338 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1339 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001340 outs() << CommentStream.str();
1341 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001342
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001343 // Try to resolve the target of a call, tail call, etc. to a specific
1344 // symbol.
1345 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1346 MIA->isConditionalBranch(Inst))) {
1347 uint64_t Target;
1348 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1349 // In a relocatable object, the target's section must reside in
1350 // the same section as the call instruction or it is accessed
1351 // through a relocation.
1352 //
1353 // In a non-relocatable object, the target may be in any section.
1354 //
1355 // N.B. We don't walk the relocations in the relocatable case yet.
1356 auto *TargetSectionSymbols = &Symbols;
1357 if (!Obj->isRelocatableObject()) {
1358 auto SectionAddress = std::upper_bound(
1359 SectionAddresses.begin(), SectionAddresses.end(), Target,
1360 [](uint64_t LHS,
1361 const std::pair<uint64_t, SectionRef> &RHS) {
1362 return LHS < RHS.first;
1363 });
1364 if (SectionAddress != SectionAddresses.begin()) {
1365 --SectionAddress;
1366 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1367 } else {
1368 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001369 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001370 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001371
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001372 // Find the first symbol in the section whose offset is less than
1373 // or equal to the target.
1374 if (TargetSectionSymbols) {
1375 auto TargetSym = std::upper_bound(
1376 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1377 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001378 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1379 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001380 });
1381 if (TargetSym != TargetSectionSymbols->begin()) {
1382 --TargetSym;
1383 uint64_t TargetAddress = std::get<0>(*TargetSym);
1384 StringRef TargetName = std::get<1>(*TargetSym);
1385 outs() << " <" << TargetName;
1386 uint64_t Disp = Target - TargetAddress;
1387 if (Disp)
1388 outs() << "+0x" << utohexstr(Disp);
1389 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001390 }
1391 }
1392 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001393 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001394 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001395
1396 // Print relocation for instruction.
1397 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001398 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001399 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001400 SmallString<16> name;
1401 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001402
1403 // If this relocation is hidden, skip it.
Owen Andersonfa3e5202011-10-25 20:35:53 +00001404 if (hidden) goto skip_print_rel;
1405
Michael J. Spencer51862b32011-10-13 22:17:18 +00001406 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001407 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001408 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001409 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001410 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001411 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001412
1413 skip_print_rel:
1414 ++rel_cur;
1415 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001416 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001417 }
1418 }
1419}
1420
Kevin Enderby98da6132015-01-20 21:47:46 +00001421void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001422 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1423 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001424 // Regular objdump doesn't print relocations in non-relocatable object
1425 // files.
1426 if (!Obj->isRelocatableObject())
1427 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001428
Colin LeMahieu77804be2015-07-29 15:45:39 +00001429 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001430 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001431 continue;
1432 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001433 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001434 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001435 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001436 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001437 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001438 SmallString<32> relocname;
1439 SmallString<32> valuestr;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001440 if (hidden)
1441 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001442 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001443 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001444 outs() << format(Fmt.data(), address) << " " << relocname << " "
1445 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001446 }
1447 outs() << "\n";
1448 }
1449}
1450
Kevin Enderby98da6132015-01-20 21:47:46 +00001451void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001452 outs() << "Sections:\n"
1453 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001454 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001455 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001456 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001457 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001458 uint64_t Address = Section.getAddress();
1459 uint64_t Size = Section.getSize();
1460 bool Text = Section.isText();
1461 bool Data = Section.isData();
1462 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001463 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001464 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001465 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1466 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001467 ++i;
1468 }
1469}
1470
Kevin Enderby98da6132015-01-20 21:47:46 +00001471void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001472 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001473 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001474 StringRef Name;
1475 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001476 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001477 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001478 uint64_t Size = Section.getSize();
1479 if (!Size)
1480 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001481
1482 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001483 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001484 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001485 ", %04" PRIx64 ")>\n",
1486 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001487 continue;
1488 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001489
Davide Italianoccd53fe2015-08-05 07:18:31 +00001490 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001491
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001492 // Dump out the content as hex and printable ascii characters.
1493 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001494 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001495 // Dump line of hex.
1496 for (std::size_t i = 0; i < 16; ++i) {
1497 if (i != 0 && i % 4 == 0)
1498 outs() << ' ';
1499 if (addr + i < end)
1500 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1501 << hexdigit(Contents[addr + i] & 0xF, true);
1502 else
1503 outs() << " ";
1504 }
1505 // Print ascii.
1506 outs() << " ";
1507 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001508 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001509 outs() << Contents[addr + i];
1510 else
1511 outs() << ".";
1512 }
1513 outs() << "\n";
1514 }
1515 }
1516}
1517
Kevin Enderby9acb1092016-05-31 20:35:34 +00001518void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1519 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001520 outs() << "SYMBOL TABLE:\n";
1521
Rui Ueyama4e39f712014-03-18 18:58:51 +00001522 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001523 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001524 return;
1525 }
1526 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001527 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1528 if (!AddressOrError)
1529 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +00001530 uint64_t Address = *AddressOrError;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001531 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1532 if (!TypeOrError)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001533 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001534 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001535 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001536 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1537 error(errorToErrorCode(SectionOrErr.takeError()));
Rafael Espindola8bab8892015-08-07 23:27:14 +00001538 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001539 StringRef Name;
1540 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1541 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001542 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001543 Expected<StringRef> NameOrErr = Symbol.getName();
1544 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001545 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1546 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001547 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001548 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001549
Rui Ueyama4e39f712014-03-18 18:58:51 +00001550 bool Global = Flags & SymbolRef::SF_Global;
1551 bool Weak = Flags & SymbolRef::SF_Weak;
1552 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001553 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001554 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001555
Rui Ueyama4e39f712014-03-18 18:58:51 +00001556 char GlobLoc = ' ';
1557 if (Type != SymbolRef::ST_Unknown)
1558 GlobLoc = Global ? 'g' : 'l';
1559 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1560 ? 'd' : ' ';
1561 char FileFunc = ' ';
1562 if (Type == SymbolRef::ST_File)
1563 FileFunc = 'f';
1564 else if (Type == SymbolRef::ST_Function)
1565 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001566
Rui Ueyama4e39f712014-03-18 18:58:51 +00001567 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1568 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001569
Rui Ueyama4e39f712014-03-18 18:58:51 +00001570 outs() << format(Fmt, Address) << " "
1571 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1572 << (Weak ? 'w' : ' ') // Weak?
1573 << ' ' // Constructor. Not supported yet.
1574 << ' ' // Warning. Not supported yet.
1575 << ' ' // Indirect reference to another symbol.
1576 << Debug // Debugging (d) or dynamic (D) symbol.
1577 << FileFunc // Name of function (F), file (f) or object (O).
1578 << ' ';
1579 if (Absolute) {
1580 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001581 } else if (Common) {
1582 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001583 } else if (Section == o->section_end()) {
1584 outs() << "*UND*";
1585 } else {
1586 if (const MachOObjectFile *MachO =
1587 dyn_cast<const MachOObjectFile>(o)) {
1588 DataRefImpl DR = Section->getRawDataRefImpl();
1589 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1590 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001591 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001592 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001593 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001594 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001595 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001596
1597 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001598 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001599 uint64_t Val =
1600 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001601 outs() << format("\t %08" PRIx64 " ", Val);
1602 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001603
Davide Italianocd2514d2015-04-30 23:08:53 +00001604 if (Hidden) {
1605 outs() << ".hidden ";
1606 }
1607 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001608 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001609 }
1610}
1611
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001612static void PrintUnwindInfo(const ObjectFile *o) {
1613 outs() << "Unwind info:\n\n";
1614
1615 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1616 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001617 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1618 printMachOUnwindInfo(MachO);
1619 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001620 // TODO: Extract DWARF dump tool to objdump.
1621 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001622 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001623 return;
1624 }
1625}
1626
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001627void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001628 outs() << "Exports trie:\n";
1629 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1630 printMachOExportsTrie(MachO);
1631 else {
1632 errs() << "This operation is only currently supported "
1633 "for Mach-O executable files.\n";
1634 return;
1635 }
1636}
1637
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001638void llvm::printRebaseTable(const ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001639 outs() << "Rebase table:\n";
1640 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1641 printMachORebaseTable(MachO);
1642 else {
1643 errs() << "This operation is only currently supported "
1644 "for Mach-O executable files.\n";
1645 return;
1646 }
1647}
1648
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001649void llvm::printBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001650 outs() << "Bind table:\n";
1651 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1652 printMachOBindTable(MachO);
1653 else {
1654 errs() << "This operation is only currently supported "
1655 "for Mach-O executable files.\n";
1656 return;
1657 }
1658}
1659
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001660void llvm::printLazyBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001661 outs() << "Lazy bind table:\n";
1662 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1663 printMachOLazyBindTable(MachO);
1664 else {
1665 errs() << "This operation is only currently supported "
1666 "for Mach-O executable files.\n";
1667 return;
1668 }
1669}
1670
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001671void llvm::printWeakBindTable(const ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001672 outs() << "Weak bind table:\n";
1673 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1674 printMachOWeakBindTable(MachO);
1675 else {
1676 errs() << "This operation is only currently supported "
1677 "for Mach-O executable files.\n";
1678 return;
1679 }
1680}
Nick Kledzikac431442014-09-12 21:34:15 +00001681
Adrian Prantl437105a2015-07-08 02:04:15 +00001682/// Dump the raw contents of the __clangast section so the output can be piped
1683/// into llvm-bcanalyzer.
1684void llvm::printRawClangAST(const ObjectFile *Obj) {
1685 if (outs().is_displayed()) {
1686 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1687 "the clang ast section.\n"
1688 "Please redirect the output to a file or another program such as "
1689 "llvm-bcanalyzer.\n";
1690 return;
1691 }
1692
1693 StringRef ClangASTSectionName("__clangast");
1694 if (isa<COFFObjectFile>(Obj)) {
1695 ClangASTSectionName = "clangast";
1696 }
1697
1698 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001699 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001700 StringRef Name;
1701 Sec.getName(Name);
1702 if (Name == ClangASTSectionName) {
1703 ClangASTSection = Sec;
1704 break;
1705 }
1706 }
1707 if (!ClangASTSection)
1708 return;
1709
1710 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001711 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001712 outs().write(ClangASTContents.data(), ClangASTContents.size());
1713}
1714
Sanjoy Das6f567a42015-06-22 18:03:02 +00001715static void printFaultMaps(const ObjectFile *Obj) {
1716 const char *FaultMapSectionName = nullptr;
1717
1718 if (isa<ELFObjectFileBase>(Obj)) {
1719 FaultMapSectionName = ".llvm_faultmaps";
1720 } else if (isa<MachOObjectFile>(Obj)) {
1721 FaultMapSectionName = "__llvm_faultmaps";
1722 } else {
1723 errs() << "This operation is only currently supported "
1724 "for ELF and Mach-O executable files.\n";
1725 return;
1726 }
1727
1728 Optional<object::SectionRef> FaultMapSection;
1729
Colin LeMahieu77804be2015-07-29 15:45:39 +00001730 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001731 StringRef Name;
1732 Sec.getName(Name);
1733 if (Name == FaultMapSectionName) {
1734 FaultMapSection = Sec;
1735 break;
1736 }
1737 }
1738
1739 outs() << "FaultMap table:\n";
1740
1741 if (!FaultMapSection.hasValue()) {
1742 outs() << "<not found>\n";
1743 return;
1744 }
1745
1746 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001747 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001748
1749 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1750 FaultMapContents.bytes_end());
1751
1752 outs() << FMP;
1753}
1754
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001755static void printPrivateFileHeaders(const ObjectFile *o) {
1756 if (o->isELF())
1757 printELFFileHeader(o);
1758 else if (o->isCOFF())
1759 printCOFFFileHeader(o);
1760 else if (o->isMachO()) {
1761 printMachOFileHeader(o);
1762 printMachOLoadCommands(o);
1763 } else
1764 report_fatal_error("Invalid/Unsupported object file format");
1765}
1766
1767static void printFirstPrivateFileHeader(const ObjectFile *o) {
Davide Italiano540e9212015-12-19 22:09:40 +00001768 if (o->isELF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001769 printELFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001770 else if (o->isCOFF())
Rui Ueyamac2bed422013-09-27 21:04:00 +00001771 printCOFFFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001772 else if (o->isMachO())
Kevin Enderbyb76d3862014-08-22 20:35:18 +00001773 printMachOFileHeader(o);
Davide Italiano540e9212015-12-19 22:09:40 +00001774 else
1775 report_fatal_error("Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001776}
1777
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001778static void DumpObject(const ObjectFile *o, const Archive *a = nullptr) {
1779 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00001780 // Avoid other output when using a raw option.
1781 if (!RawClangAST) {
1782 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001783 if (a)
1784 outs() << a->getFileName() << "(" << o->getFileName() << ")";
1785 else
1786 outs() << o->getFileName();
1787 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001788 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001789
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001790 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00001791 DisassembleObject(o, Relocations);
1792 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001793 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001794 if (SectionHeaders)
1795 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001796 if (SectionContents)
1797 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001798 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001799 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001800 if (UnwindInfo)
1801 PrintUnwindInfo(o);
Rui Ueyamac2bed422013-09-27 21:04:00 +00001802 if (PrivateHeaders)
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001803 printPrivateFileHeaders(o);
1804 if (FirstPrivateHeader)
1805 printFirstPrivateFileHeader(o);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001806 if (ExportsTrie)
1807 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00001808 if (Rebase)
1809 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001810 if (Bind)
1811 printBindTable(o);
1812 if (LazyBind)
1813 printLazyBindTable(o);
1814 if (WeakBind)
1815 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00001816 if (RawClangAST)
1817 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00001818 if (PrintFaultMaps)
1819 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001820 if (DwarfDumpType != DIDT_Null) {
1821 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*o));
1822 // Dump the complete DWARF structure.
1823 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1824 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001825}
1826
1827/// @brief Dump each object file in \a a;
1828static void DumpArchive(const Archive *a) {
Lang Hamesfc209622016-07-14 02:24:01 +00001829 Error Err;
1830 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001831 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1832 if (!ChildOrErr) {
1833 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1834 report_error(a->getFileName(), C, std::move(E));
1835 continue;
1836 }
Rafael Espindolaae460022014-06-16 16:08:36 +00001837 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001838 DumpObject(o, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001839 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001840 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001841 }
Lang Hamesfc209622016-07-14 02:24:01 +00001842 if (Err)
1843 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001844}
1845
1846/// @brief Open file and figure out how to dump it.
1847static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001848
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001849 // If we are using the Mach-O specific object file parser, then let it parse
1850 // the file and process the command line options. So the -arch flags can
1851 // be used to select specific slices, etc.
1852 if (MachOOpt) {
1853 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001854 return;
1855 }
1856
1857 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001858 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
1859 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00001860 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00001861 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001862
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001863 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001864 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00001865 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001866 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001867 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00001868 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001869}
1870
Michael J. Spencer2670c252011-01-20 06:39:06 +00001871int main(int argc, char **argv) {
1872 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00001873 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001874 PrettyStackTraceProgram X(argc, argv);
1875 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
1876
1877 // Initialize targets and assembly printers/parsers.
1878 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00001879 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00001880 llvm::InitializeAllDisassemblers();
1881
Pete Cooper28fb4fc2012-05-03 23:20:10 +00001882 // Register the target printer for --version.
1883 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
1884
Michael J. Spencer2670c252011-01-20 06:39:06 +00001885 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
1886 TripleName = Triple::normalize(TripleName);
1887
1888 ToolName = argv[0];
1889
1890 // Defaults to a.out if no filenames specified.
1891 if (InputFilenames.size() == 0)
1892 InputFilenames.push_back("a.out");
1893
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001894 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001895 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001896 if (!Disassemble
1897 && !Relocations
1898 && !SectionHeaders
1899 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001900 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00001901 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00001902 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001903 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00001904 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00001905 && !Rebase
1906 && !Bind
1907 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00001908 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00001909 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00001910 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001911 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001912 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00001913 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001914 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00001915 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001916 && !(DylibsUsed && MachOOpt)
1917 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00001918 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00001919 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00001920 && !PrintFaultMaps
1921 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00001922 cl::PrintHelpMessage();
1923 return 2;
1924 }
1925
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001926 std::for_each(InputFilenames.begin(), InputFilenames.end(),
1927 DumpInput);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001928
Davide Italianoccd53fe2015-08-05 07:18:31 +00001929 return EXIT_SUCCESS;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001930}