blob: 7d0e7e9406867f5db0a2e157346b43be330d1306 [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"
Rafael Aulerb0e4b912018-03-09 19:13:44 +000023#include "llvm/ADT/StringSet.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000024#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000025#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000026#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000027#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Paul Semel007dedb2018-07-18 16:39:21 +000028#include "llvm/Demangle/Demangle.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000029#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000030#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000031#include "llvm/MC/MCDisassembler/MCDisassembler.h"
32#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000033#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000035#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000036#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000037#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000038#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000039#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Object/Archive.h"
41#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000042#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000043#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000044#include "llvm/Object/MachO.h"
Dave Lee3fb120f2018-08-03 00:06:38 +000045#include "llvm/Object/MachOUniversal.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000046#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000047#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000048#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000049#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000051#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000052#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000053#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000054#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000055#include "llvm/Support/Host.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000056#include "llvm/Support/InitLLVM.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000058#include "llvm/Support/SourceMgr.h"
Joel Galenson134cf472018-08-24 15:21:57 +000059#include "llvm/Support/StringSaver.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000060#include "llvm/Support/TargetRegistry.h"
61#include "llvm/Support/TargetSelect.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000062#include "llvm/Support/WithColor.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000064#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000065#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000066#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000067#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000068#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000069#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000070
Michael J. Spencer2670c252011-01-20 06:39:06 +000071using namespace llvm;
72using namespace object;
73
Fangrui Song8513cd42018-06-27 20:45:11 +000074cl::opt<bool>
75 llvm::AllHeaders("all-headers",
76 cl::desc("Display all available header information"));
77static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
78 cl::aliasopt(AllHeaders));
79
Benjamin Kramer43a772e2011-09-19 17:56:04 +000080static cl::list<std::string>
81InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000082
Kevin Enderbye2297dd2015-01-07 21:02:18 +000083cl::opt<bool>
84llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000085 cl::desc("Display assembler mnemonics for the machine instructions"));
86static cl::alias
87Disassembled("d", cl::desc("Alias for --disassemble"),
Colin LeMahieu77804be2015-07-29 15:45:39 +000088 cl::aliasopt(Disassemble));
89
90cl::opt<bool>
91llvm::DisassembleAll("disassemble-all",
92 cl::desc("Display assembler mnemonics for the machine instructions"));
93static cl::alias
94DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
Colin LeMahieuf34933e2015-07-23 20:58:49 +000095 cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000096
Zachary Turner030ad372018-08-20 22:18:21 +000097cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
98 cl::init(false));
Paul Semel007dedb2018-07-18 16:39:21 +000099
100static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
Zachary Turner030ad372018-08-20 22:18:21 +0000101 cl::aliasopt(llvm::Demangle));
Paul Semel007dedb2018-07-18 16:39:21 +0000102
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000103static cl::list<std::string>
104DisassembleFunctions("df",
105 cl::CommaSeparated,
106 cl::desc("List of functions to disassemble"));
107static StringSet<> DisasmFuncsSet;
108
Kevin Enderby98da6132015-01-20 21:47:46 +0000109cl::opt<bool>
Kristina Brooks31579e92018-10-31 09:34:08 +0000110llvm::Relocations("reloc",
111 cl::desc("Display the relocation entries in the file"));
112static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
113 cl::NotHidden,
114 cl::aliasopt(llvm::Relocations));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000115
Kevin Enderby98da6132015-01-20 21:47:46 +0000116cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +0000117llvm::DynamicRelocations("dynamic-reloc",
118 cl::desc("Display the dynamic relocation entries in the file"));
119static cl::alias
120DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
121 cl::aliasopt(DynamicRelocations));
122
123cl::opt<bool>
James Hendersonb55b6582018-10-29 10:05:39 +0000124 llvm::SectionContents("full-contents",
125 cl::desc("Display the content of each section"));
126static cl::alias SectionContentsShort("s",
127 cl::desc("Alias for --full-contents"),
128 cl::aliasopt(SectionContents));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000129
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000130cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
131static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
Kristina Brooks889356e2018-10-31 09:35:25 +0000132 cl::NotHidden,
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000133 cl::aliasopt(llvm::SymbolTable));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000134
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000135cl::opt<bool>
136llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000137
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000138cl::opt<bool>
139llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000140
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000141cl::opt<bool>
142llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000143
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000144cl::opt<bool>
145llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000146
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000147cl::opt<bool>
148llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000149
Adrian Prantl437105a2015-07-08 02:04:15 +0000150cl::opt<bool>
151llvm::RawClangAST("raw-clang-ast",
152 cl::desc("Dump the raw binary contents of the clang AST section"));
153
Nick Kledzik56ebef42014-09-16 01:41:51 +0000154static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000155MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000156static cl::alias
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000157MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000158
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159cl::opt<std::string>
160llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
161 "see -version for available targets"));
162
163cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000164llvm::MCPU("mcpu",
165 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
166 cl::value_desc("cpu-name"),
167 cl::init(""));
168
169cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000170llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000171 "see -version for available targets"));
172
Kevin Enderby98da6132015-01-20 21:47:46 +0000173cl::opt<bool>
174llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
175 "headers for each section."));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000176static cl::alias
177SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
178 cl::aliasopt(SectionHeaders));
179static cl::alias
180SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
181 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000182
Colin LeMahieu77804be2015-07-29 15:45:39 +0000183cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000184llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
185 "With -macho dump segment,section"));
186cl::alias
187static FilterSectionsj("j", cl::desc("Alias for --section"),
188 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000189
Kevin Enderbyc9595622014-08-06 23:24:41 +0000190cl::list<std::string>
191llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000192 cl::CommaSeparated,
193 cl::desc("Target specific attributes"),
194 cl::value_desc("a1,+a2,-a3,..."));
195
Kevin Enderbybf246f52014-09-24 23:08:22 +0000196cl::opt<bool>
197llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
198 "instructions, do not print "
199 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000200cl::opt<bool>
201llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000202
Kevin Enderby98da6132015-01-20 21:47:46 +0000203cl::opt<bool>
204llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000205
206static cl::alias
207UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
208 cl::aliasopt(UnwindInfo));
209
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000210cl::opt<bool>
211llvm::PrivateHeaders("private-headers",
212 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000213
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000214cl::opt<bool>
215llvm::FirstPrivateHeader("private-header",
216 cl::desc("Display only the first format specific file "
217 "header"));
218
Michael J. Spencer209565db2013-01-06 03:56:49 +0000219static cl::alias
220PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
221 cl::aliasopt(PrivateHeaders));
222
Paul Semeld2af4d62018-07-04 15:25:03 +0000223cl::opt<bool> llvm::FileHeaders(
224 "file-headers",
225 cl::desc("Display the contents of the overall file header"));
226
227static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
228 cl::aliasopt(FileHeaders));
229
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000230cl::opt<bool>
Paul Semel0dc92f62018-07-05 14:43:29 +0000231 llvm::ArchiveHeaders("archive-headers",
232 cl::desc("Display archive header information"));
233
234cl::alias
235ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
236 cl::aliasopt(ArchiveHeaders));
237
238cl::opt<bool>
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000239 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000240 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000241
Sanjoy Das6f567a42015-06-22 18:03:02 +0000242cl::opt<bool> PrintFaultMaps("fault-map-section",
243 cl::desc("Display contents of faultmap section"));
244
Igor Laevsky03a670c2016-01-26 15:09:42 +0000245cl::opt<DIDumpType> llvm::DwarfDumpType(
246 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000247 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000248
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000249cl::opt<bool> PrintSource(
250 "source",
251 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000252 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000253
254cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
255 cl::aliasopt(PrintSource));
256
257cl::opt<bool> PrintLines("line-numbers",
258 cl::desc("Display source line numbers with "
259 "disassembly. Implies disassemble object"));
260
261cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
262 cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000263
264cl::opt<unsigned long long>
265 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
266 cl::value_desc("address"), cl::init(0));
267cl::opt<unsigned long long>
George Rimar70d197d2019-01-10 14:55:26 +0000268 StopAddress("stop-address",
George Rimar3687c3e92019-01-15 14:03:50 +0000269 cl::desc("Stop disassembly at address"),
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000270 cl::value_desc("address"), cl::init(UINT64_MAX));
George Rimar70d197d2019-01-10 14:55:26 +0000271
George Rimar3687c3e92019-01-15 14:03:50 +0000272cl::opt<bool> DisassembleZeroes(
273 "disassemble-zeroes",
274 cl::desc("Do not skip blocks of zeroes when disassembling"));
George Rimar70d197d2019-01-10 14:55:26 +0000275cl::alias DisassembleZeroesShort("z",
276 cl::desc("Alias for --disassemble-zeroes"),
277 cl::aliasopt(DisassembleZeroes));
278
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000279static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000280
Clement Courbet2d7d4a32019-01-18 09:40:19 +0000281typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
282
Colin LeMahieu77804be2015-07-29 15:45:39 +0000283namespace {
Colin LeMahieufcc32762015-07-29 19:08:10 +0000284typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
Colin LeMahieu77804be2015-07-29 15:45:39 +0000285
286class SectionFilterIterator {
287public:
288 SectionFilterIterator(FilterPredicate P,
289 llvm::object::section_iterator const &I,
290 llvm::object::section_iterator const &E)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000291 : Predicate(std::move(P)), Iterator(I), End(E) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000292 ScanPredicate();
293 }
Benjamin Kramerac9257b2015-09-24 14:52:52 +0000294 const llvm::object::SectionRef &operator*() const { return *Iterator; }
Colin LeMahieu77804be2015-07-29 15:45:39 +0000295 SectionFilterIterator &operator++() {
296 ++Iterator;
297 ScanPredicate();
298 return *this;
299 }
300 bool operator!=(SectionFilterIterator const &Other) const {
301 return Iterator != Other.Iterator;
302 }
303
304private:
305 void ScanPredicate() {
Colin LeMahieuda1723f2015-07-29 19:21:13 +0000306 while (Iterator != End && !Predicate(*Iterator)) {
Colin LeMahieu77804be2015-07-29 15:45:39 +0000307 ++Iterator;
308 }
309 }
310 FilterPredicate Predicate;
311 llvm::object::section_iterator Iterator;
312 llvm::object::section_iterator End;
313};
314
315class SectionFilter {
316public:
317 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000318 : Predicate(std::move(P)), Object(O) {}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000319 SectionFilterIterator begin() {
320 return SectionFilterIterator(Predicate, Object.section_begin(),
321 Object.section_end());
322 }
323 SectionFilterIterator end() {
324 return SectionFilterIterator(Predicate, Object.section_end(),
325 Object.section_end());
326 }
327
328private:
329 FilterPredicate Predicate;
330 llvm::object::ObjectFile const &Object;
331};
332SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000333 return SectionFilter(
334 [](llvm::object::SectionRef const &S) {
335 if (FilterSections.empty())
336 return true;
337 llvm::StringRef String;
338 std::error_code error = S.getName(String);
339 if (error)
340 return false;
341 return is_contained(FilterSections, String);
342 },
343 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000344}
345}
346
Davide Italianoccd53fe2015-08-05 07:18:31 +0000347void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000348 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000349 return;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000350 WithColor::error(errs(), ToolName)
351 << "reading file: " << EC.message() << ".\n";
Davide Italiano140af642015-12-25 18:16:45 +0000352 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000353 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000354}
355
Kevin Enderby42398052016-06-28 23:16:13 +0000356LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000357 WithColor::error(errs(), ToolName) << Message << ".\n";
Kevin Enderby42398052016-06-28 23:16:13 +0000358 errs().flush();
359 exit(1);
360}
361
Paul Semel007dedb2018-07-18 16:39:21 +0000362void llvm::warn(StringRef Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000363 WithColor::warning(errs(), ToolName) << Message << ".\n";
Paul Semel007dedb2018-07-18 16:39:21 +0000364 errs().flush();
365}
366
Davide Italianoed9d95b2015-12-29 13:41:02 +0000367LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000368 Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000369 WithColor::error(errs(), ToolName)
370 << "'" << File << "': " << Message << ".\n";
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000371 exit(1);
372}
373
374LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000375 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000376 assert(EC);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000377 WithColor::error(errs(), ToolName)
378 << "'" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000379 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000380}
381
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000382LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
383 llvm::Error E) {
384 assert(E);
385 std::string Buf;
386 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000387 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000388 OS.flush();
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000389 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000390 exit(1);
391}
392
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000393LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
394 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000395 llvm::Error E,
396 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000397 assert(E);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000398 WithColor::error(errs(), ToolName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000399 if (ArchiveName != "")
400 errs() << ArchiveName << "(" << FileName << ")";
401 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000402 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000403 if (!ArchitectureName.empty())
404 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000405 std::string Buf;
406 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000407 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000408 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000409 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000410 exit(1);
411}
412
413LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
414 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000415 llvm::Error E,
416 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000417 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000418 // TODO: if we have a error getting the name then it would be nice to print
419 // the index of which archive member this is and or its offset in the
420 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000421 if (!NameOrErr) {
422 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000423 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000424 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000425 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
426 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000427}
428
Craig Toppere6cb63e2014-04-25 04:24:47 +0000429static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000430 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000431 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000432 if (TripleName.empty()) {
George Rimar73a27232019-01-15 09:19:18 +0000433 if (Obj)
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000434 TheTriple = Obj->makeTriple();
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000435 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000436 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000437
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000438 // Use the triple, but also try to combine with ARM build attributes.
439 if (Obj) {
440 auto Arch = Obj->getArch();
George Rimar73a27232019-01-15 09:19:18 +0000441 if (Arch == Triple::arm || Arch == Triple::armeb)
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000442 Obj->setARMSubArch(TheTriple);
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000443 }
444 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000445
446 // Get the target specific parser.
447 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000448 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
449 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000450 if (!TheTarget) {
451 if (Obj)
452 report_error(Obj->getFileName(), "can't find target: " + Error);
453 else
454 error("can't find target: " + Error);
455 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000456
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000457 // Update the triple name and return the found target.
458 TripleName = TheTriple.getTriple();
459 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000460}
461
George Rimar73a27232019-01-15 09:19:18 +0000462bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
463 return A.getOffset() < B.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000464}
465
Rafael Espindola37070a52015-06-03 04:48:06 +0000466template <class ELFT>
Rafael Espindola37070a52015-06-03 04:48:06 +0000467static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000468 const RelocationRef &RelRef,
Rafael Espindola37070a52015-06-03 04:48:06 +0000469 SmallVectorImpl<char> &Result) {
470 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
471 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000472 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
473
Rafael Espindola37070a52015-06-03 04:48:06 +0000474 const ELFFile<ELFT> &EF = *Obj->getELFFile();
George Rimar73a27232019-01-15 09:19:18 +0000475 DataRefImpl Rel = RelRef.getRawDataRefImpl();
Davide Italiano6cf09262016-11-16 05:10:28 +0000476 auto SecOrErr = EF.getSection(Rel.d.a);
477 if (!SecOrErr)
478 return errorToErrorCode(SecOrErr.takeError());
George Rimar6ce6bfa2019-01-17 09:13:17 +0000479
George Rimar73a27232019-01-15 09:19:18 +0000480 int64_t Addend = 0;
Paul Semelcb0f0432018-06-07 13:30:55 +0000481 // If there is no Symbol associated with the relocation, we set the undef
482 // boolean value to 'true'. This will prevent us from calling functions that
483 // requires the relocation to be associated with a symbol.
George Rimar6ce6bfa2019-01-17 09:13:17 +0000484 //
485 // In SHT_REL case we would need to read the addend from section data.
George Rimarce5cafe2019-01-17 09:14:33 +0000486 // GNU objdump does not do that and we just follow for simplicity.
George Rimar73a27232019-01-15 09:19:18 +0000487 bool Undef = false;
George Rimar6ce6bfa2019-01-17 09:13:17 +0000488 if ((*SecOrErr)->sh_type == ELF::SHT_RELA) {
Rafael Espindola7f162ec2015-07-02 14:21:38 +0000489 const Elf_Rela *ERela = Obj->getRela(Rel);
George Rimar73a27232019-01-15 09:19:18 +0000490 Addend = ERela->r_addend;
491 Undef = ERela->getSymbol(false) == 0;
George Rimar6ce6bfa2019-01-17 09:13:17 +0000492 } else if ((*SecOrErr)->sh_type != ELF::SHT_REL) {
493 return object_error::parse_failed;
Rafael Espindola37070a52015-06-03 04:48:06 +0000494 }
George Rimar6ce6bfa2019-01-17 09:13:17 +0000495
496 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
497 // addend. Should be acceptable for all normal purposes.
498 std::string FmtBuf;
499 raw_string_ostream Fmt(FmtBuf);
500
George Rimar73a27232019-01-15 09:19:18 +0000501 if (!Undef) {
Paul Semelcb0f0432018-06-07 13:30:55 +0000502 symbol_iterator SI = RelRef.getSymbol();
George Rimar6ce6bfa2019-01-17 09:13:17 +0000503 const Elf_Sym *Sym = Obj->getSymbol(SI->getRawDataRefImpl());
504 if (Sym->getType() == ELF::STT_SECTION) {
Paul Semelcb0f0432018-06-07 13:30:55 +0000505 Expected<section_iterator> SymSI = SI->getSection();
506 if (!SymSI)
507 return errorToErrorCode(SymSI.takeError());
508 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
509 auto SecName = EF.getSectionName(SymSec);
510 if (!SecName)
511 return errorToErrorCode(SecName.takeError());
George Rimar6ce6bfa2019-01-17 09:13:17 +0000512 Fmt << *SecName;
Paul Semelcb0f0432018-06-07 13:30:55 +0000513 } else {
George Rimar6ce6bfa2019-01-17 09:13:17 +0000514 Expected<StringRef> SymName = SI->getName();
Paul Semelcb0f0432018-06-07 13:30:55 +0000515 if (!SymName)
516 return errorToErrorCode(SymName.takeError());
George Rimar7120fb92018-12-19 10:44:49 +0000517 if (Demangle)
George Rimar6ce6bfa2019-01-17 09:13:17 +0000518 Fmt << demangle(*SymName);
George Rimar7120fb92018-12-19 10:44:49 +0000519 else
George Rimar6ce6bfa2019-01-17 09:13:17 +0000520 Fmt << *SymName;
Paul Semelcb0f0432018-06-07 13:30:55 +0000521 }
George Rimar6ce6bfa2019-01-17 09:13:17 +0000522 } else {
523 Fmt << "*ABS*";
524 }
Daniel Cedermand72b9fd2018-06-01 05:31:58 +0000525
George Rimar73a27232019-01-15 09:19:18 +0000526 if (Addend != 0)
527 Fmt << (Addend < 0 ? "" : "+") << Addend;
528 Fmt.flush();
529 Result.append(FmtBuf.begin(), FmtBuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000530 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000531}
532
533static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
Rafael Espindolaa01ff222015-08-10 20:50:40 +0000534 const RelocationRef &Rel,
Rafael Espindola37070a52015-06-03 04:48:06 +0000535 SmallVectorImpl<char> &Result) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000536 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
537 return getRelocationValueString(ELF32LE, Rel, Result);
538 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
539 return getRelocationValueString(ELF64LE, Rel, Result);
540 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
541 return getRelocationValueString(ELF32BE, Rel, Result);
542 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
543 return getRelocationValueString(ELF64BE, Rel, Result);
544}
545
546static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
547 const RelocationRef &Rel,
548 SmallVectorImpl<char> &Result) {
549 symbol_iterator SymI = Rel.getSymbol();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000550 Expected<StringRef> SymNameOrErr = SymI->getName();
551 if (!SymNameOrErr)
552 return errorToErrorCode(SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000553 StringRef SymName = *SymNameOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000554 Result.append(SymName.begin(), SymName.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000555 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000556}
557
558static void printRelocationTargetName(const MachOObjectFile *O,
559 const MachO::any_relocation_info &RE,
George Rimar73a27232019-01-15 09:19:18 +0000560 raw_string_ostream &Fmt) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000561 // Target of a scattered relocation is an address. In the interest of
562 // generating pretty output, scan through the symbol table looking for a
563 // symbol that aligns with that address. If we find one, print it.
564 // Otherwise, we just print the hex address of the target.
George Rimar73a27232019-01-15 09:19:18 +0000565 if (O->isRelocationScattered(RE)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000566 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
567
568 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +0000569 Expected<uint64_t> Addr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000570 if (!Addr)
571 report_error(O->getFileName(), Addr.takeError());
Rafael Espindolaed067c42015-07-03 18:19:00 +0000572 if (*Addr != Val)
Rafael Espindola37070a52015-06-03 04:48:06 +0000573 continue;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000574 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000575 if (!Name)
576 report_error(O->getFileName(), Name.takeError());
George Rimar73a27232019-01-15 09:19:18 +0000577 Fmt << *Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000578 return;
579 }
580
581 // If we couldn't find a symbol that this relocation refers to, try
582 // to find a section beginning instead.
Colin LeMahieu77804be2015-07-29 15:45:39 +0000583 for (const SectionRef &Section : ToolSectionFilter(*O)) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000584 std::error_code ec;
585
586 StringRef Name;
587 uint64_t Addr = Section.getAddress();
588 if (Addr != Val)
589 continue;
590 if ((ec = Section.getName(Name)))
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000591 report_error(O->getFileName(), ec);
George Rimar73a27232019-01-15 09:19:18 +0000592 Fmt << Name;
Rafael Espindola37070a52015-06-03 04:48:06 +0000593 return;
594 }
595
George Rimar73a27232019-01-15 09:19:18 +0000596 Fmt << format("0x%x", Val);
Rafael Espindola37070a52015-06-03 04:48:06 +0000597 return;
598 }
599
600 StringRef S;
601 bool isExtern = O->getPlainRelocationExternal(RE);
602 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
603
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000604 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
George Rimar73a27232019-01-15 09:19:18 +0000605 Fmt << format("0x%0" PRIx64, Val);
Martin Storsjo8c0317d2017-07-13 17:03:02 +0000606 return;
George Rimar73a27232019-01-15 09:19:18 +0000607 }
608
609 if (isExtern) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000610 symbol_iterator SI = O->symbol_begin();
611 advance(SI, Val);
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000612 Expected<StringRef> SOrErr = SI->getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000613 if (!SOrErr)
614 report_error(O->getFileName(), SOrErr.takeError());
Davide Italianoccd53fe2015-08-05 07:18:31 +0000615 S = *SOrErr;
Rafael Espindola37070a52015-06-03 04:48:06 +0000616 } else {
617 section_iterator SI = O->section_begin();
618 // Adjust for the fact that sections are 1-indexed.
Kevin Enderby3fc91882017-11-03 21:32:44 +0000619 if (Val == 0) {
George Rimar73a27232019-01-15 09:19:18 +0000620 Fmt << "0 (?,?)";
Kevin Enderby3fc91882017-11-03 21:32:44 +0000621 return;
622 }
George Rimar73a27232019-01-15 09:19:18 +0000623 uint32_t I = Val - 1;
624 while (I != 0 && SI != O->section_end()) {
625 --I;
Kevin Enderby3fc91882017-11-03 21:32:44 +0000626 advance(SI, 1);
627 }
628 if (SI == O->section_end())
George Rimar73a27232019-01-15 09:19:18 +0000629 Fmt << Val << " (?,?)";
Kevin Enderby3fc91882017-11-03 21:32:44 +0000630 else
631 SI->getName(S);
Rafael Espindola37070a52015-06-03 04:48:06 +0000632 }
633
George Rimar73a27232019-01-15 09:19:18 +0000634 Fmt << S;
Rafael Espindola37070a52015-06-03 04:48:06 +0000635}
636
Sam Clegg4df5d762017-06-27 20:40:53 +0000637static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
638 const RelocationRef &RelRef,
639 SmallVectorImpl<char> &Result) {
640 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
Sam Cleggf676cdd2018-04-26 16:41:51 +0000641 symbol_iterator SI = RelRef.getSymbol();
George Rimar73a27232019-01-15 09:19:18 +0000642 std::string FmtBuf;
643 raw_string_ostream Fmt(FmtBuf);
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000644 if (SI == Obj->symbol_end()) {
645 // Not all wasm relocations have symbols associated with them.
646 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
George Rimar73a27232019-01-15 09:19:18 +0000647 Fmt << Rel.Index;
Sam Cleggf676cdd2018-04-26 16:41:51 +0000648 } else {
Sam Clegg8c4b0ce2018-04-26 17:05:04 +0000649 Expected<StringRef> SymNameOrErr = SI->getName();
650 if (!SymNameOrErr)
651 return errorToErrorCode(SymNameOrErr.takeError());
Sam Cleggf676cdd2018-04-26 16:41:51 +0000652 StringRef SymName = *SymNameOrErr;
653 Result.append(SymName.begin(), SymName.end());
654 }
George Rimar73a27232019-01-15 09:19:18 +0000655 Fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
656 Fmt.flush();
657 Result.append(FmtBuf.begin(), FmtBuf.end());
Sam Clegg4df5d762017-06-27 20:40:53 +0000658 return std::error_code();
659}
660
Rafael Espindola37070a52015-06-03 04:48:06 +0000661static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
662 const RelocationRef &RelRef,
663 SmallVectorImpl<char> &Result) {
664 DataRefImpl Rel = RelRef.getRawDataRefImpl();
665 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
666
667 unsigned Arch = Obj->getArch();
668
George Rimar73a27232019-01-15 09:19:18 +0000669 std::string FmtBuf;
670 raw_string_ostream Fmt(FmtBuf);
Rafael Espindola37070a52015-06-03 04:48:06 +0000671 unsigned Type = Obj->getAnyRelocationType(RE);
672 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
673
674 // Determine any addends that should be displayed with the relocation.
675 // These require decoding the relocation type, which is triple-specific.
676
677 // X86_64 has entirely custom relocation types.
678 if (Arch == Triple::x86_64) {
Rafael Espindola37070a52015-06-03 04:48:06 +0000679 switch (Type) {
680 case MachO::X86_64_RELOC_GOT_LOAD:
681 case MachO::X86_64_RELOC_GOT: {
George Rimar73a27232019-01-15 09:19:18 +0000682 printRelocationTargetName(Obj, RE, Fmt);
683 Fmt << "@GOT";
684 if (IsPCRel)
685 Fmt << "PCREL";
Rafael Espindola37070a52015-06-03 04:48:06 +0000686 break;
687 }
688 case MachO::X86_64_RELOC_SUBTRACTOR: {
689 DataRefImpl RelNext = Rel;
690 Obj->moveRelocationNext(RelNext);
691 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
692
693 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
694 // X86_64_RELOC_UNSIGNED.
695 // NOTE: Scattered relocations don't exist on x86_64.
696 unsigned RType = Obj->getAnyRelocationType(RENext);
697 if (RType != MachO::X86_64_RELOC_UNSIGNED)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000698 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
699 "X86_64_RELOC_SUBTRACTOR.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000700
701 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
702 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
George Rimar73a27232019-01-15 09:19:18 +0000703 printRelocationTargetName(Obj, RENext, Fmt);
704 Fmt << "-";
705 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000706 break;
707 }
708 case MachO::X86_64_RELOC_TLV:
George Rimar73a27232019-01-15 09:19:18 +0000709 printRelocationTargetName(Obj, RE, Fmt);
710 Fmt << "@TLV";
711 if (IsPCRel)
712 Fmt << "P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000713 break;
714 case MachO::X86_64_RELOC_SIGNED_1:
George Rimar73a27232019-01-15 09:19:18 +0000715 printRelocationTargetName(Obj, RE, Fmt);
716 Fmt << "-1";
Rafael Espindola37070a52015-06-03 04:48:06 +0000717 break;
718 case MachO::X86_64_RELOC_SIGNED_2:
George Rimar73a27232019-01-15 09:19:18 +0000719 printRelocationTargetName(Obj, RE, Fmt);
720 Fmt << "-2";
Rafael Espindola37070a52015-06-03 04:48:06 +0000721 break;
722 case MachO::X86_64_RELOC_SIGNED_4:
George Rimar73a27232019-01-15 09:19:18 +0000723 printRelocationTargetName(Obj, RE, Fmt);
724 Fmt << "-4";
Rafael Espindola37070a52015-06-03 04:48:06 +0000725 break;
726 default:
George Rimar73a27232019-01-15 09:19:18 +0000727 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000728 break;
729 }
730 // X86 and ARM share some relocation types in common.
731 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
732 Arch == Triple::ppc) {
733 // Generic relocation types...
734 switch (Type) {
735 case MachO::GENERIC_RELOC_PAIR: // prints no info
Rui Ueyama7d099192015-06-09 15:20:42 +0000736 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000737 case MachO::GENERIC_RELOC_SECTDIFF: {
738 DataRefImpl RelNext = Rel;
739 Obj->moveRelocationNext(RelNext);
740 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
741
742 // X86 sect diff's must be followed by a relocation of type
743 // GENERIC_RELOC_PAIR.
744 unsigned RType = Obj->getAnyRelocationType(RENext);
745
746 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000747 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
748 "GENERIC_RELOC_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000749
George Rimar73a27232019-01-15 09:19:18 +0000750 printRelocationTargetName(Obj, RE, Fmt);
751 Fmt << "-";
752 printRelocationTargetName(Obj, RENext, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000753 break;
754 }
755 }
756
757 if (Arch == Triple::x86 || Arch == Triple::ppc) {
758 switch (Type) {
759 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
760 DataRefImpl RelNext = Rel;
761 Obj->moveRelocationNext(RelNext);
762 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
763
764 // X86 sect diff's must be followed by a relocation of type
765 // GENERIC_RELOC_PAIR.
766 unsigned RType = Obj->getAnyRelocationType(RENext);
767 if (RType != MachO::GENERIC_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000768 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
769 "GENERIC_RELOC_LOCAL_SECTDIFF.");
Rafael Espindola37070a52015-06-03 04:48:06 +0000770
George Rimar73a27232019-01-15 09:19:18 +0000771 printRelocationTargetName(Obj, RE, Fmt);
772 Fmt << "-";
773 printRelocationTargetName(Obj, RENext, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000774 break;
775 }
776 case MachO::GENERIC_RELOC_TLV: {
George Rimar73a27232019-01-15 09:19:18 +0000777 printRelocationTargetName(Obj, RE, Fmt);
778 Fmt << "@TLV";
Rafael Espindola37070a52015-06-03 04:48:06 +0000779 if (IsPCRel)
George Rimar73a27232019-01-15 09:19:18 +0000780 Fmt << "P";
Rafael Espindola37070a52015-06-03 04:48:06 +0000781 break;
782 }
783 default:
George Rimar73a27232019-01-15 09:19:18 +0000784 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000785 }
786 } else { // ARM-specific relocations
787 switch (Type) {
788 case MachO::ARM_RELOC_HALF:
789 case MachO::ARM_RELOC_HALF_SECTDIFF: {
790 // Half relocations steal a bit from the length field to encode
791 // whether this is an upper16 or a lower16 relocation.
Martin Storsjofa5183b2017-07-13 05:54:08 +0000792 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
Rafael Espindola37070a52015-06-03 04:48:06 +0000793
794 if (isUpper)
George Rimar73a27232019-01-15 09:19:18 +0000795 Fmt << ":upper16:(";
Rafael Espindola37070a52015-06-03 04:48:06 +0000796 else
George Rimar73a27232019-01-15 09:19:18 +0000797 Fmt << ":lower16:(";
798 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000799
800 DataRefImpl RelNext = Rel;
801 Obj->moveRelocationNext(RelNext);
802 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
803
804 // ARM half relocs must be followed by a relocation of type
805 // ARM_RELOC_PAIR.
806 unsigned RType = Obj->getAnyRelocationType(RENext);
807 if (RType != MachO::ARM_RELOC_PAIR)
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000808 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
809 "ARM_RELOC_HALF");
Rafael Espindola37070a52015-06-03 04:48:06 +0000810
811 // NOTE: The half of the target virtual address is stashed in the
812 // address field of the secondary relocation, but we can't reverse
813 // engineer the constant offset from it without decoding the movw/movt
814 // instruction to find the other half in its immediate field.
815
816 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
817 // symbol/section pointer of the follow-on relocation.
818 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
George Rimar73a27232019-01-15 09:19:18 +0000819 Fmt << "-";
820 printRelocationTargetName(Obj, RENext, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000821 }
822
George Rimar73a27232019-01-15 09:19:18 +0000823 Fmt << ")";
Rafael Espindola37070a52015-06-03 04:48:06 +0000824 break;
825 }
George Rimar73a27232019-01-15 09:19:18 +0000826 default: { printRelocationTargetName(Obj, RE, Fmt); }
Rafael Espindola37070a52015-06-03 04:48:06 +0000827 }
828 }
829 } else
George Rimar73a27232019-01-15 09:19:18 +0000830 printRelocationTargetName(Obj, RE, Fmt);
Rafael Espindola37070a52015-06-03 04:48:06 +0000831
George Rimar73a27232019-01-15 09:19:18 +0000832 Fmt.flush();
833 Result.append(FmtBuf.begin(), FmtBuf.end());
Rui Ueyama7d099192015-06-09 15:20:42 +0000834 return std::error_code();
Rafael Espindola37070a52015-06-03 04:48:06 +0000835}
836
837static std::error_code getRelocationValueString(const RelocationRef &Rel,
838 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000839 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000840 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
841 return getRelocationValueString(ELF, Rel, Result);
842 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
843 return getRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000844 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
845 return getRelocationValueString(Wasm, Rel, Result);
846 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
847 return getRelocationValueString(MachO, Rel, Result);
848 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000849}
850
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000851/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000852/// relocations, usually because it is the trailing part of a multipart
853/// relocation that will be printed as part of the leading relocation.
854static bool getHidden(RelocationRef RelRef) {
George Rimar73a27232019-01-15 09:19:18 +0000855 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000856 if (!MachO)
857 return false;
858
859 unsigned Arch = MachO->getArch();
860 DataRefImpl Rel = RelRef.getRawDataRefImpl();
861 uint64_t Type = MachO->getRelocationType(Rel);
862
863 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
864 // is always hidden.
George Rimar73a27232019-01-15 09:19:18 +0000865 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
866 return Type == MachO::GENERIC_RELOC_PAIR;
867
868 if (Arch == Triple::x86_64) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000869 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
870 // an X86_64_RELOC_SUBTRACTOR.
871 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
872 DataRefImpl RelPrev = Rel;
873 RelPrev.d.a--;
874 uint64_t PrevType = MachO->getRelocationType(RelPrev);
875 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
876 return true;
877 }
878 }
879
880 return false;
881}
882
Sid Manningd9f28732018-05-14 19:46:08 +0000883namespace {
884class SourcePrinter {
885protected:
886 DILineInfo OldLineInfo;
887 const ObjectFile *Obj = nullptr;
888 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
889 // File name to file contents of source
890 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
891 // Mark the line endings of the cached source
892 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
893
894private:
895 bool cacheSource(const DILineInfo& LineInfoFile);
896
897public:
898 SourcePrinter() = default;
899 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
900 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
901 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
902 DefaultArch);
903 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
904 }
905 virtual ~SourcePrinter() = default;
906 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
907 StringRef Delimiter = "; ");
908};
909
910bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
911 std::unique_ptr<MemoryBuffer> Buffer;
912 if (LineInfo.Source) {
913 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
914 } else {
915 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
916 if (!BufferOrError)
917 return false;
918 Buffer = std::move(*BufferOrError);
919 }
920 // Chomp the file to get lines
921 size_t BufferSize = Buffer->getBufferSize();
922 const char *BufferStart = Buffer->getBufferStart();
923 for (const char *Start = BufferStart, *End = BufferStart;
924 End < BufferStart + BufferSize; End++)
925 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
926 (*End == '\r' && *(End + 1) == '\n')) {
927 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
928 if (*End == '\r')
929 End++;
930 Start = End + 1;
931 }
932 SourceCache[LineInfo.FileName] = std::move(Buffer);
933 return true;
934}
935
936void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
937 StringRef Delimiter) {
938 if (!Symbolizer)
939 return;
940 DILineInfo LineInfo = DILineInfo();
941 auto ExpectecLineInfo =
942 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
943 if (!ExpectecLineInfo)
944 consumeError(ExpectecLineInfo.takeError());
945 else
946 LineInfo = *ExpectecLineInfo;
947
948 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
949 LineInfo.Line == 0)
950 return;
951
952 if (PrintLines)
953 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
954 if (PrintSource) {
955 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
956 if (!cacheSource(LineInfo))
957 return;
958 auto FileBuffer = SourceCache.find(LineInfo.FileName);
959 if (FileBuffer != SourceCache.end()) {
960 auto LineBuffer = LineCache.find(LineInfo.FileName);
961 if (LineBuffer != LineCache.end()) {
962 if (LineInfo.Line > LineBuffer->second.size())
963 return;
964 // Vector begins at 0, line numbers are non-zero
965 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
966 << "\n";
967 }
968 }
969 }
970 OldLineInfo = LineInfo;
971}
972
973static bool isArmElf(const ObjectFile *Obj) {
974 return (Obj->isELF() &&
975 (Obj->getArch() == Triple::aarch64 ||
976 Obj->getArch() == Triple::aarch64_be ||
977 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
978 Obj->getArch() == Triple::thumb ||
979 Obj->getArch() == Triple::thumbeb));
980}
981
982class PrettyPrinter {
983public:
984 virtual ~PrettyPrinter() = default;
985 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
986 ArrayRef<uint8_t> Bytes, uint64_t Address,
987 raw_ostream &OS, StringRef Annot,
988 MCSubtargetInfo const &STI, SourcePrinter *SP,
989 std::vector<RelocationRef> *Rels = nullptr) {
990 if (SP && (PrintSource || PrintLines))
991 SP->printSourceLine(OS, Address);
992 if (!NoLeadingAddr)
993 OS << format("%8" PRIx64 ":", Address);
994 if (!NoShowRawInsn) {
995 OS << "\t";
996 dumpBytes(Bytes, OS);
997 }
998 if (MI)
999 IP.printInst(MI, OS, "", STI);
1000 else
1001 OS << " <unknown>";
1002 }
1003};
1004PrettyPrinter PrettyPrinterInst;
1005class HexagonPrettyPrinter : public PrettyPrinter {
1006public:
1007 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1008 raw_ostream &OS) {
1009 uint32_t opcode =
1010 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1011 if (!NoLeadingAddr)
1012 OS << format("%8" PRIx64 ":", Address);
1013 if (!NoShowRawInsn) {
1014 OS << "\t";
1015 dumpBytes(Bytes.slice(0, 4), OS);
1016 OS << format("%08" PRIx32, opcode);
1017 }
1018 }
1019 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1020 uint64_t Address, raw_ostream &OS, StringRef Annot,
1021 MCSubtargetInfo const &STI, SourcePrinter *SP,
1022 std::vector<RelocationRef> *Rels) override {
1023 if (SP && (PrintSource || PrintLines))
1024 SP->printSourceLine(OS, Address, "");
1025 if (!MI) {
1026 printLead(Bytes, Address, OS);
1027 OS << " <unknown>";
1028 return;
1029 }
1030 std::string Buffer;
1031 {
1032 raw_string_ostream TempStream(Buffer);
1033 IP.printInst(MI, TempStream, "", STI);
1034 }
1035 StringRef Contents(Buffer);
1036 // Split off bundle attributes
1037 auto PacketBundle = Contents.rsplit('\n');
1038 // Split off first instruction from the rest
1039 auto HeadTail = PacketBundle.first.split('\n');
1040 auto Preamble = " { ";
1041 auto Separator = "";
1042 StringRef Fmt = "\t\t\t%08" PRIx64 ": ";
George Rimar73a27232019-01-15 09:19:18 +00001043 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
1044 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
Sid Manningd9f28732018-05-14 19:46:08 +00001045
1046 // Hexagon's packets require relocations to be inline rather than
1047 // clustered at the end of the packet.
1048 auto PrintReloc = [&]() -> void {
George Rimar73a27232019-01-15 09:19:18 +00001049 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
1050 if (RelCur->getOffset() == Address) {
1051 SmallString<16> Name;
1052 SmallString<32> Val;
1053 RelCur->getTypeName(Name);
1054 error(getRelocationValueString(*RelCur, Val));
1055 OS << Separator << format(Fmt.data(), Address) << Name << "\t" << Val
Sid Manningd9f28732018-05-14 19:46:08 +00001056 << "\n";
1057 return;
1058 }
George Rimar73a27232019-01-15 09:19:18 +00001059 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +00001060 }
1061 };
1062
George Rimar73a27232019-01-15 09:19:18 +00001063 while (!HeadTail.first.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +00001064 OS << Separator;
1065 Separator = "\n";
1066 if (SP && (PrintSource || PrintLines))
1067 SP->printSourceLine(OS, Address, "");
1068 printLead(Bytes, Address, OS);
1069 OS << Preamble;
1070 Preamble = " ";
1071 StringRef Inst;
1072 auto Duplex = HeadTail.first.split('\v');
George Rimar73a27232019-01-15 09:19:18 +00001073 if (!Duplex.second.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +00001074 OS << Duplex.first;
1075 OS << "; ";
1076 Inst = Duplex.second;
1077 }
1078 else
1079 Inst = HeadTail.first;
1080 OS << Inst;
1081 HeadTail = HeadTail.second.split('\n');
1082 if (HeadTail.first.empty())
1083 OS << " } " << PacketBundle.second;
1084 PrintReloc();
1085 Bytes = Bytes.slice(4);
1086 Address += 4;
1087 }
1088 }
1089};
1090HexagonPrettyPrinter HexagonPrettyPrinterInst;
1091
1092class AMDGCNPrettyPrinter : public PrettyPrinter {
1093public:
1094 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1095 uint64_t Address, raw_ostream &OS, StringRef Annot,
1096 MCSubtargetInfo const &STI, SourcePrinter *SP,
1097 std::vector<RelocationRef> *Rels) override {
1098 if (SP && (PrintSource || PrintLines))
1099 SP->printSourceLine(OS, Address);
1100
1101 typedef support::ulittle32_t U32;
1102
1103 if (MI) {
1104 SmallString<40> InstStr;
1105 raw_svector_ostream IS(InstStr);
1106
1107 IP.printInst(MI, IS, "", STI);
1108
1109 OS << left_justify(IS.str(), 60);
1110 } else {
1111 // an unrecognized encoding - this is probably data so represent it
1112 // using the .long directive, or .byte directive if fewer than 4 bytes
1113 // remaining
1114 if (Bytes.size() >= 4) {
1115 OS << format("\t.long 0x%08" PRIx32 " ",
1116 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1117 OS.indent(42);
1118 } else {
1119 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
1120 for (unsigned int i = 1; i < Bytes.size(); i++)
1121 OS << format(", 0x%02" PRIx8, Bytes[i]);
1122 OS.indent(55 - (6 * Bytes.size()));
1123 }
1124 }
1125
1126 OS << format("// %012" PRIX64 ": ", Address);
1127 if (Bytes.size() >=4) {
1128 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1129 Bytes.size() / sizeof(U32)))
1130 // D should be explicitly casted to uint32_t here as it is passed
1131 // by format to snprintf as vararg.
1132 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
1133 } else {
1134 for (unsigned int i = 0; i < Bytes.size(); i++)
1135 OS << format("%02" PRIX8 " ", Bytes[i]);
1136 }
1137
1138 if (!Annot.empty())
1139 OS << "// " << Annot;
1140 }
1141};
1142AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1143
1144class BPFPrettyPrinter : public PrettyPrinter {
1145public:
1146 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1147 uint64_t Address, raw_ostream &OS, StringRef Annot,
1148 MCSubtargetInfo const &STI, SourcePrinter *SP,
1149 std::vector<RelocationRef> *Rels) override {
1150 if (SP && (PrintSource || PrintLines))
1151 SP->printSourceLine(OS, Address);
1152 if (!NoLeadingAddr)
1153 OS << format("%8" PRId64 ":", Address / 8);
1154 if (!NoShowRawInsn) {
1155 OS << "\t";
1156 dumpBytes(Bytes, OS);
1157 }
1158 if (MI)
1159 IP.printInst(MI, OS, "", STI);
1160 else
1161 OS << " <unknown>";
1162 }
1163};
1164BPFPrettyPrinter BPFPrettyPrinterInst;
1165
1166PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1167 switch(Triple.getArch()) {
1168 default:
1169 return PrettyPrinterInst;
1170 case Triple::hexagon:
1171 return HexagonPrettyPrinterInst;
1172 case Triple::amdgcn:
1173 return AMDGCNPrettyPrinterInst;
1174 case Triple::bpfel:
1175 case Triple::bpfeb:
1176 return BPFPrettyPrinterInst;
1177 }
1178}
1179}
1180
Sam Koltonc05d7782016-08-17 10:17:57 +00001181static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1182 assert(Obj->isELF());
1183 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1184 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1185 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1186 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1187 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1188 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1189 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1190 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1191 llvm_unreachable("Unsupported binary format");
1192}
1193
Sam Parker5fba45a2017-02-08 09:44:18 +00001194template <class ELFT> static void
1195addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1196 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1197 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1198 uint8_t SymbolType = Symbol.getELFType();
1199 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1200 continue;
1201
1202 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1203 if (!AddressOrErr)
1204 report_error(Obj->getFileName(), AddressOrErr.takeError());
Sam Parker5fba45a2017-02-08 09:44:18 +00001205
1206 Expected<StringRef> Name = Symbol.getName();
1207 if (!Name)
1208 report_error(Obj->getFileName(), Name.takeError());
1209 if (Name->empty())
1210 continue;
1211
1212 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1213 if (!SectionOrErr)
1214 report_error(Obj->getFileName(), SectionOrErr.takeError());
1215 section_iterator SecI = *SectionOrErr;
1216 if (SecI == Obj->section_end())
1217 continue;
1218
George Rimar73a27232019-01-15 09:19:18 +00001219 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
Sam Parker5fba45a2017-02-08 09:44:18 +00001220 }
1221}
1222
1223static void
1224addDynamicElfSymbols(const ObjectFile *Obj,
1225 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1226 assert(Obj->isELF());
1227 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1228 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1229 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1230 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1231 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1232 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1233 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1234 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1235 else
1236 llvm_unreachable("Unsupported binary format");
1237}
1238
Joel Galenson134cf472018-08-24 15:21:57 +00001239static void addPltEntries(const ObjectFile *Obj,
1240 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1241 StringSaver &Saver) {
1242 Optional<SectionRef> Plt = None;
1243 for (const SectionRef &Section : Obj->sections()) {
1244 StringRef Name;
1245 if (Section.getName(Name))
1246 continue;
1247 if (Name == ".plt")
1248 Plt = Section;
1249 }
1250 if (!Plt)
1251 return;
1252 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1253 for (auto PltEntry : ElfObj->getPltAddresses()) {
1254 SymbolRef Symbol(PltEntry.first, ElfObj);
Joel Galenson134cf472018-08-24 15:21:57 +00001255 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1256
1257 Expected<StringRef> NameOrErr = Symbol.getName();
1258 if (!NameOrErr)
1259 report_error(Obj->getFileName(), NameOrErr.takeError());
1260 if (NameOrErr->empty())
1261 continue;
1262 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1263
1264 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1265 }
1266 }
1267}
1268
George Rimar70d197d2019-01-10 14:55:26 +00001269// Normally the disassembly output will skip blocks of zeroes. This function
1270// returns the number of zero bytes that can be skipped when dumping the
1271// disassembly of the instructions in Buf.
1272static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
1273 // When -z or --disassemble-zeroes are given we always dissasemble them.
1274 if (DisassembleZeroes)
1275 return 0;
1276
1277 // Find the number of leading zeroes.
1278 size_t N = 0;
1279 while (N < Buf.size() && !Buf[N])
1280 ++N;
1281
1282 // We may want to skip blocks of zero bytes, but unless we see
1283 // at least 8 of them in a row.
1284 if (N < 8)
1285 return 0;
1286
1287 // We skip zeroes in multiples of 4 because do not want to truncate an
1288 // instruction if it starts with a zero byte.
1289 return N & ~0x3;
1290}
1291
George Rimar73a27232019-01-15 09:19:18 +00001292static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001293 if (StartAddress > StopAddress)
1294 error("Start address should be less than stop address");
1295
Jim Grosbachaf9aec02012-08-07 17:53:14 +00001296 const Target *TheTarget = getTarget(Obj);
Michael J. Spencer2670c252011-01-20 06:39:06 +00001297
Jack Carter551efd72012-08-28 19:24:49 +00001298 // Package up features to be passed to target/subtarget
Daniel Sanders1d148642016-06-16 09:17:03 +00001299 SubtargetFeatures Features = Obj->getFeatures();
George Rimar73a27232019-01-15 09:19:18 +00001300 if (!MAttrs.empty())
1301 for (unsigned I = 0; I != MAttrs.size(); ++I)
1302 Features.AddFeature(MAttrs[I]);
Jack Carter551efd72012-08-28 19:24:49 +00001303
Ahmed Charles56440fd2014-03-06 05:51:42 +00001304 std::unique_ptr<const MCRegisterInfo> MRI(
1305 TheTarget->createMCRegInfo(TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001306 if (!MRI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001307 report_error(Obj->getFileName(), "no register info for target " +
1308 TripleName);
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001309
1310 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001311 std::unique_ptr<const MCAsmInfo> AsmInfo(
1312 TheTarget->createMCAsmInfo(*MRI, TripleName));
Davide Italiano711e4952015-12-17 01:59:50 +00001313 if (!AsmInfo)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001314 report_error(Obj->getFileName(), "no assembly info for target " +
1315 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001316 std::unique_ptr<const MCSubtargetInfo> STI(
Daniel Sanders1d148642016-06-16 09:17:03 +00001317 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
Davide Italiano711e4952015-12-17 01:59:50 +00001318 if (!STI)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001319 report_error(Obj->getFileName(), "no subtarget info for target " +
1320 TripleName);
Ahmed Charles56440fd2014-03-06 05:51:42 +00001321 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
Davide Italiano711e4952015-12-17 01:59:50 +00001322 if (!MII)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001323 report_error(Obj->getFileName(), "no instruction info for target " +
1324 TripleName);
Sam Kolton3381d7a2016-10-06 13:46:08 +00001325 MCObjectFileInfo MOFI;
1326 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1327 // FIXME: for now initialize MCObjectFileInfo with default values
Rafael Espindola9f929952017-08-02 20:32:26 +00001328 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
Lang Hamesa1bc0f52014-04-15 04:40:56 +00001329
1330 std::unique_ptr<MCDisassembler> DisAsm(
1331 TheTarget->createMCDisassembler(*STI, Ctx));
Davide Italiano711e4952015-12-17 01:59:50 +00001332 if (!DisAsm)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001333 report_error(Obj->getFileName(), "no disassembler for target " +
1334 TripleName);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001335
Ahmed Charles56440fd2014-03-06 05:51:42 +00001336 std::unique_ptr<const MCInstrAnalysis> MIA(
1337 TheTarget->createMCInstrAnalysis(MII.get()));
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001338
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001339 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Daniel Sanders50f17232015-09-15 16:17:27 +00001340 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1341 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
Davide Italiano711e4952015-12-17 01:59:50 +00001342 if (!IP)
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001343 report_error(Obj->getFileName(), "no instruction printer for target " +
1344 TripleName);
Colin LeMahieu14ec76e2015-06-07 21:07:17 +00001345 IP->setPrintImmHex(PrintImmHex);
Colin LeMahieu35436a22015-05-29 14:48:25 +00001346 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
Ahmed Bougacha0835ca12013-05-16 21:28:23 +00001347
Greg Fitzgerald18432272014-03-20 22:55:15 +00001348 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ": " :
1349 "\t\t\t%08" PRIx64 ": ";
1350
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001351 SourcePrinter SP(Obj, TheTarget->getName());
1352
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001353 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1354 // in RelocSecs contain the relocations for section S.
Rafael Espindola4453e42942014-06-13 03:07:50 +00001355 std::error_code EC;
Alexey Samsonov48803e52014-03-13 14:37:36 +00001356 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001357 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001358 section_iterator Sec2 = Section.getRelocatedSection();
Rafael Espindolab5155a52014-02-10 20:24:04 +00001359 if (Sec2 != Obj->section_end())
Alexey Samsonov48803e52014-03-13 14:37:36 +00001360 SectionRelocMap[*Sec2].push_back(Section);
Mark Seaborn0929d3d2014-01-25 17:38:19 +00001361 }
1362
David Majnemer81afca62015-07-07 22:06:59 +00001363 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001364 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001365 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001366 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001367 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +00001368 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001369 if (!AddressOrErr)
1370 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001371 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +00001372
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001373 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001374 if (!Name)
1375 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001376 if (Name->empty())
1377 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001378
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001379 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001380 if (!SectionOrErr)
1381 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001382
Sam Koltonc05d7782016-08-17 10:17:57 +00001383 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001384 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +00001385 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +00001386
Sterling Augustinebc78b622018-06-28 18:57:13 +00001387 section_iterator SecI = *SectionOrErr;
1388 if (SecI != Obj->section_end())
1389 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1390 else
1391 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1392
Sam Koltonc05d7782016-08-17 10:17:57 +00001393
David Majnemer81afca62015-07-07 22:06:59 +00001394 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001395 if (AllSymbols.empty() && Obj->isELF())
1396 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001397
Joel Galenson134cf472018-08-24 15:21:57 +00001398 BumpPtrAllocator A;
1399 StringSaver Saver(A);
1400 addPltEntries(Obj, AllSymbols, Saver);
1401
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001402 // Create a mapping from virtual address to section.
1403 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1404 for (SectionRef Sec : Obj->sections())
1405 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1406 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1407
1408 // Linked executables (.exe and .dll files) typically don't include a real
1409 // symbol table but they might contain an export table.
1410 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1411 for (const auto &ExportEntry : COFFObj->export_directories()) {
1412 StringRef Name;
1413 error(ExportEntry.getSymbolName(Name));
1414 if (Name.empty())
1415 continue;
1416 uint32_t RVA;
1417 error(ExportEntry.getExportRVA(RVA));
1418
1419 uint64_t VA = COFFObj->getImageBase() + RVA;
1420 auto Sec = std::upper_bound(
1421 SectionAddresses.begin(), SectionAddresses.end(), VA,
1422 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1423 return LHS < RHS.first;
1424 });
1425 if (Sec != SectionAddresses.begin())
1426 --Sec;
1427 else
1428 Sec = SectionAddresses.end();
1429
1430 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +00001431 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001432 else
1433 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001434 }
1435 }
1436
1437 // Sort all the symbols, this allows us to use a simple binary search to find
1438 // a symbol near an address.
1439 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1440 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001441 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001442
Colin LeMahieu77804be2015-07-29 15:45:39 +00001443 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001444 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001445 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001446
Rafael Espindola80291272014-10-08 15:28:58 +00001447 uint64_t SectionAddr = Section.getAddress();
1448 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001449 if (!SectSize)
1450 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001451
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001452 // Get the list of all the symbols in this section.
1453 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001454 std::vector<uint64_t> DataMappingSymsAddr;
1455 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001456 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001457 for (const auto &Symb : Symbols) {
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001458 uint64_t Address = std::get<0>(Symb);
1459 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001460 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001461 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001462 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001463 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001464 if (Name.startswith("$a"))
1465 TextMappingSymsAddr.push_back(Address - SectionAddr);
1466 if (Name.startswith("$t"))
1467 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001468 }
1469 }
1470
Fangrui Song0cac7262018-09-27 02:13:45 +00001471 llvm::sort(DataMappingSymsAddr);
1472 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001473
Sam Kolton3381d7a2016-10-06 13:46:08 +00001474 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1475 // AMDGPU disassembler uses symbolizer for printing labels
1476 std::unique_ptr<MCRelocationInfo> RelInfo(
1477 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1478 if (RelInfo) {
1479 std::unique_ptr<MCSymbolizer> Symbolizer(
1480 TheTarget->createMCSymbolizer(
1481 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1482 DisAsm->setSymbolizer(std::move(Symbolizer));
1483 }
1484 }
1485
Michael J. Spencer51862b32011-10-13 22:17:18 +00001486 // Make a list of all the relocations for this section.
1487 std::vector<RelocationRef> Rels;
1488 if (InlineRelocs) {
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001489 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1490 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1491 Rels.push_back(Reloc);
1492 }
Michael J. Spencer51862b32011-10-13 22:17:18 +00001493 }
1494 }
1495
1496 // Sort relocations by address.
George Rimar73a27232019-01-15 09:19:18 +00001497 llvm::sort(Rels, isRelocAddressLess);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001498
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001499 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001500 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001501 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001502 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001503 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001504 StringRef SectionName;
1505 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001506
Rafael Espindola7884c952015-06-04 15:01:05 +00001507 // If the section has no symbol at the start, just insert a dummy one.
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001508 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001509 Symbols.insert(
1510 Symbols.begin(),
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001511 std::make_tuple(SectionAddr, SectionName,
1512 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001513 }
Alp Tokere69170a2014-06-26 22:52:05 +00001514
1515 SmallString<40> Comments;
1516 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001517
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001518 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001519 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001520 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1521 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001522
Michael J. Spencer2670c252011-01-20 06:39:06 +00001523 uint64_t Size;
1524 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001525 bool PrintedSection = false;
Michael J. Spencer2670c252011-01-20 06:39:06 +00001526
George Rimar73a27232019-01-15 09:19:18 +00001527 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1528 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001529 // Disassemble symbol by symbol.
George Rimar73a27232019-01-15 09:19:18 +00001530 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001531 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001532 // The end is either the section end or the beginning of the next
1533 // symbol.
George Rimar73a27232019-01-15 09:19:18 +00001534 uint64_t End = (SI == SE - 1)
1535 ? SectSize
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001536 : std::get<0>(Symbols[SI + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001537 // Don't try to disassemble beyond the end of section contents.
1538 if (End > SectSize)
1539 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001540 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001541 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001542 continue;
1543
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001544 // Check if we need to skip symbol
1545 // Skip if the symbol's data is not between StartAddress and StopAddress
1546 if (End + SectionAddr < StartAddress ||
1547 Start + SectionAddr > StopAddress) {
1548 continue;
1549 }
1550
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001551 /// Skip if user requested specific symbols and this is not in the list
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001552 if (!DisasmFuncsSet.empty() &&
1553 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001554 continue;
1555
1556 if (!PrintedSection) {
1557 PrintedSection = true;
1558 outs() << "Disassembly of section ";
1559 if (!SegmentName.empty())
1560 outs() << SegmentName << ",";
1561 outs() << SectionName << ':';
1562 }
1563
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001564 // Stop disassembly at the stop address specified
1565 if (End + SectionAddr > StopAddress)
1566 End = StopAddress - SectionAddr;
1567
Valery Pykhtinde048052016-04-07 07:24:01 +00001568 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001569 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001570 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1571 Start += 256;
1572 }
George Rimar73a27232019-01-15 09:19:18 +00001573 if (SI == SE - 1 ||
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001574 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001575 // cut trailing zeroes at the end of kernel
1576 // cut up to 256 bytes
1577 const uint64_t EndAlign = 256;
1578 const auto Limit = End - (std::min)(EndAlign, End - Start);
1579 while (End > Limit &&
1580 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1581 End -= 4;
1582 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001583 }
1584
George Rimar6622d412018-12-19 10:21:45 +00001585 outs() << '\n';
George Rimar3ba0f3c02019-01-09 14:43:33 +00001586 if (!NoLeadingAddr)
1587 outs() << format("%016" PRIx64 " ", SectionAddr + Start);
1588
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001589 StringRef SymbolName = std::get<1>(Symbols[SI]);
George Rimar6622d412018-12-19 10:21:45 +00001590 if (Demangle)
1591 outs() << demangle(SymbolName) << ":\n";
1592 else
1593 outs() << SymbolName << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001594
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001595 // Don't print raw contents of a virtual section. A virtual section
1596 // doesn't have any contents in the file.
1597 if (Section.isVirtual()) {
1598 outs() << "...\n";
1599 continue;
1600 }
1601
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001602#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001603 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001604#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001605 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001606#endif
1607
Wouter van Oortmerssenf3b762a2019-01-17 18:14:09 +00001608 // Some targets (like WebAssembly) have a special prelude at the start
1609 // of each symbol.
1610 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1611 SectionAddr + Start, DebugOut, CommentStream);
1612 Start += Size;
1613
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001614 for (Index = Start; Index < End; Index += Size) {
1615 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001616
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001617 if (Index + SectionAddr < StartAddress ||
1618 Index + SectionAddr > StopAddress) {
1619 // skip byte by byte till StartAddress is reached
1620 Size = 1;
1621 continue;
1622 }
Davide Italianof0706882015-10-01 21:57:09 +00001623 // AArch64 ELF binaries can interleave data and text in the
1624 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001625 // understand what we need to dump. If the data marker is within a
1626 // function, it is denoted as a word/short etc
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001627 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001628 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001629 uint64_t Stride = 0;
1630
1631 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1632 DataMappingSymsAddr.end(), Index);
1633 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1634 // Switch to data.
1635 while (Index < End) {
1636 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1637 outs() << "\t";
1638 if (Index + 4 <= End) {
1639 Stride = 4;
1640 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001641 outs() << "\t.word\t";
1642 uint32_t Data = 0;
1643 if (Obj->isLittleEndian()) {
1644 const auto Word =
1645 reinterpret_cast<const support::ulittle32_t *>(
1646 Bytes.data() + Index);
1647 Data = *Word;
1648 } else {
1649 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1650 Bytes.data() + Index);
1651 Data = *Word;
1652 }
1653 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001654 } else if (Index + 2 <= End) {
1655 Stride = 2;
1656 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001657 outs() << "\t\t.short\t";
1658 uint16_t Data = 0;
1659 if (Obj->isLittleEndian()) {
1660 const auto Short =
1661 reinterpret_cast<const support::ulittle16_t *>(
1662 Bytes.data() + Index);
1663 Data = *Short;
1664 } else {
1665 const auto Short =
1666 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1667 Index);
1668 Data = *Short;
1669 }
1670 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001671 } else {
1672 Stride = 1;
1673 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001674 outs() << "\t\t.byte\t";
1675 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001676 }
1677 Index += Stride;
1678 outs() << "\n";
1679 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1680 TextMappingSymsAddr.end(), Index);
1681 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1682 break;
1683 }
1684 }
1685 }
1686
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001687 // If there is a data symbol inside an ELF text section and we are only
1688 // disassembling text (applicable all architectures),
1689 // we are in a situation where we must print the data and not
1690 // disassemble it.
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001691 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001692 !DisassembleAll && Section.isText()) {
1693 // print out data up to 8 bytes at a time in hex and ascii
1694 uint8_t AsciiData[9] = {'\0'};
1695 uint8_t Byte;
1696 int NumBytes = 0;
1697
1698 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001699 if (((SectionAddr + Index) < StartAddress) ||
1700 ((SectionAddr + Index) > StopAddress))
1701 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001702 if (NumBytes == 0) {
1703 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1704 outs() << "\t";
1705 }
1706 Byte = Bytes.slice(Index)[0];
1707 outs() << format(" %02x", Byte);
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001708 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001709
1710 uint8_t IndentOffset = 0;
1711 NumBytes++;
1712 if (Index == End - 1 || NumBytes > 8) {
1713 // Indent the space for less than 8 bytes data.
1714 // 2 spaces for byte and one for space between bytes
1715 IndentOffset = 3 * (8 - NumBytes);
1716 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1717 AsciiData[Excess] = '\0';
1718 NumBytes = 8;
1719 }
1720 if (NumBytes == 8) {
1721 AsciiData[8] = '\0';
1722 outs() << std::string(IndentOffset, ' ') << " ";
1723 outs() << reinterpret_cast<char *>(AsciiData);
1724 outs() << '\n';
1725 NumBytes = 0;
1726 }
1727 }
1728 }
Davide Italianof0706882015-10-01 21:57:09 +00001729 if (Index >= End)
1730 break;
1731
George Rimar70d197d2019-01-10 14:55:26 +00001732 if (size_t N =
1733 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) {
1734 outs() << "\t\t..." << '\n';
1735 Index += N;
1736 if (Index >= End)
1737 break;
1738 }
1739
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001740 // Disassemble a real instruction or a data when disassemble all is
1741 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001742 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1743 SectionAddr + Index, DebugOut,
1744 CommentStream);
1745 if (Size == 0)
1746 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001747
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001748 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001749 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
Sid Manningd9f28732018-05-14 19:46:08 +00001750 *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001751 outs() << CommentStream.str();
1752 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001753
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001754 // Try to resolve the target of a call, tail call, etc. to a specific
1755 // symbol.
1756 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1757 MIA->isConditionalBranch(Inst))) {
1758 uint64_t Target;
1759 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1760 // In a relocatable object, the target's section must reside in
1761 // the same section as the call instruction or it is accessed
1762 // through a relocation.
1763 //
1764 // In a non-relocatable object, the target may be in any section.
1765 //
1766 // N.B. We don't walk the relocations in the relocatable case yet.
1767 auto *TargetSectionSymbols = &Symbols;
1768 if (!Obj->isRelocatableObject()) {
1769 auto SectionAddress = std::upper_bound(
1770 SectionAddresses.begin(), SectionAddresses.end(), Target,
1771 [](uint64_t LHS,
1772 const std::pair<uint64_t, SectionRef> &RHS) {
1773 return LHS < RHS.first;
1774 });
1775 if (SectionAddress != SectionAddresses.begin()) {
1776 --SectionAddress;
1777 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1778 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001779 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001780 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001781 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001782
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001783 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001784 // or equal to the target. If there isn't a section that contains
1785 // the target, find the nearest preceding absolute symbol.
1786 auto TargetSym = std::upper_bound(
1787 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001788 Target, [](uint64_t LHS,
1789 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1790 return LHS < std::get<0>(RHS);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001791 });
1792 if (TargetSym == TargetSectionSymbols->begin()) {
1793 TargetSectionSymbols = &AbsoluteSymbols;
1794 TargetSym = std::upper_bound(
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001795 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1796 Target, [](uint64_t LHS,
1797 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1798 return LHS < std::get<0>(RHS);
1799 });
Sterling Augustinebc78b622018-06-28 18:57:13 +00001800 }
1801 if (TargetSym != TargetSectionSymbols->begin()) {
1802 --TargetSym;
Clement Courbet2d7d4a32019-01-18 09:40:19 +00001803 uint64_t TargetAddress = std::get<0>(*TargetSym);
1804 StringRef TargetName = std::get<1>(*TargetSym);
1805 outs() << " <" << TargetName;
1806 uint64_t Disp = Target - TargetAddress;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001807 if (Disp)
1808 outs() << "+0x" << Twine::utohexstr(Disp);
1809 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001810 }
1811 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001812 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001813 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001814
Sid Manningd9f28732018-05-14 19:46:08 +00001815 // Hexagon does this in pretty printer
1816 if (Obj->getArch() != Triple::hexagon)
1817 // Print relocation for instruction.
George Rimar73a27232019-01-15 09:19:18 +00001818 while (RelCur != RelEnd) {
1819 uint64_t Addr = RelCur->getOffset();
1820 SmallString<16> Name;
1821 SmallString<32> Val;
Owen Andersonfa3e5202011-10-25 20:35:53 +00001822
Sid Manningd9f28732018-05-14 19:46:08 +00001823 // If this relocation is hidden, skip it.
George Rimar73a27232019-01-15 09:19:18 +00001824 if (getHidden(*RelCur) || ((SectionAddr + Addr) < StartAddress)) {
1825 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +00001826 continue;
1827 }
1828
1829 // Stop when rel_cur's address is past the current instruction.
George Rimar73a27232019-01-15 09:19:18 +00001830 if (Addr >= Index + Size)
1831 break;
1832 RelCur->getTypeName(Name);
1833 error(getRelocationValueString(*RelCur, Val));
1834 outs() << format(Fmt.data(), SectionAddr + Addr) << Name << "\t"
1835 << Val << "\n";
1836 ++RelCur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001837 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001838 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001839 }
1840 }
1841}
1842
George Rimar73a27232019-01-15 09:19:18 +00001843void llvm::printRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001844 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1845 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001846 // Regular objdump doesn't print relocations in non-relocatable object
1847 // files.
1848 if (!Obj->isRelocatableObject())
1849 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001850
Colin LeMahieu77804be2015-07-29 15:45:39 +00001851 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001852 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001853 continue;
George Rimar73a27232019-01-15 09:19:18 +00001854 StringRef SecName;
1855 error(Section.getName(SecName));
1856 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001857 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001858 uint64_t Address = Reloc.getOffset();
1859 SmallString<32> RelocName;
1860 SmallString<32> ValueStr;
1861 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001862 continue;
George Rimar73a27232019-01-15 09:19:18 +00001863 Reloc.getTypeName(RelocName);
1864 error(getRelocationValueString(Reloc, ValueStr));
1865 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1866 << ValueStr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001867 }
1868 outs() << "\n";
1869 }
1870}
1871
George Rimar73a27232019-01-15 09:19:18 +00001872void llvm::printDynamicRelocations(const ObjectFile *Obj) {
Paul Semelcb0f0432018-06-07 13:30:55 +00001873 // For the moment, this option is for ELF only
1874 if (!Obj->isELF())
1875 return;
1876
1877 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
Paul Semelcb0f0432018-06-07 13:30:55 +00001878 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1879 error("not a dynamic object");
1880 return;
1881 }
1882
Paul Semelcb0f0432018-06-07 13:30:55 +00001883 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1884 if (DynRelSec.empty())
1885 return;
1886
1887 outs() << "DYNAMIC RELOCATION RECORDS\n";
George Rimar73a27232019-01-15 09:19:18 +00001888 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Paul Semelcb0f0432018-06-07 13:30:55 +00001889 for (const SectionRef &Section : DynRelSec) {
1890 if (Section.relocation_begin() == Section.relocation_end())
1891 continue;
1892 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001893 uint64_t Address = Reloc.getOffset();
1894 SmallString<32> RelocName;
1895 SmallString<32> ValueStr;
1896 Reloc.getTypeName(RelocName);
1897 error(getRelocationValueString(Reloc, ValueStr));
1898 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1899 << ValueStr << "\n";
Paul Semelcb0f0432018-06-07 13:30:55 +00001900 }
1901 }
1902}
1903
George Rimar73a27232019-01-15 09:19:18 +00001904void llvm::printSectionHeaders(const ObjectFile *Obj) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001905 outs() << "Sections:\n"
1906 "Idx Name Size Address Type\n";
Colin LeMahieu77804be2015-07-29 15:45:39 +00001907 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001908 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001909 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001910 uint64_t Address = Section.getAddress();
1911 uint64_t Size = Section.getSize();
1912 bool Text = Section.isText();
1913 bool Data = Section.isData();
1914 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001915 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001916 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimare35e6442018-07-18 08:34:35 +00001917 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
George Rimarc1090da2018-07-18 09:25:36 +00001918 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1919 Address, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001920 }
Xing GUO785edea2018-11-17 08:12:48 +00001921 outs() << "\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001922}
1923
George Rimar73a27232019-01-15 09:19:18 +00001924void llvm::printSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001925 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001926 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001927 StringRef Name;
1928 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001929 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001930 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001931 uint64_t Size = Section.getSize();
1932 if (!Size)
1933 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001934
1935 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001936 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001937 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001938 ", %04" PRIx64 ")>\n",
1939 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001940 continue;
1941 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001942
Davide Italianoccd53fe2015-08-05 07:18:31 +00001943 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001944
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001945 // Dump out the content as hex and printable ascii characters.
George Rimar73a27232019-01-15 09:19:18 +00001946 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1947 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001948 // Dump line of hex.
George Rimar73a27232019-01-15 09:19:18 +00001949 for (std::size_t I = 0; I < 16; ++I) {
1950 if (I != 0 && I % 4 == 0)
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001951 outs() << ' ';
George Rimar73a27232019-01-15 09:19:18 +00001952 if (Addr + I < End)
1953 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1954 << hexdigit(Contents[Addr + I] & 0xF, true);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001955 else
1956 outs() << " ";
1957 }
1958 // Print ascii.
1959 outs() << " ";
George Rimar73a27232019-01-15 09:19:18 +00001960 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1961 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1962 outs() << Contents[Addr + I];
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001963 else
1964 outs() << ".";
1965 }
1966 outs() << "\n";
1967 }
1968 }
1969}
1970
George Rimar73a27232019-01-15 09:19:18 +00001971void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
Kevin Enderby9acb1092016-05-31 20:35:34 +00001972 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001973 outs() << "SYMBOL TABLE:\n";
1974
George Rimar73a27232019-01-15 09:19:18 +00001975 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1976 printCOFFSymbolTable(Coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001977 return;
1978 }
George Rimar8e0a70b2019-01-10 16:24:10 +00001979
George Rimar73a27232019-01-15 09:19:18 +00001980 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
George Rimar8e0a70b2019-01-10 16:24:10 +00001981 // Skip printing the special zero symbol when dumping an ELF file.
1982 // This makes the output consistent with the GNU objdump.
George Rimar73a27232019-01-15 09:19:18 +00001983 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
George Rimar8e0a70b2019-01-10 16:24:10 +00001984 continue;
1985
1986 const SymbolRef &Symbol = *I;
Kevin Enderby931cb652016-06-24 18:24:42 +00001987 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1988 if (!AddressOrError)
George Rimar73a27232019-01-15 09:19:18 +00001989 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001990 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001991 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001992 if ((Address < StartAddress) || (Address > StopAddress))
1993 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001994 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1995 if (!TypeOrError)
George Rimar73a27232019-01-15 09:19:18 +00001996 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001997 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001998 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001999 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00002000 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002001 if (!SectionOrErr)
George Rimar73a27232019-01-15 09:19:18 +00002002 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00002003 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00002004 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00002005 StringRef Name;
George Rimar73a27232019-01-15 09:19:18 +00002006 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
Rafael Espindola75d5b542015-06-03 05:14:22 +00002007 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002008 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002009 Expected<StringRef> NameOrErr = Symbol.getName();
2010 if (!NameOrErr)
George Rimar73a27232019-01-15 09:19:18 +00002011 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
Kevin Enderby9acb1092016-05-31 20:35:34 +00002012 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002013 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00002014 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002015
Rui Ueyama4e39f712014-03-18 18:58:51 +00002016 bool Global = Flags & SymbolRef::SF_Global;
2017 bool Weak = Flags & SymbolRef::SF_Weak;
2018 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00002019 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00002020 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00002021
Rui Ueyama4e39f712014-03-18 18:58:51 +00002022 char GlobLoc = ' ';
2023 if (Type != SymbolRef::ST_Unknown)
2024 GlobLoc = Global ? 'g' : 'l';
2025 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2026 ? 'd' : ' ';
2027 char FileFunc = ' ';
2028 if (Type == SymbolRef::ST_File)
2029 FileFunc = 'f';
2030 else if (Type == SymbolRef::ST_Function)
2031 FileFunc = 'F';
Kristina Brooks0674f9d2018-11-11 17:47:13 +00002032 else if (Type == SymbolRef::ST_Data)
2033 FileFunc = 'O';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002034
George Rimar73a27232019-01-15 09:19:18 +00002035 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
Rui Ueyama4e39f712014-03-18 18:58:51 +00002036 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00002037
Rui Ueyama4e39f712014-03-18 18:58:51 +00002038 outs() << format(Fmt, Address) << " "
2039 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2040 << (Weak ? 'w' : ' ') // Weak?
2041 << ' ' // Constructor. Not supported yet.
2042 << ' ' // Warning. Not supported yet.
2043 << ' ' // Indirect reference to another symbol.
2044 << Debug // Debugging (d) or dynamic (D) symbol.
2045 << FileFunc // Name of function (F), file (f) or object (O).
2046 << ' ';
2047 if (Absolute) {
2048 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00002049 } else if (Common) {
2050 outs() << "*COM*";
George Rimar73a27232019-01-15 09:19:18 +00002051 } else if (Section == O->section_end()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00002052 outs() << "*UND*";
2053 } else {
2054 if (const MachOObjectFile *MachO =
George Rimar73a27232019-01-15 09:19:18 +00002055 dyn_cast<const MachOObjectFile>(O)) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00002056 DataRefImpl DR = Section->getRawDataRefImpl();
2057 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2058 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002059 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00002060 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002061 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00002062 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002063 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002064
2065 outs() << '\t';
George Rimar73a27232019-01-15 09:19:18 +00002066 if (Common || isa<ELFObjectFileBase>(O)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00002067 uint64_t Val =
2068 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00002069 outs() << format("\t %08" PRIx64 " ", Val);
2070 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00002071
George Rimar73a27232019-01-15 09:19:18 +00002072 if (Hidden)
Davide Italianocd2514d2015-04-30 23:08:53 +00002073 outs() << ".hidden ";
George Rimar6622d412018-12-19 10:21:45 +00002074
2075 if (Demangle)
2076 outs() << demangle(Name) << '\n';
2077 else
2078 outs() << Name << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002079 }
2080}
2081
George Rimar73a27232019-01-15 09:19:18 +00002082static void printUnwindInfo(const ObjectFile *O) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002083 outs() << "Unwind info:\n\n";
2084
George Rimar73a27232019-01-15 09:19:18 +00002085 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
2086 printCOFFUnwindInfo(Coff);
2087 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
Tim Northover4bd286a2014-08-01 13:07:19 +00002088 printMachOUnwindInfo(MachO);
George Rimar73a27232019-01-15 09:19:18 +00002089 else
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002090 // TODO: Extract DWARF dump tool to objdump.
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002091 WithColor::error(errs(), ToolName)
2092 << "This operation is only currently supported "
2093 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002094}
2095
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002096void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00002097 outs() << "Exports trie:\n";
2098 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2099 printMachOExportsTrie(MachO);
George Rimar73a27232019-01-15 09:19:18 +00002100 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002101 WithColor::error(errs(), ToolName)
2102 << "This operation is only currently supported "
2103 "for Mach-O executable files.\n";
Nick Kledzikd04bc352014-08-30 00:20:14 +00002104}
2105
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002106void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00002107 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002108 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00002109 printMachORebaseTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00002110 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002111 WithColor::error(errs(), ToolName)
2112 << "This operation is only currently supported "
2113 "for Mach-O executable files.\n";
Nick Kledzikac431442014-09-12 21:34:15 +00002114}
2115
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002116void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002117 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002118 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002119 printMachOBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00002120 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002121 WithColor::error(errs(), ToolName)
2122 << "This operation is only currently supported "
2123 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00002124}
2125
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002126void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002127 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002128 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002129 printMachOLazyBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00002130 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002131 WithColor::error(errs(), ToolName)
2132 << "This operation is only currently supported "
2133 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00002134}
2135
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002136void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00002137 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00002138 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00002139 printMachOWeakBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00002140 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002141 WithColor::error(errs(), ToolName)
2142 << "This operation is only currently supported "
2143 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00002144}
Nick Kledzikac431442014-09-12 21:34:15 +00002145
Adrian Prantl437105a2015-07-08 02:04:15 +00002146/// Dump the raw contents of the __clangast section so the output can be piped
2147/// into llvm-bcanalyzer.
2148void llvm::printRawClangAST(const ObjectFile *Obj) {
2149 if (outs().is_displayed()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002150 WithColor::error(errs(), ToolName)
2151 << "The -raw-clang-ast option will dump the raw binary contents of "
2152 "the clang ast section.\n"
2153 "Please redirect the output to a file or another program such as "
2154 "llvm-bcanalyzer.\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002155 return;
2156 }
2157
2158 StringRef ClangASTSectionName("__clangast");
2159 if (isa<COFFObjectFile>(Obj)) {
2160 ClangASTSectionName = "clangast";
2161 }
2162
2163 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00002164 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002165 StringRef Name;
2166 Sec.getName(Name);
2167 if (Name == ClangASTSectionName) {
2168 ClangASTSection = Sec;
2169 break;
2170 }
2171 }
2172 if (!ClangASTSection)
2173 return;
2174
2175 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002176 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00002177 outs().write(ClangASTContents.data(), ClangASTContents.size());
2178}
2179
Sanjoy Das6f567a42015-06-22 18:03:02 +00002180static void printFaultMaps(const ObjectFile *Obj) {
George Rimar73a27232019-01-15 09:19:18 +00002181 StringRef FaultMapSectionName;
Sanjoy Das6f567a42015-06-22 18:03:02 +00002182
2183 if (isa<ELFObjectFileBase>(Obj)) {
2184 FaultMapSectionName = ".llvm_faultmaps";
2185 } else if (isa<MachOObjectFile>(Obj)) {
2186 FaultMapSectionName = "__llvm_faultmaps";
2187 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002188 WithColor::error(errs(), ToolName)
2189 << "This operation is only currently supported "
2190 "for ELF and Mach-O executable files.\n";
Sanjoy Das6f567a42015-06-22 18:03:02 +00002191 return;
2192 }
2193
2194 Optional<object::SectionRef> FaultMapSection;
2195
Colin LeMahieu77804be2015-07-29 15:45:39 +00002196 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00002197 StringRef Name;
2198 Sec.getName(Name);
2199 if (Name == FaultMapSectionName) {
2200 FaultMapSection = Sec;
2201 break;
2202 }
2203 }
2204
2205 outs() << "FaultMap table:\n";
2206
2207 if (!FaultMapSection.hasValue()) {
2208 outs() << "<not found>\n";
2209 return;
2210 }
2211
2212 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00002213 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00002214
2215 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2216 FaultMapContents.bytes_end());
2217
2218 outs() << FMP;
2219}
2220
George Rimar73a27232019-01-15 09:19:18 +00002221static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
2222 if (O->isELF()) {
2223 printELFFileHeader(O);
2224 return printELFDynamicSection(O);
Paul Semel0913dcd2018-07-25 11:09:20 +00002225 }
George Rimar73a27232019-01-15 09:19:18 +00002226 if (O->isCOFF())
2227 return printCOFFFileHeader(O);
2228 if (O->isWasm())
2229 return printWasmFileHeader(O);
2230 if (O->isMachO()) {
2231 printMachOFileHeader(O);
2232 if (!OnlyFirst)
2233 printMachOLoadCommands(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002234 return;
2235 }
George Rimar73a27232019-01-15 09:19:18 +00002236 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00002237}
2238
George Rimar73a27232019-01-15 09:19:18 +00002239static void printFileHeaders(const ObjectFile *O) {
2240 if (!O->isELF() && !O->isCOFF())
2241 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Paul Semeld2af4d62018-07-04 15:25:03 +00002242
George Rimar73a27232019-01-15 09:19:18 +00002243 Triple::ArchType AT = O->getArch();
Paul Semeld2af4d62018-07-04 15:25:03 +00002244 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
George Rimar73a27232019-01-15 09:19:18 +00002245 Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
Paul Semeld2af4d62018-07-04 15:25:03 +00002246 if (!StartAddrOrErr)
George Rimar73a27232019-01-15 09:19:18 +00002247 report_error(O->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002248
George Rimar73a27232019-01-15 09:19:18 +00002249 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00002250 uint64_t Address = StartAddrOrErr.get();
Paul Semeld2af4d62018-07-04 15:25:03 +00002251 outs() << "start address: "
George Rimar9b6fe7e2019-01-12 12:17:24 +00002252 << "0x" << format(Fmt.data(), Address) << "\n\n";
Paul Semeld2af4d62018-07-04 15:25:03 +00002253}
2254
Paul Semel0dc92f62018-07-05 14:43:29 +00002255static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2256 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2257 if (!ModeOrErr) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002258 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
Paul Semel0dc92f62018-07-05 14:43:29 +00002259 consumeError(ModeOrErr.takeError());
2260 return;
2261 }
2262 sys::fs::perms Mode = ModeOrErr.get();
2263 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2264 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2265 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2266 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2267 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2268 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2269 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2270 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2271 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2272
2273 outs() << " ";
2274
2275 Expected<unsigned> UIDOrErr = C.getUID();
2276 if (!UIDOrErr)
2277 report_error(Filename, UIDOrErr.takeError());
2278 unsigned UID = UIDOrErr.get();
2279 outs() << format("%d/", UID);
2280
2281 Expected<unsigned> GIDOrErr = C.getGID();
2282 if (!GIDOrErr)
2283 report_error(Filename, GIDOrErr.takeError());
2284 unsigned GID = GIDOrErr.get();
2285 outs() << format("%-d ", GID);
2286
2287 Expected<uint64_t> Size = C.getRawSize();
2288 if (!Size)
2289 report_error(Filename, Size.takeError());
2290 outs() << format("%6" PRId64, Size.get()) << " ";
2291
2292 StringRef RawLastModified = C.getRawLastModified();
2293 unsigned Seconds;
2294 if (RawLastModified.getAsInteger(10, Seconds))
2295 outs() << "(date: \"" << RawLastModified
2296 << "\" contains non-decimal chars) ";
2297 else {
2298 // Since ctime(3) returns a 26 character string of the form:
2299 // "Sun Sep 16 01:03:52 1973\n\0"
2300 // just print 24 characters.
2301 time_t t = Seconds;
2302 outs() << format("%.24s ", ctime(&t));
2303 }
2304
2305 StringRef Name = "";
2306 Expected<StringRef> NameOrErr = C.getName();
2307 if (!NameOrErr) {
2308 consumeError(NameOrErr.takeError());
2309 Expected<StringRef> RawNameOrErr = C.getRawName();
2310 if (!RawNameOrErr)
2311 report_error(Filename, NameOrErr.takeError());
2312 Name = RawNameOrErr.get();
2313 } else {
2314 Name = NameOrErr.get();
2315 }
2316 outs() << Name << "\n";
2317}
2318
George Rimar73a27232019-01-15 09:19:18 +00002319static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
2320 const Archive::Child *C = nullptr) {
Adrian Prantl437105a2015-07-08 02:04:15 +00002321 // Avoid other output when using a raw option.
2322 if (!RawClangAST) {
2323 outs() << '\n';
George Rimar73a27232019-01-15 09:19:18 +00002324 if (A)
2325 outs() << A->getFileName() << "(" << O->getFileName() << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002326 else
George Rimar73a27232019-01-15 09:19:18 +00002327 outs() << O->getFileName();
2328 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00002329 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002330
George Rimar73a27232019-01-15 09:19:18 +00002331 StringRef ArchiveName = A ? A->getFileName() : "";
George Rimar9b6fe7e2019-01-12 12:17:24 +00002332 if (FileHeaders)
George Rimar73a27232019-01-15 09:19:18 +00002333 printFileHeaders(O);
2334 if (ArchiveHeaders && !MachOOpt && C)
2335 printArchiveChild(ArchiveName, *C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002336 if (Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00002337 disassembleObject(O, Relocations);
Michael J. Spencer51862b32011-10-13 22:17:18 +00002338 if (Relocations && !Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00002339 printRelocations(O);
Paul Semelcb0f0432018-06-07 13:30:55 +00002340 if (DynamicRelocations)
George Rimar73a27232019-01-15 09:19:18 +00002341 printDynamicRelocations(O);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00002342 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00002343 printSectionHeaders(O);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00002344 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00002345 printSectionContents(O);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002346 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00002347 printSymbolTable(O, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002348 if (UnwindInfo)
George Rimar73a27232019-01-15 09:19:18 +00002349 printUnwindInfo(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00002350 if (PrivateHeaders || FirstPrivateHeader)
George Rimar73a27232019-01-15 09:19:18 +00002351 printPrivateFileHeaders(O, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002352 if (ExportsTrie)
George Rimar73a27232019-01-15 09:19:18 +00002353 printExportsTrie(O);
Nick Kledzikac431442014-09-12 21:34:15 +00002354 if (Rebase)
George Rimar73a27232019-01-15 09:19:18 +00002355 printRebaseTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002356 if (Bind)
George Rimar73a27232019-01-15 09:19:18 +00002357 printBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002358 if (LazyBind)
George Rimar73a27232019-01-15 09:19:18 +00002359 printLazyBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002360 if (WeakBind)
George Rimar73a27232019-01-15 09:19:18 +00002361 printWeakBindTable(O);
Adrian Prantl437105a2015-07-08 02:04:15 +00002362 if (RawClangAST)
George Rimar73a27232019-01-15 09:19:18 +00002363 printRawClangAST(O);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002364 if (PrintFaultMaps)
George Rimar73a27232019-01-15 09:19:18 +00002365 printFaultMaps(O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002366 if (DwarfDumpType != DIDT_Null) {
George Rimar73a27232019-01-15 09:19:18 +00002367 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002368 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002369 DIDumpOptions DumpOpts;
2370 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002371 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002372 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002373}
2374
George Rimar73a27232019-01-15 09:19:18 +00002375static void dumpObject(const COFFImportFile *I, const Archive *A,
Paul Semel0dc92f62018-07-05 14:43:29 +00002376 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002377 StringRef ArchiveName = A ? A->getFileName() : "";
2378
2379 // Avoid other output when using a raw option.
2380 if (!RawClangAST)
2381 outs() << '\n'
2382 << ArchiveName << "(" << I->getFileName() << ")"
2383 << ":\tfile format COFF-import-file"
2384 << "\n\n";
2385
James Hendersonc1608c92018-10-29 14:17:08 +00002386 if (ArchiveHeaders && !MachOOpt && C)
2387 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002388 if (SymbolTable)
2389 printCOFFSymbolTable(I);
2390}
2391
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002392/// Dump each object file in \a a;
George Rimar73a27232019-01-15 09:19:18 +00002393static void dumpArchive(const Archive *A) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002394 Error Err = Error::success();
George Rimar73a27232019-01-15 09:19:18 +00002395 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002396 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2397 if (!ChildOrErr) {
2398 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimar73a27232019-01-15 09:19:18 +00002399 report_error(A->getFileName(), C, std::move(E));
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002400 continue;
2401 }
George Rimar73a27232019-01-15 09:19:18 +00002402 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2403 dumpObject(O, A, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002404 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
George Rimar73a27232019-01-15 09:19:18 +00002405 dumpObject(I, A, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002406 else
George Rimar73a27232019-01-15 09:19:18 +00002407 report_error(A->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002408 }
Lang Hamesfc209622016-07-14 02:24:01 +00002409 if (Err)
George Rimar73a27232019-01-15 09:19:18 +00002410 report_error(A->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002411}
2412
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002413/// Open file and figure out how to dump it.
George Rimar73a27232019-01-15 09:19:18 +00002414static void dumpInput(StringRef file) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002415 // If we are using the Mach-O specific object file parser, then let it parse
2416 // the file and process the command line options. So the -arch flags can
2417 // be used to select specific slices, etc.
2418 if (MachOOpt) {
George Rimar73a27232019-01-15 09:19:18 +00002419 parseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002420 return;
2421 }
2422
2423 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002424 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2425 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002426 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002427 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002428
George Rimar73a27232019-01-15 09:19:18 +00002429 if (Archive *A = dyn_cast<Archive>(&Binary))
2430 dumpArchive(A);
2431 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2432 dumpObject(O);
Dave Lee3fb120f2018-08-03 00:06:38 +00002433 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
George Rimar73a27232019-01-15 09:19:18 +00002434 parseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002435 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002436 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002437}
2438
Michael J. Spencer2670c252011-01-20 06:39:06 +00002439int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002440 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002441
2442 // Initialize targets and assembly printers/parsers.
2443 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002444 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002445 llvm::InitializeAllDisassemblers();
2446
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002447 // Register the target printer for --version.
2448 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2449
Michael J. Spencer2670c252011-01-20 06:39:06 +00002450 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002451
2452 ToolName = argv[0];
2453
2454 // Defaults to a.out if no filenames specified.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002455 if (InputFilenames.empty())
Michael J. Spencer2670c252011-01-20 06:39:06 +00002456 InputFilenames.push_back("a.out");
2457
Fangrui Song8513cd42018-06-27 20:45:11 +00002458 if (AllHeaders)
George Rimar9b6fe7e2019-01-12 12:17:24 +00002459 FileHeaders = PrivateHeaders = Relocations = SectionHeaders = SymbolTable =
2460 true;
Fangrui Song8513cd42018-06-27 20:45:11 +00002461
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002462 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002463 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002464
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002465 if (!Disassemble
2466 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002467 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002468 && !SectionHeaders
2469 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002470 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002471 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002472 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002473 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002474 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002475 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002476 && !Rebase
2477 && !Bind
2478 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002479 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002480 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002481 && !(UniversalHeaders && MachOOpt)
Paul Semel0dc92f62018-07-05 14:43:29 +00002482 && !ArchiveHeaders
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002483 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002484 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002485 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002486 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002487 && !(DylibsUsed && MachOOpt)
2488 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002489 && !(ObjcMetaData && MachOOpt)
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002490 && !(!FilterSections.empty() && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002491 && !PrintFaultMaps
2492 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002493 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002494 return 2;
2495 }
2496
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002497 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2498 DisassembleFunctions.end());
2499
George Rimar73a27232019-01-15 09:19:18 +00002500 llvm::for_each(InputFilenames, dumpInput);
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002501
2502 return EXIT_SUCCESS;
2503}