blob: 87ed8bbe6abca7227ea2c43d91552aaaa68d0088 [file] [log] [blame]
Michael J. Spencer2670c252011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Michael J. Spencer2670c252011-01-20 06:39:06 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This program is a utility that works like binutils "objdump", that is, it
10// dumps out a plethora of information about an object file depending on the
11// flags.
12//
Michael J. Spencerd7e70032013-02-05 20:27:22 +000013// The flags and output of this program should be near identical to those of
14// binutils objdump.
15//
Michael J. Spencer2670c252011-01-20 06:39:06 +000016//===----------------------------------------------------------------------===//
17
Benjamin Kramer43a772e2011-09-19 17:56:04 +000018#include "llvm-objdump.h"
Sanjoy Das6f567a42015-06-22 18:03:02 +000019#include "llvm/ADT/Optional.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000020#include "llvm/ADT/STLExtras.h"
Michael J. Spencer4e25c022011-10-17 17:13:22 +000021#include "llvm/ADT/StringExtras.h"
Rafael Aulerb0e4b912018-03-09 19:13:44 +000022#include "llvm/ADT/StringSet.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Sanjoy Das3f1bc3b2015-06-23 20:09:03 +000024#include "llvm/CodeGen/FaultMaps.h"
Igor Laevsky03a670c2016-01-26 15:09:42 +000025#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000026#include "llvm/DebugInfo/Symbolize/Symbolize.h"
Paul Semel007dedb2018-07-18 16:39:21 +000027#include "llvm/Demangle/Demangle.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000028#include "llvm/MC/MCAsmInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000029#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000030#include "llvm/MC/MCDisassembler/MCDisassembler.h"
31#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000032#include "llvm/MC/MCInst.h"
33#include "llvm/MC/MCInstPrinter.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000034#include "llvm/MC/MCInstrAnalysis.h"
Craig Topper54bfde72012-04-02 06:09:36 +000035#include "llvm/MC/MCInstrInfo.h"
Ahmed Bougachaad1084d2013-05-24 00:39:57 +000036#include "llvm/MC/MCObjectFileInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000037#include "llvm/MC/MCRegisterInfo.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000038#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Object/Archive.h"
40#include "llvm/Object/COFF.h"
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +000041#include "llvm/Object/COFFImportFile.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000042#include "llvm/Object/ELFObjectFile.h"
Rafael Espindolaa9f810b2012-12-21 03:47:03 +000043#include "llvm/Object/MachO.h"
Dave Lee3fb120f2018-08-03 00:06:38 +000044#include "llvm/Object/MachOUniversal.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000045#include "llvm/Object/ObjectFile.h"
Sam Clegg4df5d762017-06-27 20:40:53 +000046#include "llvm/Object/Wasm.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000047#include "llvm/Support/Casting.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000048#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Debug.h"
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +000050#include "llvm/Support/Errc.h"
Michael J. Spencerba4a3622011-10-08 00:18:30 +000051#include "llvm/Support/FileSystem.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000052#include "llvm/Support/Format.h"
Benjamin Kramerbf115312011-07-25 23:04:36 +000053#include "llvm/Support/GraphWriter.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000054#include "llvm/Support/Host.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000055#include "llvm/Support/InitLLVM.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000056#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000057#include "llvm/Support/SourceMgr.h"
Joel Galenson134cf472018-08-24 15:21:57 +000058#include "llvm/Support/StringSaver.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000059#include "llvm/Support/TargetRegistry.h"
60#include "llvm/Support/TargetSelect.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000061#include "llvm/Support/WithColor.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000062#include "llvm/Support/raw_ostream.h"
Michael J. Spencer2670c252011-01-20 06:39:06 +000063#include <algorithm>
Benjamin Kramera5177e62012-03-23 11:49:32 +000064#include <cctype>
Michael J. Spencer2670c252011-01-20 06:39:06 +000065#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000066#include <system_error>
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +000067#include <unordered_map>
Rafael Espindolac398e672017-07-19 22:27:28 +000068#include <utility>
Ahmed Bougacha17926472013-08-21 07:29:02 +000069
Michael J. Spencer2670c252011-01-20 06:39:06 +000070using namespace llvm;
71using namespace object;
72
George Rimar4c3b2972019-01-28 10:44:01 +000073cl::opt<unsigned long long> AdjustVMA(
74 "adjust-vma",
75 cl::desc("Increase the displayed address by the specified offset"),
76 cl::value_desc("offset"), cl::init(0));
77
Fangrui Song8513cd42018-06-27 20:45:11 +000078cl::opt<bool>
79 llvm::AllHeaders("all-headers",
80 cl::desc("Display all available header information"));
81static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
George Rimar845d3292019-01-18 10:41:26 +000082 cl::NotHidden, cl::aliasopt(AllHeaders));
Fangrui Song8513cd42018-06-27 20:45:11 +000083
Benjamin Kramer43a772e2011-09-19 17:56:04 +000084static cl::list<std::string>
85InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer2670c252011-01-20 06:39:06 +000086
Kevin Enderbye2297dd2015-01-07 21:02:18 +000087cl::opt<bool>
88llvm::Disassemble("disassemble",
Benjamin Kramer43a772e2011-09-19 17:56:04 +000089 cl::desc("Display assembler mnemonics for the machine instructions"));
George Rimar845d3292019-01-18 10:41:26 +000090static cl::alias Disassembled("d", cl::desc("Alias for --disassemble"),
91 cl::NotHidden, cl::aliasopt(Disassemble));
Colin LeMahieu77804be2015-07-29 15:45:39 +000092
93cl::opt<bool>
94llvm::DisassembleAll("disassemble-all",
95 cl::desc("Display assembler mnemonics for the machine instructions"));
George Rimar845d3292019-01-18 10:41:26 +000096static cl::alias DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
97 cl::NotHidden, cl::aliasopt(DisassembleAll));
Michael J. Spencer2670c252011-01-20 06:39:06 +000098
Zachary Turner030ad372018-08-20 22:18:21 +000099cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
100 cl::init(false));
Paul Semel007dedb2018-07-18 16:39:21 +0000101
102static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
George Rimar845d3292019-01-18 10:41:26 +0000103 cl::NotHidden, cl::aliasopt(llvm::Demangle));
Paul Semel007dedb2018-07-18 16:39:21 +0000104
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000105static cl::list<std::string>
106DisassembleFunctions("df",
107 cl::CommaSeparated,
108 cl::desc("List of functions to disassemble"));
109static StringSet<> DisasmFuncsSet;
110
Kevin Enderby98da6132015-01-20 21:47:46 +0000111cl::opt<bool>
Kristina Brooks31579e92018-10-31 09:34:08 +0000112llvm::Relocations("reloc",
113 cl::desc("Display the relocation entries in the file"));
114static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
115 cl::NotHidden,
116 cl::aliasopt(llvm::Relocations));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000117
Kevin Enderby98da6132015-01-20 21:47:46 +0000118cl::opt<bool>
Paul Semelcb0f0432018-06-07 13:30:55 +0000119llvm::DynamicRelocations("dynamic-reloc",
120 cl::desc("Display the dynamic relocation entries in the file"));
George Rimar845d3292019-01-18 10:41:26 +0000121static cl::alias DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
122 cl::NotHidden,
123 cl::aliasopt(DynamicRelocations));
Paul Semelcb0f0432018-06-07 13:30:55 +0000124
125cl::opt<bool>
James Hendersonb55b6582018-10-29 10:05:39 +0000126 llvm::SectionContents("full-contents",
127 cl::desc("Display the content of each section"));
128static cl::alias SectionContentsShort("s",
129 cl::desc("Alias for --full-contents"),
George Rimar845d3292019-01-18 10:41:26 +0000130 cl::NotHidden,
James Hendersonb55b6582018-10-29 10:05:39 +0000131 cl::aliasopt(SectionContents));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000132
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000133cl::opt<bool> llvm::SymbolTable("syms", cl::desc("Display the symbol table"));
134static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
Kristina Brooks889356e2018-10-31 09:35:25 +0000135 cl::NotHidden,
Kristina Brooks3baa5f72018-10-31 05:45:01 +0000136 cl::aliasopt(llvm::SymbolTable));
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000137
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000138cl::opt<bool>
139llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
Nick Kledzikd04bc352014-08-30 00:20:14 +0000140
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000141cl::opt<bool>
142llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
Nick Kledzikac431442014-09-12 21:34:15 +0000143
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000144cl::opt<bool>
145llvm::Bind("bind", cl::desc("Display mach-o binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000146
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000147cl::opt<bool>
148llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000149
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000150cl::opt<bool>
151llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
Nick Kledzik56ebef42014-09-16 01:41:51 +0000152
Adrian Prantl437105a2015-07-08 02:04:15 +0000153cl::opt<bool>
154llvm::RawClangAST("raw-clang-ast",
155 cl::desc("Dump the raw binary contents of the clang AST section"));
156
Nick Kledzik56ebef42014-09-16 01:41:51 +0000157static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000158MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
George Rimar845d3292019-01-18 10:41:26 +0000159static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
160 cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000161
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162cl::opt<std::string>
163llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
164 "see -version for available targets"));
165
166cl::opt<std::string>
Kevin Enderbyc9595622014-08-06 23:24:41 +0000167llvm::MCPU("mcpu",
168 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
169 cl::value_desc("cpu-name"),
170 cl::init(""));
171
172cl::opt<std::string>
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000173llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
Michael J. Spencer2670c252011-01-20 06:39:06 +0000174 "see -version for available targets"));
175
Kevin Enderby98da6132015-01-20 21:47:46 +0000176cl::opt<bool>
177llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
178 "headers for each section."));
George Rimar845d3292019-01-18 10:41:26 +0000179static cl::alias SectionHeadersShort("headers",
180 cl::desc("Alias for --section-headers"),
181 cl::NotHidden,
182 cl::aliasopt(SectionHeaders));
183static cl::alias SectionHeadersShorter("h",
184 cl::desc("Alias for --section-headers"),
185 cl::NotHidden,
186 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000187
George Rimar87fa2e62019-01-28 14:11:35 +0000188static cl::opt<bool>
189 ShowLMA("show-lma",
190 cl::desc("Display LMA column when dumping ELF section headers"));
191
Colin LeMahieu77804be2015-07-29 15:45:39 +0000192cl::list<std::string>
Colin LeMahieufcc32762015-07-29 19:08:10 +0000193llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
194 "With -macho dump segment,section"));
George Rimar845d3292019-01-18 10:41:26 +0000195cl::alias static FilterSectionsj("j", cl::desc("Alias for --section"),
196 cl::NotHidden,
197 cl::aliasopt(llvm::FilterSections));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000198
Kevin Enderbyc9595622014-08-06 23:24:41 +0000199cl::list<std::string>
200llvm::MAttrs("mattr",
Jack Carter551efd72012-08-28 19:24:49 +0000201 cl::CommaSeparated,
202 cl::desc("Target specific attributes"),
203 cl::value_desc("a1,+a2,-a3,..."));
204
Kevin Enderbybf246f52014-09-24 23:08:22 +0000205cl::opt<bool>
206llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
207 "instructions, do not print "
208 "the instruction bytes."));
Saleem Abdulrasooldea14b22017-02-08 18:11:31 +0000209cl::opt<bool>
210llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000211
Kevin Enderby98da6132015-01-20 21:47:46 +0000212cl::opt<bool>
213llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000214
George Rimar845d3292019-01-18 10:41:26 +0000215static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
216 cl::NotHidden, cl::aliasopt(UnwindInfo));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000217
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000218cl::opt<bool>
219llvm::PrivateHeaders("private-headers",
220 cl::desc("Display format specific file headers"));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000221
Kevin Enderby0ae163f2016-01-13 00:25:36 +0000222cl::opt<bool>
223llvm::FirstPrivateHeader("private-header",
224 cl::desc("Display only the first format specific file "
225 "header"));
226
George Rimar845d3292019-01-18 10:41:26 +0000227static cl::alias PrivateHeadersShort("p",
228 cl::desc("Alias for --private-headers"),
229 cl::NotHidden,
230 cl::aliasopt(PrivateHeaders));
Michael J. Spencer209565db2013-01-06 03:56:49 +0000231
Paul Semeld2af4d62018-07-04 15:25:03 +0000232cl::opt<bool> llvm::FileHeaders(
233 "file-headers",
234 cl::desc("Display the contents of the overall file header"));
235
236static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
George Rimar845d3292019-01-18 10:41:26 +0000237 cl::NotHidden, cl::aliasopt(FileHeaders));
Paul Semeld2af4d62018-07-04 15:25:03 +0000238
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000239cl::opt<bool>
Paul Semel0dc92f62018-07-05 14:43:29 +0000240 llvm::ArchiveHeaders("archive-headers",
241 cl::desc("Display archive header information"));
242
George Rimar845d3292019-01-18 10:41:26 +0000243cl::alias ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
244 cl::NotHidden, cl::aliasopt(ArchiveHeaders));
Paul Semel0dc92f62018-07-05 14:43:29 +0000245
246cl::opt<bool>
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000247 llvm::PrintImmHex("print-imm-hex",
Colin LeMahieuefe37322016-04-08 18:15:37 +0000248 cl::desc("Use hex format for immediate values"));
Colin LeMahieu14ec76e2015-06-07 21:07:17 +0000249
Sanjoy Das6f567a42015-06-22 18:03:02 +0000250cl::opt<bool> PrintFaultMaps("fault-map-section",
251 cl::desc("Display contents of faultmap section"));
252
Igor Laevsky03a670c2016-01-26 15:09:42 +0000253cl::opt<DIDumpType> llvm::DwarfDumpType(
254 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
Jonas Devliegherec0a758d2017-09-18 14:15:57 +0000255 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
Igor Laevsky03a670c2016-01-26 15:09:42 +0000256
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000257cl::opt<bool> PrintSource(
258 "source",
259 cl::desc(
Alex Denisova07169e2018-02-02 19:20:37 +0000260 "Display source inlined with disassembly. Implies disassemble object"));
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000261
George Rimar845d3292019-01-18 10:41:26 +0000262cl::alias PrintSourceShort("S", cl::desc("Alias for -source"), cl::NotHidden,
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +0000263 cl::aliasopt(PrintSource));
264
265cl::opt<bool> PrintLines("line-numbers",
266 cl::desc("Display source line numbers with "
267 "disassembly. Implies disassemble object"));
268
269cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
George Rimar845d3292019-01-18 10:41:26 +0000270 cl::NotHidden, cl::aliasopt(PrintLines));
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000271
272cl::opt<unsigned long long>
273 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
274 cl::value_desc("address"), cl::init(0));
275cl::opt<unsigned long long>
George Rimar70d197d2019-01-10 14:55:26 +0000276 StopAddress("stop-address",
George Rimar3687c3e92019-01-15 14:03:50 +0000277 cl::desc("Stop disassembly at address"),
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +0000278 cl::value_desc("address"), cl::init(UINT64_MAX));
George Rimar70d197d2019-01-10 14:55:26 +0000279
George Rimar3687c3e92019-01-15 14:03:50 +0000280cl::opt<bool> DisassembleZeroes(
281 "disassemble-zeroes",
282 cl::desc("Do not skip blocks of zeroes when disassembling"));
George Rimar70d197d2019-01-10 14:55:26 +0000283cl::alias DisassembleZeroesShort("z",
284 cl::desc("Alias for --disassemble-zeroes"),
George Rimar845d3292019-01-18 10:41:26 +0000285 cl::NotHidden,
George Rimar70d197d2019-01-10 14:55:26 +0000286 cl::aliasopt(DisassembleZeroes));
287
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000288static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000289
Clement Courbetd1a3bd42019-01-18 15:26:14 +0000290typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
Clement Courbet2d7d4a32019-01-18 09:40:19 +0000291
George Rimarc1964882019-01-18 11:33:26 +0000292SectionFilter llvm::ToolSectionFilter(llvm::object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000293 return SectionFilter(
294 [](llvm::object::SectionRef const &S) {
295 if (FilterSections.empty())
296 return true;
297 llvm::StringRef String;
298 std::error_code error = S.getName(String);
299 if (error)
300 return false;
301 return is_contained(FilterSections, String);
302 },
303 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000304}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000305
Davide Italianoccd53fe2015-08-05 07:18:31 +0000306void llvm::error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000307 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000308 return;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000309 WithColor::error(errs(), ToolName)
310 << "reading file: " << EC.message() << ".\n";
Davide Italiano140af642015-12-25 18:16:45 +0000311 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000312 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000313}
314
Kevin Enderby42398052016-06-28 23:16:13 +0000315LLVM_ATTRIBUTE_NORETURN void llvm::error(Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000316 WithColor::error(errs(), ToolName) << Message << ".\n";
Kevin Enderby42398052016-06-28 23:16:13 +0000317 errs().flush();
318 exit(1);
319}
320
Paul Semel007dedb2018-07-18 16:39:21 +0000321void llvm::warn(StringRef Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000322 WithColor::warning(errs(), ToolName) << Message << ".\n";
Paul Semel007dedb2018-07-18 16:39:21 +0000323 errs().flush();
324}
325
Davide Italianoed9d95b2015-12-29 13:41:02 +0000326LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000327 Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000328 WithColor::error(errs(), ToolName)
329 << "'" << File << "': " << Message << ".\n";
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000330 exit(1);
331}
332
333LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
Davide Italianoed9d95b2015-12-29 13:41:02 +0000334 std::error_code EC) {
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000335 assert(EC);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000336 WithColor::error(errs(), ToolName)
337 << "'" << File << "': " << EC.message() << ".\n";
Davide Italianoccd53fe2015-08-05 07:18:31 +0000338 exit(1);
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +0000339}
340
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000341LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef File,
342 llvm::Error E) {
343 assert(E);
344 std::string Buf;
345 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000346 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000347 OS.flush();
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000348 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000349 exit(1);
350}
351
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000352LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
353 StringRef FileName,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000354 llvm::Error E,
355 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000356 assert(E);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000357 WithColor::error(errs(), ToolName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000358 if (ArchiveName != "")
359 errs() << ArchiveName << "(" << FileName << ")";
360 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000361 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000362 if (!ArchitectureName.empty())
363 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000364 std::string Buf;
365 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000366 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000367 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000368 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000369 exit(1);
370}
371
372LLVM_ATTRIBUTE_NORETURN void llvm::report_error(StringRef ArchiveName,
373 const object::Archive::Child &C,
Kevin Enderby9acb1092016-05-31 20:35:34 +0000374 llvm::Error E,
375 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000376 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000377 // TODO: if we have a error getting the name then it would be nice to print
378 // the index of which archive member this is and or its offset in the
379 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000380 if (!NameOrErr) {
381 consumeError(NameOrErr.takeError());
Kevin Enderby9acb1092016-05-31 20:35:34 +0000382 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000383 } else
Kevin Enderby9acb1092016-05-31 20:35:34 +0000384 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
385 ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000386}
387
Craig Toppere6cb63e2014-04-25 04:24:47 +0000388static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000389 // Figure out the target triple.
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000390 llvm::Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000391 if (TripleName.empty()) {
George Rimar73a27232019-01-15 09:19:18 +0000392 if (Obj)
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000393 TheTriple = Obj->makeTriple();
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000394 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000395 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000396
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000397 // Use the triple, but also try to combine with ARM build attributes.
398 if (Obj) {
399 auto Arch = Obj->getArch();
George Rimar73a27232019-01-15 09:19:18 +0000400 if (Arch == Triple::arm || Arch == Triple::armeb)
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000401 Obj->setARMSubArch(TheTriple);
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000402 }
403 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000404
405 // Get the target specific parser.
406 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000407 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
408 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000409 if (!TheTarget) {
410 if (Obj)
411 report_error(Obj->getFileName(), "can't find target: " + Error);
412 else
413 error("can't find target: " + Error);
414 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000415
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000416 // Update the triple name and return the found target.
417 TripleName = TheTriple.getTriple();
418 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000419}
420
George Rimar73a27232019-01-15 09:19:18 +0000421bool llvm::isRelocAddressLess(RelocationRef A, RelocationRef B) {
422 return A.getOffset() < B.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000423}
424
Rafael Espindola37070a52015-06-03 04:48:06 +0000425static std::error_code getRelocationValueString(const RelocationRef &Rel,
426 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000427 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000428 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000429 return getELFRelocationValueString(ELF, Rel, Result);
Rafael Espindola37070a52015-06-03 04:48:06 +0000430 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000431 return getCOFFRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000432 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000433 return getWasmRelocationValueString(Wasm, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000434 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000435 return getMachORelocationValueString(MachO, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000436 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000437}
438
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000439/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000440/// relocations, usually because it is the trailing part of a multipart
441/// relocation that will be printed as part of the leading relocation.
442static bool getHidden(RelocationRef RelRef) {
George Rimar73a27232019-01-15 09:19:18 +0000443 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000444 if (!MachO)
445 return false;
446
447 unsigned Arch = MachO->getArch();
448 DataRefImpl Rel = RelRef.getRawDataRefImpl();
449 uint64_t Type = MachO->getRelocationType(Rel);
450
451 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
452 // is always hidden.
George Rimar73a27232019-01-15 09:19:18 +0000453 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
454 return Type == MachO::GENERIC_RELOC_PAIR;
455
456 if (Arch == Triple::x86_64) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000457 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
458 // an X86_64_RELOC_SUBTRACTOR.
459 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
460 DataRefImpl RelPrev = Rel;
461 RelPrev.d.a--;
462 uint64_t PrevType = MachO->getRelocationType(RelPrev);
463 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
464 return true;
465 }
466 }
467
468 return false;
469}
470
Sid Manningd9f28732018-05-14 19:46:08 +0000471namespace {
472class SourcePrinter {
473protected:
474 DILineInfo OldLineInfo;
475 const ObjectFile *Obj = nullptr;
476 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
477 // File name to file contents of source
478 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
479 // Mark the line endings of the cached source
480 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
481
482private:
483 bool cacheSource(const DILineInfo& LineInfoFile);
484
485public:
486 SourcePrinter() = default;
487 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
488 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
489 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
490 DefaultArch);
491 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
492 }
493 virtual ~SourcePrinter() = default;
494 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
495 StringRef Delimiter = "; ");
496};
497
498bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
499 std::unique_ptr<MemoryBuffer> Buffer;
500 if (LineInfo.Source) {
501 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
502 } else {
503 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
504 if (!BufferOrError)
505 return false;
506 Buffer = std::move(*BufferOrError);
507 }
508 // Chomp the file to get lines
509 size_t BufferSize = Buffer->getBufferSize();
510 const char *BufferStart = Buffer->getBufferStart();
511 for (const char *Start = BufferStart, *End = BufferStart;
512 End < BufferStart + BufferSize; End++)
513 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
514 (*End == '\r' && *(End + 1) == '\n')) {
515 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
516 if (*End == '\r')
517 End++;
518 Start = End + 1;
519 }
520 SourceCache[LineInfo.FileName] = std::move(Buffer);
521 return true;
522}
523
524void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
525 StringRef Delimiter) {
526 if (!Symbolizer)
527 return;
528 DILineInfo LineInfo = DILineInfo();
529 auto ExpectecLineInfo =
530 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
531 if (!ExpectecLineInfo)
532 consumeError(ExpectecLineInfo.takeError());
533 else
534 LineInfo = *ExpectecLineInfo;
535
536 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
537 LineInfo.Line == 0)
538 return;
539
540 if (PrintLines)
541 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
542 if (PrintSource) {
543 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
544 if (!cacheSource(LineInfo))
545 return;
546 auto FileBuffer = SourceCache.find(LineInfo.FileName);
547 if (FileBuffer != SourceCache.end()) {
548 auto LineBuffer = LineCache.find(LineInfo.FileName);
549 if (LineBuffer != LineCache.end()) {
550 if (LineInfo.Line > LineBuffer->second.size())
551 return;
552 // Vector begins at 0, line numbers are non-zero
553 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
554 << "\n";
555 }
556 }
557 }
558 OldLineInfo = LineInfo;
559}
560
561static bool isArmElf(const ObjectFile *Obj) {
562 return (Obj->isELF() &&
563 (Obj->getArch() == Triple::aarch64 ||
564 Obj->getArch() == Triple::aarch64_be ||
565 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
566 Obj->getArch() == Triple::thumb ||
567 Obj->getArch() == Triple::thumbeb));
568}
569
George Rimar617adef2019-01-23 13:39:12 +0000570static void printRelocation(const RelocationRef &Rel, uint64_t Address,
571 uint8_t AddrSize) {
572 StringRef Fmt =
573 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
574 SmallString<16> Name;
575 SmallString<32> Val;
576 Rel.getTypeName(Name);
577 error(getRelocationValueString(Rel, Val));
578 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
579}
580
Sid Manningd9f28732018-05-14 19:46:08 +0000581class PrettyPrinter {
582public:
583 virtual ~PrettyPrinter() = default;
584 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
585 ArrayRef<uint8_t> Bytes, uint64_t Address,
586 raw_ostream &OS, StringRef Annot,
587 MCSubtargetInfo const &STI, SourcePrinter *SP,
588 std::vector<RelocationRef> *Rels = nullptr) {
589 if (SP && (PrintSource || PrintLines))
590 SP->printSourceLine(OS, Address);
591 if (!NoLeadingAddr)
592 OS << format("%8" PRIx64 ":", Address);
593 if (!NoShowRawInsn) {
594 OS << "\t";
595 dumpBytes(Bytes, OS);
596 }
597 if (MI)
598 IP.printInst(MI, OS, "", STI);
599 else
600 OS << " <unknown>";
601 }
602};
603PrettyPrinter PrettyPrinterInst;
604class HexagonPrettyPrinter : public PrettyPrinter {
605public:
606 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
607 raw_ostream &OS) {
608 uint32_t opcode =
609 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
610 if (!NoLeadingAddr)
611 OS << format("%8" PRIx64 ":", Address);
612 if (!NoShowRawInsn) {
613 OS << "\t";
614 dumpBytes(Bytes.slice(0, 4), OS);
615 OS << format("%08" PRIx32, opcode);
616 }
617 }
618 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
619 uint64_t Address, raw_ostream &OS, StringRef Annot,
620 MCSubtargetInfo const &STI, SourcePrinter *SP,
621 std::vector<RelocationRef> *Rels) override {
622 if (SP && (PrintSource || PrintLines))
623 SP->printSourceLine(OS, Address, "");
624 if (!MI) {
625 printLead(Bytes, Address, OS);
626 OS << " <unknown>";
627 return;
628 }
629 std::string Buffer;
630 {
631 raw_string_ostream TempStream(Buffer);
632 IP.printInst(MI, TempStream, "", STI);
633 }
634 StringRef Contents(Buffer);
635 // Split off bundle attributes
636 auto PacketBundle = Contents.rsplit('\n');
637 // Split off first instruction from the rest
638 auto HeadTail = PacketBundle.first.split('\n');
639 auto Preamble = " { ";
640 auto Separator = "";
Sid Manningd9f28732018-05-14 19:46:08 +0000641
642 // Hexagon's packets require relocations to be inline rather than
643 // clustered at the end of the packet.
George Rimar617adef2019-01-23 13:39:12 +0000644 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
645 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
Sid Manningd9f28732018-05-14 19:46:08 +0000646 auto PrintReloc = [&]() -> void {
George Rimar73a27232019-01-15 09:19:18 +0000647 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address)) {
648 if (RelCur->getOffset() == Address) {
George Rimar617adef2019-01-23 13:39:12 +0000649 printRelocation(*RelCur, Address, 4);
Sid Manningd9f28732018-05-14 19:46:08 +0000650 return;
651 }
George Rimar73a27232019-01-15 09:19:18 +0000652 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +0000653 }
654 };
655
George Rimar73a27232019-01-15 09:19:18 +0000656 while (!HeadTail.first.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +0000657 OS << Separator;
658 Separator = "\n";
659 if (SP && (PrintSource || PrintLines))
660 SP->printSourceLine(OS, Address, "");
661 printLead(Bytes, Address, OS);
662 OS << Preamble;
663 Preamble = " ";
664 StringRef Inst;
665 auto Duplex = HeadTail.first.split('\v');
George Rimar73a27232019-01-15 09:19:18 +0000666 if (!Duplex.second.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +0000667 OS << Duplex.first;
668 OS << "; ";
669 Inst = Duplex.second;
670 }
671 else
672 Inst = HeadTail.first;
673 OS << Inst;
674 HeadTail = HeadTail.second.split('\n');
675 if (HeadTail.first.empty())
676 OS << " } " << PacketBundle.second;
677 PrintReloc();
678 Bytes = Bytes.slice(4);
679 Address += 4;
680 }
681 }
682};
683HexagonPrettyPrinter HexagonPrettyPrinterInst;
684
685class AMDGCNPrettyPrinter : public PrettyPrinter {
686public:
687 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
688 uint64_t Address, raw_ostream &OS, StringRef Annot,
689 MCSubtargetInfo const &STI, SourcePrinter *SP,
690 std::vector<RelocationRef> *Rels) override {
691 if (SP && (PrintSource || PrintLines))
692 SP->printSourceLine(OS, Address);
693
694 typedef support::ulittle32_t U32;
695
696 if (MI) {
697 SmallString<40> InstStr;
698 raw_svector_ostream IS(InstStr);
699
700 IP.printInst(MI, IS, "", STI);
701
702 OS << left_justify(IS.str(), 60);
703 } else {
704 // an unrecognized encoding - this is probably data so represent it
705 // using the .long directive, or .byte directive if fewer than 4 bytes
706 // remaining
707 if (Bytes.size() >= 4) {
708 OS << format("\t.long 0x%08" PRIx32 " ",
709 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
710 OS.indent(42);
711 } else {
712 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
713 for (unsigned int i = 1; i < Bytes.size(); i++)
714 OS << format(", 0x%02" PRIx8, Bytes[i]);
715 OS.indent(55 - (6 * Bytes.size()));
716 }
717 }
718
719 OS << format("// %012" PRIX64 ": ", Address);
720 if (Bytes.size() >=4) {
721 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
722 Bytes.size() / sizeof(U32)))
723 // D should be explicitly casted to uint32_t here as it is passed
724 // by format to snprintf as vararg.
725 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
726 } else {
727 for (unsigned int i = 0; i < Bytes.size(); i++)
728 OS << format("%02" PRIX8 " ", Bytes[i]);
729 }
730
731 if (!Annot.empty())
732 OS << "// " << Annot;
733 }
734};
735AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
736
737class BPFPrettyPrinter : public PrettyPrinter {
738public:
739 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
740 uint64_t Address, raw_ostream &OS, StringRef Annot,
741 MCSubtargetInfo const &STI, SourcePrinter *SP,
742 std::vector<RelocationRef> *Rels) override {
743 if (SP && (PrintSource || PrintLines))
744 SP->printSourceLine(OS, Address);
745 if (!NoLeadingAddr)
746 OS << format("%8" PRId64 ":", Address / 8);
747 if (!NoShowRawInsn) {
748 OS << "\t";
749 dumpBytes(Bytes, OS);
750 }
751 if (MI)
752 IP.printInst(MI, OS, "", STI);
753 else
754 OS << " <unknown>";
755 }
756};
757BPFPrettyPrinter BPFPrettyPrinterInst;
758
759PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
760 switch(Triple.getArch()) {
761 default:
762 return PrettyPrinterInst;
763 case Triple::hexagon:
764 return HexagonPrettyPrinterInst;
765 case Triple::amdgcn:
766 return AMDGCNPrettyPrinterInst;
767 case Triple::bpfel:
768 case Triple::bpfeb:
769 return BPFPrettyPrinterInst;
770 }
771}
772}
773
Sam Koltonc05d7782016-08-17 10:17:57 +0000774static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
775 assert(Obj->isELF());
776 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
777 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
778 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
779 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
780 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
781 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
782 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
783 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
784 llvm_unreachable("Unsupported binary format");
785}
786
Sam Parker5fba45a2017-02-08 09:44:18 +0000787template <class ELFT> static void
788addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
789 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
790 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
791 uint8_t SymbolType = Symbol.getELFType();
792 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
793 continue;
794
795 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
796 if (!AddressOrErr)
797 report_error(Obj->getFileName(), AddressOrErr.takeError());
Sam Parker5fba45a2017-02-08 09:44:18 +0000798
799 Expected<StringRef> Name = Symbol.getName();
800 if (!Name)
801 report_error(Obj->getFileName(), Name.takeError());
802 if (Name->empty())
803 continue;
804
805 Expected<section_iterator> SectionOrErr = Symbol.getSection();
806 if (!SectionOrErr)
807 report_error(Obj->getFileName(), SectionOrErr.takeError());
808 section_iterator SecI = *SectionOrErr;
809 if (SecI == Obj->section_end())
810 continue;
811
George Rimar73a27232019-01-15 09:19:18 +0000812 AllSymbols[*SecI].emplace_back(*AddressOrErr, *Name, SymbolType);
Sam Parker5fba45a2017-02-08 09:44:18 +0000813 }
814}
815
816static void
817addDynamicElfSymbols(const ObjectFile *Obj,
818 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
819 assert(Obj->isELF());
820 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
821 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
822 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
823 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
824 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
825 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
826 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
827 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
828 else
829 llvm_unreachable("Unsupported binary format");
830}
831
Joel Galenson134cf472018-08-24 15:21:57 +0000832static void addPltEntries(const ObjectFile *Obj,
833 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
834 StringSaver &Saver) {
835 Optional<SectionRef> Plt = None;
836 for (const SectionRef &Section : Obj->sections()) {
837 StringRef Name;
838 if (Section.getName(Name))
839 continue;
840 if (Name == ".plt")
841 Plt = Section;
842 }
843 if (!Plt)
844 return;
845 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
846 for (auto PltEntry : ElfObj->getPltAddresses()) {
847 SymbolRef Symbol(PltEntry.first, ElfObj);
Joel Galenson134cf472018-08-24 15:21:57 +0000848 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
849
850 Expected<StringRef> NameOrErr = Symbol.getName();
851 if (!NameOrErr)
852 report_error(Obj->getFileName(), NameOrErr.takeError());
853 if (NameOrErr->empty())
854 continue;
855 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
856
857 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
858 }
859 }
860}
861
George Rimar70d197d2019-01-10 14:55:26 +0000862// Normally the disassembly output will skip blocks of zeroes. This function
863// returns the number of zero bytes that can be skipped when dumping the
864// disassembly of the instructions in Buf.
865static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
866 // When -z or --disassemble-zeroes are given we always dissasemble them.
867 if (DisassembleZeroes)
868 return 0;
869
870 // Find the number of leading zeroes.
871 size_t N = 0;
872 while (N < Buf.size() && !Buf[N])
873 ++N;
874
875 // We may want to skip blocks of zero bytes, but unless we see
876 // at least 8 of them in a row.
877 if (N < 8)
878 return 0;
879
880 // We skip zeroes in multiples of 4 because do not want to truncate an
881 // instruction if it starts with a zero byte.
882 return N & ~0x3;
883}
884
George Rimar121fcd72019-01-22 14:09:37 +0000885// Returns a map from sections to their relocations.
886static std::map<SectionRef, std::vector<RelocationRef>>
887getRelocsMap(llvm::object::ObjectFile const &Obj) {
888 std::map<SectionRef, std::vector<RelocationRef>> Ret;
889 for (const SectionRef &Section : ToolSectionFilter(Obj)) {
890 section_iterator RelSec = Section.getRelocatedSection();
891 if (RelSec == Obj.section_end())
892 continue;
893 std::vector<RelocationRef> &V = Ret[*RelSec];
894 for (const RelocationRef &R : Section.relocations())
895 V.push_back(R);
896 // Sort relocations by address.
897 llvm::sort(V, isRelocAddressLess);
898 }
899 return Ret;
900}
901
George Rimar4c3b2972019-01-28 10:44:01 +0000902// Used for --adjust-vma to check if address should be adjusted by the
903// specified value for a given section.
904// For ELF we do not adjust non-allocatable sections like debug ones,
905// because they are not loadable.
906// TODO: implement for other file formats.
907static bool shouldAdjustVA(const SectionRef &Section) {
908 const ObjectFile *Obj = Section.getObject();
909 if (isa<object::ELFObjectFileBase>(Obj))
910 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
911 return false;
912}
913
George Rimarbcbe98b2019-01-23 10:33:26 +0000914static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
915 MCContext &Ctx, MCDisassembler *DisAsm,
916 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
917 const MCSubtargetInfo *STI, PrettyPrinter &PIP,
918 SourcePrinter &SP, bool InlineRelocs) {
George Rimar121fcd72019-01-22 14:09:37 +0000919 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
920 if (InlineRelocs)
921 RelocMap = getRelocsMap(*Obj);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000922
David Majnemer81afca62015-07-07 22:06:59 +0000923 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000924 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000925 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +0000926 SectionSymbolsTy AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000927 for (const SymbolRef &Symbol : Obj->symbols()) {
Kevin Enderby931cb652016-06-24 18:24:42 +0000928 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000929 if (!AddressOrErr)
930 report_error(Obj->getFileName(), AddressOrErr.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000931 uint64_t Address = *AddressOrErr;
David Majnemer2603a8fa2015-07-09 18:11:40 +0000932
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000933 Expected<StringRef> Name = Symbol.getName();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000934 if (!Name)
935 report_error(Obj->getFileName(), Name.takeError());
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000936 if (Name->empty())
937 continue;
David Majnemer81afca62015-07-07 22:06:59 +0000938
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000939 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000940 if (!SectionOrErr)
941 report_error(Obj->getFileName(), SectionOrErr.takeError());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000942
Sam Koltonc05d7782016-08-17 10:17:57 +0000943 uint8_t SymbolType = ELF::STT_NOTYPE;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +0000944 if (Obj->isELF())
Sam Koltonc05d7782016-08-17 10:17:57 +0000945 SymbolType = getElfSymbolType(Obj, Symbol);
David Majnemer81afca62015-07-07 22:06:59 +0000946
Sterling Augustinebc78b622018-06-28 18:57:13 +0000947 section_iterator SecI = *SectionOrErr;
948 if (SecI != Obj->section_end())
949 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
950 else
951 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
952
Sam Koltonc05d7782016-08-17 10:17:57 +0000953
David Majnemer81afca62015-07-07 22:06:59 +0000954 }
Sam Parker5fba45a2017-02-08 09:44:18 +0000955 if (AllSymbols.empty() && Obj->isELF())
956 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +0000957
Joel Galenson134cf472018-08-24 15:21:57 +0000958 BumpPtrAllocator A;
959 StringSaver Saver(A);
960 addPltEntries(Obj, AllSymbols, Saver);
961
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000962 // Create a mapping from virtual address to section.
963 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
964 for (SectionRef Sec : Obj->sections())
965 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
966 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
967
968 // Linked executables (.exe and .dll files) typically don't include a real
969 // symbol table but they might contain an export table.
970 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
971 for (const auto &ExportEntry : COFFObj->export_directories()) {
972 StringRef Name;
973 error(ExportEntry.getSymbolName(Name));
974 if (Name.empty())
975 continue;
976 uint32_t RVA;
977 error(ExportEntry.getExportRVA(RVA));
978
979 uint64_t VA = COFFObj->getImageBase() + RVA;
980 auto Sec = std::upper_bound(
981 SectionAddresses.begin(), SectionAddresses.end(), VA,
982 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
983 return LHS < RHS.first;
984 });
985 if (Sec != SectionAddresses.begin())
986 --Sec;
987 else
988 Sec = SectionAddresses.end();
989
990 if (Sec != SectionAddresses.end())
Sam Koltonc05d7782016-08-17 10:17:57 +0000991 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Sterling Augustinebc78b622018-06-28 18:57:13 +0000992 else
993 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +0000994 }
995 }
996
997 // Sort all the symbols, this allows us to use a simple binary search to find
998 // a symbol near an address.
999 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1000 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001001 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001002
Colin LeMahieu77804be2015-07-29 15:45:39 +00001003 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001004 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001005 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001006
Rafael Espindola80291272014-10-08 15:28:58 +00001007 uint64_t SectionAddr = Section.getAddress();
1008 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001009 if (!SectSize)
1010 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001011
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001012 // Get the list of all the symbols in this section.
1013 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001014 std::vector<uint64_t> DataMappingSymsAddr;
1015 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001016 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001017 for (const auto &Symb : Symbols) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001018 uint64_t Address = std::get<0>(Symb);
1019 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001020 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001021 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001022 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001023 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001024 if (Name.startswith("$a"))
1025 TextMappingSymsAddr.push_back(Address - SectionAddr);
1026 if (Name.startswith("$t"))
1027 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001028 }
1029 }
1030
Fangrui Song0cac7262018-09-27 02:13:45 +00001031 llvm::sort(DataMappingSymsAddr);
1032 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001033
Sam Kolton3381d7a2016-10-06 13:46:08 +00001034 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1035 // AMDGPU disassembler uses symbolizer for printing labels
1036 std::unique_ptr<MCRelocationInfo> RelInfo(
1037 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1038 if (RelInfo) {
1039 std::unique_ptr<MCSymbolizer> Symbolizer(
1040 TheTarget->createMCSymbolizer(
1041 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1042 DisAsm->setSymbolizer(std::move(Symbolizer));
1043 }
1044 }
1045
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001046 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001047 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001048 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001049 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001050 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001051 StringRef SectionName;
1052 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001053
Rafael Espindola7884c952015-06-04 15:01:05 +00001054 // If the section has no symbol at the start, just insert a dummy one.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001055 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001056 Symbols.insert(
1057 Symbols.begin(),
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001058 std::make_tuple(SectionAddr, SectionName,
1059 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001060 }
Alp Tokere69170a2014-06-26 22:52:05 +00001061
1062 SmallString<40> Comments;
1063 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001064
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001065 StringRef BytesStr;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001066 error(Section.getContents(BytesStr));
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001067 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1068 BytesStr.size());
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001069
George Rimar4c3b2972019-01-28 10:44:01 +00001070 uint64_t VMAAdjustment = 0;
1071 if (shouldAdjustVA(Section))
1072 VMAAdjustment = AdjustVMA;
1073
Michael J. Spencer2670c252011-01-20 06:39:06 +00001074 uint64_t Size;
1075 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001076 bool PrintedSection = false;
George Rimar121fcd72019-01-22 14:09:37 +00001077 std::vector<RelocationRef> Rels = RelocMap[Section];
George Rimar73a27232019-01-15 09:19:18 +00001078 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1079 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001080 // Disassemble symbol by symbol.
George Rimar73a27232019-01-15 09:19:18 +00001081 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001082 uint64_t Start = std::get<0>(Symbols[SI]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001083 // The end is either the section end or the beginning of the next
1084 // symbol.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001085 uint64_t End = (SI == SE - 1)
1086 ? SectSize
1087 : std::get<0>(Symbols[SI + 1]) - SectionAddr;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001088 // Don't try to disassemble beyond the end of section contents.
1089 if (End > SectSize)
1090 End = SectSize;
Rafael Espindolae45c7402014-08-17 16:31:39 +00001091 // If this symbol has the same address as the next symbol, then skip it.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001092 if (Start >= End)
Michael J. Spenceree84f642011-10-13 20:37:08 +00001093 continue;
1094
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001095 // Check if we need to skip symbol
1096 // Skip if the symbol's data is not between StartAddress and StopAddress
1097 if (End + SectionAddr < StartAddress ||
1098 Start + SectionAddr > StopAddress) {
1099 continue;
1100 }
1101
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001102 /// Skip if user requested specific symbols and this is not in the list
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001103 if (!DisasmFuncsSet.empty() &&
1104 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001105 continue;
1106
1107 if (!PrintedSection) {
1108 PrintedSection = true;
1109 outs() << "Disassembly of section ";
1110 if (!SegmentName.empty())
1111 outs() << SegmentName << ",";
1112 outs() << SectionName << ':';
1113 }
1114
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001115 // Stop disassembly at the stop address specified
1116 if (End + SectionAddr > StopAddress)
1117 End = StopAddress - SectionAddr;
1118
Valery Pykhtinde048052016-04-07 07:24:01 +00001119 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001120 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001121 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1122 Start += 256;
1123 }
George Rimar73a27232019-01-15 09:19:18 +00001124 if (SI == SE - 1 ||
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001125 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001126 // cut trailing zeroes at the end of kernel
1127 // cut up to 256 bytes
1128 const uint64_t EndAlign = 256;
1129 const auto Limit = End - (std::min)(EndAlign, End - Start);
1130 while (End > Limit &&
1131 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1132 End -= 4;
1133 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001134 }
1135
George Rimar6622d412018-12-19 10:21:45 +00001136 outs() << '\n';
George Rimar3ba0f3c02019-01-09 14:43:33 +00001137 if (!NoLeadingAddr)
George Rimar4c3b2972019-01-28 10:44:01 +00001138 outs() << format("%016" PRIx64 " ",
1139 SectionAddr + Start + VMAAdjustment);
George Rimar3ba0f3c02019-01-09 14:43:33 +00001140
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001141 StringRef SymbolName = std::get<1>(Symbols[SI]);
George Rimar6622d412018-12-19 10:21:45 +00001142 if (Demangle)
1143 outs() << demangle(SymbolName) << ":\n";
1144 else
1145 outs() << SymbolName << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001146
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001147 // Don't print raw contents of a virtual section. A virtual section
1148 // doesn't have any contents in the file.
1149 if (Section.isVirtual()) {
1150 outs() << "...\n";
1151 continue;
1152 }
1153
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001154#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001155 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001156#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001157 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001158#endif
1159
Wouter van Oortmerssenf3b762a2019-01-17 18:14:09 +00001160 // Some targets (like WebAssembly) have a special prelude at the start
1161 // of each symbol.
1162 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1163 SectionAddr + Start, DebugOut, CommentStream);
1164 Start += Size;
1165
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001166 for (Index = Start; Index < End; Index += Size) {
1167 MCInst Inst;
Owen Andersona0c3b972011-09-15 23:38:46 +00001168
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001169 if (Index + SectionAddr < StartAddress ||
1170 Index + SectionAddr > StopAddress) {
1171 // skip byte by byte till StartAddress is reached
1172 Size = 1;
1173 continue;
1174 }
Davide Italianof0706882015-10-01 21:57:09 +00001175 // AArch64 ELF binaries can interleave data and text in the
1176 // same section. We rely on the markers introduced to
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001177 // understand what we need to dump. If the data marker is within a
1178 // function, it is denoted as a word/short etc
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001179 if (isArmElf(Obj) && std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001180 !DisassembleAll) {
Davide Italianof0706882015-10-01 21:57:09 +00001181 uint64_t Stride = 0;
1182
1183 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1184 DataMappingSymsAddr.end(), Index);
1185 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1186 // Switch to data.
1187 while (Index < End) {
1188 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1189 outs() << "\t";
1190 if (Index + 4 <= End) {
1191 Stride = 4;
1192 dumpBytes(Bytes.slice(Index, 4), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001193 outs() << "\t.word\t";
1194 uint32_t Data = 0;
1195 if (Obj->isLittleEndian()) {
1196 const auto Word =
1197 reinterpret_cast<const support::ulittle32_t *>(
1198 Bytes.data() + Index);
1199 Data = *Word;
1200 } else {
1201 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1202 Bytes.data() + Index);
1203 Data = *Word;
1204 }
1205 outs() << "0x" << format("%08" PRIx32, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001206 } else if (Index + 2 <= End) {
1207 Stride = 2;
1208 dumpBytes(Bytes.slice(Index, 2), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001209 outs() << "\t\t.short\t";
1210 uint16_t Data = 0;
1211 if (Obj->isLittleEndian()) {
1212 const auto Short =
1213 reinterpret_cast<const support::ulittle16_t *>(
1214 Bytes.data() + Index);
1215 Data = *Short;
1216 } else {
1217 const auto Short =
1218 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1219 Index);
1220 Data = *Short;
1221 }
1222 outs() << "0x" << format("%04" PRIx16, Data);
Davide Italianof0706882015-10-01 21:57:09 +00001223 } else {
1224 Stride = 1;
1225 dumpBytes(Bytes.slice(Index, 1), outs());
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001226 outs() << "\t\t.byte\t";
1227 outs() << "0x" << format("%02" PRIx8, Bytes.slice(Index, 1)[0]);
Davide Italianof0706882015-10-01 21:57:09 +00001228 }
1229 Index += Stride;
1230 outs() << "\n";
1231 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1232 TextMappingSymsAddr.end(), Index);
1233 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1234 break;
1235 }
1236 }
1237 }
1238
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001239 // If there is a data symbol inside an ELF text section and we are only
1240 // disassembling text (applicable all architectures),
1241 // we are in a situation where we must print the data and not
1242 // disassemble it.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001243 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001244 !DisassembleAll && Section.isText()) {
1245 // print out data up to 8 bytes at a time in hex and ascii
1246 uint8_t AsciiData[9] = {'\0'};
1247 uint8_t Byte;
1248 int NumBytes = 0;
1249
1250 for (Index = Start; Index < End; Index += 1) {
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001251 if (((SectionAddr + Index) < StartAddress) ||
1252 ((SectionAddr + Index) > StopAddress))
1253 continue;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001254 if (NumBytes == 0) {
1255 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
1256 outs() << "\t";
1257 }
1258 Byte = Bytes.slice(Index)[0];
1259 outs() << format(" %02x", Byte);
Michael Kruse6f1da6e2018-07-26 15:31:41 +00001260 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001261
1262 uint8_t IndentOffset = 0;
1263 NumBytes++;
1264 if (Index == End - 1 || NumBytes > 8) {
1265 // Indent the space for less than 8 bytes data.
1266 // 2 spaces for byte and one for space between bytes
1267 IndentOffset = 3 * (8 - NumBytes);
1268 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1269 AsciiData[Excess] = '\0';
1270 NumBytes = 8;
1271 }
1272 if (NumBytes == 8) {
1273 AsciiData[8] = '\0';
1274 outs() << std::string(IndentOffset, ' ') << " ";
1275 outs() << reinterpret_cast<char *>(AsciiData);
1276 outs() << '\n';
1277 NumBytes = 0;
1278 }
1279 }
1280 }
Davide Italianof0706882015-10-01 21:57:09 +00001281 if (Index >= End)
1282 break;
1283
George Rimar70d197d2019-01-10 14:55:26 +00001284 if (size_t N =
1285 countSkippableZeroBytes(Bytes.slice(Index, End - Index))) {
1286 outs() << "\t\t..." << '\n';
1287 Index += N;
1288 if (Index >= End)
1289 break;
1290 }
1291
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001292 // Disassemble a real instruction or a data when disassemble all is
1293 // provided
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001294 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1295 SectionAddr + Index, DebugOut,
1296 CommentStream);
1297 if (Size == 0)
1298 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001299
George Rimar4c3b2972019-01-28 10:44:01 +00001300 PIP.printInst(
1301 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1302 SectionAddr + Index + VMAAdjustment, outs(), "", *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001303 outs() << CommentStream.str();
1304 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001305
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001306 // Try to resolve the target of a call, tail call, etc. to a specific
1307 // symbol.
1308 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1309 MIA->isConditionalBranch(Inst))) {
1310 uint64_t Target;
1311 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1312 // In a relocatable object, the target's section must reside in
1313 // the same section as the call instruction or it is accessed
1314 // through a relocation.
1315 //
1316 // In a non-relocatable object, the target may be in any section.
1317 //
1318 // N.B. We don't walk the relocations in the relocatable case yet.
1319 auto *TargetSectionSymbols = &Symbols;
1320 if (!Obj->isRelocatableObject()) {
1321 auto SectionAddress = std::upper_bound(
1322 SectionAddresses.begin(), SectionAddresses.end(), Target,
1323 [](uint64_t LHS,
1324 const std::pair<uint64_t, SectionRef> &RHS) {
1325 return LHS < RHS.first;
1326 });
1327 if (SectionAddress != SectionAddresses.begin()) {
1328 --SectionAddress;
1329 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1330 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001331 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001332 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001333 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001334
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001335 // Find the first symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001336 // or equal to the target. If there isn't a section that contains
1337 // the target, find the nearest preceding absolute symbol.
1338 auto TargetSym = std::upper_bound(
1339 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001340 Target, [](uint64_t LHS,
1341 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1342 return LHS < std::get<0>(RHS);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001343 });
1344 if (TargetSym == TargetSectionSymbols->begin()) {
1345 TargetSectionSymbols = &AbsoluteSymbols;
1346 TargetSym = std::upper_bound(
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001347 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1348 Target, [](uint64_t LHS,
1349 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1350 return LHS < std::get<0>(RHS);
1351 });
Sterling Augustinebc78b622018-06-28 18:57:13 +00001352 }
1353 if (TargetSym != TargetSectionSymbols->begin()) {
1354 --TargetSym;
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001355 uint64_t TargetAddress = std::get<0>(*TargetSym);
1356 StringRef TargetName = std::get<1>(*TargetSym);
1357 outs() << " <" << TargetName;
1358 uint64_t Disp = Target - TargetAddress;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001359 if (Disp)
1360 outs() << "+0x" << Twine::utohexstr(Disp);
1361 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001362 }
1363 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001364 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001365 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001366
Sid Manningd9f28732018-05-14 19:46:08 +00001367 // Hexagon does this in pretty printer
George Rimarfd383e72019-01-23 10:52:38 +00001368 if (Obj->getArch() != Triple::hexagon) {
Sid Manningd9f28732018-05-14 19:46:08 +00001369 // Print relocation for instruction.
George Rimar73a27232019-01-15 09:19:18 +00001370 while (RelCur != RelEnd) {
George Rimar617adef2019-01-23 13:39:12 +00001371 uint64_t Offset = RelCur->getOffset();
Sid Manningd9f28732018-05-14 19:46:08 +00001372 // If this relocation is hidden, skip it.
George Rimar617adef2019-01-23 13:39:12 +00001373 if (getHidden(*RelCur) || ((SectionAddr + Offset) < StartAddress)) {
George Rimar73a27232019-01-15 09:19:18 +00001374 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +00001375 continue;
1376 }
1377
George Rimar740974d2019-01-28 10:48:54 +00001378 // Stop when RelCur's offset is past the current instruction.
George Rimar617adef2019-01-23 13:39:12 +00001379 if (Offset >= Index + Size)
George Rimar73a27232019-01-15 09:19:18 +00001380 break;
George Rimar617adef2019-01-23 13:39:12 +00001381
George Rimar4c3b2972019-01-28 10:44:01 +00001382 // When --adjust-vma is used, update the address printed.
1383 if (RelCur->getSymbol() != Obj->symbol_end()) {
1384 Expected<section_iterator> SymSI =
1385 RelCur->getSymbol()->getSection();
1386 if (SymSI && *SymSI != Obj->section_end() &&
1387 (shouldAdjustVA(**SymSI)))
1388 Offset += AdjustVMA;
1389 }
1390
George Rimar617adef2019-01-23 13:39:12 +00001391 printRelocation(*RelCur, SectionAddr + Offset,
1392 Obj->getBytesInAddress());
George Rimar73a27232019-01-15 09:19:18 +00001393 ++RelCur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001394 }
George Rimarfd383e72019-01-23 10:52:38 +00001395 }
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001396 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001397 }
1398 }
1399}
1400
George Rimarbcbe98b2019-01-23 10:33:26 +00001401static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1402 if (StartAddress > StopAddress)
1403 error("Start address should be less than stop address");
1404
1405 const Target *TheTarget = getTarget(Obj);
1406
1407 // Package up features to be passed to target/subtarget
1408 SubtargetFeatures Features = Obj->getFeatures();
1409 if (!MAttrs.empty())
1410 for (unsigned I = 0; I != MAttrs.size(); ++I)
1411 Features.AddFeature(MAttrs[I]);
1412
1413 std::unique_ptr<const MCRegisterInfo> MRI(
1414 TheTarget->createMCRegInfo(TripleName));
1415 if (!MRI)
1416 report_error(Obj->getFileName(),
1417 "no register info for target " + TripleName);
1418
1419 // Set up disassembler.
1420 std::unique_ptr<const MCAsmInfo> AsmInfo(
1421 TheTarget->createMCAsmInfo(*MRI, TripleName));
1422 if (!AsmInfo)
1423 report_error(Obj->getFileName(),
1424 "no assembly info for target " + TripleName);
1425 std::unique_ptr<const MCSubtargetInfo> STI(
1426 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1427 if (!STI)
1428 report_error(Obj->getFileName(),
1429 "no subtarget info for target " + TripleName);
1430 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1431 if (!MII)
1432 report_error(Obj->getFileName(),
1433 "no instruction info for target " + TripleName);
1434 MCObjectFileInfo MOFI;
1435 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1436 // FIXME: for now initialize MCObjectFileInfo with default values
1437 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1438
1439 std::unique_ptr<MCDisassembler> DisAsm(
1440 TheTarget->createMCDisassembler(*STI, Ctx));
1441 if (!DisAsm)
1442 report_error(Obj->getFileName(),
1443 "no disassembler for target " + TripleName);
1444
1445 std::unique_ptr<const MCInstrAnalysis> MIA(
1446 TheTarget->createMCInstrAnalysis(MII.get()));
1447
1448 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1449 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1450 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1451 if (!IP)
1452 report_error(Obj->getFileName(),
1453 "no instruction printer for target " + TripleName);
1454 IP->setPrintImmHex(PrintImmHex);
1455
1456 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1457 SourcePrinter SP(Obj, TheTarget->getName());
1458
1459 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
1460 STI.get(), PIP, SP, InlineRelocs);
1461}
1462
George Rimar73a27232019-01-15 09:19:18 +00001463void llvm::printRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001464 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1465 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001466 // Regular objdump doesn't print relocations in non-relocatable object
1467 // files.
1468 if (!Obj->isRelocatableObject())
1469 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001470
Colin LeMahieu77804be2015-07-29 15:45:39 +00001471 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001472 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001473 continue;
George Rimar73a27232019-01-15 09:19:18 +00001474 StringRef SecName;
1475 error(Section.getName(SecName));
1476 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001477 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001478 uint64_t Address = Reloc.getOffset();
1479 SmallString<32> RelocName;
1480 SmallString<32> ValueStr;
1481 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001482 continue;
George Rimar73a27232019-01-15 09:19:18 +00001483 Reloc.getTypeName(RelocName);
1484 error(getRelocationValueString(Reloc, ValueStr));
1485 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1486 << ValueStr << "\n";
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001487 }
1488 outs() << "\n";
1489 }
1490}
1491
George Rimar73a27232019-01-15 09:19:18 +00001492void llvm::printDynamicRelocations(const ObjectFile *Obj) {
Paul Semelcb0f0432018-06-07 13:30:55 +00001493 // For the moment, this option is for ELF only
1494 if (!Obj->isELF())
1495 return;
1496
1497 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
Paul Semelcb0f0432018-06-07 13:30:55 +00001498 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1499 error("not a dynamic object");
1500 return;
1501 }
1502
Paul Semelcb0f0432018-06-07 13:30:55 +00001503 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1504 if (DynRelSec.empty())
1505 return;
1506
1507 outs() << "DYNAMIC RELOCATION RECORDS\n";
George Rimar73a27232019-01-15 09:19:18 +00001508 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Paul Semelcb0f0432018-06-07 13:30:55 +00001509 for (const SectionRef &Section : DynRelSec) {
1510 if (Section.relocation_begin() == Section.relocation_end())
1511 continue;
1512 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001513 uint64_t Address = Reloc.getOffset();
1514 SmallString<32> RelocName;
1515 SmallString<32> ValueStr;
1516 Reloc.getTypeName(RelocName);
1517 error(getRelocationValueString(Reloc, ValueStr));
1518 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1519 << ValueStr << "\n";
Paul Semelcb0f0432018-06-07 13:30:55 +00001520 }
1521 }
1522}
1523
George Rimar87fa2e62019-01-28 14:11:35 +00001524// Returns true if we need to show LMA column when dumping section headers. We
1525// show it only when the platform is ELF and either we have at least one section
1526// whose VMA and LMA are different and/or when --show-lma flag is used.
1527static bool shouldDisplayLMA(const ObjectFile *Obj) {
1528 if (!Obj->isELF())
1529 return false;
1530 for (const SectionRef &S : ToolSectionFilter(*Obj))
1531 if (S.getAddress() != getELFSectionLMA(S))
1532 return true;
1533 return ShowLMA;
1534}
1535
George Rimar73a27232019-01-15 09:19:18 +00001536void llvm::printSectionHeaders(const ObjectFile *Obj) {
George Rimar87fa2e62019-01-28 14:11:35 +00001537 bool HasLMAColumn = shouldDisplayLMA(Obj);
1538 if (HasLMAColumn)
1539 outs() << "Sections:\n"
1540 "Idx Name Size VMA LMA "
1541 "Type\n";
1542 else
1543 outs() << "Sections:\n"
1544 "Idx Name Size VMA Type\n";
1545
Colin LeMahieu77804be2015-07-29 15:45:39 +00001546 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001547 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001548 error(Section.getName(Name));
George Rimar87fa2e62019-01-28 14:11:35 +00001549 uint64_t VMA = Section.getAddress();
George Rimar4463ebe2019-01-28 16:36:12 +00001550 if (shouldAdjustVA(Section))
1551 VMA += AdjustVMA;
1552
Rafael Espindola80291272014-10-08 15:28:58 +00001553 uint64_t Size = Section.getSize();
1554 bool Text = Section.isText();
1555 bool Data = Section.isData();
1556 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001557 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001558 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimar87fa2e62019-01-28 14:11:35 +00001559
1560 if (HasLMAColumn)
1561 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1562 " %s\n",
1563 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1564 VMA, getELFSectionLMA(Section), Type.c_str());
1565 else
1566 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1567 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1568 VMA, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001569 }
Xing GUO785edea2018-11-17 08:12:48 +00001570 outs() << "\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001571}
1572
George Rimar73a27232019-01-15 09:19:18 +00001573void llvm::printSectionContents(const ObjectFile *Obj) {
Rafael Espindola4453e42942014-06-13 03:07:50 +00001574 std::error_code EC;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001575 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001576 StringRef Name;
1577 StringRef Contents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001578 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001579 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001580 uint64_t Size = Section.getSize();
1581 if (!Size)
1582 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001583
1584 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001585 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001586 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001587 ", %04" PRIx64 ")>\n",
1588 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001589 continue;
1590 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001591
Davide Italianoccd53fe2015-08-05 07:18:31 +00001592 error(Section.getContents(Contents));
David Majnemer8f6b04c2014-07-14 16:20:14 +00001593
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001594 // Dump out the content as hex and printable ascii characters.
George Rimar73a27232019-01-15 09:19:18 +00001595 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1596 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001597 // Dump line of hex.
George Rimar73a27232019-01-15 09:19:18 +00001598 for (std::size_t I = 0; I < 16; ++I) {
1599 if (I != 0 && I % 4 == 0)
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001600 outs() << ' ';
George Rimar73a27232019-01-15 09:19:18 +00001601 if (Addr + I < End)
1602 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1603 << hexdigit(Contents[Addr + I] & 0xF, true);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001604 else
1605 outs() << " ";
1606 }
1607 // Print ascii.
1608 outs() << " ";
George Rimar73a27232019-01-15 09:19:18 +00001609 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1610 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1611 outs() << Contents[Addr + I];
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001612 else
1613 outs() << ".";
1614 }
1615 outs() << "\n";
1616 }
1617 }
1618}
1619
George Rimar73a27232019-01-15 09:19:18 +00001620void llvm::printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
Kevin Enderby9acb1092016-05-31 20:35:34 +00001621 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001622 outs() << "SYMBOL TABLE:\n";
1623
George Rimar73a27232019-01-15 09:19:18 +00001624 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1625 printCOFFSymbolTable(Coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001626 return;
1627 }
George Rimar8e0a70b2019-01-10 16:24:10 +00001628
George Rimar73a27232019-01-15 09:19:18 +00001629 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
George Rimar8e0a70b2019-01-10 16:24:10 +00001630 // Skip printing the special zero symbol when dumping an ELF file.
1631 // This makes the output consistent with the GNU objdump.
George Rimar73a27232019-01-15 09:19:18 +00001632 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
George Rimar8e0a70b2019-01-10 16:24:10 +00001633 continue;
1634
1635 const SymbolRef &Symbol = *I;
Kevin Enderby931cb652016-06-24 18:24:42 +00001636 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1637 if (!AddressOrError)
George Rimar73a27232019-01-15 09:19:18 +00001638 report_error(ArchiveName, O->getFileName(), AddressOrError.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001639 ArchitectureName);
Rafael Espindolaed067c42015-07-03 18:19:00 +00001640 uint64_t Address = *AddressOrError;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001641 if ((Address < StartAddress) || (Address > StopAddress))
1642 continue;
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001643 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1644 if (!TypeOrError)
George Rimar73a27232019-01-15 09:19:18 +00001645 report_error(ArchiveName, O->getFileName(), TypeOrError.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001646 ArchitectureName);
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001647 SymbolRef::Type Type = *TypeOrError;
Rui Ueyama4e39f712014-03-18 18:58:51 +00001648 uint32_t Flags = Symbol.getFlags();
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001649 Expected<section_iterator> SectionOrErr = Symbol.getSection();
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001650 if (!SectionOrErr)
George Rimar73a27232019-01-15 09:19:18 +00001651 report_error(ArchiveName, O->getFileName(), SectionOrErr.takeError(),
Kevin Enderby7fa40c92016-11-16 22:17:38 +00001652 ArchitectureName);
Rafael Espindola8bab8892015-08-07 23:27:14 +00001653 section_iterator Section = *SectionOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001654 StringRef Name;
George Rimar73a27232019-01-15 09:19:18 +00001655 if (Type == SymbolRef::ST_Debug && Section != O->section_end()) {
Rafael Espindola75d5b542015-06-03 05:14:22 +00001656 Section->getName(Name);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001657 } else {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001658 Expected<StringRef> NameOrErr = Symbol.getName();
1659 if (!NameOrErr)
George Rimar73a27232019-01-15 09:19:18 +00001660 report_error(ArchiveName, O->getFileName(), NameOrErr.takeError(),
Kevin Enderby9acb1092016-05-31 20:35:34 +00001661 ArchitectureName);
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001662 Name = *NameOrErr;
Rafael Espindola75d5b542015-06-03 05:14:22 +00001663 }
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001664
Rui Ueyama4e39f712014-03-18 18:58:51 +00001665 bool Global = Flags & SymbolRef::SF_Global;
1666 bool Weak = Flags & SymbolRef::SF_Weak;
1667 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001668 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001669 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001670
Rui Ueyama4e39f712014-03-18 18:58:51 +00001671 char GlobLoc = ' ';
1672 if (Type != SymbolRef::ST_Unknown)
1673 GlobLoc = Global ? 'g' : 'l';
1674 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1675 ? 'd' : ' ';
1676 char FileFunc = ' ';
1677 if (Type == SymbolRef::ST_File)
1678 FileFunc = 'f';
1679 else if (Type == SymbolRef::ST_Function)
1680 FileFunc = 'F';
Kristina Brooks0674f9d2018-11-11 17:47:13 +00001681 else if (Type == SymbolRef::ST_Data)
1682 FileFunc = 'O';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001683
George Rimar73a27232019-01-15 09:19:18 +00001684 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
Rui Ueyama4e39f712014-03-18 18:58:51 +00001685 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001686
Rui Ueyama4e39f712014-03-18 18:58:51 +00001687 outs() << format(Fmt, Address) << " "
1688 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1689 << (Weak ? 'w' : ' ') // Weak?
1690 << ' ' // Constructor. Not supported yet.
1691 << ' ' // Warning. Not supported yet.
1692 << ' ' // Indirect reference to another symbol.
1693 << Debug // Debugging (d) or dynamic (D) symbol.
1694 << FileFunc // Name of function (F), file (f) or object (O).
1695 << ' ';
1696 if (Absolute) {
1697 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001698 } else if (Common) {
1699 outs() << "*COM*";
George Rimar73a27232019-01-15 09:19:18 +00001700 } else if (Section == O->section_end()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001701 outs() << "*UND*";
1702 } else {
1703 if (const MachOObjectFile *MachO =
George Rimar73a27232019-01-15 09:19:18 +00001704 dyn_cast<const MachOObjectFile>(O)) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001705 DataRefImpl DR = Section->getRawDataRefImpl();
1706 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1707 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001708 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001709 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001710 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001711 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001712 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001713
1714 outs() << '\t';
George Rimar73a27232019-01-15 09:19:18 +00001715 if (Common || isa<ELFObjectFileBase>(O)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001716 uint64_t Val =
1717 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001718 outs() << format("\t %08" PRIx64 " ", Val);
1719 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001720
George Rimar73a27232019-01-15 09:19:18 +00001721 if (Hidden)
Davide Italianocd2514d2015-04-30 23:08:53 +00001722 outs() << ".hidden ";
George Rimar6622d412018-12-19 10:21:45 +00001723
1724 if (Demangle)
1725 outs() << demangle(Name) << '\n';
1726 else
1727 outs() << Name << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001728 }
1729}
1730
George Rimar73a27232019-01-15 09:19:18 +00001731static void printUnwindInfo(const ObjectFile *O) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001732 outs() << "Unwind info:\n\n";
1733
George Rimar73a27232019-01-15 09:19:18 +00001734 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1735 printCOFFUnwindInfo(Coff);
1736 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
Tim Northover4bd286a2014-08-01 13:07:19 +00001737 printMachOUnwindInfo(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001738 else
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001739 // TODO: Extract DWARF dump tool to objdump.
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001740 WithColor::error(errs(), ToolName)
1741 << "This operation is only currently supported "
1742 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001743}
1744
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001745void llvm::printExportsTrie(const ObjectFile *o) {
Nick Kledzikd04bc352014-08-30 00:20:14 +00001746 outs() << "Exports trie:\n";
1747 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
1748 printMachOExportsTrie(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001749 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001750 WithColor::error(errs(), ToolName)
1751 << "This operation is only currently supported "
1752 "for Mach-O executable files.\n";
Nick Kledzikd04bc352014-08-30 00:20:14 +00001753}
1754
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001755void llvm::printRebaseTable(ObjectFile *o) {
Nick Kledzikac431442014-09-12 21:34:15 +00001756 outs() << "Rebase table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001757 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzikac431442014-09-12 21:34:15 +00001758 printMachORebaseTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001759 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001760 WithColor::error(errs(), ToolName)
1761 << "This operation is only currently supported "
1762 "for Mach-O executable files.\n";
Nick Kledzikac431442014-09-12 21:34:15 +00001763}
1764
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001765void llvm::printBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001766 outs() << "Bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001767 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001768 printMachOBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001769 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001770 WithColor::error(errs(), ToolName)
1771 << "This operation is only currently supported "
1772 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00001773}
1774
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001775void llvm::printLazyBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001776 outs() << "Lazy bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001777 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001778 printMachOLazyBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001779 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001780 WithColor::error(errs(), ToolName)
1781 << "This operation is only currently supported "
1782 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00001783}
1784
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001785void llvm::printWeakBindTable(ObjectFile *o) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00001786 outs() << "Weak bind table:\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00001787 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
Nick Kledzik56ebef42014-09-16 01:41:51 +00001788 printMachOWeakBindTable(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001789 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001790 WithColor::error(errs(), ToolName)
1791 << "This operation is only currently supported "
1792 "for Mach-O executable files.\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00001793}
Nick Kledzikac431442014-09-12 21:34:15 +00001794
Adrian Prantl437105a2015-07-08 02:04:15 +00001795/// Dump the raw contents of the __clangast section so the output can be piped
1796/// into llvm-bcanalyzer.
1797void llvm::printRawClangAST(const ObjectFile *Obj) {
1798 if (outs().is_displayed()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001799 WithColor::error(errs(), ToolName)
1800 << "The -raw-clang-ast option will dump the raw binary contents of "
1801 "the clang ast section.\n"
1802 "Please redirect the output to a file or another program such as "
1803 "llvm-bcanalyzer.\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001804 return;
1805 }
1806
1807 StringRef ClangASTSectionName("__clangast");
1808 if (isa<COFFObjectFile>(Obj)) {
1809 ClangASTSectionName = "clangast";
1810 }
1811
1812 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001813 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001814 StringRef Name;
1815 Sec.getName(Name);
1816 if (Name == ClangASTSectionName) {
1817 ClangASTSection = Sec;
1818 break;
1819 }
1820 }
1821 if (!ClangASTSection)
1822 return;
1823
1824 StringRef ClangASTContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001825 error(ClangASTSection.getValue().getContents(ClangASTContents));
Adrian Prantl437105a2015-07-08 02:04:15 +00001826 outs().write(ClangASTContents.data(), ClangASTContents.size());
1827}
1828
Sanjoy Das6f567a42015-06-22 18:03:02 +00001829static void printFaultMaps(const ObjectFile *Obj) {
George Rimar73a27232019-01-15 09:19:18 +00001830 StringRef FaultMapSectionName;
Sanjoy Das6f567a42015-06-22 18:03:02 +00001831
1832 if (isa<ELFObjectFileBase>(Obj)) {
1833 FaultMapSectionName = ".llvm_faultmaps";
1834 } else if (isa<MachOObjectFile>(Obj)) {
1835 FaultMapSectionName = "__llvm_faultmaps";
1836 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001837 WithColor::error(errs(), ToolName)
1838 << "This operation is only currently supported "
1839 "for ELF and Mach-O executable files.\n";
Sanjoy Das6f567a42015-06-22 18:03:02 +00001840 return;
1841 }
1842
1843 Optional<object::SectionRef> FaultMapSection;
1844
Colin LeMahieu77804be2015-07-29 15:45:39 +00001845 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001846 StringRef Name;
1847 Sec.getName(Name);
1848 if (Name == FaultMapSectionName) {
1849 FaultMapSection = Sec;
1850 break;
1851 }
1852 }
1853
1854 outs() << "FaultMap table:\n";
1855
1856 if (!FaultMapSection.hasValue()) {
1857 outs() << "<not found>\n";
1858 return;
1859 }
1860
1861 StringRef FaultMapContents;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001862 error(FaultMapSection.getValue().getContents(FaultMapContents));
Sanjoy Das6f567a42015-06-22 18:03:02 +00001863
1864 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1865 FaultMapContents.bytes_end());
1866
1867 outs() << FMP;
1868}
1869
George Rimar73a27232019-01-15 09:19:18 +00001870static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1871 if (O->isELF()) {
1872 printELFFileHeader(O);
1873 return printELFDynamicSection(O);
Paul Semel0913dcd2018-07-25 11:09:20 +00001874 }
George Rimar73a27232019-01-15 09:19:18 +00001875 if (O->isCOFF())
1876 return printCOFFFileHeader(O);
1877 if (O->isWasm())
1878 return printWasmFileHeader(O);
1879 if (O->isMachO()) {
1880 printMachOFileHeader(O);
1881 if (!OnlyFirst)
1882 printMachOLoadCommands(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001883 return;
1884 }
George Rimar73a27232019-01-15 09:19:18 +00001885 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001886}
1887
George Rimar73a27232019-01-15 09:19:18 +00001888static void printFileHeaders(const ObjectFile *O) {
1889 if (!O->isELF() && !O->isCOFF())
1890 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Paul Semeld2af4d62018-07-04 15:25:03 +00001891
George Rimar73a27232019-01-15 09:19:18 +00001892 Triple::ArchType AT = O->getArch();
Paul Semeld2af4d62018-07-04 15:25:03 +00001893 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
George Rimar73a27232019-01-15 09:19:18 +00001894 Expected<uint64_t> StartAddrOrErr = O->getStartAddress();
Paul Semeld2af4d62018-07-04 15:25:03 +00001895 if (!StartAddrOrErr)
George Rimar73a27232019-01-15 09:19:18 +00001896 report_error(O->getFileName(), StartAddrOrErr.takeError());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00001897
George Rimar73a27232019-01-15 09:19:18 +00001898 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00001899 uint64_t Address = StartAddrOrErr.get();
Paul Semeld2af4d62018-07-04 15:25:03 +00001900 outs() << "start address: "
George Rimar9b6fe7e2019-01-12 12:17:24 +00001901 << "0x" << format(Fmt.data(), Address) << "\n\n";
Paul Semeld2af4d62018-07-04 15:25:03 +00001902}
1903
Paul Semel0dc92f62018-07-05 14:43:29 +00001904static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1905 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1906 if (!ModeOrErr) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001907 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
Paul Semel0dc92f62018-07-05 14:43:29 +00001908 consumeError(ModeOrErr.takeError());
1909 return;
1910 }
1911 sys::fs::perms Mode = ModeOrErr.get();
1912 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1913 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1914 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1915 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1916 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1917 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1918 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1919 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1920 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1921
1922 outs() << " ";
1923
1924 Expected<unsigned> UIDOrErr = C.getUID();
1925 if (!UIDOrErr)
1926 report_error(Filename, UIDOrErr.takeError());
1927 unsigned UID = UIDOrErr.get();
1928 outs() << format("%d/", UID);
1929
1930 Expected<unsigned> GIDOrErr = C.getGID();
1931 if (!GIDOrErr)
1932 report_error(Filename, GIDOrErr.takeError());
1933 unsigned GID = GIDOrErr.get();
1934 outs() << format("%-d ", GID);
1935
1936 Expected<uint64_t> Size = C.getRawSize();
1937 if (!Size)
1938 report_error(Filename, Size.takeError());
1939 outs() << format("%6" PRId64, Size.get()) << " ";
1940
1941 StringRef RawLastModified = C.getRawLastModified();
1942 unsigned Seconds;
1943 if (RawLastModified.getAsInteger(10, Seconds))
1944 outs() << "(date: \"" << RawLastModified
1945 << "\" contains non-decimal chars) ";
1946 else {
1947 // Since ctime(3) returns a 26 character string of the form:
1948 // "Sun Sep 16 01:03:52 1973\n\0"
1949 // just print 24 characters.
1950 time_t t = Seconds;
1951 outs() << format("%.24s ", ctime(&t));
1952 }
1953
1954 StringRef Name = "";
1955 Expected<StringRef> NameOrErr = C.getName();
1956 if (!NameOrErr) {
1957 consumeError(NameOrErr.takeError());
1958 Expected<StringRef> RawNameOrErr = C.getRawName();
1959 if (!RawNameOrErr)
1960 report_error(Filename, NameOrErr.takeError());
1961 Name = RawNameOrErr.get();
1962 } else {
1963 Name = NameOrErr.get();
1964 }
1965 outs() << Name << "\n";
1966}
1967
George Rimar73a27232019-01-15 09:19:18 +00001968static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
1969 const Archive::Child *C = nullptr) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001970 // Avoid other output when using a raw option.
1971 if (!RawClangAST) {
1972 outs() << '\n';
George Rimar73a27232019-01-15 09:19:18 +00001973 if (A)
1974 outs() << A->getFileName() << "(" << O->getFileName() << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001975 else
George Rimar73a27232019-01-15 09:19:18 +00001976 outs() << O->getFileName();
1977 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001978 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001979
George Rimar73a27232019-01-15 09:19:18 +00001980 StringRef ArchiveName = A ? A->getFileName() : "";
George Rimar9b6fe7e2019-01-12 12:17:24 +00001981 if (FileHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001982 printFileHeaders(O);
1983 if (ArchiveHeaders && !MachOOpt && C)
1984 printArchiveChild(ArchiveName, *C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001985 if (Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00001986 disassembleObject(O, Relocations);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001987 if (Relocations && !Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00001988 printRelocations(O);
Paul Semelcb0f0432018-06-07 13:30:55 +00001989 if (DynamicRelocations)
George Rimar73a27232019-01-15 09:19:18 +00001990 printDynamicRelocations(O);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001991 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001992 printSectionHeaders(O);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001993 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001994 printSectionContents(O);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001995 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001996 printSymbolTable(O, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001997 if (UnwindInfo)
George Rimar73a27232019-01-15 09:19:18 +00001998 printUnwindInfo(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001999 if (PrivateHeaders || FirstPrivateHeader)
George Rimar73a27232019-01-15 09:19:18 +00002000 printPrivateFileHeaders(O, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00002001 if (ExportsTrie)
George Rimar73a27232019-01-15 09:19:18 +00002002 printExportsTrie(O);
Nick Kledzikac431442014-09-12 21:34:15 +00002003 if (Rebase)
George Rimar73a27232019-01-15 09:19:18 +00002004 printRebaseTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002005 if (Bind)
George Rimar73a27232019-01-15 09:19:18 +00002006 printBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002007 if (LazyBind)
George Rimar73a27232019-01-15 09:19:18 +00002008 printLazyBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00002009 if (WeakBind)
George Rimar73a27232019-01-15 09:19:18 +00002010 printWeakBindTable(O);
Adrian Prantl437105a2015-07-08 02:04:15 +00002011 if (RawClangAST)
George Rimar73a27232019-01-15 09:19:18 +00002012 printRawClangAST(O);
Sanjoy Das6f567a42015-06-22 18:03:02 +00002013 if (PrintFaultMaps)
George Rimar73a27232019-01-15 09:19:18 +00002014 printFaultMaps(O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002015 if (DwarfDumpType != DIDT_Null) {
George Rimar73a27232019-01-15 09:19:18 +00002016 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002017 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002018 DIDumpOptions DumpOpts;
2019 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00002020 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00002021 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002022}
2023
George Rimar73a27232019-01-15 09:19:18 +00002024static void dumpObject(const COFFImportFile *I, const Archive *A,
Paul Semel0dc92f62018-07-05 14:43:29 +00002025 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002026 StringRef ArchiveName = A ? A->getFileName() : "";
2027
2028 // Avoid other output when using a raw option.
2029 if (!RawClangAST)
2030 outs() << '\n'
2031 << ArchiveName << "(" << I->getFileName() << ")"
2032 << ":\tfile format COFF-import-file"
2033 << "\n\n";
2034
James Hendersonc1608c92018-10-29 14:17:08 +00002035 if (ArchiveHeaders && !MachOOpt && C)
2036 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002037 if (SymbolTable)
2038 printCOFFSymbolTable(I);
2039}
2040
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002041/// Dump each object file in \a a;
George Rimar73a27232019-01-15 09:19:18 +00002042static void dumpArchive(const Archive *A) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002043 Error Err = Error::success();
George Rimar73a27232019-01-15 09:19:18 +00002044 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002045 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2046 if (!ChildOrErr) {
2047 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
George Rimar73a27232019-01-15 09:19:18 +00002048 report_error(A->getFileName(), C, std::move(E));
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002049 continue;
2050 }
George Rimar73a27232019-01-15 09:19:18 +00002051 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2052 dumpObject(O, A, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00002053 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
George Rimar73a27232019-01-15 09:19:18 +00002054 dumpObject(I, A, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002055 else
George Rimar73a27232019-01-15 09:19:18 +00002056 report_error(A->getFileName(), object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002057 }
Lang Hamesfc209622016-07-14 02:24:01 +00002058 if (Err)
George Rimar73a27232019-01-15 09:19:18 +00002059 report_error(A->getFileName(), std::move(Err));
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002060}
2061
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00002062/// Open file and figure out how to dump it.
George Rimar73a27232019-01-15 09:19:18 +00002063static void dumpInput(StringRef file) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002064 // If we are using the Mach-O specific object file parser, then let it parse
2065 // the file and process the command line options. So the -arch flags can
2066 // be used to select specific slices, etc.
2067 if (MachOOpt) {
George Rimar73a27232019-01-15 09:19:18 +00002068 parseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002069 return;
2070 }
2071
2072 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002073 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2074 if (!BinaryOrErr)
Kevin Enderbyb34e3a12016-05-05 17:43:35 +00002075 report_error(file, BinaryOrErr.takeError());
Rafael Espindola48af1c22014-08-19 18:44:46 +00002076 Binary &Binary = *BinaryOrErr.get().getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002077
George Rimar73a27232019-01-15 09:19:18 +00002078 if (Archive *A = dyn_cast<Archive>(&Binary))
2079 dumpArchive(A);
2080 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2081 dumpObject(O);
Dave Lee3fb120f2018-08-03 00:06:38 +00002082 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
George Rimar73a27232019-01-15 09:19:18 +00002083 parseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002084 else
Alexey Samsonov50d0fbd2015-06-04 18:34:11 +00002085 report_error(file, object_error::invalid_file_type);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002086}
2087
Michael J. Spencer2670c252011-01-20 06:39:06 +00002088int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +00002089 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002090
2091 // Initialize targets and assembly printers/parsers.
2092 llvm::InitializeAllTargetInfos();
Evan Cheng8c886a42011-07-22 21:58:54 +00002093 llvm::InitializeAllTargetMCs();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002094 llvm::InitializeAllDisassemblers();
2095
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002096 // Register the target printer for --version.
2097 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2098
Michael J. Spencer2670c252011-01-20 06:39:06 +00002099 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002100
2101 ToolName = argv[0];
2102
2103 // Defaults to a.out if no filenames specified.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002104 if (InputFilenames.empty())
Michael J. Spencer2670c252011-01-20 06:39:06 +00002105 InputFilenames.push_back("a.out");
2106
Fangrui Song8513cd42018-06-27 20:45:11 +00002107 if (AllHeaders)
George Rimar5e364332019-01-18 12:01:59 +00002108 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2109 SectionHeaders = SymbolTable = true;
Fangrui Song8513cd42018-06-27 20:45:11 +00002110
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002111 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002112 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002113
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002114 if (!Disassemble
2115 && !Relocations
Paul Semelcb0f0432018-06-07 13:30:55 +00002116 && !DynamicRelocations
Michael J. Spencerbfa06782011-10-18 19:32:17 +00002117 && !SectionHeaders
2118 && !SectionContents
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00002119 && !SymbolTable
Michael J. Spencer209565db2013-01-06 03:56:49 +00002120 && !UnwindInfo
Nick Kledzikd04bc352014-08-30 00:20:14 +00002121 && !PrivateHeaders
Paul Semeld2af4d62018-07-04 15:25:03 +00002122 && !FileHeaders
Kevin Enderby0ae163f2016-01-13 00:25:36 +00002123 && !FirstPrivateHeader
Nick Kledzikac431442014-09-12 21:34:15 +00002124 && !ExportsTrie
Nick Kledzik56ebef42014-09-16 01:41:51 +00002125 && !Rebase
2126 && !Bind
2127 && !LazyBind
Kevin Enderby131d1772015-01-09 19:22:37 +00002128 && !WeakBind
Adrian Prantl437105a2015-07-08 02:04:15 +00002129 && !RawClangAST
Kevin Enderby13023a12015-01-15 23:19:11 +00002130 && !(UniversalHeaders && MachOOpt)
Paul Semel0dc92f62018-07-05 14:43:29 +00002131 && !ArchiveHeaders
Kevin Enderby69fe98d2015-01-23 18:52:17 +00002132 && !(IndirectSymbols && MachOOpt)
Kevin Enderby9a509442015-01-27 21:28:24 +00002133 && !(DataInCode && MachOOpt)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002134 && !(LinkOptHints && MachOOpt)
Kevin Enderbycd66be52015-03-11 22:06:32 +00002135 && !(InfoPlist && MachOOpt)
Kevin Enderbybc847fa2015-03-16 20:08:09 +00002136 && !(DylibsUsed && MachOOpt)
2137 && !(DylibId && MachOOpt)
Kevin Enderby0fc11822015-04-01 20:57:01 +00002138 && !(ObjcMetaData && MachOOpt)
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002139 && !(!FilterSections.empty() && MachOOpt)
Igor Laevsky03a670c2016-01-26 15:09:42 +00002140 && !PrintFaultMaps
2141 && DwarfDumpType == DIDT_Null) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002142 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002143 return 2;
2144 }
2145
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002146 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2147 DisassembleFunctions.end());
2148
George Rimar73a27232019-01-15 09:19:18 +00002149 llvm::for_each(InputFilenames, dumpInput);
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002150
2151 return EXIT_SUCCESS;
2152}