blob: 9d44ee4972634755b274f7cc31b5153f689665a5 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000014// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
Michael J. Spencer2670c252011-01-20 06:39:06 +000017//===----------------------------------------------------------------------===//
18
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000020#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000021#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000026#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000027#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000028#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000029#include "llvm/MC/MCDisassembler/MCDisassembler.h"
30#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000031#include "llvm/MC/MCInst.h"
32#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000033#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000034#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000035#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000036#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000037#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Object/Archive.h"
39#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000040#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000041#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000042#include "llvm/Object/MachO.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000043#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000044#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000045#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000046#include "llvm/Support/CommandLine.h"
47#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000048#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000049#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000050#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000051#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/Host.h"
53#include "llvm/Support/ManagedStatic.h"
54#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include "llvm/Support/PrettyStackTrace.h"
56#include "llvm/Support/Signals.h"
57#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000058#include "llvm/Support/TargetRegistry.h"
59#include "llvm/Support/TargetSelect.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000060#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000061#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000062#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000064#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000065#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000066#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000067
Michael J. Spencer2670c252011-01-20 06:39:06 +000068using namespace llvm;
69using namespace object;
70
Benjamin Kramer43a772e2011-09-19 17:56:04 +000071static cl::list<std::string>
72InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000073
Kevin Enderbye2297dd2015-01-07 21:02:18 +000074cl::opt<bool>
75llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000076 cl::desc("Display assembler mnemonics for the machine instructions"));
77static cl::alias
78Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000079 cl::aliasopt(Disassemble));
80
81cl::opt<bool>
82llvm::DisassembleAll("disassemble-all",
83 cl::desc("Display assembler mnemonics for the machine instructions"));
84static cl::alias
85DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000086 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000087
Kevin Enderby98da6132015-01-20 21:47:46 +000088cl::opt<bool>
89llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
Michael J. Spencerba4a3622011-10-08 00:18:30 +000090
Kevin Enderby98da6132015-01-20 21:47:46 +000091cl::opt<bool>
92llvm::SectionContents("s", cl::desc("Display the content of each section"));
Michael J. Spencer4e25c022011-10-17 17:13:22 +000093
Kevin Enderby98da6132015-01-20 21:47:46 +000094cl::opt<bool>
95llvm::SymbolTable("t", cl::desc("Display the symbol table"));
Michael J. Spencerbfa06782011-10-18 19:32:17 +000096
Kevin Enderbye2297dd2015-01-07 21:02:18 +000097cl::opt<bool>
98llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +000099
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000100cl::opt<bool>
101llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000102
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000103cl::opt<bool>
104llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000105
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000106cl::opt<bool>
107llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000108
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000109cl::opt<bool>
110llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000111
Adrian Prantl437105a2015-07-08 02:04:15 +0000112cl::opt<bool>
113llvm::RawClangAST("raw-clang-ast",
114 cl::desc("Dump the raw binary contents of the clang AST section"));
115
Nick Kledzik56ebef42014-09-16 01:41:51 +0000116static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000117MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000118static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000119MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000120
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000121cl::opt<std::string>
122llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
123 "see -version for available targets"));
124
125cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000126llvm::MCPU("mcpu",
127 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
128 cl::value_desc("cpu-name"),
129 cl::init(""));
130
131cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000132llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000133 "see -version for available targets"));
134
Kevin Enderby98da6132015-01-20 21:47:46 +0000135cl::opt<bool>
136llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
137 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000138static cl::alias
139SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
140 cl::aliasopt(SectionHeaders));
141static cl::alias
142SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
143 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000144
Colin LeMahieu77804be2015-07-29 15:45:39 +0000145cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000146llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
147 "With -macho dump segment,section"));
148cl::alias
149static FilterSectionsj("j", cl::desc("Alias for --section"),
150 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000151
Kevin Enderbyc9595622014-08-06 23:24:41 +0000152cl::list<std::string>
153llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000154 cl::CommaSeparated,
155 cl::desc("Target specific attributes"),
156 cl::value_desc("a1,+a2,-a3,..."));
157
Kevin Enderbybf246f52014-09-24 23:08:22 +0000158cl::opt<bool>
159llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
160 "instructions, do not print "
161 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000162cl::opt<bool>
163llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000164
Kevin Enderby98da6132015-01-20 21:47:46 +0000165cl::opt<bool>
166llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000167
168static cl::alias
169UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
170 cl::aliasopt(UnwindInfo));
171
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000172cl::opt<bool>
173llvm::PrivateHeaders("private-headers",
174 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000175
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000176cl::opt<bool>
177llvm::FirstPrivateHeader("private-header",
178 cl::desc("Display only the first format specific file "
179 "header"));
180
Michael J. Spencer209565db2013-01-06 03:56:49 +0000181static cl::alias
182PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
183 cl::aliasopt(PrivateHeaders));
184
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000185cl::opt<bool>
186 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000187 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000188
Sanjoy Das6f567a42015-06-22 18:03:02 +0000189cl::opt<bool> PrintFaultMaps("fault-map-section",
190 cl::desc("Display contents of faultmap section"));
191
Igor Laevsky03a670c2016-01-26 15:09:42 +0000192cl::opt<DIDumpType> llvm::DwarfDumpType(
193 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000194 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000195
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000196cl::opt<bool> PrintSource(
197 "source",
198 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000199 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000200
201cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
202 cl::aliasopt(PrintSource));
203
204cl::opt<bool> PrintLines("line-numbers",
205 cl::desc("Display source line numbers with "
206 "disassembly. Implies disassemble object"));
207
208cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
209 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000210
211cl::opt<unsigned long long>
212 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
213 cl::value_desc("address"), cl::init(0));
214cl::opt<unsigned long long>
215 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
216 cl::value_desc("address"), cl::init(UINT64_MAX));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000217static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000218
Sam Parker5fba45a2017-02-08 09:44:18 +0000219typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
220
Colin LeMahieu77804be2015-07-29 15:45:39 +0000221namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000222typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000223
224class SectionFilterIterator {
225public:
226 SectionFilterIterator(FilterPredicate P,
227 llvm::object::section_iterator const &I,
228 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000229 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000230 ScanPredicate();
231 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000232 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000233 SectionFilterIterator &operator++() {
234 ++Iterator;
235 ScanPredicate();
236 return *this;
237 }
238 bool operator!=(SectionFilterIterator const &Other) const {
239 return Iterator != Other.Iterator;
240 }
241
242private:
243 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000244 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000245 ++Iterator;
246 }
247 }
248 FilterPredicate Predicate;
249 llvm::object::section_iterator Iterator;
250 llvm::object::section_iterator End;
251};
252
253class SectionFilter {
254public:
255 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000256 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000257 SectionFilterIterator begin() {
258 return SectionFilterIterator(Predicate, Object.section_begin(),
259 Object.section_end());
260 }
261 SectionFilterIterator end() {
262 return SectionFilterIterator(Predicate, Object.section_end(),
263 Object.section_end());
264 }
265
266private:
267 FilterPredicate Predicate;
268 llvm::object::ObjectFile const &Object;
269};
270SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000271 return SectionFilter(
272 [](llvm::object::SectionRef const &S) {
273 if (FilterSections.empty())
274 return true;
275 llvm::StringRef String;
276 std::error_code error = S.getName(String);
277 if (error)
278 return false;
279 return is_contained(FilterSections, String);
280 },
281 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000282}
283}
284
Davide Italianoccd53fe2015-08-05 07:18:31 +0000285void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000286 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000287 return;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +0000288
Davide Italiano140af642015-12-25 18:16:45 +0000289 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
290 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000291 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000292}
293
Kevin Enderby42398052016-06-28 23:16:13 +0000294LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
295 errs() << ToolName << ": " << Message << ".\n";
296 errs().flush();
297 exit(1);
298}
299
Davide Italianoed9d95b2015-12-29 13:41:02 +0000300LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000301 Twine Message) {
302 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
303 exit(1);
304}
305
306LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000307 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000308 assert(EC);
309 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000310 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000311}
312
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000313LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
314 llvm::Error E) {
315 assert(E);
316 std::string Buf;
317 raw_string_ostream OS(Buf);
318 logAllUnhandledErrors(std::move(E), OS, "");
319 OS.flush();
Kevin Enderbyb34e3a12016-05-05 17:43:35 +0000320 errs() << ToolName << ": '" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000321 exit(1);
322}
323
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000324LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
325 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000326 llvm::Error E,
327 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000328 assert(E);
329 errs() << ToolName << ": ";
330 if (ArchiveName != "")
331 errs() << ArchiveName << "(" << FileName << ")";
332 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000333 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000334 if (!ArchitectureName.empty())
335 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000336 std::string Buf;
337 raw_string_ostream OS(Buf);
338 logAllUnhandledErrors(std::move(E), OS, "");
339 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000340 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000341 exit(1);
342}
343
344LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
345 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000346 llvm::Error E,
347 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000348 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000349 // TODO: if we have a error getting the name then it would be nice to print
350 // the index of which archive member this is and or its offset in the
351 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000352 if (!NameOrErr) {
353 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000354 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000355 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000356 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
357 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000358}
359
Craig Toppere6cb63e2014-04-25 04:24:47 +0000360static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000361 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000362 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000363 if (TripleName.empty()) {
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000364 if (Obj) {
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000365 TheTriple = Obj->makeTriple();
Ahmed Bougachaad1084d2013-05-24 00:39:57 +0000366 }
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000367 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000368 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000369
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000370 // Use the triple, but also try to combine with ARM build attributes.
371 if (Obj) {
372 auto Arch = Obj->getArch();
373 if (Arch == Triple::arm || Arch == Triple::armeb) {
374 Obj->setARMSubArch(TheTriple);
375 }
376 }
377 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000378
379 // Get the target specific parser.
380 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000381 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
382 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000383 if (!TheTarget) {
384 if (Obj)
385 report_error(Obj->getFileName(), "can't find target: " + Error);
386 else
387 error("can't find target: " + Error);
388 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000389
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000390 // Update the triple name and return the found target.
391 TripleName = TheTriple.getTriple();
392 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000393}
394
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000395bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
Rafael Espindola704cd842015-07-06 15:47:43 +0000396 return a.getOffset() < b.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000397}
398
Colin LeMahieufb76b002015-05-28 19:07:14 +0000399namespace {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000400class SourcePrinter {
401protected:
402 DILineInfo OldLineInfo;
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000403 const ObjectFile *Obj = nullptr;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000404 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
405 // File name to file contents of source
406 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
407 // Mark the line endings of the cached source
408 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
409
410private:
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000411 bool cacheSource(const std::string& File);
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000412
413public:
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000414 SourcePrinter() = default;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000415 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
416 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
417 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
418 DefaultArch);
419 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
420 }
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000421 virtual ~SourcePrinter() = default;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000422 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
423 StringRef Delimiter = "; ");
424};
425
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000426bool SourcePrinter::cacheSource(const std::string& File) {
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000427 auto BufferOrError = MemoryBuffer::getFile(File);
428 if (!BufferOrError)
429 return false;
430 // Chomp the file to get lines
431 size_t BufferSize = (*BufferOrError)->getBufferSize();
432 const char *BufferStart = (*BufferOrError)->getBufferStart();
433 for (const char *Start = BufferStart, *End = BufferStart;
434 End < BufferStart + BufferSize; End++)
435 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
436 (*End == '\r' && *(End + 1) == '\n')) {
437 LineCache[File].push_back(StringRef(Start, End - Start));
438 if (*End == '\r')
439 End++;
440 Start = End + 1;
441 }
442 SourceCache[File] = std::move(*BufferOrError);
443 return true;
444}
445
446void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
447 StringRef Delimiter) {
448 if (!Symbolizer)
449 return;
450 DILineInfo LineInfo = DILineInfo();
451 auto ExpectecLineInfo =
452 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
453 if (!ExpectecLineInfo)
454 consumeError(ExpectecLineInfo.takeError());
455 else
456 LineInfo = *ExpectecLineInfo;
457
458 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
459 LineInfo.Line == 0)
460 return;
461
462 if (PrintLines)
463 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
464 if (PrintSource) {
465 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
466 if (!cacheSource(LineInfo.FileName))
467 return;
468 auto FileBuffer = SourceCache.find(LineInfo.FileName);
469 if (FileBuffer != SourceCache.end()) {
470 auto LineBuffer = LineCache.find(LineInfo.FileName);
Petr Hosek86611a02017-04-25 18:56:33 +0000471 if (LineBuffer != LineCache.end()) {
472 if (LineInfo.Line > LineBuffer->second.size())
473 return;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000474 // Vector begins at 0, line numbers are non-zero
475 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
476 << "\n";
Petr Hosek86611a02017-04-25 18:56:33 +0000477 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000478 }
479 }
480 OldLineInfo = LineInfo;
481}
482
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000483static bool isArmElf(const ObjectFile *Obj) {
484 return (Obj->isELF() &&
485 (Obj->getArch() == Triple::aarch64 ||
486 Obj->getArch() == Triple::aarch64_be ||
487 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
488 Obj->getArch() == Triple::thumb ||
489 Obj->getArch() == Triple::thumbeb));
490}
491
Colin LeMahieufb76b002015-05-28 19:07:14 +0000492class PrettyPrinter {
493public:
Vlad Tsyrklevichf1620132017-09-12 02:27:39 +0000494 virtual ~PrettyPrinter() = default;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000495 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Colin LeMahieufb76b002015-05-28 19:07:14 +0000496 ArrayRef<uint8_t> Bytes, uint64_t Address,
497 raw_ostream &OS, StringRef Annot,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000498 MCSubtargetInfo const &STI, SourcePrinter *SP) {
499 if (SP && (PrintSource || PrintLines))
500 SP->printSourceLine(OS, Address);
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000501 if (!NoLeadingAddr)
502 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000503 if (!NoShowRawInsn) {
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000504 OS << "\t";
505 dumpBytes(Bytes, OS);
Colin LeMahieufb76b002015-05-28 19:07:14 +0000506 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000507 if (MI)
508 IP.printInst(MI, OS, "", STI);
509 else
510 OS << " <unknown>";
Colin LeMahieufb76b002015-05-28 19:07:14 +0000511 }
512};
513PrettyPrinter PrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000514class HexagonPrettyPrinter : public PrettyPrinter {
515public:
516 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
517 raw_ostream &OS) {
518 uint32_t opcode =
519 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000520 if (!NoLeadingAddr)
521 OS << format("%8" PRIx64 ":", Address);
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000522 if (!NoShowRawInsn) {
523 OS << "\t";
524 dumpBytes(Bytes.slice(0, 4), OS);
525 OS << format("%08" PRIx32, opcode);
526 }
527 }
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000528 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
529 uint64_t Address, raw_ostream &OS, StringRef Annot,
530 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000531 if (SP && (PrintSource || PrintLines))
532 SP->printSourceLine(OS, Address, "");
Colin LeMahieu307a83d2016-03-18 16:26:48 +0000533 if (!MI) {
534 printLead(Bytes, Address, OS);
535 OS << " <unknown>";
536 return;
537 }
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000538 std::string Buffer;
539 {
540 raw_string_ostream TempStream(Buffer);
541 IP.printInst(MI, TempStream, "", STI);
542 }
543 StringRef Contents(Buffer);
544 // Split off bundle attributes
545 auto PacketBundle = Contents.rsplit('\n');
546 // Split off first instruction from the rest
547 auto HeadTail = PacketBundle.first.split('\n');
548 auto Preamble = " { ";
549 auto Separator = "";
550 while(!HeadTail.first.empty()) {
551 OS << Separator;
552 Separator = "\n";
Hemant Kulkarnie77a0a92016-08-18 21:50:13 +0000553 if (SP && (PrintSource || PrintLines))
554 SP->printSourceLine(OS, Address, "");
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000555 printLead(Bytes, Address, OS);
556 OS << Preamble;
557 Preamble = " ";
558 StringRef Inst;
559 auto Duplex = HeadTail.first.split('\v');
560 if(!Duplex.second.empty()){
561 OS << Duplex.first;
562 OS << "; ";
563 Inst = Duplex.second;
564 }
565 else
566 Inst = HeadTail.first;
567 OS << Inst;
568 Bytes = Bytes.slice(4);
569 Address += 4;
570 HeadTail = HeadTail.second.split('\n');
571 }
572 OS << " } " << PacketBundle.second;
573 }
574};
575HexagonPrettyPrinter HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000576
577class AMDGCNPrettyPrinter : public PrettyPrinter {
578public:
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000579 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
580 uint64_t Address, raw_ostream &OS, StringRef Annot,
581 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
Konstantin Zhuravlyovf895b202017-03-07 20:17:11 +0000582 if (SP && (PrintSource || PrintLines))
583 SP->printSourceLine(OS, Address);
584
Matt Arsenault87d80db2016-04-22 21:23:41 +0000585 if (!MI) {
586 OS << " <unknown>";
587 return;
588 }
589
Valery Pykhtinde048052016-04-07 07:24:01 +0000590 SmallString<40> InstStr;
591 raw_svector_ostream IS(InstStr);
592
593 IP.printInst(MI, IS, "", STI);
594
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000595 OS << left_justify(IS.str(), 60) << format("// %012" PRIX64 ": ", Address);
Valery Pykhtinde048052016-04-07 07:24:01 +0000596 typedef support::ulittle32_t U32;
597 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
598 Bytes.size() / sizeof(U32)))
599 // D should be explicitly casted to uint32_t here as it is passed
600 // by format to snprintf as vararg.
Valery Pykhtin8e79f5b2016-04-07 08:38:20 +0000601 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
Valery Pykhtinde048052016-04-07 07:24:01 +0000602
603 if (!Annot.empty())
604 OS << "// " << Annot;
605 }
606};
607AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
608
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000609class BPFPrettyPrinter : public PrettyPrinter {
610public:
611 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
612 uint64_t Address, raw_ostream &OS, StringRef Annot,
613 MCSubtargetInfo const &STI, SourcePrinter *SP) override {
614 if (SP && (PrintSource || PrintLines))
615 SP->printSourceLine(OS, Address);
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000616 if (!NoLeadingAddr)
617 OS << format("%8" PRId64 ":", Address / 8);
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000618 if (!NoShowRawInsn) {
619 OS << "\t";
620 dumpBytes(Bytes, OS);
621 }
622 if (MI)
623 IP.printInst(MI, OS, "", STI);
624 else
625 OS << " <unknown>";
626 }
627};
628BPFPrettyPrinter BPFPrettyPrinterInst;
629
Colin LeMahieu35436a22015-05-29 14:48:25 +0000630PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000631 switch(Triple.getArch()) {
632 default:
633 return PrettyPrinterInst;
634 case Triple::hexagon:
635 return HexagonPrettyPrinterInst;
Valery Pykhtinde048052016-04-07 07:24:01 +0000636 case Triple::amdgcn:
637 return AMDGCNPrettyPrinterInst;
Alexei Starovoitov3b9efca2016-12-13 19:07:08 +0000638 case Triple::bpfel:
639 case Triple::bpfeb:
640 return BPFPrettyPrinterInst;
Colin LeMahieu68d967d2015-05-29 14:44:13 +0000641 }
Colin LeMahieufb76b002015-05-28 19:07:14 +0000642}
643}
644
Rafael Espindola37070a52015-06-03 04:48:06 +0000645template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000646static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000647 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000648 SmallVectorImpl<char> &Result) {
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000649 DataRefImpl Rel = RelRef.getRawDataRefImpl();
650
Rafael Espindola37070a52015-06-03 04:48:06 +0000651 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
652 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000653 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
654
Rafael Espindola37070a52015-06-03 04:48:06 +0000655 const ELFFile<ELFT> &EF = *Obj->getELFFile();
656
Davide Italiano6cf09262016-11-16 05:10:28 +0000657 auto SecOrErr = EF.getSection(Rel.d.a);
658 if (!SecOrErr)
659 return errorToErrorCode(SecOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000660 const Elf_Shdr *Sec = *SecOrErr;
Davide Italiano6cf09262016-11-16 05:10:28 +0000661 auto SymTabOrErr = EF.getSection(Sec->sh_link);
662 if (!SymTabOrErr)
663 return errorToErrorCode(SymTabOrErr.takeError());
Rafael Espindola6def3042015-07-01 12:56:27 +0000664 const Elf_Shdr *SymTab = *SymTabOrErr;
Rafael Espindola719dc7c2015-06-29 12:38:31 +0000665 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||
666 SymTab->sh_type == ELF::SHT_DYNSYM);
Davide Italiano6cf09262016-11-16 05:10:28 +0000667 auto StrTabSec = EF.getSection(SymTab->sh_link);
668 if (!StrTabSec)
669 return errorToErrorCode(StrTabSec.takeError());
670 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
671 if (!StrTabOrErr)
672 return errorToErrorCode(StrTabOrErr.takeError());
Rafael Espindola6a1bfb22015-06-29 14:39:25 +0000673 StringRef StrTab = *StrTabOrErr;
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000674 uint8_t type = RelRef.getType();
Rafael Espindola37070a52015-06-03 04:48:06 +0000675 StringRef res;
676 int64_t addend = 0;
Rafael Espindola6def3042015-07-01 12:56:27 +0000677 switch (Sec->sh_type) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000678 default:
679 return object_error::parse_failed;
680 case ELF::SHT_REL: {
Rafael Espindola37070a52015-06-03 04:48:06 +0000681 // TODO: Read implicit addend from section data.
682 break;
683 }
684 case ELF::SHT_RELA: {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000685 const Elf_Rela *ERela = Obj->getRela(Rel);
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000686 addend = ERela->r_addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000687 break;
688 }
689 }
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000690 symbol_iterator SI = RelRef.getSymbol();
691 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000692 StringRef Target;
Rafael Espindola75d5b542015-06-03 05:14:22 +0000693 if (symb->getType() == ELF::STT_SECTION) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000694 Expected<section_iterator> SymSI = SI->getSection();
695 if (!SymSI)
696 return errorToErrorCode(SymSI.takeError());
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000697 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
Davide Italiano6cf09262016-11-16 05:10:28 +0000698 auto SecName = EF.getSectionName(SymSec);
699 if (!SecName)
700 return errorToErrorCode(SecName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000701 Target = *SecName;
702 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000703 Expected<StringRef> SymName = symb->getName(StrTab);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000704 if (!SymName)
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000705 return errorToErrorCode(SymName.takeError());
Rafael Espindola75d5b542015-06-03 05:14:22 +0000706 Target = *SymName;
707 }
Rafael Espindola37070a52015-06-03 04:48:06 +0000708 switch (EF.getHeader()->e_machine) {
709 case ELF::EM_X86_64:
710 switch (type) {
711 case ELF::R_X86_64_PC8:
712 case ELF::R_X86_64_PC16:
713 case ELF::R_X86_64_PC32: {
714 std::string fmtbuf;
715 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000716 fmt << Target << (addend < 0 ? "" : "+") << addend << "-P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000717 fmt.flush();
718 Result.append(fmtbuf.begin(), fmtbuf.end());
719 } break;
720 case ELF::R_X86_64_8:
721 case ELF::R_X86_64_16:
722 case ELF::R_X86_64_32:
723 case ELF::R_X86_64_32S:
724 case ELF::R_X86_64_64: {
725 std::string fmtbuf;
726 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000727 fmt << Target << (addend < 0 ? "" : "+") << addend;
Rafael Espindola37070a52015-06-03 04:48:06 +0000728 fmt.flush();
729 Result.append(fmtbuf.begin(), fmtbuf.end());
730 } break;
731 default:
732 res = "Unknown";
733 }
734 break;
Jacques Pienaarea9f25a2016-03-01 21:21:42 +0000735 case ELF::EM_LANAI:
Dylan McKay11661122016-09-28 13:15:17 +0000736 case ELF::EM_AVR:
Rafael Espindola37070a52015-06-03 04:48:06 +0000737 case ELF::EM_AARCH64: {
738 std::string fmtbuf;
739 raw_string_ostream fmt(fmtbuf);
Rafael Espindola75d5b542015-06-03 05:14:22 +0000740 fmt << Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000741 if (addend != 0)
742 fmt << (addend < 0 ? "" : "+") << addend;
743 fmt.flush();
744 Result.append(fmtbuf.begin(), fmtbuf.end());
745 break;
746 }
747 case ELF::EM_386:
Michael Kupersteina3b79dd2015-11-04 11:21:50 +0000748 case ELF::EM_IAMCU:
Rafael Espindola37070a52015-06-03 04:48:06 +0000749 case ELF::EM_ARM:
750 case ELF::EM_HEXAGON:
751 case ELF::EM_MIPS:
Alexei Starovoitovcfb51f52016-07-15 22:27:55 +0000752 case ELF::EM_BPF:
Alex Bradbury1524f622016-11-01 16:59:37 +0000753 case ELF::EM_RISCV:
Rafael Espindola75d5b542015-06-03 05:14:22 +0000754 res = Target;
Rafael Espindola37070a52015-06-03 04:48:06 +0000755 break;
Dan Gohman46350172016-01-12 20:56:01 +0000756 case ELF::EM_WEBASSEMBLY:
757 switch (type) {
758 case ELF::R_WEBASSEMBLY_DATA: {
759 std::string fmtbuf;
760 raw_string_ostream fmt(fmtbuf);
761 fmt << Target << (addend < 0 ? "" : "+") << addend;
762 fmt.flush();
763 Result.append(fmtbuf.begin(), fmtbuf.end());
764 break;
765 }
766 case ELF::R_WEBASSEMBLY_FUNCTION:
767 res = Target;
768 break;
769 default:
770 res = "Unknown";
771 }
772 break;
Rafael Espindola37070a52015-06-03 04:48:06 +0000773 default:
774 res = "Unknown";
775 }
776 if (Result.empty())
777 Result.append(res.begin(), res.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000778 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000779}
780
781static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000782 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000783 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000784 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
785 return getRelocationValueString(ELF32LE, Rel, Result);
786 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
787 return getRelocationValueString(ELF64LE, Rel, Result);
788 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
789 return getRelocationValueString(ELF32BE, Rel, Result);
790 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
791 return getRelocationValueString(ELF64BE, Rel, Result);
792}
793
794static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
795 const RelocationRef &Rel,
796 SmallVectorImpl<char> &Result) {
797 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000798 Expected<StringRef> SymNameOrErr = SymI->getName();
799 if (!SymNameOrErr)
800 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000801 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000802 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000803 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000804}
805
806static void printRelocationTargetName(const MachOObjectFile *O,
807 const MachO::any_relocation_info &RE,
808 raw_string_ostream &fmt) {
809 bool IsScattered = O->isRelocationScattered(RE);
810
811 // Target of a scattered relocation is an address. In the interest of
812 // generating pretty output, scan through the symbol table looking for a
813 // symbol that aligns with that address. If we find one, print it.
814 // Otherwise, we just print the hex address of the target.
815 if (IsScattered) {
816 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
817
818 for (const SymbolRef &Symbol : O->symbols()) {
819 std::error_code ec;
Kevin Enderby931cb652016-06-24 18:24:42 +0000820 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000821 if (!Addr)
822 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000823 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000824 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000825 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000826 if (!Name)
827 report_error(O->getFileName(), Name.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000828 fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000829 return;
830 }
831
832 // If we couldn't find a symbol that this relocation refers to, try
833 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000834 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000835 std::error_code ec;
836
837 StringRef Name;
838 uint64_t Addr = Section.getAddress();
839 if (Addr != Val)
840 continue;
841 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000842 report_error(O->getFileName(), ec);
Rafael Espindola37070a52015-06-03 04:48:06 +0000843 fmt << Name;
844 return;
845 }
846
847 fmt << format("0x%x", Val);
848 return;
849 }
850
851 StringRef S;
852 bool isExtern = O->getPlainRelocationExternal(RE);
853 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
854
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000855 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
Simon Dardis38867052017-08-07 12:29:38 +0000856 fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000857 return;
858 } else if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000859 symbol_iterator SI = O->symbol_begin();
860 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000861 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000862 if (!SOrErr)
863 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000864 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000865 } else {
866 section_iterator SI = O->section_begin();
867 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000868 if (Val == 0) {
869 fmt << "0 (?,?)";
870 return;
871 }
872 uint32_t i = Val - 1;
873 while (i != 0 && SI != O->section_end()) {
874 i--;
875 advance(SI, 1);
876 }
877 if (SI == O->section_end())
878 fmt << Val << " (?,?)";
879 else
880 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000881 }
882
883 fmt << S;
884}
885
Sam Clegg4df5d762017-06-27 20:40:53 +0000886static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
887 const RelocationRef &RelRef,
888 SmallVectorImpl<char> &Result) {
889 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
890 std::string fmtbuf;
891 raw_string_ostream fmt(fmtbuf);
892 fmt << Rel.Index << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
893 fmt.flush();
894 Result.append(fmtbuf.begin(), fmtbuf.end());
895 return std::error_code();
896}
897
Rafael Espindola37070a52015-06-03 04:48:06 +0000898static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
899 const RelocationRef &RelRef,
900 SmallVectorImpl<char> &Result) {
901 DataRefImpl Rel = RelRef.getRawDataRefImpl();
902 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
903
904 unsigned Arch = Obj->getArch();
905
906 std::string fmtbuf;
907 raw_string_ostream fmt(fmtbuf);
908 unsigned Type = Obj->getAnyRelocationType(RE);
909 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
910
911 // Determine any addends that should be displayed with the relocation.
912 // These require decoding the relocation type, which is triple-specific.
913
914 // X86_64 has entirely custom relocation types.
915 if (Arch == Triple::x86_64) {
916 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
917
918 switch (Type) {
919 case MachO::X86_64_RELOC_GOT_LOAD:
920 case MachO::X86_64_RELOC_GOT: {
921 printRelocationTargetName(Obj, RE, fmt);
922 fmt << "@GOT";
923 if (isPCRel)
924 fmt << "PCREL";
925 break;
926 }
927 case MachO::X86_64_RELOC_SUBTRACTOR: {
928 DataRefImpl RelNext = Rel;
929 Obj->moveRelocationNext(RelNext);
930 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
931
932 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
933 // X86_64_RELOC_UNSIGNED.
934 // NOTE: Scattered relocations don't exist on x86_64.
935 unsigned RType = Obj->getAnyRelocationType(RENext);
936 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000937 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
938 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000939
940 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
941 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
942 printRelocationTargetName(Obj, RENext, fmt);
943 fmt << "-";
944 printRelocationTargetName(Obj, RE, fmt);
945 break;
946 }
947 case MachO::X86_64_RELOC_TLV:
948 printRelocationTargetName(Obj, RE, fmt);
949 fmt << "@TLV";
950 if (isPCRel)
951 fmt << "P";
952 break;
953 case MachO::X86_64_RELOC_SIGNED_1:
954 printRelocationTargetName(Obj, RE, fmt);
955 fmt << "-1";
956 break;
957 case MachO::X86_64_RELOC_SIGNED_2:
958 printRelocationTargetName(Obj, RE, fmt);
959 fmt << "-2";
960 break;
961 case MachO::X86_64_RELOC_SIGNED_4:
962 printRelocationTargetName(Obj, RE, fmt);
963 fmt << "-4";
964 break;
965 default:
966 printRelocationTargetName(Obj, RE, fmt);
967 break;
968 }
969 // X86 and ARM share some relocation types in common.
970 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
971 Arch == Triple::ppc) {
972 // Generic relocation types...
973 switch (Type) {
974 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000975 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000976 case MachO::GENERIC_RELOC_SECTDIFF: {
977 DataRefImpl RelNext = Rel;
978 Obj->moveRelocationNext(RelNext);
979 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
980
981 // X86 sect diff's must be followed by a relocation of type
982 // GENERIC_RELOC_PAIR.
983 unsigned RType = Obj->getAnyRelocationType(RENext);
984
985 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000986 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
987 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000988
989 printRelocationTargetName(Obj, RE, fmt);
990 fmt << "-";
991 printRelocationTargetName(Obj, RENext, fmt);
992 break;
993 }
994 }
995
996 if (Arch == Triple::x86 || Arch == Triple::ppc) {
997 switch (Type) {
998 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
999 DataRefImpl RelNext = Rel;
1000 Obj->moveRelocationNext(RelNext);
1001 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1002
1003 // X86 sect diff's must be followed by a relocation of type
1004 // GENERIC_RELOC_PAIR.
1005 unsigned RType = Obj->getAnyRelocationType(RENext);
1006 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001007 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
1008 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +00001009
1010 printRelocationTargetName(Obj, RE, fmt);
1011 fmt << "-";
1012 printRelocationTargetName(Obj, RENext, fmt);
1013 break;
1014 }
1015 case MachO::GENERIC_RELOC_TLV: {
1016 printRelocationTargetName(Obj, RE, fmt);
1017 fmt << "@TLV";
1018 if (IsPCRel)
1019 fmt << "P";
1020 break;
1021 }
1022 default:
1023 printRelocationTargetName(Obj, RE, fmt);
1024 }
1025 } else { // ARM-specific relocations
1026 switch (Type) {
1027 case MachO::ARM_RELOC_HALF:
1028 case MachO::ARM_RELOC_HALF_SECTDIFF: {
1029 // Half relocations steal a bit from the length field to encode
1030 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +00001031 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +00001032
1033 if (isUpper)
1034 fmt << ":upper16:(";
1035 else
1036 fmt << ":lower16:(";
1037 printRelocationTargetName(Obj, RE, fmt);
1038
1039 DataRefImpl RelNext = Rel;
1040 Obj->moveRelocationNext(RelNext);
1041 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
1042
1043 // ARM half relocs must be followed by a relocation of type
1044 // ARM_RELOC_PAIR.
1045 unsigned RType = Obj->getAnyRelocationType(RENext);
1046 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001047 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
1048 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +00001049
1050 // NOTE: The half of the target virtual address is stashed in the
1051 // address field of the secondary relocation, but we can't reverse
1052 // engineer the constant offset from it without decoding the movw/movt
1053 // instruction to find the other half in its immediate field.
1054
1055 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
1056 // symbol/section pointer of the follow-on relocation.
1057 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1058 fmt << "-";
1059 printRelocationTargetName(Obj, RENext, fmt);
1060 }
1061
1062 fmt << ")";
1063 break;
1064 }
1065 default: { printRelocationTargetName(Obj, RE, fmt); }
1066 }
1067 }
1068 } else
1069 printRelocationTargetName(Obj, RE, fmt);
1070
1071 fmt.flush();
1072 Result.append(fmtbuf.begin(), fmtbuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +00001073 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +00001074}
1075
1076static std::error_code getRelocationValueString(const RelocationRef &Rel,
1077 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +00001078 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +00001079 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
1080 return getRelocationValueString(ELF, Rel, Result);
1081 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
1082 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +00001083 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
1084 return getRelocationValueString(Wasm, Rel, Result);
1085 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
1086 return getRelocationValueString(MachO, Rel, Result);
1087 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +00001088}
1089
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001090/// @brief Indicates whether this relocation should hidden when listing
1091/// relocations, usually because it is the trailing part of a multipart
1092/// relocation that will be printed as part of the leading relocation.
1093static bool getHidden(RelocationRef RelRef) {
1094 const ObjectFile *Obj = RelRef.getObject();
1095 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
1096 if (!MachO)
1097 return false;
1098
1099 unsigned Arch = MachO->getArch();
1100 DataRefImpl Rel = RelRef.getRawDataRefImpl();
1101 uint64_t Type = MachO->getRelocationType(Rel);
1102
1103 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
1104 // is always hidden.
1105 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
1106 if (Type == MachO::GENERIC_RELOC_PAIR)
1107 return true;
1108 } else if (Arch == Triple::x86_64) {
1109 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
1110 // an X86_64_RELOC_SUBTRACTOR.
1111 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
1112 DataRefImpl RelPrev = Rel;
1113 RelPrev.d.a--;
1114 uint64_t PrevType = MachO->getRelocationType(RelPrev);
1115 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
1116 return true;
1117 }
1118 }
1119
1120 return false;
1121}
1122
Sam Koltonc05d7782016-08-17 10:17:57 +00001123static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1124 assert(Obj->isELF());
1125 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1126 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1127 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1128 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1129 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1130 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1131 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1132 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1133 llvm_unreachable("Unsupported binary format");
1134}
1135
Sam Parker5fba45a2017-02-08 09:44:18 +00001136template <class ELFT> static void
1137addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1138 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1139 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1140 uint8_t SymbolType = Symbol.getELFType();
1141 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1142 continue;
1143
1144 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1145 if (!AddressOrErr)
1146 report_error(Obj->getFileName(), AddressOrErr.takeError());
1147 uint64_t Address = *AddressOrErr;
1148
1149 Expected<StringRef> Name = Symbol.getName();
1150 if (!Name)
1151 report_error(Obj->getFileName(), Name.takeError());
1152 if (Name->empty())
1153 continue;
1154
1155 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1156 if (!SectionOrErr)
1157 report_error(Obj->getFileName(), SectionOrErr.takeError());
1158 section_iterator SecI = *SectionOrErr;
1159 if (SecI == Obj->section_end())
1160 continue;
1161
1162 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1163 }
1164}
1165
1166static void
1167addDynamicElfSymbols(const ObjectFile *Obj,
1168 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1169 assert(Obj->isELF());
1170 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1171 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1172 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1173 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1174 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1175 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1176 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1177 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1178 else
1179 llvm_unreachable("Unsupported binary format");
1180}
1181
Michael J. Spencer51862b32011-10-13 22:17:18 +00001182static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001183 if (StartAddress > StopAddress)
1184 error("Start address should be less than stop address");
1185
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001186 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001187
Jack Carter551efd72012-08-28 19:24:49 +00001188 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001189 SubtargetFeatures Features = Obj->getFeatures();
Jack Carter551efd72012-08-28 19:24:49 +00001190 if (MAttrs.size()) {
Jack Carter551efd72012-08-28 19:24:49 +00001191 for (unsigned i = 0; i != MAttrs.size(); ++i)
1192 Features.AddFeature(MAttrs[i]);
Jack Carter551efd72012-08-28 19:24:49 +00001193 }
1194
Ahmed Charles56440fd2014-03-06 05:51:42 +00001195 std::unique_ptr<const MCRegisterInfo> MRI(
1196 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001197 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001198 report_error(Obj->getFileName(), "no register info for target " +
1199 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001200
1201 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001202 std::unique_ptr<const MCAsmInfo> AsmInfo(
1203 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001204 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001205 report_error(Obj->getFileName(), "no assembly info for target " +
1206 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001207 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001208 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001209 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001210 report_error(Obj->getFileName(), "no subtarget info for target " +
1211 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001212 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001213 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001214 report_error(Obj->getFileName(), "no instruction info for target " +
1215 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001216 MCObjectFileInfo MOFI;
1217 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1218 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001219 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001220
1221 std::unique_ptr<MCDisassembler> DisAsm(
1222 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001223 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001224 report_error(Obj->getFileName(), "no disassembler for target " +
1225 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001226
Ahmed Charles56440fd2014-03-06 05:51:42 +00001227 std::unique_ptr<const MCInstrAnalysis> MIA(
1228 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001229
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001230 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001231 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1232 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001233 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001234 report_error(Obj->getFileName(), "no instruction printer for target " +
1235 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001236 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001237 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001238
Greg Fitzgerald18432272014-03-20 22:55:15 +00001239 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1240 "\t\t\t%08" PRIx64 ": ";
1241
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001242 SourcePrinter SP(Obj, TheTarget->getName());
1243
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001244 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1245 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001246 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001247 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001248 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001249 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001250 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001251 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001252 }
1253
David Majnemer81afca62015-07-07 22:06:59 +00001254 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001255 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001256 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1257 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001258 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001259 if (!AddressOrErr)
1260 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001261 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001262
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001263 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001264 if (!Name)
1265 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001266 if (Name->empty())
1267 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001268
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001269 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001270 if (!SectionOrErr)
1271 report_error(Obj->getFileName(), SectionOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001272 section_iterator SecI = *SectionOrErr;
1273 if (SecI == Obj->section_end())
1274 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001275
Sam Koltonc05d7782016-08-17 10:17:57 +00001276 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001277 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001278 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001279
Sam Koltonc05d7782016-08-17 10:17:57 +00001280 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1281
David Majnemer81afca62015-07-07 22:06:59 +00001282 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001283 if (AllSymbols.empty() && Obj->isELF())
1284 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001285
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001286 // Create a mapping from virtual address to section.
1287 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1288 for (SectionRef Sec : Obj->sections())
1289 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1290 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1291
1292 // Linked executables (.exe and .dll files) typically don't include a real
1293 // symbol table but they might contain an export table.
1294 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1295 for (const auto &ExportEntry : COFFObj->export_directories()) {
1296 StringRef Name;
1297 error(ExportEntry.getSymbolName(Name));
1298 if (Name.empty())
1299 continue;
1300 uint32_t RVA;
1301 error(ExportEntry.getExportRVA(RVA));
1302
1303 uint64_t VA = COFFObj->getImageBase() + RVA;
1304 auto Sec = std::upper_bound(
1305 SectionAddresses.begin(), SectionAddresses.end(), VA,
1306 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1307 return LHS < RHS.first;
1308 });
1309 if (Sec != SectionAddresses.begin())
1310 --Sec;
1311 else
1312 Sec = SectionAddresses.end();
1313
1314 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001315 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001316 }
1317 }
1318
1319 // Sort all the symbols, this allows us to use a simple binary search to find
1320 // a symbol near an address.
1321 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1322 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1323
Colin LeMahieu77804be2015-07-29 15:45:39 +00001324 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001325 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001326 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001327
Rafael Espindola80291272014-10-08 15:28:58 +00001328 uint64_t SectionAddr = Section.getAddress();
1329 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001330 if (!SectSize)
1331 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001332
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001333 // Get the list of all the symbols in this section.
1334 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001335 std::vector<uint64_t> DataMappingSymsAddr;
1336 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001337 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001338 for (const auto &Symb : Symbols) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001339 uint64_t Address = std::get<0>(Symb);
1340 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001341 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001342 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001343 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001344 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001345 if (Name.startswith("$a"))
1346 TextMappingSymsAddr.push_back(Address - SectionAddr);
1347 if (Name.startswith("$t"))
1348 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001349 }
1350 }
1351
Davide Italianof0706882015-10-01 21:57:09 +00001352 std::sort(DataMappingSymsAddr.begin(), DataMappingSymsAddr.end());
1353 std::sort(TextMappingSymsAddr.begin(), TextMappingSymsAddr.end());
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001354
Sam Kolton3381d7a2016-10-06 13:46:08 +00001355 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1356 // AMDGPU disassembler uses symbolizer for printing labels
1357 std::unique_ptr<MCRelocationInfo> RelInfo(
1358 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1359 if (RelInfo) {
1360 std::unique_ptr<MCSymbolizer> Symbolizer(
1361 TheTarget->createMCSymbolizer(
1362 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1363 DisAsm->setSymbolizer(std::move(Symbolizer));
1364 }
1365 }
1366
Michael J. Spencer51862b32011-10-13 22:17:18 +00001367 // Make a list of all the relocations for this section.
1368 std::vector<RelocationRef> Rels;
1369 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001370 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1371 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1372 Rels.push_back(Reloc);
1373 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001374 }
1375 }
1376
1377 // Sort relocations by address.
1378 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
1379
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001380 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001381 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001382 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001383 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001384 }
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001385 StringRef name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001386 error(Section.getName(name));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001387
1388 if ((SectionAddr <= StopAddress) &&
1389 (SectionAddr + SectSize) >= StartAddress) {
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001390 outs() << "Disassembly of section ";
1391 if (!SegmentName.empty())
1392 outs() << SegmentName << ",";
1393 outs() << name << ':';
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001394 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001395
Rafael Espindola7884c952015-06-04 15:01:05 +00001396 // If the section has no symbol at the start, just insert a dummy one.
Sam Koltonc05d7782016-08-17 10:17:57 +00001397 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001398 Symbols.insert(Symbols.begin(),
1399 std::make_tuple(SectionAddr, name, Section.isText()
1400 ? ELF::STT_FUNC
1401 : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001402 }
Alp Tokere69170a2014-06-26 22:52:05 +00001403
1404 SmallString<40> Comments;
1405 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001406
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001407 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001408 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001409 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1410 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001411
Michael J. Spencer2670c252011-01-20 06:39:06 +00001412 uint64_t Size;
1413 uint64_t Index;
1414
Michael J. Spencer51862b32011-10-13 22:17:18 +00001415 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1416 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001417 // Disassemble symbol by symbol.
1418 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001419 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001420 // The end is either the section end or the beginning of the next
1421 // symbol.
1422 uint64_t End =
Sam Koltonc05d7782016-08-17 10:17:57 +00001423 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001424 // Don't try to disassemble beyond the end of section contents.
1425 if (End > SectSize)
1426 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001427 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001428 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001429 continue;
1430
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001431 // Check if we need to skip symbol
1432 // Skip if the symbol's data is not between StartAddress and StopAddress
1433 if (End + SectionAddr < StartAddress ||
1434 Start + SectionAddr > StopAddress) {
1435 continue;
1436 }
1437
1438 // Stop disassembly at the stop address specified
1439 if (End + SectionAddr > StopAddress)
1440 End = StopAddress - SectionAddr;
1441
Valery Pykhtinde048052016-04-07 07:24:01 +00001442 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1443 // make size 4 bytes folded
1444 End = Start + ((End - Start) & ~0x3ull);
Sam Koltonc05d7782016-08-17 10:17:57 +00001445 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1446 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1447 Start += 256;
1448 }
1449 if (si == se - 1 ||
1450 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1451 // cut trailing zeroes at the end of kernel
1452 // cut up to 256 bytes
1453 const uint64_t EndAlign = 256;
1454 const auto Limit = End - (std::min)(EndAlign, End - Start);
1455 while (End > Limit &&
1456 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1457 End -= 4;
1458 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001459 }
1460
Sam Koltonc05d7782016-08-17 10:17:57 +00001461 outs() << '\n' << std::get<1>(Symbols[si]) << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001462
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001463#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001464 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001465#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001466 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001467#endif
1468
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001469 for (Index = Start; Index < End; Index += Size) {
1470 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001471
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001472 if (Index + SectionAddr < StartAddress ||
1473 Index + SectionAddr > StopAddress) {
1474 // skip byte by byte till StartAddress is reached
1475 Size = 1;
1476 continue;
1477 }
Davide Italianof0706882015-10-01 21:57:09 +00001478 // AArch64 ELF binaries can interleave data and text in the
1479 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001480 // understand what we need to dump. If the data marker is within a
1481 // function, it is denoted as a word/short etc
1482 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1483 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001484 uint64_t Stride = 0;
1485
1486 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1487 DataMappingSymsAddr.end(), Index);
1488 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1489 // Switch to data.
1490 while (Index < End) {
1491 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1492 outs() << "\t";
1493 if (Index + 4 <= End) {
1494 Stride = 4;
1495 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001496 outs() << "\t.word\t";
1497 uint32_t Data = 0;
1498 if (Obj->isLittleEndian()) {
1499 const auto Word =
1500 reinterpret_cast<const support::ulittle32_t *>(
1501 Bytes.data() + Index);
1502 Data = *Word;
1503 } else {
1504 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1505 Bytes.data() + Index);
1506 Data = *Word;
1507 }
1508 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001509 } else if (Index + 2 <= End) {
1510 Stride = 2;
1511 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001512 outs() << "\t\t.short\t";
1513 uint16_t Data = 0;
1514 if (Obj->isLittleEndian()) {
1515 const auto Short =
1516 reinterpret_cast<const support::ulittle16_t *>(
1517 Bytes.data() + Index);
1518 Data = *Short;
1519 } else {
1520 const auto Short =
1521 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1522 Index);
1523 Data = *Short;
1524 }
1525 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001526 } else {
1527 Stride = 1;
1528 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001529 outs() << "\t\t.byte\t";
1530 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001531 }
1532 Index += Stride;
1533 outs() << "\n";
1534 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1535 TextMappingSymsAddr.end(), Index);
1536 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1537 break;
1538 }
1539 }
1540 }
1541
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001542 // If there is a data symbol inside an ELF text section and we are only
1543 // disassembling text (applicable all architectures),
1544 // we are in a situation where we must print the data and not
1545 // disassemble it.
1546 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1547 !DisassembleAll && Section.isText()) {
1548 // print out data up to 8 bytes at a time in hex and ascii
1549 uint8_t AsciiData[9] = {'\0'};
1550 uint8_t Byte;
1551 int NumBytes = 0;
1552
1553 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001554 if (((SectionAddr + Index) < StartAddress) ||
1555 ((SectionAddr + Index) > StopAddress))
1556 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001557 if (NumBytes == 0) {
1558 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1559 outs() << "\t";
1560 }
1561 Byte = Bytes.slice(Index)[0];
1562 outs() << format(" %02x", Byte);
1563 AsciiData[NumBytes] = isprint(Byte) ? Byte : '.';
1564
1565 uint8_t IndentOffset = 0;
1566 NumBytes++;
1567 if (Index == End - 1 || NumBytes > 8) {
1568 // Indent the space for less than 8 bytes data.
1569 // 2 spaces for byte and one for space between bytes
1570 IndentOffset = 3 * (8 - NumBytes);
1571 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1572 AsciiData[Excess] = '\0';
1573 NumBytes = 8;
1574 }
1575 if (NumBytes == 8) {
1576 AsciiData[8] = '\0';
1577 outs() << std::string(IndentOffset, ' ') << " ";
1578 outs() << reinterpret_cast<char *>(AsciiData);
1579 outs() << '\n';
1580 NumBytes = 0;
1581 }
1582 }
1583 }
Davide Italianof0706882015-10-01 21:57:09 +00001584 if (Index >= End)
1585 break;
1586
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001587 // Disassemble a real instruction or a data when disassemble all is
1588 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001589 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1590 SectionAddr + Index, DebugOut,
1591 CommentStream);
1592 if (Size == 0)
1593 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001594
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001595 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001596 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1597 *STI, &SP);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001598 outs() << CommentStream.str();
1599 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001600
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001601 // Try to resolve the target of a call, tail call, etc. to a specific
1602 // symbol.
1603 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1604 MIA->isConditionalBranch(Inst))) {
1605 uint64_t Target;
1606 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1607 // In a relocatable object, the target's section must reside in
1608 // the same section as the call instruction or it is accessed
1609 // through a relocation.
1610 //
1611 // In a non-relocatable object, the target may be in any section.
1612 //
1613 // N.B. We don't walk the relocations in the relocatable case yet.
1614 auto *TargetSectionSymbols = &Symbols;
1615 if (!Obj->isRelocatableObject()) {
1616 auto SectionAddress = std::upper_bound(
1617 SectionAddresses.begin(), SectionAddresses.end(), Target,
1618 [](uint64_t LHS,
1619 const std::pair<uint64_t, SectionRef> &RHS) {
1620 return LHS < RHS.first;
1621 });
1622 if (SectionAddress != SectionAddresses.begin()) {
1623 --SectionAddress;
1624 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1625 } else {
1626 TargetSectionSymbols = nullptr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001627 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001628 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001629
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001630 // Find the first symbol in the section whose offset is less than
1631 // or equal to the target.
1632 if (TargetSectionSymbols) {
1633 auto TargetSym = std::upper_bound(
1634 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1635 Target, [](uint64_t LHS,
Sam Koltonc05d7782016-08-17 10:17:57 +00001636 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1637 return LHS < std::get<0>(RHS);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001638 });
1639 if (TargetSym != TargetSectionSymbols->begin()) {
1640 --TargetSym;
1641 uint64_t TargetAddress = std::get<0>(*TargetSym);
1642 StringRef TargetName = std::get<1>(*TargetSym);
1643 outs() << " <" << TargetName;
1644 uint64_t Disp = Target - TargetAddress;
1645 if (Disp)
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00001646 outs() << "+0x" << Twine::utohexstr(Disp);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001647 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001648 }
1649 }
1650 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001651 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001652 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001653
1654 // Print relocation for instruction.
1655 while (rel_cur != rel_end) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001656 bool hidden = getHidden(*rel_cur);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001657 uint64_t addr = rel_cur->getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +00001658 SmallString<16> name;
1659 SmallString<32> val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001660
1661 // If this relocation is hidden, skip it.
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001662 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1663 ++rel_cur;
1664 continue;
1665 }
Owen Andersonfa3e5202011-10-25 20:35:53 +00001666
Michael J. Spencer51862b32011-10-13 22:17:18 +00001667 // Stop when rel_cur's address is past the current instruction.
Owen Andersonf20e3e52011-10-25 20:15:39 +00001668 if (addr >= Index + Size) break;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001669 rel_cur->getTypeName(name);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001670 error(getRelocationValueString(*rel_cur, val));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001671 outs() << format(Fmt.data(), SectionAddr + addr) << name
Benjamin Kramer82803112012-03-10 02:04:38 +00001672 << "\t" << val << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001673 ++rel_cur;
1674 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001675 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001676 }
1677 }
1678}
1679
Kevin Enderby98da6132015-01-20 21:47:46 +00001680void llvm::PrintRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001681 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1682 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001683 // Regular objdump doesn't print relocations in non-relocatable object
1684 // files.
1685 if (!Obj->isRelocatableObject())
1686 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001687
Colin LeMahieu77804be2015-07-29 15:45:39 +00001688 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001689 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001690 continue;
1691 StringRef secname;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001692 error(Section.getName(secname));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001693 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001694 for (const RelocationRef &Reloc : Section.relocations()) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +00001695 bool hidden = getHidden(Reloc);
Rafael Espindola96d071c2015-06-29 23:29:12 +00001696 uint64_t address = Reloc.getOffset();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001697 SmallString<32> relocname;
1698 SmallString<32> valuestr;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001699 if (address < StartAddress || address > StopAddress || hidden)
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001700 continue;
Rafael Espindola41bb4322015-06-30 04:08:37 +00001701 Reloc.getTypeName(relocname);
Davide Italianoccd53fe2015-08-05 07:18:31 +00001702 error(getRelocationValueString(Reloc, valuestr));
Greg Fitzgerald18432272014-03-20 22:55:15 +00001703 outs() << format(Fmt.data(), address) << " " << relocname << " "
1704 << valuestr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001705 }
1706 outs() << "\n";
1707 }
1708}
1709
Kevin Enderby98da6132015-01-20 21:47:46 +00001710void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001711 outs() << "Sections:\n"
1712 "Idx Name Size Address Type\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001713 unsigned i = 0;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001714 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001715 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001716 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001717 uint64_t Address = Section.getAddress();
1718 uint64_t Size = Section.getSize();
1719 bool Text = Section.isText();
1720 bool Data = Section.isData();
1721 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001722 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001723 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
Alexey Samsonov48803e52014-03-13 14:37:36 +00001724 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
1725 Name.str().c_str(), Size, Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001726 ++i;
1727 }
1728}
1729
Kevin Enderby98da6132015-01-20 21:47:46 +00001730void llvm::PrintSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001731 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001732 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001733 StringRef Name;
1734 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001735 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001736 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001737 uint64_t Size = Section.getSize();
1738 if (!Size)
1739 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001740
1741 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001742 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001743 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001744 ", %04" PRIx64 ")>\n",
1745 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001746 continue;
1747 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001748
Davide Italianoccd53fe2015-08-05 07:18:31 +00001749 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001750
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001751 // Dump out the content as hex and printable ascii characters.
1752 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Benjamin Kramer82803112012-03-10 02:04:38 +00001753 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001754 // Dump line of hex.
1755 for (std::size_t i = 0; i < 16; ++i) {
1756 if (i != 0 && i % 4 == 0)
1757 outs() << ' ';
1758 if (addr + i < end)
1759 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1760 << hexdigit(Contents[addr + i] & 0xF, true);
1761 else
1762 outs() << " ";
1763 }
1764 // Print ascii.
1765 outs() << " ";
1766 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
Guy Benyei83c74e92013-02-12 21:21:59 +00001767 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001768 outs() << Contents[addr + i];
1769 else
1770 outs() << ".";
1771 }
1772 outs() << "\n";
1773 }
1774 }
1775}
1776
Kevin Enderby9acb1092016-05-31 20:35:34 +00001777void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1778 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001779 outs() << "SYMBOL TABLE:\n";
1780
Rui Ueyama4e39f712014-03-18 18:58:51 +00001781 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
Davide Italianoe85abf72015-12-20 09:54:34 +00001782 printCOFFSymbolTable(coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001783 return;
1784 }
1785 for (const SymbolRef &Symbol : o->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001786 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1787 if (!AddressOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001788 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1789 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001790 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001791 if ((Address < StartAddress) || (Address > StopAddress))
1792 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001793 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1794 if (!TypeOrError)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001795 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1796 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001797 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001798 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001799 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001800 if (!SectionOrErr)
1801 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1802 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001803 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001804 StringRef Name;
1805 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1806 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001807 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001808 Expected<StringRef> NameOrErr = Symbol.getName();
1809 if (!NameOrErr)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001810 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1811 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001812 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001813 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001814
Rui Ueyama4e39f712014-03-18 18:58:51 +00001815 bool Global = Flags & SymbolRef::SF_Global;
1816 bool Weak = Flags & SymbolRef::SF_Weak;
1817 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001818 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001819 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001820
Rui Ueyama4e39f712014-03-18 18:58:51 +00001821 char GlobLoc = ' ';
1822 if (Type != SymbolRef::ST_Unknown)
1823 GlobLoc = Global ? 'g' : 'l';
1824 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1825 ? 'd' : ' ';
1826 char FileFunc = ' ';
1827 if (Type == SymbolRef::ST_File)
1828 FileFunc = 'f';
1829 else if (Type == SymbolRef::ST_Function)
1830 FileFunc = 'F';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001831
Rui Ueyama4e39f712014-03-18 18:58:51 +00001832 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
1833 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001834
Rui Ueyama4e39f712014-03-18 18:58:51 +00001835 outs() << format(Fmt, Address) << " "
1836 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1837 << (Weak ? 'w' : ' ') // Weak?
1838 << ' ' // Constructor. Not supported yet.
1839 << ' ' // Warning. Not supported yet.
1840 << ' ' // Indirect reference to another symbol.
1841 << Debug // Debugging (d) or dynamic (D) symbol.
1842 << FileFunc // Name of function (F), file (f) or object (O).
1843 << ' ';
1844 if (Absolute) {
1845 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001846 } else if (Common) {
1847 outs() << "*COM*";
Rui Ueyama4e39f712014-03-18 18:58:51 +00001848 } else if (Section == o->section_end()) {
1849 outs() << "*UND*";
1850 } else {
1851 if (const MachOObjectFile *MachO =
1852 dyn_cast<const MachOObjectFile>(o)) {
1853 DataRefImpl DR = Section->getRawDataRefImpl();
1854 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1855 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001856 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001857 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001858 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001859 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001860 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001861
1862 outs() << '\t';
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001863 if (Common || isa<ELFObjectFileBase>(o)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001864 uint64_t Val =
1865 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001866 outs() << format("\t %08" PRIx64 " ", Val);
1867 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001868
Davide Italianocd2514d2015-04-30 23:08:53 +00001869 if (Hidden) {
1870 outs() << ".hidden ";
1871 }
1872 outs() << Name
Rui Ueyama4e39f712014-03-18 18:58:51 +00001873 << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001874 }
1875}
1876
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001877static void PrintUnwindInfo(const ObjectFile *o) {
1878 outs() << "Unwind info:\n\n";
1879
1880 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
1881 printCOFFUnwindInfo(coff);
Tim Northover4bd286a2014-08-01 13:07:19 +00001882 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1883 printMachOUnwindInfo(MachO);
1884 else {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001885 // TODO: Extract DWARF dump tool to objdump.
1886 errs() << "This operation is only currently supported "
Tim Northover4bd286a2014-08-01 13:07:19 +00001887 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001888 return;
1889 }
1890}
1891
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001892void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001893 outs() << "Exports trie:\n";
1894 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1895 printMachOExportsTrie(MachO);
1896 else {
1897 errs() << "This operation is only currently supported "
1898 "for Mach-O executable files.\n";
1899 return;
1900 }
1901}
1902
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001903void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001904 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001905 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001906 printMachORebaseTable(MachO);
1907 else {
1908 errs() << "This operation is only currently supported "
1909 "for Mach-O executable files.\n";
1910 return;
1911 }
1912}
1913
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001914void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001915 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001916 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001917 printMachOBindTable(MachO);
1918 else {
1919 errs() << "This operation is only currently supported "
1920 "for Mach-O executable files.\n";
1921 return;
1922 }
1923}
1924
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001925void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001926 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001927 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001928 printMachOLazyBindTable(MachO);
1929 else {
1930 errs() << "This operation is only currently supported "
1931 "for Mach-O executable files.\n";
1932 return;
1933 }
1934}
1935
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001936void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001937 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001938 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001939 printMachOWeakBindTable(MachO);
1940 else {
1941 errs() << "This operation is only currently supported "
1942 "for Mach-O executable files.\n";
1943 return;
1944 }
1945}
Nick Kledzikac431442014-09-12 21:34:15 +00001946
Adrian Prantl437105a2015-07-08 02:04:15 +00001947/// Dump the raw contents of the __clangast section so the output can be piped
1948/// into llvm-bcanalyzer.
1949void llvm::printRawClangAST(const ObjectFile *Obj) {
1950 if (outs().is_displayed()) {
1951 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
1952 "the clang ast section.\n"
1953 "Please redirect the output to a file or another program such as "
1954 "llvm-bcanalyzer.\n";
1955 return;
1956 }
1957
1958 StringRef ClangASTSectionName("__clangast");
1959 if (isa<COFFObjectFile>(Obj)) {
1960 ClangASTSectionName = "clangast";
1961 }
1962
1963 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001964 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001965 StringRef Name;
1966 Sec.getName(Name);
1967 if (Name == ClangASTSectionName) {
1968 ClangASTSection = Sec;
1969 break;
1970 }
1971 }
1972 if (!ClangASTSection)
1973 return;
1974
1975 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001976 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001977 outs().write(ClangASTContents.data(), ClangASTContents.size());
1978}
1979
Sanjoy Das6f567a42015-06-22 18:03:02 +00001980static void printFaultMaps(const ObjectFile *Obj) {
1981 const char *FaultMapSectionName = nullptr;
1982
1983 if (isa<ELFObjectFileBase>(Obj)) {
1984 FaultMapSectionName = ".llvm_faultmaps";
1985 } else if (isa<MachOObjectFile>(Obj)) {
1986 FaultMapSectionName = "__llvm_faultmaps";
1987 } else {
1988 errs() << "This operation is only currently supported "
1989 "for ELF and Mach-O executable files.\n";
1990 return;
1991 }
1992
1993 Optional<object::SectionRef> FaultMapSection;
1994
Colin LeMahieu77804be2015-07-29 15:45:39 +00001995 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001996 StringRef Name;
1997 Sec.getName(Name);
1998 if (Name == FaultMapSectionName) {
1999 FaultMapSection = Sec;
2000 break;
2001 }
2002 }
2003
2004 outs() << "FaultMap table:\n";
2005
2006 if (!FaultMapSection.hasValue()) {
2007 outs() << "<not found>\n";
2008 return;
2009 }
2010
2011 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002012 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002013
2014 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2015 FaultMapContents.bytes_end());
2016
2017 outs() << FMP;
2018}
2019
Davide Italiano1bdaa202016-09-18 04:39:15 +00002020static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002021 if (o->isELF())
Davide Italiano1bdaa202016-09-18 04:39:15 +00002022 return printELFFileHeader(o);
2023 if (o->isCOFF())
2024 return printCOFFFileHeader(o);
Derek Schuff2c6f75d2016-11-30 16:49:11 +00002025 if (o->isWasm())
2026 return printWasmFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002027 if (o->isMachO()) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002028 printMachOFileHeader(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002029 if (!onlyFirst)
2030 printMachOLoadCommands(o);
2031 return;
2032 }
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002033 report_error(o->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002034}
2035
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002036static void DumpObject(ObjectFile *o, const Archive *a = nullptr) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002037 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
Adrian Prantl437105a2015-07-08 02:04:15 +00002038 // Avoid other output when using a raw option.
2039 if (!RawClangAST) {
2040 outs() << '\n';
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002041 if (a)
2042 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2043 else
2044 outs() << o->getFileName();
2045 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002046 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002047
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002048 if (Disassemble)
Michael J. Spencer51862b32011-10-13 22:17:18 +00002049 DisassembleObject(o, Relocations);
2050 if (Relocations && !Disassemble)
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002051 PrintRelocations(o);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002052 if (SectionHeaders)
2053 PrintSectionHeaders(o);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002054 if (SectionContents)
2055 PrintSectionContents(o);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002056 if (SymbolTable)
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002057 PrintSymbolTable(o, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002058 if (UnwindInfo)
2059 PrintUnwindInfo(o);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002060 if (PrivateHeaders || FirstPrivateHeader)
2061 printPrivateFileHeaders(o, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002062 if (ExportsTrie)
2063 printExportsTrie(o);
Nick Kledzikac431442014-09-12 21:34:15 +00002064 if (Rebase)
2065 printRebaseTable(o);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002066 if (Bind)
2067 printBindTable(o);
2068 if (LazyBind)
2069 printLazyBindTable(o);
2070 if (WeakBind)
2071 printWeakBindTable(o);
Adrian Prantl437105a2015-07-08 02:04:15 +00002072 if (RawClangAST)
2073 printRawClangAST(o);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002074 if (PrintFaultMaps)
2075 printFaultMaps(o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002076 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00002077 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002078 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002079 DIDumpOptions DumpOpts;
2080 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002081 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002082 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002083}
2084
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002085static void DumpObject(const COFFImportFile *I, const Archive *A) {
2086 StringRef ArchiveName = A ? A->getFileName() : "";
2087
2088 // Avoid other output when using a raw option.
2089 if (!RawClangAST)
2090 outs() << '\n'
2091 << ArchiveName << "(" << I->getFileName() << ")"
2092 << ":\tfile format COFF-import-file"
2093 << "\n\n";
2094
2095 if (SymbolTable)
2096 printCOFFSymbolTable(I);
2097}
2098
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002099/// @brief Dump each object file in \a a;
2100static void DumpArchive(const Archive *a) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002101 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002102 for (auto &C : a->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002103 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2104 if (!ChildOrErr) {
2105 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2106 report_error(a->getFileName(), C, std::move(E));
2107 continue;
2108 }
Rafael Espindolaae460022014-06-16 16:08:36 +00002109 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002110 DumpObject(o, a);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002111 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2112 DumpObject(I, a);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002113 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002114 report_error(a->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002115 }
Lang Hamesfc209622016-07-14 02:24:01 +00002116 if (Err)
2117 report_error(a->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002118}
2119
2120/// @brief Open file and figure out how to dump it.
2121static void DumpInput(StringRef file) {
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002122
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002123 // If we are using the Mach-O specific object file parser, then let it parse
2124 // the file and process the command line options. So the -arch flags can
2125 // be used to select specific slices, etc.
2126 if (MachOOpt) {
2127 ParseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002128 return;
2129 }
2130
2131 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002132 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2133 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002134 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002135 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002136
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002137 if (Archive *a = dyn_cast<Archive>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002138 DumpArchive(a);
Rafael Espindola3f6481d2014-08-01 14:31:55 +00002139 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002140 DumpObject(o);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002141 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002142 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002143}
2144
Michael J. Spencer2670c252011-01-20 06:39:06 +00002145int main(int argc, char **argv) {
2146 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +00002147 sys::PrintStackTraceOnErrorSignal(argv[0]);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002148 PrettyStackTraceProgram X(argc, argv);
2149 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
2150
2151 // Initialize targets and assembly printers/parsers.
2152 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002153 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002154 llvm::InitializeAllDisassemblers();
2155
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002156 // Register the target printer for --version.
2157 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2158
Michael J. Spencer2670c252011-01-20 06:39:06 +00002159 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2160 TripleName = Triple::normalize(TripleName);
2161
2162 ToolName = argv[0];
2163
2164 // Defaults to a.out if no filenames specified.
2165 if (InputFilenames.size() == 0)
2166 InputFilenames.push_back("a.out");
2167
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002168 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002169 Disassemble = true;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002170 if (!Disassemble
2171 && !Relocations
2172 && !SectionHeaders
2173 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002174 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002175 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002176 && !PrivateHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002177 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002178 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002179 && !Rebase
2180 && !Bind
2181 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002182 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002183 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002184 && !(UniversalHeaders && MachOOpt)
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00002185 && !(ArchiveHeaders && MachOOpt)
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002186 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002187 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002188 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002189 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002190 && !(DylibsUsed && MachOOpt)
2191 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002192 && !(ObjcMetaData && MachOOpt)
Colin LeMahieufcc32762015-07-29 19:08:10 +00002193 && !(FilterSections.size() != 0 && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002194 && !PrintFaultMaps
2195 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002196 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002197 return 2;
2198 }
2199
2200 llvm::for_each(InputFilenames, DumpInput);
2201
2202 return EXIT_SUCCESS;
2203}