blob: de26b61697cb6511aee9390d803e45f9fbcb6aee [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
Fangrui Song523758e2019-04-15 15:31:42 +000070using namespace llvm::object;
Michael J. Spencer2670c252011-01-20 06:39:06 +000071
Fangrui Song9d812f42019-04-15 15:00:10 +000072namespace llvm {
73
74// MachO specific
75extern cl::opt<bool> Bind;
76extern cl::opt<bool> DataInCode;
77extern cl::opt<bool> DylibsUsed;
78extern cl::opt<bool> DylibId;
79extern cl::opt<bool> ExportsTrie;
80extern cl::opt<bool> FirstPrivateHeader;
81extern cl::opt<bool> IndirectSymbols;
82extern cl::opt<bool> InfoPlist;
83extern cl::opt<bool> LazyBind;
84extern cl::opt<bool> LinkOptHints;
85extern cl::opt<bool> ObjcMetaData;
86extern cl::opt<bool> Rebase;
87extern cl::opt<bool> UniversalHeaders;
88extern cl::opt<bool> WeakBind;
89
Fangrui Songb5f39842019-04-24 02:40:20 +000090static cl::opt<uint64_t> AdjustVMA(
George Rimar4c3b2972019-01-28 10:44:01 +000091 "adjust-vma",
92 cl::desc("Increase the displayed address by the specified offset"),
93 cl::value_desc("offset"), cl::init(0));
94
Fangrui Song9d812f42019-04-15 15:00:10 +000095static cl::opt<bool>
96 AllHeaders("all-headers",
97 cl::desc("Display all available header information"));
Fangrui Song8513cd42018-06-27 20:45:11 +000098static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +000099 cl::NotHidden, cl::Grouping,
100 cl::aliasopt(AllHeaders));
Fangrui Song8513cd42018-06-27 20:45:11 +0000101
Fangrui Song9d812f42019-04-15 15:00:10 +0000102static cl::opt<std::string>
103 ArchName("arch-name", cl::desc("Target arch to disassemble for, "
104 "see -version for available targets"));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000105
Fangrui Song9d812f42019-04-15 15:00:10 +0000106cl::opt<bool> ArchiveHeaders("archive-headers",
107 cl::desc("Display archive header information"));
108static cl::alias ArchiveHeadersShort("a",
109 cl::desc("Alias for --archive-headers"),
110 cl::NotHidden, cl::Grouping,
111 cl::aliasopt(ArchiveHeaders));
Colin LeMahieu77804be2015-07-29 15:45:39 +0000112
Fangrui Song9d812f42019-04-15 15:00:10 +0000113cl::opt<bool> Demangle("demangle", cl::desc("Demangle symbols names"),
114 cl::init(false));
Paul Semel007dedb2018-07-18 16:39:21 +0000115static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
Matthew Voss0f436772019-02-19 19:46:08 +0000116 cl::NotHidden, cl::Grouping,
Fangrui Song9d812f42019-04-15 15:00:10 +0000117 cl::aliasopt(Demangle));
118
119cl::opt<bool> Disassemble(
120 "disassemble",
121 cl::desc("Display assembler mnemonics for the machine instructions"));
122static cl::alias DisassembleShort("d", cl::desc("Alias for --disassemble"),
123 cl::NotHidden, cl::Grouping,
124 cl::aliasopt(Disassemble));
125
126cl::opt<bool> DisassembleAll(
127 "disassemble-all",
128 cl::desc("Display assembler mnemonics for the machine instructions"));
129static cl::alias DisassembleAllShort("D",
130 cl::desc("Alias for --disassemble-all"),
131 cl::NotHidden, cl::Grouping,
132 cl::aliasopt(DisassembleAll));
Paul Semel007dedb2018-07-18 16:39:21 +0000133
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000134static cl::list<std::string>
Matthew Voss0f436772019-02-19 19:46:08 +0000135DisassembleFunctions("disassemble-functions",
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000136 cl::CommaSeparated,
137 cl::desc("List of functions to disassemble"));
Rafael Aulerb0e4b912018-03-09 19:13:44 +0000138
Fangrui Song9d812f42019-04-15 15:00:10 +0000139static cl::opt<bool> DisassembleZeroes(
140 "disassemble-zeroes",
141 cl::desc("Do not skip blocks of zeroes when disassembling"));
142static cl::alias
143 DisassembleZeroesShort("z", cl::desc("Alias for --disassemble-zeroes"),
144 cl::NotHidden, cl::Grouping,
145 cl::aliasopt(DisassembleZeroes));
146
147static cl::list<std::string>
148 DisassemblerOptions("disassembler-options",
149 cl::desc("Pass target specific disassembler options"),
150 cl::value_desc("options"), cl::CommaSeparated);
151static cl::alias
152 DisassemblerOptionsShort("M", cl::desc("Alias for --disassembler-options"),
153 cl::NotHidden, cl::Grouping, cl::Prefix,
154 cl::CommaSeparated,
155 cl::aliasopt(DisassemblerOptions));
156
157cl::opt<DIDumpType> DwarfDumpType(
158 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
159 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")));
160
161static cl::opt<bool> DynamicRelocations(
162 "dynamic-reloc",
163 cl::desc("Display the dynamic relocation entries in the file"));
164static cl::alias DynamicRelocationShort("R",
165 cl::desc("Alias for --dynamic-reloc"),
166 cl::NotHidden, cl::Grouping,
167 cl::aliasopt(DynamicRelocations));
168
169static cl::opt<bool>
170 FaultMapSection("fault-map-section",
171 cl::desc("Display contents of faultmap section"));
172
173static cl::opt<bool>
174 FileHeaders("file-headers",
175 cl::desc("Display the contents of the overall file header"));
176static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000177 cl::NotHidden, cl::Grouping,
Fangrui Song9d812f42019-04-15 15:00:10 +0000178 cl::aliasopt(FileHeaders));
Michael J. Spencerba4a3622011-10-08 00:18:30 +0000179
Fangrui Song9d812f42019-04-15 15:00:10 +0000180cl::opt<bool> SectionContents("full-contents",
181 cl::desc("Display the content of each section"));
James Hendersonb55b6582018-10-29 10:05:39 +0000182static cl::alias SectionContentsShort("s",
183 cl::desc("Alias for --full-contents"),
Matthew Voss0f436772019-02-19 19:46:08 +0000184 cl::NotHidden, cl::Grouping,
James Hendersonb55b6582018-10-29 10:05:39 +0000185 cl::aliasopt(SectionContents));
Michael J. Spencer4e25c022011-10-17 17:13:22 +0000186
Fangrui Song9d812f42019-04-15 15:00:10 +0000187static cl::list<std::string>
188InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencerbfa06782011-10-18 19:32:17 +0000189
Fangrui Song9d812f42019-04-15 15:00:10 +0000190static cl::opt<bool>
191 PrintLines("line-numbers",
192 cl::desc("Display source line numbers with "
193 "disassembly. Implies disassemble object"));
194static cl::alias PrintLinesShort("l", cl::desc("Alias for --line-numbers"),
195 cl::NotHidden, cl::Grouping,
196 cl::aliasopt(PrintLines));
Adrian Prantl437105a2015-07-08 02:04:15 +0000197
Nick Kledzik56ebef42014-09-16 01:41:51 +0000198static cl::opt<bool>
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000199MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
George Rimar845d3292019-01-18 10:41:26 +0000200static cl::alias MachOm("m", cl::desc("Alias for --macho"), cl::NotHidden,
Matthew Voss0f436772019-02-19 19:46:08 +0000201 cl::Grouping, cl::aliasopt(MachOOpt));
Benjamin Kramer87ee76c2011-07-20 19:37:35 +0000202
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000203cl::opt<std::string>
Fangrui Song9d812f42019-04-15 15:00:10 +0000204 MCPU("mcpu",
205 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
206 cl::value_desc("cpu-name"), cl::init(""));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000207
Fangrui Song9d812f42019-04-15 15:00:10 +0000208cl::list<std::string> MAttrs("mattr", cl::CommaSeparated,
209 cl::desc("Target specific attributes"),
210 cl::value_desc("a1,+a2,-a3,..."));
Kevin Enderbyc9595622014-08-06 23:24:41 +0000211
Fangrui Song9d812f42019-04-15 15:00:10 +0000212cl::opt<bool> NoShowRawInsn("no-show-raw-insn",
213 cl::desc("When disassembling "
214 "instructions, do not print "
215 "the instruction bytes."));
216cl::opt<bool> NoLeadingAddr("no-leading-addr",
217 cl::desc("Print no leading address"));
218
219static cl::opt<bool> RawClangAST(
220 "raw-clang-ast",
221 cl::desc("Dump the raw binary contents of the clang AST section"));
Michael J. Spencer2670c252011-01-20 06:39:06 +0000222
Kevin Enderby98da6132015-01-20 21:47:46 +0000223cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000224 Relocations("reloc",
225 cl::desc("Display the relocation entries in the file"));
226static cl::alias RelocationsShort("r", cl::desc("Alias for --reloc"),
227 cl::NotHidden, cl::Grouping,
228 cl::aliasopt(Relocations));
229
230cl::opt<bool>
231 PrintImmHex("print-imm-hex",
232 cl::desc("Use hex format for immediate values"));
233
234cl::opt<bool>
235 PrivateHeaders("private-headers",
236 cl::desc("Display format specific file headers"));
237static cl::alias PrivateHeadersShort("p",
238 cl::desc("Alias for --private-headers"),
239 cl::NotHidden, cl::Grouping,
240 cl::aliasopt(PrivateHeaders));
241
242cl::list<std::string>
243 FilterSections("section",
244 cl::desc("Operate on the specified sections only. "
245 "With -macho dump segment,section"));
246static cl::alias FilterSectionsj("j", cl::desc("Alias for --section"),
247 cl::NotHidden, cl::Grouping, cl::Prefix,
248 cl::aliasopt(FilterSections));
249
250cl::opt<bool> SectionHeaders("section-headers",
251 cl::desc("Display summaries of the "
252 "headers for each section."));
George Rimar845d3292019-01-18 10:41:26 +0000253static cl::alias SectionHeadersShort("headers",
254 cl::desc("Alias for --section-headers"),
255 cl::NotHidden,
256 cl::aliasopt(SectionHeaders));
257static cl::alias SectionHeadersShorter("h",
258 cl::desc("Alias for --section-headers"),
Matthew Voss0f436772019-02-19 19:46:08 +0000259 cl::NotHidden, cl::Grouping,
George Rimar845d3292019-01-18 10:41:26 +0000260 cl::aliasopt(SectionHeaders));
Colin LeMahieufcc32762015-07-29 19:08:10 +0000261
George Rimar87fa2e62019-01-28 14:11:35 +0000262static cl::opt<bool>
263 ShowLMA("show-lma",
264 cl::desc("Display LMA column when dumping ELF section headers"));
265
Fangrui Song9d812f42019-04-15 15:00:10 +0000266static cl::opt<bool> PrintSource(
267 "source",
268 cl::desc(
269 "Display source inlined with disassembly. Implies disassemble object"));
270static cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
271 cl::NotHidden, cl::Grouping,
272 cl::aliasopt(PrintSource));
Nick Lewyckyfcf84622011-10-10 21:21:34 +0000273
Fangrui Songb5f39842019-04-24 02:40:20 +0000274static cl::opt<uint64_t>
Fangrui Song9d812f42019-04-15 15:00:10 +0000275 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
276 cl::value_desc("address"), cl::init(0));
Fangrui Songb5f39842019-04-24 02:40:20 +0000277static cl::opt<uint64_t> StopAddress("stop-address",
278 cl::desc("Stop disassembly at address"),
279 cl::value_desc("address"),
280 cl::init(UINT64_MAX));
Jack Carter551efd72012-08-28 19:24:49 +0000281
Fangrui Song9d812f42019-04-15 15:00:10 +0000282cl::opt<bool> SymbolTable("syms", cl::desc("Display the symbol table"));
283static cl::alias SymbolTableShort("t", cl::desc("Alias for --syms"),
284 cl::NotHidden, cl::Grouping,
285 cl::aliasopt(SymbolTable));
Eli Bendersky3a6808c2012-11-20 22:57:02 +0000286
Fangrui Song9d812f42019-04-15 15:00:10 +0000287cl::opt<std::string> TripleName("triple",
288 cl::desc("Target triple to disassemble for, "
289 "see -version for available targets"));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000290
Fangrui Song9d812f42019-04-15 15:00:10 +0000291cl::opt<bool> UnwindInfo("unwind-info",
292 cl::desc("Display unwind information"));
George Rimar845d3292019-01-18 10:41:26 +0000293static cl::alias UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
Matthew Voss0f436772019-02-19 19:46:08 +0000294 cl::NotHidden, cl::Grouping,
295 cl::aliasopt(UnwindInfo));
Michael J. Spencer0c6ec482012-12-05 20:12:35 +0000296
Igor Kudrin2d3faad2019-02-26 12:15:14 +0000297
Fangrui Song5f2b5cd2019-04-10 04:46:01 +0000298static cl::opt<bool>
299 Wide("wide", cl::desc("Ignored for compatibility with GNU objdump"));
300static cl::alias WideShort("w", cl::Grouping, cl::aliasopt(Wide));
301
Fangrui Song9d812f42019-04-15 15:00:10 +0000302static StringSet<> DisasmFuncsSet;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000303static StringRef ToolName;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000304
Clement Courbetd1a3bd42019-01-18 15:26:14 +0000305typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
Clement Courbet2d7d4a32019-01-18 09:40:19 +0000306
Fangrui Song523758e2019-04-15 15:31:42 +0000307SectionFilter ToolSectionFilter(object::ObjectFile const &O) {
David Majnemer42531262016-08-12 03:55:06 +0000308 return SectionFilter(
Fangrui Song523758e2019-04-15 15:31:42 +0000309 [](object::SectionRef const &S) {
David Majnemer42531262016-08-12 03:55:06 +0000310 if (FilterSections.empty())
311 return true;
Fangrui Song523758e2019-04-15 15:31:42 +0000312 StringRef String;
David Majnemer42531262016-08-12 03:55:06 +0000313 std::error_code error = S.getName(String);
314 if (error)
315 return false;
316 return is_contained(FilterSections, String);
317 },
318 O);
Colin LeMahieu77804be2015-07-29 15:45:39 +0000319}
Colin LeMahieu77804be2015-07-29 15:45:39 +0000320
Fangrui Song523758e2019-04-15 15:31:42 +0000321void error(std::error_code EC) {
Mark Seaborneb03ac52014-01-25 00:32:01 +0000322 if (!EC)
Davide Italianoccd53fe2015-08-05 07:18:31 +0000323 return;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000324 WithColor::error(errs(), ToolName)
325 << "reading file: " << EC.message() << ".\n";
Davide Italiano140af642015-12-25 18:16:45 +0000326 errs().flush();
Davide Italiano7f6c3012015-08-06 00:18:52 +0000327 exit(1);
Michael J. Spencer2670c252011-01-20 06:39:06 +0000328}
329
Fangrui Song523758e2019-04-15 15:31:42 +0000330void error(Error E) {
Fangrui Songf67de6c2019-04-08 16:24:08 +0000331 if (!E)
332 return;
333 WithColor::error(errs(), ToolName) << toString(std::move(E));
334 exit(1);
335}
336
Fangrui Song523758e2019-04-15 15:31:42 +0000337LLVM_ATTRIBUTE_NORETURN void error(Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000338 WithColor::error(errs(), ToolName) << Message << ".\n";
Kevin Enderby42398052016-06-28 23:16:13 +0000339 errs().flush();
340 exit(1);
341}
342
Fangrui Song523758e2019-04-15 15:31:42 +0000343void warn(StringRef Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000344 WithColor::warning(errs(), ToolName) << Message << ".\n";
Paul Semel007dedb2018-07-18 16:39:21 +0000345 errs().flush();
346}
347
Fangrui Song523758e2019-04-15 15:31:42 +0000348LLVM_ATTRIBUTE_NORETURN void report_error(StringRef File, Twine Message) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000349 WithColor::error(errs(), ToolName)
350 << "'" << File << "': " << Message << ".\n";
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000351 exit(1);
352}
353
Fangrui Song523758e2019-04-15 15:31:42 +0000354LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef File) {
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000355 assert(E);
356 std::string Buf;
357 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000358 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000359 OS.flush();
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000360 WithColor::error(errs(), ToolName) << "'" << File << "': " << Buf;
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +0000361 exit(1);
362}
363
Fangrui Song523758e2019-04-15 15:31:42 +0000364LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
365 StringRef FileName,
366 StringRef ArchitectureName) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000367 assert(E);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000368 WithColor::error(errs(), ToolName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000369 if (ArchiveName != "")
370 errs() << ArchiveName << "(" << FileName << ")";
371 else
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000372 errs() << "'" << FileName << "'";
Kevin Enderby9acb1092016-05-31 20:35:34 +0000373 if (!ArchitectureName.empty())
374 errs() << " (for architecture " << ArchitectureName << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000375 std::string Buf;
376 raw_string_ostream OS(Buf);
Jonas Devlieghere45eb84f2018-11-11 01:46:03 +0000377 logAllUnhandledErrors(std::move(E), OS);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000378 OS.flush();
Justin Bogner31d8b7d2016-10-26 22:37:52 +0000379 errs() << ": " << Buf;
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000380 exit(1);
381}
382
Fangrui Song523758e2019-04-15 15:31:42 +0000383LLVM_ATTRIBUTE_NORETURN void report_error(Error E, StringRef ArchiveName,
384 const object::Archive::Child &C,
385 StringRef ArchitectureName) {
Kevin Enderbyf4586032016-07-29 17:44:13 +0000386 Expected<StringRef> NameOrErr = C.getName();
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000387 // TODO: if we have a error getting the name then it would be nice to print
388 // the index of which archive member this is and or its offset in the
389 // archive instead of "???" as the name.
Kevin Enderbyf4586032016-07-29 17:44:13 +0000390 if (!NameOrErr) {
391 consumeError(NameOrErr.takeError());
Fangrui Song523758e2019-04-15 15:31:42 +0000392 report_error(std::move(E), ArchiveName, "???", ArchitectureName);
Kevin Enderbyf4586032016-07-29 17:44:13 +0000393 } else
Fangrui Song523758e2019-04-15 15:31:42 +0000394 report_error(std::move(E), ArchiveName, NameOrErr.get(), ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +0000395}
396
Craig Toppere6cb63e2014-04-25 04:24:47 +0000397static const Target *getTarget(const ObjectFile *Obj = nullptr) {
Michael J. Spencer2670c252011-01-20 06:39:06 +0000398 // Figure out the target triple.
Fangrui Song523758e2019-04-15 15:31:42 +0000399 Triple TheTriple("unknown-unknown-unknown");
Michael J. Spencer05350e6d2011-01-20 07:22:04 +0000400 if (TripleName.empty()) {
George Rimar73a27232019-01-15 09:19:18 +0000401 if (Obj)
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000402 TheTriple = Obj->makeTriple();
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000403 } else {
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000404 TheTriple.setTriple(Triple::normalize(TripleName));
Vlad Tsyrklevichde620462017-09-19 02:22:48 +0000405
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000406 // Use the triple, but also try to combine with ARM build attributes.
407 if (Obj) {
408 auto Arch = Obj->getArch();
George Rimar73a27232019-01-15 09:19:18 +0000409 if (Arch == Triple::arm || Arch == Triple::armeb)
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000410 Obj->setARMSubArch(TheTriple);
Sam Parkerdf7c6ef2017-01-18 13:52:12 +0000411 }
412 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000413
414 // Get the target specific parser.
415 std::string Error;
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000416 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
417 Error);
Kevin Enderby7fa40c92016-11-16 22:17:38 +0000418 if (!TheTarget) {
419 if (Obj)
420 report_error(Obj->getFileName(), "can't find target: " + Error);
421 else
422 error("can't find target: " + Error);
423 }
Michael J. Spencer2670c252011-01-20 06:39:06 +0000424
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000425 // Update the triple name and return the found target.
426 TripleName = TheTriple.getTriple();
427 return TheTarget;
Michael J. Spencer2670c252011-01-20 06:39:06 +0000428}
429
Fangrui Song523758e2019-04-15 15:31:42 +0000430bool isRelocAddressLess(RelocationRef A, RelocationRef B) {
George Rimar73a27232019-01-15 09:19:18 +0000431 return A.getOffset() < B.getOffset();
Michael J. Spencer51862b32011-10-13 22:17:18 +0000432}
433
Fangrui Songf67de6c2019-04-08 16:24:08 +0000434static Error getRelocationValueString(const RelocationRef &Rel,
435 SmallVectorImpl<char> &Result) {
Rafael Espindola854038e2015-06-26 14:51:16 +0000436 const ObjectFile *Obj = Rel.getObject();
Rafael Espindola37070a52015-06-03 04:48:06 +0000437 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000438 return getELFRelocationValueString(ELF, Rel, Result);
Rafael Espindola37070a52015-06-03 04:48:06 +0000439 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000440 return getCOFFRelocationValueString(COFF, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000441 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000442 return getWasmRelocationValueString(Wasm, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000443 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
George Rimarc1964882019-01-18 11:33:26 +0000444 return getMachORelocationValueString(MachO, Rel, Result);
Sam Clegg4df5d762017-06-27 20:40:53 +0000445 llvm_unreachable("unknown object file format");
Rafael Espindola37070a52015-06-03 04:48:06 +0000446}
447
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +0000448/// Indicates whether this relocation should hidden when listing
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000449/// relocations, usually because it is the trailing part of a multipart
450/// relocation that will be printed as part of the leading relocation.
451static bool getHidden(RelocationRef RelRef) {
George Rimar73a27232019-01-15 09:19:18 +0000452 auto *MachO = dyn_cast<MachOObjectFile>(RelRef.getObject());
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000453 if (!MachO)
454 return false;
455
456 unsigned Arch = MachO->getArch();
457 DataRefImpl Rel = RelRef.getRawDataRefImpl();
458 uint64_t Type = MachO->getRelocationType(Rel);
459
460 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
461 // is always hidden.
George Rimar73a27232019-01-15 09:19:18 +0000462 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc)
463 return Type == MachO::GENERIC_RELOC_PAIR;
464
465 if (Arch == Triple::x86_64) {
Rafael Espindola0ad71d92015-06-30 03:41:26 +0000466 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
467 // an X86_64_RELOC_SUBTRACTOR.
468 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
469 DataRefImpl RelPrev = Rel;
470 RelPrev.d.a--;
471 uint64_t PrevType = MachO->getRelocationType(RelPrev);
472 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
473 return true;
474 }
475 }
476
477 return false;
478}
479
Sid Manningd9f28732018-05-14 19:46:08 +0000480namespace {
481class SourcePrinter {
482protected:
483 DILineInfo OldLineInfo;
484 const ObjectFile *Obj = nullptr;
485 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
486 // File name to file contents of source
487 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
488 // Mark the line endings of the cached source
489 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
490
491private:
492 bool cacheSource(const DILineInfo& LineInfoFile);
493
494public:
495 SourcePrinter() = default;
496 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
497 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
498 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
499 DefaultArch);
500 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
501 }
502 virtual ~SourcePrinter() = default;
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000503 virtual void printSourceLine(raw_ostream &OS,
504 object::SectionedAddress Address,
Sid Manningd9f28732018-05-14 19:46:08 +0000505 StringRef Delimiter = "; ");
506};
507
508bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
509 std::unique_ptr<MemoryBuffer> Buffer;
510 if (LineInfo.Source) {
511 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
512 } else {
513 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
514 if (!BufferOrError)
515 return false;
516 Buffer = std::move(*BufferOrError);
517 }
518 // Chomp the file to get lines
Fangrui Song47a76622019-04-07 10:16:46 +0000519 const char *BufferStart = Buffer->getBufferStart(),
520 *BufferEnd = Buffer->getBufferEnd();
521 std::vector<StringRef> &Lines = LineCache[LineInfo.FileName];
522 const char *Start = BufferStart;
523 for (const char *I = BufferStart; I != BufferEnd; ++I)
524 if (*I == '\n') {
525 Lines.emplace_back(Start, I - Start - (BufferStart < I && I[-1] == '\r'));
526 Start = I + 1;
Sid Manningd9f28732018-05-14 19:46:08 +0000527 }
Fangrui Song47a76622019-04-07 10:16:46 +0000528 if (Start < BufferEnd)
529 Lines.emplace_back(Start, BufferEnd - Start);
Sid Manningd9f28732018-05-14 19:46:08 +0000530 SourceCache[LineInfo.FileName] = std::move(Buffer);
531 return true;
532}
533
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000534void SourcePrinter::printSourceLine(raw_ostream &OS,
535 object::SectionedAddress Address,
Sid Manningd9f28732018-05-14 19:46:08 +0000536 StringRef Delimiter) {
537 if (!Symbolizer)
538 return;
539 DILineInfo LineInfo = DILineInfo();
Eric Christopher1857edb2019-03-28 01:12:13 +0000540 auto ExpectedLineInfo =
Sid Manningd9f28732018-05-14 19:46:08 +0000541 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
Eric Christopher1857edb2019-03-28 01:12:13 +0000542 if (!ExpectedLineInfo)
543 consumeError(ExpectedLineInfo.takeError());
Sid Manningd9f28732018-05-14 19:46:08 +0000544 else
Eric Christopher1857edb2019-03-28 01:12:13 +0000545 LineInfo = *ExpectedLineInfo;
Sid Manningd9f28732018-05-14 19:46:08 +0000546
547 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
548 LineInfo.Line == 0)
549 return;
550
551 if (PrintLines)
552 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
553 if (PrintSource) {
554 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
555 if (!cacheSource(LineInfo))
556 return;
Fangrui Song47a76622019-04-07 10:16:46 +0000557 auto LineBuffer = LineCache.find(LineInfo.FileName);
558 if (LineBuffer != LineCache.end()) {
559 if (LineInfo.Line > LineBuffer->second.size())
560 return;
561 // Vector begins at 0, line numbers are non-zero
562 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1] << '\n';
Sid Manningd9f28732018-05-14 19:46:08 +0000563 }
564 }
565 OldLineInfo = LineInfo;
566}
567
568static bool isArmElf(const ObjectFile *Obj) {
569 return (Obj->isELF() &&
570 (Obj->getArch() == Triple::aarch64 ||
571 Obj->getArch() == Triple::aarch64_be ||
572 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
573 Obj->getArch() == Triple::thumb ||
574 Obj->getArch() == Triple::thumbeb));
575}
576
George Rimar617adef2019-01-23 13:39:12 +0000577static void printRelocation(const RelocationRef &Rel, uint64_t Address,
578 uint8_t AddrSize) {
579 StringRef Fmt =
580 AddrSize > 4 ? "\t\t%016" PRIx64 ": " : "\t\t\t%08" PRIx64 ": ";
581 SmallString<16> Name;
582 SmallString<32> Val;
583 Rel.getTypeName(Name);
584 error(getRelocationValueString(Rel, Val));
585 outs() << format(Fmt.data(), Address) << Name << "\t" << Val << "\n";
586}
587
Sid Manningd9f28732018-05-14 19:46:08 +0000588class PrettyPrinter {
589public:
590 virtual ~PrettyPrinter() = default;
591 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000592 ArrayRef<uint8_t> Bytes,
593 object::SectionedAddress Address, raw_ostream &OS,
594 StringRef Annot, MCSubtargetInfo const &STI,
595 SourcePrinter *SP,
Sid Manningd9f28732018-05-14 19:46:08 +0000596 std::vector<RelocationRef> *Rels = nullptr) {
597 if (SP && (PrintSource || PrintLines))
598 SP->printSourceLine(OS, Address);
Fangrui Songfa860ff2019-04-16 03:56:55 +0000599
600 {
601 formatted_raw_ostream FOS(OS);
602 if (!NoLeadingAddr)
603 FOS << format("%8" PRIx64 ":", Address.Address);
604 if (!NoShowRawInsn) {
605 FOS << ' ';
606 dumpBytes(Bytes, FOS);
607 }
608 FOS.flush();
609 // The output of printInst starts with a tab. Print some spaces so that
610 // the tab has 1 column and advances to the target tab stop.
611 unsigned TabStop = NoShowRawInsn ? 16 : 40;
612 unsigned Column = FOS.getColumn();
613 FOS.indent(Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8);
614
615 // The dtor calls flush() to ensure the indent comes before printInst().
Sid Manningd9f28732018-05-14 19:46:08 +0000616 }
Fangrui Songfa860ff2019-04-16 03:56:55 +0000617
Sid Manningd9f28732018-05-14 19:46:08 +0000618 if (MI)
619 IP.printInst(MI, OS, "", STI);
620 else
Fangrui Song7d4ad142019-04-10 05:31:21 +0000621 OS << "\t<unknown>";
Sid Manningd9f28732018-05-14 19:46:08 +0000622 }
623};
624PrettyPrinter PrettyPrinterInst;
625class HexagonPrettyPrinter : public PrettyPrinter {
626public:
627 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
628 raw_ostream &OS) {
629 uint32_t opcode =
630 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
631 if (!NoLeadingAddr)
632 OS << format("%8" PRIx64 ":", Address);
633 if (!NoShowRawInsn) {
634 OS << "\t";
635 dumpBytes(Bytes.slice(0, 4), OS);
Fangrui Song7d4ad142019-04-10 05:31:21 +0000636 OS << format("\t%08" PRIx32, opcode);
Sid Manningd9f28732018-05-14 19:46:08 +0000637 }
638 }
639 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000640 object::SectionedAddress Address, raw_ostream &OS,
641 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
Sid Manningd9f28732018-05-14 19:46:08 +0000642 std::vector<RelocationRef> *Rels) override {
643 if (SP && (PrintSource || PrintLines))
644 SP->printSourceLine(OS, Address, "");
645 if (!MI) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000646 printLead(Bytes, Address.Address, OS);
Sid Manningd9f28732018-05-14 19:46:08 +0000647 OS << " <unknown>";
648 return;
649 }
650 std::string Buffer;
651 {
652 raw_string_ostream TempStream(Buffer);
653 IP.printInst(MI, TempStream, "", STI);
654 }
655 StringRef Contents(Buffer);
656 // Split off bundle attributes
657 auto PacketBundle = Contents.rsplit('\n');
658 // Split off first instruction from the rest
659 auto HeadTail = PacketBundle.first.split('\n');
660 auto Preamble = " { ";
661 auto Separator = "";
Sid Manningd9f28732018-05-14 19:46:08 +0000662
663 // Hexagon's packets require relocations to be inline rather than
664 // clustered at the end of the packet.
George Rimar617adef2019-01-23 13:39:12 +0000665 std::vector<RelocationRef>::const_iterator RelCur = Rels->begin();
666 std::vector<RelocationRef>::const_iterator RelEnd = Rels->end();
Sid Manningd9f28732018-05-14 19:46:08 +0000667 auto PrintReloc = [&]() -> void {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000668 while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) {
669 if (RelCur->getOffset() == Address.Address) {
670 printRelocation(*RelCur, Address.Address, 4);
Sid Manningd9f28732018-05-14 19:46:08 +0000671 return;
672 }
George Rimar73a27232019-01-15 09:19:18 +0000673 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +0000674 }
675 };
676
George Rimar73a27232019-01-15 09:19:18 +0000677 while (!HeadTail.first.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +0000678 OS << Separator;
679 Separator = "\n";
680 if (SP && (PrintSource || PrintLines))
681 SP->printSourceLine(OS, Address, "");
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000682 printLead(Bytes, Address.Address, OS);
Sid Manningd9f28732018-05-14 19:46:08 +0000683 OS << Preamble;
684 Preamble = " ";
685 StringRef Inst;
686 auto Duplex = HeadTail.first.split('\v');
George Rimar73a27232019-01-15 09:19:18 +0000687 if (!Duplex.second.empty()) {
Sid Manningd9f28732018-05-14 19:46:08 +0000688 OS << Duplex.first;
689 OS << "; ";
690 Inst = Duplex.second;
691 }
692 else
693 Inst = HeadTail.first;
694 OS << Inst;
695 HeadTail = HeadTail.second.split('\n');
696 if (HeadTail.first.empty())
697 OS << " } " << PacketBundle.second;
698 PrintReloc();
699 Bytes = Bytes.slice(4);
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000700 Address.Address += 4;
Sid Manningd9f28732018-05-14 19:46:08 +0000701 }
702 }
703};
704HexagonPrettyPrinter HexagonPrettyPrinterInst;
705
706class AMDGCNPrettyPrinter : public PrettyPrinter {
707public:
708 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000709 object::SectionedAddress Address, raw_ostream &OS,
710 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
Sid Manningd9f28732018-05-14 19:46:08 +0000711 std::vector<RelocationRef> *Rels) override {
712 if (SP && (PrintSource || PrintLines))
713 SP->printSourceLine(OS, Address);
714
715 typedef support::ulittle32_t U32;
716
717 if (MI) {
718 SmallString<40> InstStr;
719 raw_svector_ostream IS(InstStr);
720
721 IP.printInst(MI, IS, "", STI);
722
723 OS << left_justify(IS.str(), 60);
724 } else {
725 // an unrecognized encoding - this is probably data so represent it
726 // using the .long directive, or .byte directive if fewer than 4 bytes
727 // remaining
728 if (Bytes.size() >= 4) {
729 OS << format("\t.long 0x%08" PRIx32 " ",
730 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
731 OS.indent(42);
732 } else {
733 OS << format("\t.byte 0x%02" PRIx8, Bytes[0]);
734 for (unsigned int i = 1; i < Bytes.size(); i++)
735 OS << format(", 0x%02" PRIx8, Bytes[i]);
736 OS.indent(55 - (6 * Bytes.size()));
737 }
738 }
739
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000740 OS << format("// %012" PRIX64 ": ", Address.Address);
Sid Manningd9f28732018-05-14 19:46:08 +0000741 if (Bytes.size() >=4) {
742 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
743 Bytes.size() / sizeof(U32)))
744 // D should be explicitly casted to uint32_t here as it is passed
745 // by format to snprintf as vararg.
746 OS << format("%08" PRIX32 " ", static_cast<uint32_t>(D));
747 } else {
748 for (unsigned int i = 0; i < Bytes.size(); i++)
749 OS << format("%02" PRIX8 " ", Bytes[i]);
750 }
751
752 if (!Annot.empty())
753 OS << "// " << Annot;
754 }
755};
756AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
757
758class BPFPrettyPrinter : public PrettyPrinter {
759public:
760 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000761 object::SectionedAddress Address, raw_ostream &OS,
762 StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP,
Sid Manningd9f28732018-05-14 19:46:08 +0000763 std::vector<RelocationRef> *Rels) override {
764 if (SP && (PrintSource || PrintLines))
765 SP->printSourceLine(OS, Address);
766 if (!NoLeadingAddr)
Alexey Lapshin77fc1f62019-02-27 13:17:36 +0000767 OS << format("%8" PRId64 ":", Address.Address / 8);
Sid Manningd9f28732018-05-14 19:46:08 +0000768 if (!NoShowRawInsn) {
769 OS << "\t";
770 dumpBytes(Bytes, OS);
771 }
772 if (MI)
773 IP.printInst(MI, OS, "", STI);
774 else
Fangrui Song7d4ad142019-04-10 05:31:21 +0000775 OS << "\t<unknown>";
Sid Manningd9f28732018-05-14 19:46:08 +0000776 }
777};
778BPFPrettyPrinter BPFPrettyPrinterInst;
779
780PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
781 switch(Triple.getArch()) {
782 default:
783 return PrettyPrinterInst;
784 case Triple::hexagon:
785 return HexagonPrettyPrinterInst;
786 case Triple::amdgcn:
787 return AMDGCNPrettyPrinterInst;
788 case Triple::bpfel:
789 case Triple::bpfeb:
790 return BPFPrettyPrinterInst;
791 }
792}
793}
794
Sam Koltonc05d7782016-08-17 10:17:57 +0000795static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
796 assert(Obj->isELF());
797 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
798 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
799 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
800 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
801 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
802 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
803 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
804 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
805 llvm_unreachable("Unsupported binary format");
806}
807
Sam Parker5fba45a2017-02-08 09:44:18 +0000808template <class ELFT> static void
809addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
810 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
811 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
812 uint8_t SymbolType = Symbol.getELFType();
813 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
814 continue;
815
Fangrui Songe7834bd2019-04-07 08:19:55 +0000816 uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj->getFileName());
817 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
818 if (Name.empty())
Sam Parker5fba45a2017-02-08 09:44:18 +0000819 continue;
820
Fangrui Songe7834bd2019-04-07 08:19:55 +0000821 section_iterator SecI =
822 unwrapOrError(Symbol.getSection(), Obj->getFileName());
Sam Parker5fba45a2017-02-08 09:44:18 +0000823 if (SecI == Obj->section_end())
824 continue;
825
Fangrui Songe7834bd2019-04-07 08:19:55 +0000826 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
Sam Parker5fba45a2017-02-08 09:44:18 +0000827 }
828}
829
830static void
831addDynamicElfSymbols(const ObjectFile *Obj,
832 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
833 assert(Obj->isELF());
834 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
835 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
836 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
837 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
838 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
839 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
840 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
841 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
842 else
843 llvm_unreachable("Unsupported binary format");
844}
845
Joel Galenson134cf472018-08-24 15:21:57 +0000846static void addPltEntries(const ObjectFile *Obj,
847 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
848 StringSaver &Saver) {
849 Optional<SectionRef> Plt = None;
850 for (const SectionRef &Section : Obj->sections()) {
851 StringRef Name;
852 if (Section.getName(Name))
853 continue;
854 if (Name == ".plt")
855 Plt = Section;
856 }
857 if (!Plt)
858 return;
859 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
860 for (auto PltEntry : ElfObj->getPltAddresses()) {
861 SymbolRef Symbol(PltEntry.first, ElfObj);
Joel Galenson134cf472018-08-24 15:21:57 +0000862 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
863
Fangrui Songe7834bd2019-04-07 08:19:55 +0000864 StringRef Name = unwrapOrError(Symbol.getName(), Obj->getFileName());
865 if (!Name.empty())
866 AllSymbols[*Plt].emplace_back(
867 PltEntry.second, Saver.save((Name + "@plt").str()), SymbolType);
Joel Galenson134cf472018-08-24 15:21:57 +0000868 }
869 }
870}
871
George Rimar70d197d2019-01-10 14:55:26 +0000872// Normally the disassembly output will skip blocks of zeroes. This function
873// returns the number of zero bytes that can be skipped when dumping the
874// disassembly of the instructions in Buf.
875static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) {
George Rimar70d197d2019-01-10 14:55:26 +0000876 // Find the number of leading zeroes.
877 size_t N = 0;
878 while (N < Buf.size() && !Buf[N])
879 ++N;
880
881 // We may want to skip blocks of zero bytes, but unless we see
882 // at least 8 of them in a row.
883 if (N < 8)
884 return 0;
885
886 // We skip zeroes in multiples of 4 because do not want to truncate an
887 // instruction if it starts with a zero byte.
888 return N & ~0x3;
889}
890
George Rimar121fcd72019-01-22 14:09:37 +0000891// Returns a map from sections to their relocations.
892static std::map<SectionRef, std::vector<RelocationRef>>
Fangrui Song523758e2019-04-15 15:31:42 +0000893getRelocsMap(object::ObjectFile const &Obj) {
George Rimar121fcd72019-01-22 14:09:37 +0000894 std::map<SectionRef, std::vector<RelocationRef>> Ret;
895 for (const SectionRef &Section : ToolSectionFilter(Obj)) {
896 section_iterator RelSec = Section.getRelocatedSection();
897 if (RelSec == Obj.section_end())
898 continue;
899 std::vector<RelocationRef> &V = Ret[*RelSec];
900 for (const RelocationRef &R : Section.relocations())
901 V.push_back(R);
902 // Sort relocations by address.
903 llvm::sort(V, isRelocAddressLess);
904 }
905 return Ret;
906}
907
George Rimar4c3b2972019-01-28 10:44:01 +0000908// Used for --adjust-vma to check if address should be adjusted by the
909// specified value for a given section.
910// For ELF we do not adjust non-allocatable sections like debug ones,
911// because they are not loadable.
912// TODO: implement for other file formats.
913static bool shouldAdjustVA(const SectionRef &Section) {
914 const ObjectFile *Obj = Section.getObject();
915 if (isa<object::ELFObjectFileBase>(Obj))
916 return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC;
917 return false;
918}
919
Fangrui Song32087b62019-04-07 16:33:24 +0000920static uint64_t
921dumpARMELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
922 const ObjectFile *Obj, ArrayRef<uint8_t> Bytes,
923 const std::vector<uint64_t> &TextMappingSymsAddr) {
924 support::endianness Endian =
925 Obj->isLittleEndian() ? support::little : support::big;
926 while (Index < End) {
927 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
928 outs() << "\t";
929 if (Index + 4 <= End) {
930 dumpBytes(Bytes.slice(Index, 4), outs());
931 outs() << "\t.word\t"
932 << format_hex(
933 support::endian::read32(Bytes.data() + Index, Endian), 10);
934 Index += 4;
935 } else if (Index + 2 <= End) {
936 dumpBytes(Bytes.slice(Index, 2), outs());
937 outs() << "\t\t.short\t"
938 << format_hex(
939 support::endian::read16(Bytes.data() + Index, Endian), 6);
940 Index += 2;
941 } else {
942 dumpBytes(Bytes.slice(Index, 1), outs());
943 outs() << "\t\t.byte\t" << format_hex(Bytes[0], 4);
944 ++Index;
945 }
946 outs() << "\n";
947 if (std::binary_search(TextMappingSymsAddr.begin(),
948 TextMappingSymsAddr.end(), Index))
949 break;
950 }
951 return Index;
952}
953
954static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End,
955 ArrayRef<uint8_t> Bytes) {
956 // print out data up to 8 bytes at a time in hex and ascii
957 uint8_t AsciiData[9] = {'\0'};
958 uint8_t Byte;
959 int NumBytes = 0;
960
961 for (; Index < End; ++Index) {
962 if (NumBytes == 0) {
963 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
964 outs() << "\t";
965 }
966 Byte = Bytes.slice(Index)[0];
967 outs() << format(" %02x", Byte);
968 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
969
970 uint8_t IndentOffset = 0;
971 NumBytes++;
972 if (Index == End - 1 || NumBytes > 8) {
973 // Indent the space for less than 8 bytes data.
974 // 2 spaces for byte and one for space between bytes
975 IndentOffset = 3 * (8 - NumBytes);
976 for (int Excess = NumBytes; Excess < 8; Excess++)
977 AsciiData[Excess] = '\0';
978 NumBytes = 8;
979 }
980 if (NumBytes == 8) {
981 AsciiData[8] = '\0';
982 outs() << std::string(IndentOffset, ' ') << " ";
983 outs() << reinterpret_cast<char *>(AsciiData);
984 outs() << '\n';
985 NumBytes = 0;
986 }
987 }
988}
989
George Rimarbcbe98b2019-01-23 10:33:26 +0000990static void disassembleObject(const Target *TheTarget, const ObjectFile *Obj,
991 MCContext &Ctx, MCDisassembler *DisAsm,
992 const MCInstrAnalysis *MIA, MCInstPrinter *IP,
993 const MCSubtargetInfo *STI, PrettyPrinter &PIP,
994 SourcePrinter &SP, bool InlineRelocs) {
George Rimar121fcd72019-01-22 14:09:37 +0000995 std::map<SectionRef, std::vector<RelocationRef>> RelocMap;
996 if (InlineRelocs)
997 RelocMap = getRelocsMap(*Obj);
Mark Seaborn0929d3d2014-01-25 17:38:19 +0000998
David Majnemer81afca62015-07-07 22:06:59 +0000999 // Create a mapping from virtual address to symbol name. This is used to
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001000 // pretty print the symbols while disassembling.
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001001 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001002 SectionSymbolsTy AbsoluteSymbols;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001003 const StringRef FileName = Obj->getFileName();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001004 for (const SymbolRef &Symbol : Obj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001005 uint64_t Address = unwrapOrError(Symbol.getAddress(), FileName);
David Majnemer2603a8fa2015-07-09 18:11:40 +00001006
Fangrui Songe7834bd2019-04-07 08:19:55 +00001007 StringRef Name = unwrapOrError(Symbol.getName(), FileName);
1008 if (Name.empty())
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001009 continue;
David Majnemer81afca62015-07-07 22:06:59 +00001010
Sam Koltonc05d7782016-08-17 10:17:57 +00001011 uint8_t SymbolType = ELF::STT_NOTYPE;
Matt Davis82937e42019-01-31 19:42:21 +00001012 if (Obj->isELF()) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001013 SymbolType = getElfSymbolType(Obj, Symbol);
Matt Davis82937e42019-01-31 19:42:21 +00001014 if (SymbolType == ELF::STT_SECTION)
1015 continue;
1016 }
David Majnemer81afca62015-07-07 22:06:59 +00001017
Fangrui Songe7834bd2019-04-07 08:19:55 +00001018 section_iterator SecI = unwrapOrError(Symbol.getSection(), FileName);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001019 if (SecI != Obj->section_end())
Fangrui Songe7834bd2019-04-07 08:19:55 +00001020 AllSymbols[*SecI].emplace_back(Address, Name, SymbolType);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001021 else
Fangrui Songe7834bd2019-04-07 08:19:55 +00001022 AbsoluteSymbols.emplace_back(Address, Name, SymbolType);
David Majnemer81afca62015-07-07 22:06:59 +00001023 }
Sam Parker5fba45a2017-02-08 09:44:18 +00001024 if (AllSymbols.empty() && Obj->isELF())
1025 addDynamicElfSymbols(Obj, AllSymbols);
David Majnemer81afca62015-07-07 22:06:59 +00001026
Joel Galenson134cf472018-08-24 15:21:57 +00001027 BumpPtrAllocator A;
1028 StringSaver Saver(A);
1029 addPltEntries(Obj, AllSymbols, Saver);
1030
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001031 // Create a mapping from virtual address to section.
1032 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1033 for (SectionRef Sec : Obj->sections())
1034 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1035 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1036
1037 // Linked executables (.exe and .dll files) typically don't include a real
1038 // symbol table but they might contain an export table.
1039 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1040 for (const auto &ExportEntry : COFFObj->export_directories()) {
1041 StringRef Name;
1042 error(ExportEntry.getSymbolName(Name));
1043 if (Name.empty())
1044 continue;
1045 uint32_t RVA;
1046 error(ExportEntry.getExportRVA(RVA));
1047
1048 uint64_t VA = COFFObj->getImageBase() + RVA;
Fangrui Songc82e92b2019-04-17 07:58:05 +00001049 auto Sec = llvm::bsearch(
1050 SectionAddresses, [VA](const std::pair<uint64_t, SectionRef> &RHS) {
1051 return VA < RHS.first;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001052 });
Fangrui Song545ed222019-04-07 05:32:16 +00001053 if (Sec != SectionAddresses.begin()) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001054 --Sec;
Sam Koltonc05d7782016-08-17 10:17:57 +00001055 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
Fangrui Song545ed222019-04-07 05:32:16 +00001056 } else
Sterling Augustinebc78b622018-06-28 18:57:13 +00001057 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001058 }
1059 }
1060
1061 // Sort all the symbols, this allows us to use a simple binary search to find
1062 // a symbol near an address.
1063 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1064 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
Sterling Augustinebc78b622018-06-28 18:57:13 +00001065 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001066
Colin LeMahieu77804be2015-07-29 15:45:39 +00001067 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Colin LeMahieuf34933e2015-07-23 20:58:49 +00001068 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
Mark Seaborneb03ac52014-01-25 00:32:01 +00001069 continue;
Michael J. Spencer1d6167f2011-06-25 17:55:23 +00001070
Rafael Espindola80291272014-10-08 15:28:58 +00001071 uint64_t SectionAddr = Section.getAddress();
1072 uint64_t SectSize = Section.getSize();
David Majnemer185b5b12014-11-11 09:58:25 +00001073 if (!SectSize)
1074 continue;
Simon Atanasyan2b614e12014-02-24 22:12:11 +00001075
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001076 // Get the list of all the symbols in this section.
1077 SectionSymbolsTy &Symbols = AllSymbols[Section];
Davide Italianof0706882015-10-01 21:57:09 +00001078 std::vector<uint64_t> DataMappingSymsAddr;
1079 std::vector<uint64_t> TextMappingSymsAddr;
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001080 if (isArmElf(Obj)) {
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001081 for (const auto &Symb : Symbols) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001082 uint64_t Address = std::get<0>(Symb);
1083 StringRef Name = std::get<1>(Symb);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001084 if (Name.startswith("$d"))
David Majnemer153722d2015-11-18 04:35:32 +00001085 DataMappingSymsAddr.push_back(Address - SectionAddr);
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001086 if (Name.startswith("$x"))
David Majnemer153722d2015-11-18 04:35:32 +00001087 TextMappingSymsAddr.push_back(Address - SectionAddr);
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001088 if (Name.startswith("$a"))
1089 TextMappingSymsAddr.push_back(Address - SectionAddr);
1090 if (Name.startswith("$t"))
1091 TextMappingSymsAddr.push_back(Address - SectionAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001092 }
1093 }
1094
Fangrui Song0cac7262018-09-27 02:13:45 +00001095 llvm::sort(DataMappingSymsAddr);
1096 llvm::sort(TextMappingSymsAddr);
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001097
Sam Kolton3381d7a2016-10-06 13:46:08 +00001098 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1099 // AMDGPU disassembler uses symbolizer for printing labels
1100 std::unique_ptr<MCRelocationInfo> RelInfo(
1101 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1102 if (RelInfo) {
1103 std::unique_ptr<MCSymbolizer> Symbolizer(
1104 TheTarget->createMCSymbolizer(
1105 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1106 DisAsm->setSymbolizer(std::move(Symbolizer));
1107 }
1108 }
1109
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001110 StringRef SegmentName = "";
Mark Seaborneb03ac52014-01-25 00:32:01 +00001111 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001112 DataRefImpl DR = Section.getRawDataRefImpl();
Rafael Espindola56f976f2013-04-18 18:08:55 +00001113 SegmentName = MachO->getSectionFinalSegmentName(DR);
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001114 }
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001115 StringRef SectionName;
1116 error(Section.getName(SectionName));
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001117
Rafael Espindola7884c952015-06-04 15:01:05 +00001118 // If the section has no symbol at the start, just insert a dummy one.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001119 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001120 Symbols.insert(
1121 Symbols.begin(),
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001122 std::make_tuple(SectionAddr, SectionName,
1123 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
Sam Koltonc05d7782016-08-17 10:17:57 +00001124 }
Alp Tokere69170a2014-06-26 22:52:05 +00001125
1126 SmallString<40> Comments;
1127 raw_svector_ostream CommentStream(Comments);
Ahmed Bougachaad1084d2013-05-24 00:39:57 +00001128
Fangrui Songa076ec52019-05-16 11:33:48 +00001129 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(
1130 unwrapOrError(Section.getContents(), Obj->getFileName()));
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001131
George Rimar4c3b2972019-01-28 10:44:01 +00001132 uint64_t VMAAdjustment = 0;
1133 if (shouldAdjustVA(Section))
1134 VMAAdjustment = AdjustVMA;
1135
Michael J. Spencer2670c252011-01-20 06:39:06 +00001136 uint64_t Size;
1137 uint64_t Index;
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001138 bool PrintedSection = false;
George Rimar121fcd72019-01-22 14:09:37 +00001139 std::vector<RelocationRef> Rels = RelocMap[Section];
George Rimar73a27232019-01-15 09:19:18 +00001140 std::vector<RelocationRef>::const_iterator RelCur = Rels.begin();
1141 std::vector<RelocationRef>::const_iterator RelEnd = Rels.end();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001142 // Disassemble symbol by symbol.
George Rimar73a27232019-01-15 09:19:18 +00001143 for (unsigned SI = 0, SE = Symbols.size(); SI != SE; ++SI) {
Fangrui Song8f28f7a2019-04-20 02:10:48 +00001144 // Skip if --disassemble-functions is not empty and the symbol is not in
1145 // the list.
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001146 if (!DisasmFuncsSet.empty() &&
1147 !DisasmFuncsSet.count(std::get<1>(Symbols[SI])))
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001148 continue;
1149
Fangrui Song8f28f7a2019-04-20 02:10:48 +00001150 uint64_t Start = std::get<0>(Symbols[SI]);
Fangrui Songce12ea82019-04-20 07:19:24 +00001151 if (Start < SectionAddr || StopAddress <= Start)
1152 continue;
Fangrui Song8f28f7a2019-04-20 02:10:48 +00001153
1154 // The end is the section end, the beginning of the next symbol, or
1155 // --stop-address.
Fangrui Songb48e41b2019-04-20 07:48:41 +00001156 uint64_t End = std::min<uint64_t>(SectionAddr + SectSize, StopAddress);
1157 if (SI + 1 < SE)
1158 End = std::min(End, std::get<0>(Symbols[SI + 1]));
Fangrui Songce12ea82019-04-20 07:19:24 +00001159 if (Start >= End || End <= StartAddress)
Fangrui Song8f28f7a2019-04-20 02:10:48 +00001160 continue;
1161 Start -= SectionAddr;
1162 End -= SectionAddr;
1163
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001164 if (!PrintedSection) {
1165 PrintedSection = true;
Fangrui Song5387c2c2019-05-01 10:40:48 +00001166 outs() << "\nDisassembly of section ";
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001167 if (!SegmentName.empty())
1168 outs() << SegmentName << ",";
Fangrui Song5387c2c2019-05-01 10:40:48 +00001169 outs() << SectionName << ":\n";
Rafael Aulerb0e4b912018-03-09 19:13:44 +00001170 }
1171
Valery Pykhtinde048052016-04-07 07:24:01 +00001172 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001173 if (std::get<2>(Symbols[SI]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001174 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1175 Start += 256;
1176 }
George Rimar73a27232019-01-15 09:19:18 +00001177 if (SI == SE - 1 ||
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001178 std::get<2>(Symbols[SI + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
Sam Koltonc05d7782016-08-17 10:17:57 +00001179 // cut trailing zeroes at the end of kernel
1180 // cut up to 256 bytes
1181 const uint64_t EndAlign = 256;
1182 const auto Limit = End - (std::min)(EndAlign, End - Start);
1183 while (End > Limit &&
1184 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1185 End -= 4;
1186 }
Valery Pykhtinde048052016-04-07 07:24:01 +00001187 }
1188
George Rimar6622d412018-12-19 10:21:45 +00001189 outs() << '\n';
George Rimar3ba0f3c02019-01-09 14:43:33 +00001190 if (!NoLeadingAddr)
George Rimar4c3b2972019-01-28 10:44:01 +00001191 outs() << format("%016" PRIx64 " ",
1192 SectionAddr + Start + VMAAdjustment);
George Rimar3ba0f3c02019-01-09 14:43:33 +00001193
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001194 StringRef SymbolName = std::get<1>(Symbols[SI]);
George Rimar6622d412018-12-19 10:21:45 +00001195 if (Demangle)
1196 outs() << demangle(SymbolName) << ":\n";
1197 else
1198 outs() << SymbolName << ":\n";
Michael J. Spencer2670c252011-01-20 06:39:06 +00001199
Francis Visoiu Mistrih18346822018-04-19 17:02:57 +00001200 // Don't print raw contents of a virtual section. A virtual section
1201 // doesn't have any contents in the file.
1202 if (Section.isVirtual()) {
1203 outs() << "...\n";
1204 continue;
1205 }
1206
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001207#ifndef NDEBUG
Mark Seaborneb03ac52014-01-25 00:32:01 +00001208 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001209#else
Mark Seaborneb03ac52014-01-25 00:32:01 +00001210 raw_ostream &DebugOut = nulls();
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001211#endif
1212
Wouter van Oortmerssenf3b762a2019-01-17 18:14:09 +00001213 // Some targets (like WebAssembly) have a special prelude at the start
1214 // of each symbol.
1215 DisAsm->onSymbolStart(SymbolName, Size, Bytes.slice(Start, End - Start),
1216 SectionAddr + Start, DebugOut, CommentStream);
1217 Start += Size;
1218
Fangrui Song32087b62019-04-07 16:33:24 +00001219 Index = Start;
1220 if (SectionAddr < StartAddress)
1221 Index = std::max<uint64_t>(Index, StartAddress - SectionAddr);
Owen Andersona0c3b972011-09-15 23:38:46 +00001222
Fangrui Song32087b62019-04-07 16:33:24 +00001223 // If there is a data symbol inside an ELF text section and we are
1224 // only disassembling text (applicable all architectures), we are in a
1225 // situation where we must print the data and not disassemble it.
1226 if (Obj->isELF() && std::get<2>(Symbols[SI]) == ELF::STT_OBJECT &&
1227 !DisassembleAll && Section.isText()) {
1228 dumpELFData(SectionAddr, Index, End, Bytes);
1229 Index = End;
1230 }
1231
1232 bool CheckARMELFData = isArmElf(Obj) &&
1233 std::get<2>(Symbols[SI]) != ELF::STT_OBJECT &&
1234 !DisassembleAll;
Fangrui Song32087b62019-04-07 16:33:24 +00001235 while (Index < End) {
1236 // AArch64 ELF binaries can interleave data and text in the same
1237 // section. We rely on the markers introduced to understand what we
1238 // need to dump. If the data marker is within a function, it is
1239 // denoted as a word/short etc.
1240 if (CheckARMELFData &&
Fangrui Song545ed222019-04-07 05:32:16 +00001241 std::binary_search(DataMappingSymsAddr.begin(),
1242 DataMappingSymsAddr.end(), Index)) {
Fangrui Song32087b62019-04-07 16:33:24 +00001243 Index = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes,
1244 TextMappingSymsAddr);
1245 continue;
Davide Italianof0706882015-10-01 21:57:09 +00001246 }
1247
Fangrui Song32087b62019-04-07 16:33:24 +00001248 // When -z or --disassemble-zeroes are given we always dissasemble
1249 // them. Otherwise we might want to skip zero bytes we see.
George Rimarc5f29202019-02-19 12:38:36 +00001250 if (!DisassembleZeroes) {
1251 uint64_t MaxOffset = End - Index;
1252 // For -reloc: print zero blocks patched by relocations, so that
1253 // relocations can be shown in the dump.
1254 if (RelCur != RelEnd)
1255 MaxOffset = RelCur->getOffset() - Index;
1256
1257 if (size_t N =
1258 countSkippableZeroBytes(Bytes.slice(Index, MaxOffset))) {
1259 outs() << "\t\t..." << '\n';
1260 Index += N;
Fangrui Song32087b62019-04-07 16:33:24 +00001261 continue;
George Rimarc5f29202019-02-19 12:38:36 +00001262 }
George Rimar70d197d2019-01-10 14:55:26 +00001263 }
1264
Hemant Kulkarni5b60f632016-08-25 19:41:08 +00001265 // Disassemble a real instruction or a data when disassemble all is
1266 // provided
Fangrui Song996b9092019-04-08 01:22:38 +00001267 MCInst Inst;
Fangrui Song32087b62019-04-07 16:33:24 +00001268 bool Disassembled = DisAsm->getInstruction(
1269 Inst, Size, Bytes.slice(Index), SectionAddr + Index, DebugOut,
1270 CommentStream);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001271 if (Size == 0)
1272 Size = 1;
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00001273
Fangrui Song32087b62019-04-07 16:33:24 +00001274 PIP.printInst(
1275 *IP, Disassembled ? &Inst : nullptr, Bytes.slice(Index, Size),
1276 {SectionAddr + Index + VMAAdjustment, Section.getIndex()}, outs(),
1277 "", *STI, &SP, &Rels);
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001278 outs() << CommentStream.str();
1279 Comments.clear();
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001280
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001281 // Try to resolve the target of a call, tail call, etc. to a specific
1282 // symbol.
1283 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1284 MIA->isConditionalBranch(Inst))) {
1285 uint64_t Target;
1286 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1287 // In a relocatable object, the target's section must reside in
1288 // the same section as the call instruction or it is accessed
1289 // through a relocation.
1290 //
1291 // In a non-relocatable object, the target may be in any section.
1292 //
1293 // N.B. We don't walk the relocations in the relocatable case yet.
1294 auto *TargetSectionSymbols = &Symbols;
1295 if (!Obj->isRelocatableObject()) {
Fangrui Songc82e92b2019-04-17 07:58:05 +00001296 auto It = llvm::bsearch(
1297 SectionAddresses,
1298 [=](const std::pair<uint64_t, SectionRef> &RHS) {
1299 return Target < RHS.first;
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001300 });
Fangrui Songc82e92b2019-04-17 07:58:05 +00001301 if (It != SectionAddresses.begin()) {
1302 --It;
1303 TargetSectionSymbols = &AllSymbols[It->second];
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001304 } else {
Sterling Augustinebc78b622018-06-28 18:57:13 +00001305 TargetSectionSymbols = &AbsoluteSymbols;
David Majnemerfbb1c3a2015-11-18 02:49:19 +00001306 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001307 }
David Majnemer2603a8fa2015-07-09 18:11:40 +00001308
Fangrui Songc82e92b2019-04-17 07:58:05 +00001309 // Find the last symbol in the section whose offset is less than
Sterling Augustinebc78b622018-06-28 18:57:13 +00001310 // or equal to the target. If there isn't a section that contains
1311 // the target, find the nearest preceding absolute symbol.
Fangrui Songc82e92b2019-04-17 07:58:05 +00001312 auto TargetSym = llvm::bsearch(
1313 *TargetSectionSymbols,
1314 [=](const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1315 return Target < std::get<0>(RHS);
Sterling Augustinebc78b622018-06-28 18:57:13 +00001316 });
1317 if (TargetSym == TargetSectionSymbols->begin()) {
1318 TargetSectionSymbols = &AbsoluteSymbols;
Fangrui Songc82e92b2019-04-17 07:58:05 +00001319 TargetSym = llvm::bsearch(
1320 AbsoluteSymbols,
1321 [=](const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1322 return Target < std::get<0>(RHS);
Fangrui Song545ed222019-04-07 05:32:16 +00001323 });
Sterling Augustinebc78b622018-06-28 18:57:13 +00001324 }
1325 if (TargetSym != TargetSectionSymbols->begin()) {
1326 --TargetSym;
Clement Courbetd1a3bd42019-01-18 15:26:14 +00001327 uint64_t TargetAddress = std::get<0>(*TargetSym);
1328 StringRef TargetName = std::get<1>(*TargetSym);
1329 outs() << " <" << TargetName;
1330 uint64_t Disp = Target - TargetAddress;
Sterling Augustinebc78b622018-06-28 18:57:13 +00001331 if (Disp)
1332 outs() << "+0x" << Twine::utohexstr(Disp);
1333 outs() << '>';
David Majnemer81afca62015-07-07 22:06:59 +00001334 }
1335 }
Benjamin Kramere0dda9c2011-07-15 18:39:24 +00001336 }
Colin LeMahieu307a83d2016-03-18 16:26:48 +00001337 outs() << "\n";
Michael J. Spencer51862b32011-10-13 22:17:18 +00001338
Sid Manningd9f28732018-05-14 19:46:08 +00001339 // Hexagon does this in pretty printer
George Rimarfd383e72019-01-23 10:52:38 +00001340 if (Obj->getArch() != Triple::hexagon) {
Sid Manningd9f28732018-05-14 19:46:08 +00001341 // Print relocation for instruction.
George Rimar73a27232019-01-15 09:19:18 +00001342 while (RelCur != RelEnd) {
George Rimar617adef2019-01-23 13:39:12 +00001343 uint64_t Offset = RelCur->getOffset();
Sid Manningd9f28732018-05-14 19:46:08 +00001344 // If this relocation is hidden, skip it.
Fangrui Song32087b62019-04-07 16:33:24 +00001345 if (getHidden(*RelCur) || SectionAddr + Offset < StartAddress) {
George Rimar73a27232019-01-15 09:19:18 +00001346 ++RelCur;
Sid Manningd9f28732018-05-14 19:46:08 +00001347 continue;
1348 }
1349
George Rimar740974d2019-01-28 10:48:54 +00001350 // Stop when RelCur's offset is past the current instruction.
George Rimar617adef2019-01-23 13:39:12 +00001351 if (Offset >= Index + Size)
George Rimar73a27232019-01-15 09:19:18 +00001352 break;
George Rimar617adef2019-01-23 13:39:12 +00001353
George Rimar4c3b2972019-01-28 10:44:01 +00001354 // When --adjust-vma is used, update the address printed.
1355 if (RelCur->getSymbol() != Obj->symbol_end()) {
1356 Expected<section_iterator> SymSI =
1357 RelCur->getSymbol()->getSection();
1358 if (SymSI && *SymSI != Obj->section_end() &&
Fangrui Song32087b62019-04-07 16:33:24 +00001359 shouldAdjustVA(**SymSI))
George Rimar4c3b2972019-01-28 10:44:01 +00001360 Offset += AdjustVMA;
1361 }
1362
George Rimar617adef2019-01-23 13:39:12 +00001363 printRelocation(*RelCur, SectionAddr + Offset,
1364 Obj->getBytesInAddress());
George Rimar73a27232019-01-15 09:19:18 +00001365 ++RelCur;
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001366 }
George Rimarfd383e72019-01-23 10:52:38 +00001367 }
Fangrui Song32087b62019-04-07 16:33:24 +00001368
1369 Index += Size;
Benjamin Kramer87ee76c2011-07-20 19:37:35 +00001370 }
Michael J. Spencer2670c252011-01-20 06:39:06 +00001371 }
1372 }
1373}
1374
George Rimarbcbe98b2019-01-23 10:33:26 +00001375static void disassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1376 if (StartAddress > StopAddress)
1377 error("Start address should be less than stop address");
1378
1379 const Target *TheTarget = getTarget(Obj);
1380
1381 // Package up features to be passed to target/subtarget
1382 SubtargetFeatures Features = Obj->getFeatures();
1383 if (!MAttrs.empty())
1384 for (unsigned I = 0; I != MAttrs.size(); ++I)
1385 Features.AddFeature(MAttrs[I]);
1386
1387 std::unique_ptr<const MCRegisterInfo> MRI(
1388 TheTarget->createMCRegInfo(TripleName));
1389 if (!MRI)
1390 report_error(Obj->getFileName(),
1391 "no register info for target " + TripleName);
1392
1393 // Set up disassembler.
1394 std::unique_ptr<const MCAsmInfo> AsmInfo(
1395 TheTarget->createMCAsmInfo(*MRI, TripleName));
1396 if (!AsmInfo)
1397 report_error(Obj->getFileName(),
1398 "no assembly info for target " + TripleName);
1399 std::unique_ptr<const MCSubtargetInfo> STI(
1400 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1401 if (!STI)
1402 report_error(Obj->getFileName(),
1403 "no subtarget info for target " + TripleName);
1404 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1405 if (!MII)
1406 report_error(Obj->getFileName(),
1407 "no instruction info for target " + TripleName);
1408 MCObjectFileInfo MOFI;
1409 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1410 // FIXME: for now initialize MCObjectFileInfo with default values
1411 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1412
1413 std::unique_ptr<MCDisassembler> DisAsm(
1414 TheTarget->createMCDisassembler(*STI, Ctx));
1415 if (!DisAsm)
1416 report_error(Obj->getFileName(),
1417 "no disassembler for target " + TripleName);
1418
1419 std::unique_ptr<const MCInstrAnalysis> MIA(
1420 TheTarget->createMCInstrAnalysis(MII.get()));
1421
1422 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1423 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1424 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1425 if (!IP)
1426 report_error(Obj->getFileName(),
1427 "no instruction printer for target " + TripleName);
1428 IP->setPrintImmHex(PrintImmHex);
1429
1430 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1431 SourcePrinter SP(Obj, TheTarget->getName());
1432
Igor Kudrin2d3faad2019-02-26 12:15:14 +00001433 for (StringRef Opt : DisassemblerOptions)
1434 if (!IP->applyTargetSpecificCLOption(Opt))
1435 error("Unrecognized disassembler option: " + Opt);
1436
George Rimarbcbe98b2019-01-23 10:33:26 +00001437 disassembleObject(TheTarget, Obj, Ctx, DisAsm.get(), MIA.get(), IP.get(),
1438 STI.get(), PIP, SP, InlineRelocs);
1439}
1440
Fangrui Song523758e2019-04-15 15:31:42 +00001441void printRelocations(const ObjectFile *Obj) {
Greg Fitzgerald18432272014-03-20 22:55:15 +00001442 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
1443 "%08" PRIx64;
Rafael Espindola9219fe72016-03-21 20:59:15 +00001444 // Regular objdump doesn't print relocations in non-relocatable object
1445 // files.
1446 if (!Obj->isRelocatableObject())
1447 return;
Rafael Espindolac66d7612014-08-17 19:09:37 +00001448
George Rimar5c922f62019-05-07 13:14:18 +00001449 // Build a mapping from relocation target to a vector of relocation
1450 // sections. Usually, there is an only one relocation section for
1451 // each relocated section.
1452 MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001453 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Alexey Samsonov48803e52014-03-13 14:37:36 +00001454 if (Section.relocation_begin() == Section.relocation_end())
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001455 continue;
George Rimar5c922f62019-05-07 13:14:18 +00001456 const SectionRef TargetSec = *Section.getRelocatedSection();
1457 SecToRelSec[TargetSec].push_back(Section);
1458 }
1459
1460 for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) {
George Rimar73a27232019-01-15 09:19:18 +00001461 StringRef SecName;
George Rimar5c922f62019-05-07 13:14:18 +00001462 error(P.first.getName(SecName));
George Rimar73a27232019-01-15 09:19:18 +00001463 outs() << "RELOCATION RECORDS FOR [" << SecName << "]:\n";
George Rimar5c922f62019-05-07 13:14:18 +00001464
1465 for (SectionRef Section : P.second) {
1466 for (const RelocationRef &Reloc : Section.relocations()) {
1467 uint64_t Address = Reloc.getOffset();
1468 SmallString<32> RelocName;
1469 SmallString<32> ValueStr;
1470 if (Address < StartAddress || Address > StopAddress || getHidden(Reloc))
1471 continue;
1472 Reloc.getTypeName(RelocName);
1473 error(getRelocationValueString(Reloc, ValueStr));
1474 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1475 << ValueStr << "\n";
1476 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001477 }
1478 outs() << "\n";
1479 }
1480}
1481
Fangrui Song523758e2019-04-15 15:31:42 +00001482void printDynamicRelocations(const ObjectFile *Obj) {
Paul Semelcb0f0432018-06-07 13:30:55 +00001483 // For the moment, this option is for ELF only
1484 if (!Obj->isELF())
1485 return;
1486
1487 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
Paul Semelcb0f0432018-06-07 13:30:55 +00001488 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1489 error("not a dynamic object");
1490 return;
1491 }
1492
Paul Semelcb0f0432018-06-07 13:30:55 +00001493 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1494 if (DynRelSec.empty())
1495 return;
1496
1497 outs() << "DYNAMIC RELOCATION RECORDS\n";
George Rimar73a27232019-01-15 09:19:18 +00001498 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Fangrui Songaaecb8f2019-04-24 15:09:23 +00001499 for (const SectionRef &Section : DynRelSec)
Paul Semelcb0f0432018-06-07 13:30:55 +00001500 for (const RelocationRef &Reloc : Section.relocations()) {
George Rimar73a27232019-01-15 09:19:18 +00001501 uint64_t Address = Reloc.getOffset();
1502 SmallString<32> RelocName;
1503 SmallString<32> ValueStr;
1504 Reloc.getTypeName(RelocName);
1505 error(getRelocationValueString(Reloc, ValueStr));
1506 outs() << format(Fmt.data(), Address) << " " << RelocName << " "
1507 << ValueStr << "\n";
Paul Semelcb0f0432018-06-07 13:30:55 +00001508 }
Paul Semelcb0f0432018-06-07 13:30:55 +00001509}
1510
George Rimar87fa2e62019-01-28 14:11:35 +00001511// Returns true if we need to show LMA column when dumping section headers. We
1512// show it only when the platform is ELF and either we have at least one section
1513// whose VMA and LMA are different and/or when --show-lma flag is used.
1514static bool shouldDisplayLMA(const ObjectFile *Obj) {
1515 if (!Obj->isELF())
1516 return false;
1517 for (const SectionRef &S : ToolSectionFilter(*Obj))
1518 if (S.getAddress() != getELFSectionLMA(S))
1519 return true;
1520 return ShowLMA;
1521}
1522
Fangrui Song523758e2019-04-15 15:31:42 +00001523void printSectionHeaders(const ObjectFile *Obj) {
George Rimar87fa2e62019-01-28 14:11:35 +00001524 bool HasLMAColumn = shouldDisplayLMA(Obj);
1525 if (HasLMAColumn)
1526 outs() << "Sections:\n"
1527 "Idx Name Size VMA LMA "
1528 "Type\n";
1529 else
1530 outs() << "Sections:\n"
1531 "Idx Name Size VMA Type\n";
1532
Colin LeMahieu77804be2015-07-29 15:45:39 +00001533 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001534 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001535 error(Section.getName(Name));
George Rimar87fa2e62019-01-28 14:11:35 +00001536 uint64_t VMA = Section.getAddress();
George Rimar4463ebe2019-01-28 16:36:12 +00001537 if (shouldAdjustVA(Section))
1538 VMA += AdjustVMA;
1539
Rafael Espindola80291272014-10-08 15:28:58 +00001540 uint64_t Size = Section.getSize();
1541 bool Text = Section.isText();
1542 bool Data = Section.isData();
1543 bool BSS = Section.isBSS();
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001544 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer8f67d472011-10-13 20:37:20 +00001545 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
George Rimar87fa2e62019-01-28 14:11:35 +00001546
1547 if (HasLMAColumn)
1548 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %016" PRIx64
1549 " %s\n",
1550 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1551 VMA, getELFSectionLMA(Section), Type.c_str());
1552 else
1553 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
1554 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1555 VMA, Type.c_str());
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001556 }
Xing GUO785edea2018-11-17 08:12:48 +00001557 outs() << "\n";
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001558}
1559
Fangrui Song523758e2019-04-15 15:31:42 +00001560void printSectionContents(const ObjectFile *Obj) {
Colin LeMahieu77804be2015-07-29 15:45:39 +00001561 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001562 StringRef Name;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001563 error(Section.getName(Name));
Rafael Espindola80291272014-10-08 15:28:58 +00001564 uint64_t BaseAddr = Section.getAddress();
David Majnemer185b5b12014-11-11 09:58:25 +00001565 uint64_t Size = Section.getSize();
1566 if (!Size)
1567 continue;
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001568
1569 outs() << "Contents of section " << Name << ":\n";
David Majnemer185b5b12014-11-11 09:58:25 +00001570 if (Section.isBSS()) {
Alexey Samsonov209095c2013-04-16 10:53:11 +00001571 outs() << format("<skipping contents of bss section at [%04" PRIx64
David Majnemer8f6b04c2014-07-14 16:20:14 +00001572 ", %04" PRIx64 ")>\n",
1573 BaseAddr, BaseAddr + Size);
Alexey Samsonov209095c2013-04-16 10:53:11 +00001574 continue;
1575 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001576
Fangrui Songa076ec52019-05-16 11:33:48 +00001577 StringRef Contents = unwrapOrError(Section.getContents(), Obj->getFileName());
David Majnemer8f6b04c2014-07-14 16:20:14 +00001578
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001579 // Dump out the content as hex and printable ascii characters.
George Rimar73a27232019-01-15 09:19:18 +00001580 for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) {
1581 outs() << format(" %04" PRIx64 " ", BaseAddr + Addr);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001582 // Dump line of hex.
George Rimar73a27232019-01-15 09:19:18 +00001583 for (std::size_t I = 0; I < 16; ++I) {
1584 if (I != 0 && I % 4 == 0)
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001585 outs() << ' ';
George Rimar73a27232019-01-15 09:19:18 +00001586 if (Addr + I < End)
1587 outs() << hexdigit((Contents[Addr + I] >> 4) & 0xF, true)
1588 << hexdigit(Contents[Addr + I] & 0xF, true);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001589 else
1590 outs() << " ";
1591 }
1592 // Print ascii.
1593 outs() << " ";
George Rimar73a27232019-01-15 09:19:18 +00001594 for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) {
1595 if (isPrint(static_cast<unsigned char>(Contents[Addr + I]) & 0xFF))
1596 outs() << Contents[Addr + I];
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001597 else
1598 outs() << ".";
1599 }
1600 outs() << "\n";
1601 }
1602 }
1603}
1604
Fangrui Song523758e2019-04-15 15:31:42 +00001605void printSymbolTable(const ObjectFile *O, StringRef ArchiveName,
1606 StringRef ArchitectureName) {
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001607 outs() << "SYMBOL TABLE:\n";
1608
George Rimar73a27232019-01-15 09:19:18 +00001609 if (const COFFObjectFile *Coff = dyn_cast<const COFFObjectFile>(O)) {
1610 printCOFFSymbolTable(Coff);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001611 return;
1612 }
George Rimar8e0a70b2019-01-10 16:24:10 +00001613
Fangrui Songe7834bd2019-04-07 08:19:55 +00001614 const StringRef FileName = O->getFileName();
George Rimar73a27232019-01-15 09:19:18 +00001615 for (auto I = O->symbol_begin(), E = O->symbol_end(); I != E; ++I) {
George Rimar8e0a70b2019-01-10 16:24:10 +00001616 // Skip printing the special zero symbol when dumping an ELF file.
1617 // This makes the output consistent with the GNU objdump.
George Rimar73a27232019-01-15 09:19:18 +00001618 if (I == O->symbol_begin() && isa<ELFObjectFileBase>(O))
George Rimar8e0a70b2019-01-10 16:24:10 +00001619 continue;
1620
1621 const SymbolRef &Symbol = *I;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001622 uint64_t Address = unwrapOrError(Symbol.getAddress(), ArchiveName, FileName,
1623 ArchitectureName);
Hemant Kulkarniaecf9d02016-09-12 17:08:22 +00001624 if ((Address < StartAddress) || (Address > StopAddress))
1625 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001626 SymbolRef::Type Type = unwrapOrError(Symbol.getType(), ArchiveName,
1627 FileName, ArchitectureName);
Rui Ueyama4e39f712014-03-18 18:58:51 +00001628 uint32_t Flags = Symbol.getFlags();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001629 section_iterator Section = unwrapOrError(Symbol.getSection(), ArchiveName,
1630 FileName, ArchitectureName);
Rafael Espindola75d5b542015-06-03 05:14:22 +00001631 StringRef Name;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001632 if (Type == SymbolRef::ST_Debug && Section != O->section_end())
Rafael Espindola75d5b542015-06-03 05:14:22 +00001633 Section->getName(Name);
Fangrui Songe7834bd2019-04-07 08:19:55 +00001634 else
1635 Name = unwrapOrError(Symbol.getName(), ArchiveName, FileName,
1636 ArchitectureName);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001637
Rui Ueyama4e39f712014-03-18 18:58:51 +00001638 bool Global = Flags & SymbolRef::SF_Global;
1639 bool Weak = Flags & SymbolRef::SF_Weak;
1640 bool Absolute = Flags & SymbolRef::SF_Absolute;
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001641 bool Common = Flags & SymbolRef::SF_Common;
Davide Italianocd2514d2015-04-30 23:08:53 +00001642 bool Hidden = Flags & SymbolRef::SF_Hidden;
David Meyer1df4b842012-02-28 23:47:53 +00001643
Rui Ueyama4e39f712014-03-18 18:58:51 +00001644 char GlobLoc = ' ';
1645 if (Type != SymbolRef::ST_Unknown)
1646 GlobLoc = Global ? 'g' : 'l';
1647 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
1648 ? 'd' : ' ';
1649 char FileFunc = ' ';
1650 if (Type == SymbolRef::ST_File)
1651 FileFunc = 'f';
1652 else if (Type == SymbolRef::ST_Function)
1653 FileFunc = 'F';
Kristina Brooks0674f9d2018-11-11 17:47:13 +00001654 else if (Type == SymbolRef::ST_Data)
1655 FileFunc = 'O';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001656
George Rimar73a27232019-01-15 09:19:18 +00001657 const char *Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 :
Rui Ueyama4e39f712014-03-18 18:58:51 +00001658 "%08" PRIx64;
Michael J. Spencerd857c1c2013-01-10 22:40:50 +00001659
Rui Ueyama4e39f712014-03-18 18:58:51 +00001660 outs() << format(Fmt, Address) << " "
1661 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
1662 << (Weak ? 'w' : ' ') // Weak?
1663 << ' ' // Constructor. Not supported yet.
1664 << ' ' // Warning. Not supported yet.
1665 << ' ' // Indirect reference to another symbol.
1666 << Debug // Debugging (d) or dynamic (D) symbol.
1667 << FileFunc // Name of function (F), file (f) or object (O).
1668 << ' ';
1669 if (Absolute) {
1670 outs() << "*ABS*";
Colin LeMahieubc2f47a2015-01-23 20:06:24 +00001671 } else if (Common) {
1672 outs() << "*COM*";
George Rimar73a27232019-01-15 09:19:18 +00001673 } else if (Section == O->section_end()) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001674 outs() << "*UND*";
1675 } else {
1676 if (const MachOObjectFile *MachO =
George Rimar73a27232019-01-15 09:19:18 +00001677 dyn_cast<const MachOObjectFile>(O)) {
Rui Ueyama4e39f712014-03-18 18:58:51 +00001678 DataRefImpl DR = Section->getRawDataRefImpl();
1679 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
1680 outs() << SegmentName << ",";
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001681 }
Rui Ueyama4e39f712014-03-18 18:58:51 +00001682 StringRef SectionName;
Davide Italianoccd53fe2015-08-05 07:18:31 +00001683 error(Section->getName(SectionName));
Rui Ueyama4e39f712014-03-18 18:58:51 +00001684 outs() << SectionName;
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001685 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001686
George Rimar73a27232019-01-15 09:19:18 +00001687 if (Common || isa<ELFObjectFileBase>(O)) {
Rafael Espindoladbb6bd32015-06-25 22:10:04 +00001688 uint64_t Val =
1689 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
Fangrui Song61504072019-05-10 16:24:57 +00001690 outs() << format("\t%08" PRIx64, Val);
Rafael Espindolaae3ac082015-06-23 18:34:25 +00001691 }
Rafael Espindola5f7ade22015-06-23 15:45:38 +00001692
Fangrui Song61504072019-05-10 16:24:57 +00001693 if (isa<ELFObjectFileBase>(O)) {
1694 uint8_t Other = ELFSymbolRef(Symbol).getOther();
1695 switch (Other) {
1696 case ELF::STV_DEFAULT:
1697 break;
1698 case ELF::STV_INTERNAL:
1699 outs() << " .internal";
1700 break;
1701 case ELF::STV_HIDDEN:
1702 outs() << " .hidden";
1703 break;
1704 case ELF::STV_PROTECTED:
1705 outs() << " .protected";
1706 break;
1707 default:
1708 outs() << format(" 0x%02x", Other);
1709 break;
1710 }
1711 } else if (Hidden) {
1712 outs() << " .hidden";
1713 }
George Rimar6622d412018-12-19 10:21:45 +00001714
1715 if (Demangle)
Fangrui Song61504072019-05-10 16:24:57 +00001716 outs() << ' ' << demangle(Name) << '\n';
George Rimar6622d412018-12-19 10:21:45 +00001717 else
Fangrui Song61504072019-05-10 16:24:57 +00001718 outs() << ' ' << Name << '\n';
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001719 }
1720}
1721
George Rimar73a27232019-01-15 09:19:18 +00001722static void printUnwindInfo(const ObjectFile *O) {
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001723 outs() << "Unwind info:\n\n";
1724
George Rimar73a27232019-01-15 09:19:18 +00001725 if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(O))
1726 printCOFFUnwindInfo(Coff);
1727 else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O))
Tim Northover4bd286a2014-08-01 13:07:19 +00001728 printMachOUnwindInfo(MachO);
George Rimar73a27232019-01-15 09:19:18 +00001729 else
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001730 // TODO: Extract DWARF dump tool to objdump.
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001731 WithColor::error(errs(), ToolName)
1732 << "This operation is only currently supported "
1733 "for COFF and MachO object files.\n";
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001734}
1735
Adrian Prantl437105a2015-07-08 02:04:15 +00001736/// Dump the raw contents of the __clangast section so the output can be piped
1737/// into llvm-bcanalyzer.
Fangrui Song523758e2019-04-15 15:31:42 +00001738void printRawClangAST(const ObjectFile *Obj) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001739 if (outs().is_displayed()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001740 WithColor::error(errs(), ToolName)
1741 << "The -raw-clang-ast option will dump the raw binary contents of "
1742 "the clang ast section.\n"
1743 "Please redirect the output to a file or another program such as "
1744 "llvm-bcanalyzer.\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001745 return;
1746 }
1747
1748 StringRef ClangASTSectionName("__clangast");
1749 if (isa<COFFObjectFile>(Obj)) {
1750 ClangASTSectionName = "clangast";
1751 }
1752
1753 Optional<object::SectionRef> ClangASTSection;
Colin LeMahieu77804be2015-07-29 15:45:39 +00001754 for (auto Sec : ToolSectionFilter(*Obj)) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001755 StringRef Name;
1756 Sec.getName(Name);
1757 if (Name == ClangASTSectionName) {
1758 ClangASTSection = Sec;
1759 break;
1760 }
1761 }
1762 if (!ClangASTSection)
1763 return;
1764
Fangrui Songa076ec52019-05-16 11:33:48 +00001765 StringRef ClangASTContents = unwrapOrError(
1766 ClangASTSection.getValue().getContents(), Obj->getFileName());
Adrian Prantl437105a2015-07-08 02:04:15 +00001767 outs().write(ClangASTContents.data(), ClangASTContents.size());
1768}
1769
Sanjoy Das6f567a42015-06-22 18:03:02 +00001770static void printFaultMaps(const ObjectFile *Obj) {
George Rimar73a27232019-01-15 09:19:18 +00001771 StringRef FaultMapSectionName;
Sanjoy Das6f567a42015-06-22 18:03:02 +00001772
1773 if (isa<ELFObjectFileBase>(Obj)) {
1774 FaultMapSectionName = ".llvm_faultmaps";
1775 } else if (isa<MachOObjectFile>(Obj)) {
1776 FaultMapSectionName = "__llvm_faultmaps";
1777 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001778 WithColor::error(errs(), ToolName)
1779 << "This operation is only currently supported "
1780 "for ELF and Mach-O executable files.\n";
Sanjoy Das6f567a42015-06-22 18:03:02 +00001781 return;
1782 }
1783
1784 Optional<object::SectionRef> FaultMapSection;
1785
Colin LeMahieu77804be2015-07-29 15:45:39 +00001786 for (auto Sec : ToolSectionFilter(*Obj)) {
Sanjoy Das6f567a42015-06-22 18:03:02 +00001787 StringRef Name;
1788 Sec.getName(Name);
1789 if (Name == FaultMapSectionName) {
1790 FaultMapSection = Sec;
1791 break;
1792 }
1793 }
1794
1795 outs() << "FaultMap table:\n";
1796
1797 if (!FaultMapSection.hasValue()) {
1798 outs() << "<not found>\n";
1799 return;
1800 }
1801
Fangrui Songa076ec52019-05-16 11:33:48 +00001802 StringRef FaultMapContents =
1803 unwrapOrError(FaultMapSection.getValue().getContents(), Obj->getFileName());
Sanjoy Das6f567a42015-06-22 18:03:02 +00001804 FaultMapParser FMP(FaultMapContents.bytes_begin(),
1805 FaultMapContents.bytes_end());
1806
1807 outs() << FMP;
1808}
1809
George Rimar73a27232019-01-15 09:19:18 +00001810static void printPrivateFileHeaders(const ObjectFile *O, bool OnlyFirst) {
1811 if (O->isELF()) {
1812 printELFFileHeader(O);
Xing GUO56d651d2019-02-25 13:13:19 +00001813 printELFDynamicSection(O);
1814 printELFSymbolVersionInfo(O);
1815 return;
Paul Semel0913dcd2018-07-25 11:09:20 +00001816 }
George Rimar73a27232019-01-15 09:19:18 +00001817 if (O->isCOFF())
1818 return printCOFFFileHeader(O);
1819 if (O->isWasm())
1820 return printWasmFileHeader(O);
1821 if (O->isMachO()) {
1822 printMachOFileHeader(O);
1823 if (!OnlyFirst)
1824 printMachOLoadCommands(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001825 return;
1826 }
George Rimar73a27232019-01-15 09:19:18 +00001827 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Rui Ueyamac2bed422013-09-27 21:04:00 +00001828}
1829
George Rimar73a27232019-01-15 09:19:18 +00001830static void printFileHeaders(const ObjectFile *O) {
1831 if (!O->isELF() && !O->isCOFF())
1832 report_error(O->getFileName(), "Invalid/Unsupported object file format");
Paul Semeld2af4d62018-07-04 15:25:03 +00001833
George Rimar73a27232019-01-15 09:19:18 +00001834 Triple::ArchType AT = O->getArch();
Paul Semeld2af4d62018-07-04 15:25:03 +00001835 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
Fangrui Songe7834bd2019-04-07 08:19:55 +00001836 uint64_t Address = unwrapOrError(O->getStartAddress(), O->getFileName());
Petar Jovanovic8d947ba2018-10-19 22:16:49 +00001837
George Rimar73a27232019-01-15 09:19:18 +00001838 StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64;
Paul Semeld2af4d62018-07-04 15:25:03 +00001839 outs() << "start address: "
George Rimar9b6fe7e2019-01-12 12:17:24 +00001840 << "0x" << format(Fmt.data(), Address) << "\n\n";
Paul Semeld2af4d62018-07-04 15:25:03 +00001841}
1842
Paul Semel0dc92f62018-07-05 14:43:29 +00001843static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
1844 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1845 if (!ModeOrErr) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001846 WithColor::error(errs(), ToolName) << "ill-formed archive entry.\n";
Paul Semel0dc92f62018-07-05 14:43:29 +00001847 consumeError(ModeOrErr.takeError());
1848 return;
1849 }
1850 sys::fs::perms Mode = ModeOrErr.get();
1851 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1852 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1853 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1854 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1855 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1856 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1857 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1858 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1859 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1860
1861 outs() << " ";
1862
Fangrui Songe7834bd2019-04-07 08:19:55 +00001863 outs() << format("%d/%d %6" PRId64 " ", unwrapOrError(C.getUID(), Filename),
1864 unwrapOrError(C.getGID(), Filename),
1865 unwrapOrError(C.getRawSize(), Filename));
Paul Semel0dc92f62018-07-05 14:43:29 +00001866
1867 StringRef RawLastModified = C.getRawLastModified();
1868 unsigned Seconds;
1869 if (RawLastModified.getAsInteger(10, Seconds))
1870 outs() << "(date: \"" << RawLastModified
1871 << "\" contains non-decimal chars) ";
1872 else {
1873 // Since ctime(3) returns a 26 character string of the form:
1874 // "Sun Sep 16 01:03:52 1973\n\0"
1875 // just print 24 characters.
1876 time_t t = Seconds;
1877 outs() << format("%.24s ", ctime(&t));
1878 }
1879
1880 StringRef Name = "";
1881 Expected<StringRef> NameOrErr = C.getName();
1882 if (!NameOrErr) {
1883 consumeError(NameOrErr.takeError());
Fangrui Songe7834bd2019-04-07 08:19:55 +00001884 Name = unwrapOrError(C.getRawName(), Filename);
Paul Semel0dc92f62018-07-05 14:43:29 +00001885 } else {
1886 Name = NameOrErr.get();
1887 }
1888 outs() << Name << "\n";
1889}
1890
George Rimar73a27232019-01-15 09:19:18 +00001891static void dumpObject(ObjectFile *O, const Archive *A = nullptr,
1892 const Archive::Child *C = nullptr) {
Adrian Prantl437105a2015-07-08 02:04:15 +00001893 // Avoid other output when using a raw option.
1894 if (!RawClangAST) {
1895 outs() << '\n';
George Rimar73a27232019-01-15 09:19:18 +00001896 if (A)
1897 outs() << A->getFileName() << "(" << O->getFileName() << ")";
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001898 else
George Rimar73a27232019-01-15 09:19:18 +00001899 outs() << O->getFileName();
1900 outs() << ":\tfile format " << O->getFileFormatName() << "\n\n";
Adrian Prantl437105a2015-07-08 02:04:15 +00001901 }
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001902
George Rimar73a27232019-01-15 09:19:18 +00001903 StringRef ArchiveName = A ? A->getFileName() : "";
George Rimar9b6fe7e2019-01-12 12:17:24 +00001904 if (FileHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001905 printFileHeaders(O);
1906 if (ArchiveHeaders && !MachOOpt && C)
1907 printArchiveChild(ArchiveName, *C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001908 if (Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00001909 disassembleObject(O, Relocations);
Michael J. Spencer51862b32011-10-13 22:17:18 +00001910 if (Relocations && !Disassemble)
George Rimar73a27232019-01-15 09:19:18 +00001911 printRelocations(O);
Paul Semelcb0f0432018-06-07 13:30:55 +00001912 if (DynamicRelocations)
George Rimar73a27232019-01-15 09:19:18 +00001913 printDynamicRelocations(O);
Nick Lewyckyfcf84622011-10-10 21:21:34 +00001914 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001915 printSectionHeaders(O);
Michael J. Spencer4e25c022011-10-17 17:13:22 +00001916 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001917 printSectionContents(O);
Michael J. Spencerbfa06782011-10-18 19:32:17 +00001918 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001919 printSymbolTable(O, ArchiveName);
Michael J. Spencer0c6ec482012-12-05 20:12:35 +00001920 if (UnwindInfo)
George Rimar73a27232019-01-15 09:19:18 +00001921 printUnwindInfo(O);
Davide Italiano1bdaa202016-09-18 04:39:15 +00001922 if (PrivateHeaders || FirstPrivateHeader)
George Rimar73a27232019-01-15 09:19:18 +00001923 printPrivateFileHeaders(O, FirstPrivateHeader);
Nick Kledzikd04bc352014-08-30 00:20:14 +00001924 if (ExportsTrie)
George Rimar73a27232019-01-15 09:19:18 +00001925 printExportsTrie(O);
Nick Kledzikac431442014-09-12 21:34:15 +00001926 if (Rebase)
George Rimar73a27232019-01-15 09:19:18 +00001927 printRebaseTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001928 if (Bind)
George Rimar73a27232019-01-15 09:19:18 +00001929 printBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001930 if (LazyBind)
George Rimar73a27232019-01-15 09:19:18 +00001931 printLazyBindTable(O);
Nick Kledzik56ebef42014-09-16 01:41:51 +00001932 if (WeakBind)
George Rimar73a27232019-01-15 09:19:18 +00001933 printWeakBindTable(O);
Adrian Prantl437105a2015-07-08 02:04:15 +00001934 if (RawClangAST)
George Rimar73a27232019-01-15 09:19:18 +00001935 printRawClangAST(O);
Fangrui Song9d812f42019-04-15 15:00:10 +00001936 if (FaultMapSection)
George Rimar73a27232019-01-15 09:19:18 +00001937 printFaultMaps(O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001938 if (DwarfDumpType != DIDT_Null) {
George Rimar73a27232019-01-15 09:19:18 +00001939 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*O);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001940 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001941 DIDumpOptions DumpOpts;
1942 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001943 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001944 }
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001945}
1946
George Rimar73a27232019-01-15 09:19:18 +00001947static void dumpObject(const COFFImportFile *I, const Archive *A,
Paul Semel0dc92f62018-07-05 14:43:29 +00001948 const Archive::Child *C = nullptr) {
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001949 StringRef ArchiveName = A ? A->getFileName() : "";
1950
1951 // Avoid other output when using a raw option.
1952 if (!RawClangAST)
1953 outs() << '\n'
1954 << ArchiveName << "(" << I->getFileName() << ")"
1955 << ":\tfile format COFF-import-file"
1956 << "\n\n";
1957
James Hendersonc1608c92018-10-29 14:17:08 +00001958 if (ArchiveHeaders && !MachOOpt && C)
1959 printArchiveChild(ArchiveName, *C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001960 if (SymbolTable)
1961 printCOFFSymbolTable(I);
1962}
1963
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00001964/// Dump each object file in \a a;
George Rimar73a27232019-01-15 09:19:18 +00001965static void dumpArchive(const Archive *A) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001966 Error Err = Error::success();
George Rimar73a27232019-01-15 09:19:18 +00001967 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001968 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1969 if (!ChildOrErr) {
1970 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Fangrui Songe7834bd2019-04-07 08:19:55 +00001971 report_error(std::move(E), A->getFileName(), C);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001972 continue;
1973 }
George Rimar73a27232019-01-15 09:19:18 +00001974 if (ObjectFile *O = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
1975 dumpObject(O, A, &C);
Saleem Abdulrasoolc6bf5472016-08-18 16:39:19 +00001976 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
George Rimar73a27232019-01-15 09:19:18 +00001977 dumpObject(I, A, &C);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001978 else
Fangrui Song3f209682019-04-09 05:41:24 +00001979 report_error(errorCodeToError(object_error::invalid_file_type),
1980 A->getFileName());
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001981 }
Lang Hamesfc209622016-07-14 02:24:01 +00001982 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00001983 report_error(std::move(Err), A->getFileName());
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001984}
1985
Adrian Prantl4dfcc4a2018-05-01 16:10:38 +00001986/// Open file and figure out how to dump it.
George Rimar73a27232019-01-15 09:19:18 +00001987static void dumpInput(StringRef file) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001988 // If we are using the Mach-O specific object file parser, then let it parse
1989 // the file and process the command line options. So the -arch flags can
1990 // be used to select specific slices, etc.
1991 if (MachOOpt) {
George Rimar73a27232019-01-15 09:19:18 +00001992 parseInputMachO(file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001993 return;
1994 }
1995
1996 // Attempt to open the binary.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001997 OwningBinary<Binary> OBinary = unwrapOrError(createBinary(file), file);
1998 Binary &Binary = *OBinary.getBinary();
Michael J. Spencerba4a3622011-10-08 00:18:30 +00001999
George Rimar73a27232019-01-15 09:19:18 +00002000 if (Archive *A = dyn_cast<Archive>(&Binary))
2001 dumpArchive(A);
2002 else if (ObjectFile *O = dyn_cast<ObjectFile>(&Binary))
2003 dumpObject(O);
Dave Lee3fb120f2018-08-03 00:06:38 +00002004 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
George Rimar73a27232019-01-15 09:19:18 +00002005 parseInputMachO(UB);
Jim Grosbachaf9aec02012-08-07 17:53:14 +00002006 else
Fangrui Song3f209682019-04-09 05:41:24 +00002007 report_error(errorCodeToError(object_error::invalid_file_type), file);
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002008}
Fangrui Song523758e2019-04-15 15:31:42 +00002009} // namespace llvm
Michael J. Spencerba4a3622011-10-08 00:18:30 +00002010
Michael J. Spencer2670c252011-01-20 06:39:06 +00002011int main(int argc, char **argv) {
Fangrui Song523758e2019-04-15 15:31:42 +00002012 using namespace llvm;
Rui Ueyama197194b2018-04-13 18:26:06 +00002013 InitLLVM X(argc, argv);
Michael J. Spencer2670c252011-01-20 06:39:06 +00002014
2015 // Initialize targets and assembly printers/parsers.
Fangrui Song523758e2019-04-15 15:31:42 +00002016 InitializeAllTargetInfos();
2017 InitializeAllTargetMCs();
2018 InitializeAllDisassemblers();
Michael J. Spencer2670c252011-01-20 06:39:06 +00002019
Pete Cooper28fb4fc2012-05-03 23:20:10 +00002020 // Register the target printer for --version.
2021 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2022
Michael J. Spencer2670c252011-01-20 06:39:06 +00002023 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
Michael J. Spencer2670c252011-01-20 06:39:06 +00002024
2025 ToolName = argv[0];
2026
2027 // Defaults to a.out if no filenames specified.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002028 if (InputFilenames.empty())
Michael J. Spencer2670c252011-01-20 06:39:06 +00002029 InputFilenames.push_back("a.out");
2030
Fangrui Song8513cd42018-06-27 20:45:11 +00002031 if (AllHeaders)
George Rimar5e364332019-01-18 12:01:59 +00002032 ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations =
2033 SectionHeaders = SymbolTable = true;
Fangrui Song8513cd42018-06-27 20:45:11 +00002034
Hemant Kulkarni8dfc0b52016-08-15 19:49:24 +00002035 if (DisassembleAll || PrintSource || PrintLines)
Colin LeMahieuf34933e2015-07-23 20:58:49 +00002036 Disassemble = true;
Paul Semel007dedb2018-07-18 16:39:21 +00002037
Fangrui Song051a6992019-04-16 02:37:29 +00002038 if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null &&
2039 !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST &&
2040 !Relocations && !SectionHeaders && !SectionContents && !SymbolTable &&
2041 !UnwindInfo && !FaultMapSection &&
2042 !(MachOOpt &&
2043 (Bind || DataInCode || DylibId || DylibsUsed || ExportsTrie ||
2044 FirstPrivateHeader || IndirectSymbols || InfoPlist || LazyBind ||
2045 LinkOptHints || ObjcMetaData || Rebase || UniversalHeaders ||
2046 WeakBind || !FilterSections.empty()))) {
Michael J. Spencer2670c252011-01-20 06:39:06 +00002047 cl::PrintHelpMessage();
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002048 return 2;
2049 }
2050
Rafael Aulerb0e4b912018-03-09 19:13:44 +00002051 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2052 DisassembleFunctions.end());
2053
George Rimar73a27232019-01-15 09:19:18 +00002054 llvm::for_each(InputFilenames, dumpInput);
Dimitry Andrice4f5d012017-12-18 19:46:56 +00002055
2056 return EXIT_SUCCESS;
2057}