blob: e5e039cd054f442d1a70e6659afe244f129e7128 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.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
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000014#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000018#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000019#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000020#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000022#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000046#include "llvm/Support/WithColor.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Fangrui Song523758e2019-04-15 15:31:42 +000058using namespace llvm::object;
Benjamin Kramer43a772e2011-09-19 17:56:04 +000059
Fangrui Song9d812f42019-04-15 15:00:10 +000060namespace llvm {
61
62extern cl::opt<bool> ArchiveHeaders;
63extern cl::opt<bool> Disassemble;
64extern cl::opt<bool> DisassembleAll;
65extern cl::opt<DIDumpType> DwarfDumpType;
66extern cl::list<std::string> FilterSections;
67extern cl::list<std::string> MAttrs;
68extern cl::opt<std::string> MCPU;
69extern cl::opt<bool> NoShowRawInsn;
70extern cl::opt<bool> NoLeadingAddr;
71extern cl::opt<bool> PrintImmHex;
72extern cl::opt<bool> PrivateHeaders;
73extern cl::opt<bool> Relocations;
74extern cl::opt<bool> SectionHeaders;
75extern cl::opt<bool> SectionContents;
76extern cl::opt<bool> SymbolTable;
77extern cl::opt<std::string> TripleName;
78extern cl::opt<bool> UnwindInfo;
79
80cl::opt<bool>
81 FirstPrivateHeader("private-header",
82 cl::desc("Display only the first format specific file "
83 "header"));
84
85cl::opt<bool> ExportsTrie("exports-trie",
86 cl::desc("Display mach-o exported symbols"));
87
88cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"));
89
90cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"));
91
92cl::opt<bool> LazyBind("lazy-bind",
93 cl::desc("Display mach-o lazy binding info"));
94
95cl::opt<bool> WeakBind("weak-bind",
96 cl::desc("Display mach-o weak binding info"));
97
Benjamin Kramer43a772e2011-09-19 17:56:04 +000098static cl::opt<bool>
Matthew Voss0f436772019-02-19 19:46:08 +000099 UseDbg("g", cl::Grouping,
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000100 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000101
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000102static cl::opt<std::string> DSYMFile("dsym",
103 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000104
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000105static cl::opt<bool> FullLeadingAddr("full-leading-addr",
106 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +0000107
Kevin Enderbyf9d60f02016-11-29 21:43:40 +0000108static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
109 cl::desc("Print no leading headers"));
110
Fangrui Song9d812f42019-04-15 15:00:10 +0000111cl::opt<bool> UniversalHeaders("universal-headers",
112 cl::desc("Print Mach-O universal headers "
113 "(requires -macho)"));
Kevin Enderby13023a12015-01-15 23:19:11 +0000114
Kevin Enderby131d1772015-01-09 19:22:37 +0000115cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +0000116 ArchiveMemberOffsets("archive-member-offsets",
117 cl::desc("Print the offset to each archive member for "
118 "Mach-O archives (requires -macho and "
119 "-archive-headers)"));
120
Fangrui Song9d812f42019-04-15 15:00:10 +0000121cl::opt<bool> IndirectSymbols("indirect-symbols",
122 cl::desc("Print indirect symbol table for Mach-O "
123 "objects (requires -macho)"));
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000124
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000125cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000126 DataInCode("data-in-code",
127 cl::desc("Print the data in code table for Mach-O objects "
128 "(requires -macho)"));
129
130cl::opt<bool> LinkOptHints("link-opt-hints",
131 cl::desc("Print the linker optimization hints for "
132 "Mach-O objects (requires -macho)"));
133
134cl::opt<bool> InfoPlist("info-plist",
135 cl::desc("Print the info plist section as strings for "
136 "Mach-O objects (requires -macho)"));
137
138cl::opt<bool> DylibsUsed("dylibs-used",
139 cl::desc("Print the shared libraries used for linked "
140 "Mach-O files (requires -macho)"));
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000141
Kevin Enderby9a509442015-01-27 21:28:24 +0000142cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000143 DylibId("dylib-id",
144 cl::desc("Print the shared library's id for the dylib Mach-O "
145 "file (requires -macho)"));
Kevin Enderby9a509442015-01-27 21:28:24 +0000146
Kevin Enderbycd66be52015-03-11 22:06:32 +0000147cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000148 NonVerbose("non-verbose",
149 cl::desc("Print the info for Mach-O objects in "
150 "non-verbose or numeric form (requires -macho)"));
Kevin Enderbycd66be52015-03-11 22:06:32 +0000151
Kevin Enderbyf0640752015-03-13 17:56:32 +0000152cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000153 ObjcMetaData("objc-meta-data",
154 cl::desc("Print the Objective-C runtime meta data for "
155 "Mach-O files (requires -macho)"));
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000156
Fangrui Song9d812f42019-04-15 15:00:10 +0000157cl::opt<std::string> DisSymName(
Kevin Enderby6a221752015-03-17 17:10:57 +0000158 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000159 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000160
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000161static cl::opt<bool> NoSymbolicOperands(
162 "no-symbolic-operands",
163 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
164
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000165static cl::list<std::string>
166 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
167 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000168
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000169bool ArchAll = false;
170
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000171static std::string ThumbTripleName;
172
173static const Target *GetTarget(const MachOObjectFile *MachOObj,
174 const char **McpuDefault,
175 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000176 // Figure out the target triple.
Fangrui Song523758e2019-04-15 15:31:42 +0000177 Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000178 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000179 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000180 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000181 }
182
183 if (TT.getArch() == Triple::arm) {
184 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
185 // that support ARM are also capable of Thumb mode.
Fangrui Song523758e2019-04-15 15:31:42 +0000186 Triple ThumbTriple = TT;
Tim Northover9e8eb412016-04-22 23:21:13 +0000187 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
188 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000189 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000190 }
191
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000192 // Get the target specific parser.
193 std::string Error;
194 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000195 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000196 return TheTarget;
197
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000198 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
199 if (*ThumbTarget)
200 return TheTarget;
201
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000202 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000203 if (!TheTarget)
204 errs() << TripleName;
205 else
206 errs() << ThumbTripleName;
207 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000208 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000209}
210
Owen Andersond9243c42011-10-17 21:37:35 +0000211struct SymbolSorter {
212 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000213 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000214 if (!ATypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000215 report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000216 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000217 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000218 if (!BTypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000219 report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000220 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000221 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
222 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000223 return AAddr < BAddr;
224 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000225};
226
Kevin Enderby273ae012013-06-06 17:20:50 +0000227// Types for the storted data in code table that is built before disassembly
228// and the predicate function to sort them.
229typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
230typedef std::vector<DiceTableEntry> DiceTable;
231typedef DiceTable::iterator dice_table_iterator;
232
Francis Ricci195a66f2017-10-06 15:54:20 +0000233#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000234namespace {
235struct ScopedXarFile {
236 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000237 ScopedXarFile(const char *filename, int32_t flags)
238 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000239 ~ScopedXarFile() {
240 if (xar)
241 xar_close(xar);
242 }
243 ScopedXarFile(const ScopedXarFile &) = delete;
244 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
245 operator xar_t() { return xar; }
246};
247
248struct ScopedXarIter {
249 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000250 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000251 ~ScopedXarIter() {
252 if (iter)
253 xar_iter_free(iter);
254 }
255 ScopedXarIter(const ScopedXarIter &) = delete;
256 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
257 operator xar_iter_t() { return iter; }
258};
259} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000260#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000261
Kevin Enderby930fdc72014-11-06 19:00:13 +0000262// This is used to search for a data in code table entry for the PC being
263// disassembled. The j parameter has the PC in j.first. A single data in code
264// table entry can cover many bytes for each of its Kind's. So if the offset,
265// aka the i.first value, of the data in code table entry plus its Length
266// covers the PC being searched for this will return true. If not it will
267// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000268static bool compareDiceTableEntries(const DiceTableEntry &i,
269 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000270 uint16_t Length;
271 i.second.getLength(Length);
272
273 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000274}
275
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000276static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000277 unsigned short Kind) {
278 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000279
280 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000281 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000282 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 if (Length >= 4) {
284 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000285 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000286 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000287 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000288 Size = 4;
289 } else if (Length >= 2) {
290 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000291 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000292 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000293 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 Size = 2;
295 } else {
296 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000297 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000298 Value = bytes[0];
299 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000300 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000301 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000302 if (Kind == MachO::DICE_KIND_DATA)
303 outs() << "\t@ KIND_DATA\n";
304 else
305 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000306 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000307 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000308 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000309 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000310 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000311 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
312 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000313 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000314 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000315 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000316 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000317 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000318 outs() << "\t.short " << format("%5u", Value & 0xffff)
319 << "\t@ KIND_JUMP_TABLE16\n";
320 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000321 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000322 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000323 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
324 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000325 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000326 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000327 outs() << "\t.long " << Value;
328 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
329 outs() << "\t@ KIND_JUMP_TABLE32\n";
330 else
331 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
332 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000333 break;
334 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000335 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000336}
337
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000338static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000339 std::vector<SectionRef> &Sections,
340 std::vector<SymbolRef> &Symbols,
341 SmallVectorImpl<uint64_t> &FoundFns,
342 uint64_t &BaseSegmentAddress) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000343 const StringRef FileName = MachOObj->getFileName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000344 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000345 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
346 if (!SymName.startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000347 Symbols.push_back(Symbol);
348 }
Owen Andersond9243c42011-10-17 21:37:35 +0000349
Alexey Samsonov48803e52014-03-13 14:37:36 +0000350 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000351 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000352 Section.getName(SectName);
353 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000354 }
355
Kevin Enderby273ae012013-06-06 17:20:50 +0000356 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000357 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000358 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000359 // We found a function starts segment, parse the addresses for later
360 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000361 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000362 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000363
Charles Davis8bdfafd2013-09-01 04:28:48 +0000364 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000365 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
366 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000367 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000368 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000369 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000370 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000371 }
372 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000373 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000374}
375
George Rimarc1964882019-01-18 11:33:26 +0000376static void printRelocationTargetName(const MachOObjectFile *O,
377 const MachO::any_relocation_info &RE,
378 raw_string_ostream &Fmt) {
379 // Target of a scattered relocation is an address. In the interest of
380 // generating pretty output, scan through the symbol table looking for a
381 // symbol that aligns with that address. If we find one, print it.
382 // Otherwise, we just print the hex address of the target.
Fangrui Songe7834bd2019-04-07 08:19:55 +0000383 const StringRef FileName = O->getFileName();
George Rimarc1964882019-01-18 11:33:26 +0000384 if (O->isRelocationScattered(RE)) {
385 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
386
387 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000388 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
389 if (Addr != Val)
George Rimarc1964882019-01-18 11:33:26 +0000390 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000391 Fmt << unwrapOrError(Symbol.getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000392 return;
393 }
394
395 // If we couldn't find a symbol that this relocation refers to, try
396 // to find a section beginning instead.
397 for (const SectionRef &Section : ToolSectionFilter(*O)) {
George Rimarc1964882019-01-18 11:33:26 +0000398 StringRef Name;
399 uint64_t Addr = Section.getAddress();
400 if (Addr != Val)
401 continue;
Fangrui Song3f209682019-04-09 05:41:24 +0000402 if (std::error_code EC = Section.getName(Name))
403 report_error(errorCodeToError(EC), O->getFileName());
George Rimarc1964882019-01-18 11:33:26 +0000404 Fmt << Name;
405 return;
406 }
407
408 Fmt << format("0x%x", Val);
409 return;
410 }
411
412 StringRef S;
413 bool isExtern = O->getPlainRelocationExternal(RE);
414 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
415
416 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
417 Fmt << format("0x%0" PRIx64, Val);
418 return;
419 }
420
421 if (isExtern) {
422 symbol_iterator SI = O->symbol_begin();
423 advance(SI, Val);
Fangrui Songe7834bd2019-04-07 08:19:55 +0000424 S = unwrapOrError(SI->getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000425 } else {
426 section_iterator SI = O->section_begin();
427 // Adjust for the fact that sections are 1-indexed.
428 if (Val == 0) {
429 Fmt << "0 (?,?)";
430 return;
431 }
432 uint32_t I = Val - 1;
433 while (I != 0 && SI != O->section_end()) {
434 --I;
435 advance(SI, 1);
436 }
437 if (SI == O->section_end())
438 Fmt << Val << " (?,?)";
439 else
440 SI->getName(S);
441 }
442
443 Fmt << S;
444}
445
Fangrui Song523758e2019-04-15 15:31:42 +0000446Error getMachORelocationValueString(const MachOObjectFile *Obj,
447 const RelocationRef &RelRef,
448 SmallVectorImpl<char> &Result) {
George Rimarc1964882019-01-18 11:33:26 +0000449 DataRefImpl Rel = RelRef.getRawDataRefImpl();
450 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
451
452 unsigned Arch = Obj->getArch();
453
454 std::string FmtBuf;
455 raw_string_ostream Fmt(FmtBuf);
456 unsigned Type = Obj->getAnyRelocationType(RE);
457 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
458
459 // Determine any addends that should be displayed with the relocation.
460 // These require decoding the relocation type, which is triple-specific.
461
462 // X86_64 has entirely custom relocation types.
463 if (Arch == Triple::x86_64) {
464 switch (Type) {
465 case MachO::X86_64_RELOC_GOT_LOAD:
466 case MachO::X86_64_RELOC_GOT: {
467 printRelocationTargetName(Obj, RE, Fmt);
468 Fmt << "@GOT";
469 if (IsPCRel)
470 Fmt << "PCREL";
471 break;
472 }
473 case MachO::X86_64_RELOC_SUBTRACTOR: {
474 DataRefImpl RelNext = Rel;
475 Obj->moveRelocationNext(RelNext);
476 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
477
478 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
479 // X86_64_RELOC_UNSIGNED.
480 // NOTE: Scattered relocations don't exist on x86_64.
481 unsigned RType = Obj->getAnyRelocationType(RENext);
482 if (RType != MachO::X86_64_RELOC_UNSIGNED)
483 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
484 "X86_64_RELOC_SUBTRACTOR.");
485
486 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
487 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
488 printRelocationTargetName(Obj, RENext, Fmt);
489 Fmt << "-";
490 printRelocationTargetName(Obj, RE, Fmt);
491 break;
492 }
493 case MachO::X86_64_RELOC_TLV:
494 printRelocationTargetName(Obj, RE, Fmt);
495 Fmt << "@TLV";
496 if (IsPCRel)
497 Fmt << "P";
498 break;
499 case MachO::X86_64_RELOC_SIGNED_1:
500 printRelocationTargetName(Obj, RE, Fmt);
501 Fmt << "-1";
502 break;
503 case MachO::X86_64_RELOC_SIGNED_2:
504 printRelocationTargetName(Obj, RE, Fmt);
505 Fmt << "-2";
506 break;
507 case MachO::X86_64_RELOC_SIGNED_4:
508 printRelocationTargetName(Obj, RE, Fmt);
509 Fmt << "-4";
510 break;
511 default:
512 printRelocationTargetName(Obj, RE, Fmt);
513 break;
514 }
515 // X86 and ARM share some relocation types in common.
516 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
517 Arch == Triple::ppc) {
518 // Generic relocation types...
519 switch (Type) {
520 case MachO::GENERIC_RELOC_PAIR: // prints no info
Fangrui Songf67de6c2019-04-08 16:24:08 +0000521 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000522 case MachO::GENERIC_RELOC_SECTDIFF: {
523 DataRefImpl RelNext = Rel;
524 Obj->moveRelocationNext(RelNext);
525 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
526
527 // X86 sect diff's must be followed by a relocation of type
528 // GENERIC_RELOC_PAIR.
529 unsigned RType = Obj->getAnyRelocationType(RENext);
530
531 if (RType != MachO::GENERIC_RELOC_PAIR)
532 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
533 "GENERIC_RELOC_SECTDIFF.");
534
535 printRelocationTargetName(Obj, RE, Fmt);
536 Fmt << "-";
537 printRelocationTargetName(Obj, RENext, Fmt);
538 break;
539 }
540 }
541
542 if (Arch == Triple::x86 || Arch == Triple::ppc) {
543 switch (Type) {
544 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
545 DataRefImpl RelNext = Rel;
546 Obj->moveRelocationNext(RelNext);
547 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
548
549 // X86 sect diff's must be followed by a relocation of type
550 // GENERIC_RELOC_PAIR.
551 unsigned RType = Obj->getAnyRelocationType(RENext);
552 if (RType != MachO::GENERIC_RELOC_PAIR)
553 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
554 "GENERIC_RELOC_LOCAL_SECTDIFF.");
555
556 printRelocationTargetName(Obj, RE, Fmt);
557 Fmt << "-";
558 printRelocationTargetName(Obj, RENext, Fmt);
559 break;
560 }
561 case MachO::GENERIC_RELOC_TLV: {
562 printRelocationTargetName(Obj, RE, Fmt);
563 Fmt << "@TLV";
564 if (IsPCRel)
565 Fmt << "P";
566 break;
567 }
568 default:
569 printRelocationTargetName(Obj, RE, Fmt);
570 }
571 } else { // ARM-specific relocations
572 switch (Type) {
573 case MachO::ARM_RELOC_HALF:
574 case MachO::ARM_RELOC_HALF_SECTDIFF: {
575 // Half relocations steal a bit from the length field to encode
576 // whether this is an upper16 or a lower16 relocation.
577 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
578
579 if (isUpper)
580 Fmt << ":upper16:(";
581 else
582 Fmt << ":lower16:(";
583 printRelocationTargetName(Obj, RE, Fmt);
584
585 DataRefImpl RelNext = Rel;
586 Obj->moveRelocationNext(RelNext);
587 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
588
589 // ARM half relocs must be followed by a relocation of type
590 // ARM_RELOC_PAIR.
591 unsigned RType = Obj->getAnyRelocationType(RENext);
592 if (RType != MachO::ARM_RELOC_PAIR)
593 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
594 "ARM_RELOC_HALF");
595
596 // NOTE: The half of the target virtual address is stashed in the
597 // address field of the secondary relocation, but we can't reverse
598 // engineer the constant offset from it without decoding the movw/movt
599 // instruction to find the other half in its immediate field.
600
601 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
602 // symbol/section pointer of the follow-on relocation.
603 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
604 Fmt << "-";
605 printRelocationTargetName(Obj, RENext, Fmt);
606 }
607
608 Fmt << ")";
609 break;
610 }
611 default: {
612 printRelocationTargetName(Obj, RE, Fmt);
613 }
614 }
615 }
616 } else
617 printRelocationTargetName(Obj, RE, Fmt);
618
619 Fmt.flush();
620 Result.append(FmtBuf.begin(), FmtBuf.end());
Fangrui Songf67de6c2019-04-08 16:24:08 +0000621 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000622}
623
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000624static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
625 uint32_t n, uint32_t count,
626 uint32_t stride, uint64_t addr) {
627 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
628 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
629 if (n > nindirectsyms)
630 outs() << " (entries start past the end of the indirect symbol "
631 "table) (reserved1 field greater than the table size)";
632 else if (n + count > nindirectsyms)
633 outs() << " (entries extends past the end of the indirect symbol "
634 "table)";
635 outs() << "\n";
636 uint32_t cputype = O->getHeader().cputype;
637 if (cputype & MachO::CPU_ARCH_ABI64)
638 outs() << "address index";
639 else
640 outs() << "address index";
641 if (verbose)
642 outs() << " name\n";
643 else
644 outs() << "\n";
645 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
646 if (cputype & MachO::CPU_ARCH_ABI64)
647 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
648 else
Tim Northover43978372016-04-26 18:29:16 +0000649 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000650 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
651 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
652 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
653 outs() << "LOCAL\n";
654 continue;
655 }
656 if (indirect_symbol ==
657 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
658 outs() << "LOCAL ABSOLUTE\n";
659 continue;
660 }
661 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
662 outs() << "ABSOLUTE\n";
663 continue;
664 }
665 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000666 if (verbose) {
667 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
668 if (indirect_symbol < Symtab.nsyms) {
669 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
670 SymbolRef Symbol = *Sym;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000671 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
Kevin Enderbyf0640752015-03-13 17:56:32 +0000672 } else {
673 outs() << "?";
674 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000675 }
676 outs() << "\n";
677 }
678}
679
680static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000681 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000682 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
683 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
684 for (unsigned J = 0; J < Seg.nsects; ++J) {
685 MachO::section_64 Sec = O->getSection64(Load, J);
686 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
687 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
688 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
689 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
690 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
691 section_type == MachO::S_SYMBOL_STUBS) {
692 uint32_t stride;
693 if (section_type == MachO::S_SYMBOL_STUBS)
694 stride = Sec.reserved2;
695 else
696 stride = 8;
697 if (stride == 0) {
698 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
699 << Sec.sectname << ") "
700 << "(size of stubs in reserved2 field is zero)\n";
701 continue;
702 }
703 uint32_t count = Sec.size / stride;
704 outs() << "Indirect symbols for (" << Sec.segname << ","
705 << Sec.sectname << ") " << count << " entries";
706 uint32_t n = Sec.reserved1;
707 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
708 }
709 }
710 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
711 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
712 for (unsigned J = 0; J < Seg.nsects; ++J) {
713 MachO::section Sec = O->getSection(Load, J);
714 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
715 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
716 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
717 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
718 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
719 section_type == MachO::S_SYMBOL_STUBS) {
720 uint32_t stride;
721 if (section_type == MachO::S_SYMBOL_STUBS)
722 stride = Sec.reserved2;
723 else
724 stride = 4;
725 if (stride == 0) {
726 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
727 << Sec.sectname << ") "
728 << "(size of stubs in reserved2 field is zero)\n";
729 continue;
730 }
731 uint32_t count = Sec.size / stride;
732 outs() << "Indirect symbols for (" << Sec.segname << ","
733 << Sec.sectname << ") " << count << " entries";
734 uint32_t n = Sec.reserved1;
735 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
736 }
737 }
738 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000739 }
740}
741
Michael Trenta1703b12017-12-15 17:57:40 +0000742static void PrintRType(const uint64_t cputype, const unsigned r_type) {
743 static char const *generic_r_types[] = {
744 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
745 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
746 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
747 };
748 static char const *x86_64_r_types[] = {
749 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
750 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
751 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
752 };
753 static char const *arm_r_types[] = {
754 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
755 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
756 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
757 };
758 static char const *arm64_r_types[] = {
759 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
760 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
761 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
762 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000763
Michael Trenta1703b12017-12-15 17:57:40 +0000764 if (r_type > 0xf){
765 outs() << format("%-7u", r_type) << " ";
766 return;
767 }
768 switch (cputype) {
769 case MachO::CPU_TYPE_I386:
770 outs() << generic_r_types[r_type];
771 break;
772 case MachO::CPU_TYPE_X86_64:
773 outs() << x86_64_r_types[r_type];
774 break;
775 case MachO::CPU_TYPE_ARM:
776 outs() << arm_r_types[r_type];
777 break;
778 case MachO::CPU_TYPE_ARM64:
779 outs() << arm64_r_types[r_type];
780 break;
781 default:
782 outs() << format("%-7u ", r_type);
783 }
784}
785
786static void PrintRLength(const uint64_t cputype, const unsigned r_type,
787 const unsigned r_length, const bool previous_arm_half){
788 if (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000789 (r_type == MachO::ARM_RELOC_HALF ||
790 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
Michael Trenta1703b12017-12-15 17:57:40 +0000791 if ((r_length & 0x1) == 0)
792 outs() << "lo/";
793 else
794 outs() << "hi/";
795 if ((r_length & 0x1) == 0)
796 outs() << "arm ";
797 else
798 outs() << "thm ";
799 } else {
800 switch (r_length) {
801 case 0:
802 outs() << "byte ";
803 break;
804 case 1:
805 outs() << "word ";
806 break;
807 case 2:
808 outs() << "long ";
809 break;
810 case 3:
811 if (cputype == MachO::CPU_TYPE_X86_64)
812 outs() << "quad ";
813 else
814 outs() << format("?(%2d) ", r_length);
815 break;
816 default:
817 outs() << format("?(%2d) ", r_length);
818 }
819 }
820}
821
822static void PrintRelocationEntries(const MachOObjectFile *O,
823 const relocation_iterator Begin,
824 const relocation_iterator End,
825 const uint64_t cputype,
826 const bool verbose) {
827 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
828 bool previous_arm_half = false;
829 bool previous_sectdiff = false;
830 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000831
Michael Trenta1703b12017-12-15 17:57:40 +0000832 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
833 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
834 const MachO::any_relocation_info RE = O->getRelocation(Rel);
835 const unsigned r_type = O->getAnyRelocationType(RE);
836 const bool r_scattered = O->isRelocationScattered(RE);
837 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
838 const unsigned r_length = O->getAnyRelocationLength(RE);
839 const unsigned r_address = O->getAnyRelocationAddress(RE);
840 const bool r_extern = (r_scattered ? false :
841 O->getPlainRelocationExternal(RE));
842 const uint32_t r_value = (r_scattered ?
843 O->getScatteredRelocationValue(RE) : 0);
844 const unsigned r_symbolnum = (r_scattered ? 0 :
845 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000846
Michael Trenta1703b12017-12-15 17:57:40 +0000847 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
848 if (verbose) {
849 // scattered: address
850 if ((cputype == MachO::CPU_TYPE_I386 &&
Fangrui Song523758e2019-04-15 15:31:42 +0000851 r_type == MachO::GENERIC_RELOC_PAIR) ||
852 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
Michael Trenta1703b12017-12-15 17:57:40 +0000853 outs() << " ";
854 else
855 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000856
Michael Trenta1703b12017-12-15 17:57:40 +0000857 // scattered: pcrel
858 if (r_pcrel)
859 outs() << "True ";
860 else
861 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000862
Michael Trenta1703b12017-12-15 17:57:40 +0000863 // scattered: length
864 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000865
Michael Trenta1703b12017-12-15 17:57:40 +0000866 // scattered: extern & type
867 outs() << "n/a ";
868 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000869
Michael Trenta1703b12017-12-15 17:57:40 +0000870 // scattered: scattered & value
871 outs() << format("True 0x%08x", (unsigned int)r_value);
872 if (previous_sectdiff == false) {
873 if ((cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000874 r_type == MachO::ARM_RELOC_PAIR))
Michael Trenta1703b12017-12-15 17:57:40 +0000875 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
Fangrui Song523758e2019-04-15 15:31:42 +0000876 } else if (cputype == MachO::CPU_TYPE_ARM &&
877 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
Michael Trenta1703b12017-12-15 17:57:40 +0000878 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
879 if ((cputype == MachO::CPU_TYPE_I386 &&
Fangrui Song523758e2019-04-15 15:31:42 +0000880 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
881 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
Michael Trenta1703b12017-12-15 17:57:40 +0000882 (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000883 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
884 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
885 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
886 previous_sectdiff = true;
887 sectdiff_r_type = r_type;
888 } else {
Michael Trenta1703b12017-12-15 17:57:40 +0000889 previous_sectdiff = false;
890 sectdiff_r_type = 0;
891 }
892 if (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000893 (r_type == MachO::ARM_RELOC_HALF ||
894 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
Michael Trenta1703b12017-12-15 17:57:40 +0000895 previous_arm_half = true;
896 else
897 previous_arm_half = false;
898 outs() << "\n";
899 }
900 else {
901 // scattered: address pcrel length extern type scattered value
902 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
903 (unsigned int)r_address, r_pcrel, r_length, r_type,
904 (unsigned int)r_value);
905 }
906 }
907 else {
908 if (verbose) {
909 // plain: address
Fangrui Song523758e2019-04-15 15:31:42 +0000910 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
Michael Trenta1703b12017-12-15 17:57:40 +0000911 outs() << " ";
912 else
913 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000914
Michael Trenta1703b12017-12-15 17:57:40 +0000915 // plain: pcrel
916 if (r_pcrel)
917 outs() << "True ";
918 else
919 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000920
Michael Trenta1703b12017-12-15 17:57:40 +0000921 // plain: length
922 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000923
Michael Trenta1703b12017-12-15 17:57:40 +0000924 if (r_extern) {
925 // plain: extern & type & scattered
926 outs() << "True ";
927 PrintRType(cputype, r_type);
928 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000929
Michael Trenta1703b12017-12-15 17:57:40 +0000930 // plain: symbolnum/value
931 if (r_symbolnum > Symtab.nsyms)
932 outs() << format("?(%d)\n", r_symbolnum);
933 else {
934 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
935 Expected<StringRef> SymNameNext = Symbol.getName();
936 const char *name = NULL;
937 if (SymNameNext)
938 name = SymNameNext->data();
939 if (name == NULL)
940 outs() << format("?(%d)\n", r_symbolnum);
941 else
942 outs() << name << "\n";
943 }
944 }
945 else {
946 // plain: extern & type & scattered
947 outs() << "False ";
948 PrintRType(cputype, r_type);
949 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000950
Michael Trenta1703b12017-12-15 17:57:40 +0000951 // plain: symbolnum/value
Fangrui Song523758e2019-04-15 15:31:42 +0000952 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
Michael Trenta1703b12017-12-15 17:57:40 +0000953 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
954 else if (cputype == MachO::CPU_TYPE_ARM64 &&
Fangrui Song523758e2019-04-15 15:31:42 +0000955 r_type == MachO::ARM64_RELOC_ADDEND)
Michael Trenta1703b12017-12-15 17:57:40 +0000956 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
957 else {
958 outs() << format("%d ", r_symbolnum);
Fangrui Song523758e2019-04-15 15:31:42 +0000959 if (r_symbolnum == MachO::R_ABS)
Michael Trenta1703b12017-12-15 17:57:40 +0000960 outs() << "R_ABS\n";
961 else {
962 // in this case, r_symbolnum is actually a 1-based section number
963 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
964 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
Fangrui Song523758e2019-04-15 15:31:42 +0000965 object::DataRefImpl DRI;
Michael Trenta1703b12017-12-15 17:57:40 +0000966 DRI.d.a = r_symbolnum-1;
967 StringRef SegName = O->getSectionFinalSegmentName(DRI);
968 StringRef SectName;
969 if (O->getSectionName(DRI, SectName))
970 outs() << "(?,?)\n";
971 else
972 outs() << "(" << SegName << "," << SectName << ")\n";
973 }
974 else {
975 outs() << "(?,?)\n";
976 }
977 }
978 }
979 }
980 if (cputype == MachO::CPU_TYPE_ARM &&
Fangrui Song523758e2019-04-15 15:31:42 +0000981 (r_type == MachO::ARM_RELOC_HALF ||
982 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
Michael Trenta1703b12017-12-15 17:57:40 +0000983 previous_arm_half = true;
984 else
985 previous_arm_half = false;
986 }
987 else {
988 // plain: address pcrel length extern type scattered symbolnum/section
989 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
990 (unsigned int)r_address, r_pcrel, r_length, r_extern,
991 r_type, r_symbolnum);
992 }
993 }
994 }
995}
996
997static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
998 const uint64_t cputype = O->getHeader().cputype;
999 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1000 if (Dysymtab.nextrel != 0) {
1001 outs() << "External relocation information " << Dysymtab.nextrel
1002 << " entries";
1003 outs() << "\naddress pcrel length extern type scattered "
1004 "symbolnum/value\n";
1005 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1006 verbose);
1007 }
1008 if (Dysymtab.nlocrel != 0) {
1009 outs() << format("Local relocation information %u entries",
1010 Dysymtab.nlocrel);
1011 outs() << "\naddress pcrel length extern type scattered "
1012 "symbolnum/value\n";
1013 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1014 verbose);
1015 }
1016 for (const auto &Load : O->load_commands()) {
1017 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1018 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1019 for (unsigned J = 0; J < Seg.nsects; ++J) {
1020 const MachO::section_64 Sec = O->getSection64(Load, J);
1021 if (Sec.nreloc != 0) {
1022 DataRefImpl DRI;
1023 DRI.d.a = J;
1024 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1025 StringRef SectName;
1026 if (O->getSectionName(DRI, SectName))
1027 outs() << "Relocation information (" << SegName << ",?) "
1028 << format("%u entries", Sec.nreloc);
1029 else
1030 outs() << "Relocation information (" << SegName << ","
1031 << SectName << format(") %u entries", Sec.nreloc);
1032 outs() << "\naddress pcrel length extern type scattered "
1033 "symbolnum/value\n";
1034 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1035 O->section_rel_end(DRI), cputype, verbose);
1036 }
1037 }
1038 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1039 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1040 for (unsigned J = 0; J < Seg.nsects; ++J) {
1041 const MachO::section Sec = O->getSection(Load, J);
1042 if (Sec.nreloc != 0) {
1043 DataRefImpl DRI;
1044 DRI.d.a = J;
1045 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1046 StringRef SectName;
1047 if (O->getSectionName(DRI, SectName))
1048 outs() << "Relocation information (" << SegName << ",?) "
1049 << format("%u entries", Sec.nreloc);
1050 else
1051 outs() << "Relocation information (" << SegName << ","
1052 << SectName << format(") %u entries", Sec.nreloc);
1053 outs() << "\naddress pcrel length extern type scattered "
1054 "symbolnum/value\n";
1055 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1056 O->section_rel_end(DRI), cputype, verbose);
1057 }
1058 }
1059 }
1060 }
1061}
1062
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001063static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1064 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1065 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1066 outs() << "Data in code table (" << nentries << " entries)\n";
1067 outs() << "offset length kind\n";
1068 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1069 ++DI) {
1070 uint32_t Offset;
1071 DI->getOffset(Offset);
1072 outs() << format("0x%08" PRIx32, Offset) << " ";
1073 uint16_t Length;
1074 DI->getLength(Length);
1075 outs() << format("%6u", Length) << " ";
1076 uint16_t Kind;
1077 DI->getKind(Kind);
1078 if (verbose) {
1079 switch (Kind) {
1080 case MachO::DICE_KIND_DATA:
1081 outs() << "DATA";
1082 break;
1083 case MachO::DICE_KIND_JUMP_TABLE8:
1084 outs() << "JUMP_TABLE8";
1085 break;
1086 case MachO::DICE_KIND_JUMP_TABLE16:
1087 outs() << "JUMP_TABLE16";
1088 break;
1089 case MachO::DICE_KIND_JUMP_TABLE32:
1090 outs() << "JUMP_TABLE32";
1091 break;
1092 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1093 outs() << "ABS_JUMP_TABLE32";
1094 break;
1095 default:
1096 outs() << format("0x%04" PRIx32, Kind);
1097 break;
1098 }
1099 } else
1100 outs() << format("0x%04" PRIx32, Kind);
1101 outs() << "\n";
1102 }
1103}
1104
Kevin Enderby9a509442015-01-27 21:28:24 +00001105static void PrintLinkOptHints(MachOObjectFile *O) {
1106 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1107 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1108 uint32_t nloh = LohLC.datasize;
1109 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1110 for (uint32_t i = 0; i < nloh;) {
1111 unsigned n;
1112 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1113 i += n;
1114 outs() << " identifier " << identifier << " ";
1115 if (i >= nloh)
1116 return;
1117 switch (identifier) {
1118 case 1:
1119 outs() << "AdrpAdrp\n";
1120 break;
1121 case 2:
1122 outs() << "AdrpLdr\n";
1123 break;
1124 case 3:
1125 outs() << "AdrpAddLdr\n";
1126 break;
1127 case 4:
1128 outs() << "AdrpLdrGotLdr\n";
1129 break;
1130 case 5:
1131 outs() << "AdrpAddStr\n";
1132 break;
1133 case 6:
1134 outs() << "AdrpLdrGotStr\n";
1135 break;
1136 case 7:
1137 outs() << "AdrpAdd\n";
1138 break;
1139 case 8:
1140 outs() << "AdrpLdrGot\n";
1141 break;
1142 default:
1143 outs() << "Unknown identifier value\n";
1144 break;
1145 }
1146 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1147 i += n;
1148 outs() << " narguments " << narguments << "\n";
1149 if (i >= nloh)
1150 return;
1151
1152 for (uint32_t j = 0; j < narguments; j++) {
1153 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1154 i += n;
1155 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1156 if (i >= nloh)
1157 return;
1158 }
1159 }
1160}
1161
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001162static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001163 unsigned Index = 0;
1164 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001165 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1166 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1167 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1168 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1169 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1170 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1171 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1172 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1173 if (dl.dylib.name < dl.cmdsize) {
1174 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1175 if (JustId)
1176 outs() << p << "\n";
1177 else {
1178 outs() << "\t" << p;
1179 outs() << " (compatibility version "
1180 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1181 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1182 << (dl.dylib.compatibility_version & 0xff) << ",";
1183 outs() << " current version "
1184 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1185 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1186 << (dl.dylib.current_version & 0xff) << ")\n";
1187 }
1188 } else {
1189 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1190 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1191 outs() << "LC_ID_DYLIB ";
1192 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1193 outs() << "LC_LOAD_DYLIB ";
1194 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1195 outs() << "LC_LOAD_WEAK_DYLIB ";
1196 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1197 outs() << "LC_LAZY_LOAD_DYLIB ";
1198 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1199 outs() << "LC_REEXPORT_DYLIB ";
1200 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1201 outs() << "LC_LOAD_UPWARD_DYLIB ";
1202 else
1203 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001204 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001205 }
1206 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001207 }
1208}
1209
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001210typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1211
1212static void CreateSymbolAddressMap(MachOObjectFile *O,
1213 SymbolAddressMap *AddrMap) {
1214 // Create a map of symbol addresses to symbol names.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001215 const StringRef FileName = O->getFileName();
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001216 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001217 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001218 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1219 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001220 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001221 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
Kevin Enderby846c0002015-04-16 17:19:59 +00001222 if (!SymName.startswith(".objc"))
1223 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001224 }
1225 }
1226}
1227
1228// GuessSymbolName is passed the address of what might be a symbol and a
1229// pointer to the SymbolAddressMap. It returns the name of a symbol
1230// with that address or nullptr if no symbol is found with that address.
1231static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1232 const char *SymbolName = nullptr;
1233 // A DenseMap can't lookup up some values.
1234 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1235 StringRef name = AddrMap->lookup(value);
1236 if (!name.empty())
1237 SymbolName = name.data();
1238 }
1239 return SymbolName;
1240}
1241
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001242static void DumpCstringChar(const char c) {
1243 char p[2];
1244 p[0] = c;
1245 p[1] = '\0';
1246 outs().write_escaped(p);
1247}
1248
Kevin Enderby10ba0412015-02-04 21:38:42 +00001249static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1250 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001251 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001252 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001253 if (print_addresses) {
1254 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001255 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001256 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001257 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001258 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001259 for (; i < sect_size && sect[i] != '\0'; i++)
1260 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001261 if (i < sect_size && sect[i] == '\0')
1262 outs() << "\n";
1263 }
1264}
1265
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001266static void DumpLiteral4(uint32_t l, float f) {
1267 outs() << format("0x%08" PRIx32, l);
1268 if ((l & 0x7f800000) != 0x7f800000)
1269 outs() << format(" (%.16e)\n", f);
1270 else {
1271 if (l == 0x7f800000)
1272 outs() << " (+Infinity)\n";
1273 else if (l == 0xff800000)
1274 outs() << " (-Infinity)\n";
1275 else if ((l & 0x00400000) == 0x00400000)
1276 outs() << " (non-signaling Not-a-Number)\n";
1277 else
1278 outs() << " (signaling Not-a-Number)\n";
1279 }
1280}
1281
1282static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1283 uint32_t sect_size, uint64_t sect_addr,
1284 bool print_addresses) {
1285 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1286 if (print_addresses) {
1287 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001288 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001289 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001290 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001291 }
1292 float f;
1293 memcpy(&f, sect + i, sizeof(float));
1294 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1295 sys::swapByteOrder(f);
1296 uint32_t l;
1297 memcpy(&l, sect + i, sizeof(uint32_t));
1298 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1299 sys::swapByteOrder(l);
1300 DumpLiteral4(l, f);
1301 }
1302}
1303
1304static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1305 double d) {
1306 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1307 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001308 Hi = (O->isLittleEndian()) ? l1 : l0;
1309 Lo = (O->isLittleEndian()) ? l0 : l1;
1310
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001311 // Hi is the high word, so this is equivalent to if(isfinite(d))
1312 if ((Hi & 0x7ff00000) != 0x7ff00000)
1313 outs() << format(" (%.16e)\n", d);
1314 else {
1315 if (Hi == 0x7ff00000 && Lo == 0)
1316 outs() << " (+Infinity)\n";
1317 else if (Hi == 0xfff00000 && Lo == 0)
1318 outs() << " (-Infinity)\n";
1319 else if ((Hi & 0x00080000) == 0x00080000)
1320 outs() << " (non-signaling Not-a-Number)\n";
1321 else
1322 outs() << " (signaling Not-a-Number)\n";
1323 }
1324}
1325
1326static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1327 uint32_t sect_size, uint64_t sect_addr,
1328 bool print_addresses) {
1329 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1330 if (print_addresses) {
1331 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001332 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001333 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001334 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001335 }
1336 double d;
1337 memcpy(&d, sect + i, sizeof(double));
1338 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1339 sys::swapByteOrder(d);
1340 uint32_t l0, l1;
1341 memcpy(&l0, sect + i, sizeof(uint32_t));
1342 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1343 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1344 sys::swapByteOrder(l0);
1345 sys::swapByteOrder(l1);
1346 }
1347 DumpLiteral8(O, l0, l1, d);
1348 }
1349}
1350
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001351static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1352 outs() << format("0x%08" PRIx32, l0) << " ";
1353 outs() << format("0x%08" PRIx32, l1) << " ";
1354 outs() << format("0x%08" PRIx32, l2) << " ";
1355 outs() << format("0x%08" PRIx32, l3) << "\n";
1356}
1357
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001358static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1359 uint32_t sect_size, uint64_t sect_addr,
1360 bool print_addresses) {
1361 for (uint32_t i = 0; i < sect_size; i += 16) {
1362 if (print_addresses) {
1363 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001364 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001365 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001366 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001367 }
1368 uint32_t l0, l1, l2, l3;
1369 memcpy(&l0, sect + i, sizeof(uint32_t));
1370 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1371 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1372 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1373 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1374 sys::swapByteOrder(l0);
1375 sys::swapByteOrder(l1);
1376 sys::swapByteOrder(l2);
1377 sys::swapByteOrder(l3);
1378 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001379 DumpLiteral16(l0, l1, l2, l3);
1380 }
1381}
1382
1383static void DumpLiteralPointerSection(MachOObjectFile *O,
1384 const SectionRef &Section,
1385 const char *sect, uint32_t sect_size,
1386 uint64_t sect_addr,
1387 bool print_addresses) {
1388 // Collect the literal sections in this Mach-O file.
1389 std::vector<SectionRef> LiteralSections;
1390 for (const SectionRef &Section : O->sections()) {
1391 DataRefImpl Ref = Section.getRawDataRefImpl();
1392 uint32_t section_type;
1393 if (O->is64Bit()) {
1394 const MachO::section_64 Sec = O->getSection64(Ref);
1395 section_type = Sec.flags & MachO::SECTION_TYPE;
1396 } else {
1397 const MachO::section Sec = O->getSection(Ref);
1398 section_type = Sec.flags & MachO::SECTION_TYPE;
1399 }
1400 if (section_type == MachO::S_CSTRING_LITERALS ||
1401 section_type == MachO::S_4BYTE_LITERALS ||
1402 section_type == MachO::S_8BYTE_LITERALS ||
1403 section_type == MachO::S_16BYTE_LITERALS)
1404 LiteralSections.push_back(Section);
1405 }
1406
1407 // Set the size of the literal pointer.
1408 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1409
Eric Christopher572e03a2015-06-19 01:53:21 +00001410 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001411 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1412 for (const RelocationRef &Reloc : Section.relocations()) {
1413 DataRefImpl Rel;
1414 MachO::any_relocation_info RE;
1415 bool isExtern = false;
1416 Rel = Reloc.getRawDataRefImpl();
1417 RE = O->getRelocation(Rel);
1418 isExtern = O->getPlainRelocationExternal(RE);
1419 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001420 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001421 symbol_iterator RelocSym = Reloc.getSymbol();
1422 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1423 }
1424 }
1425 array_pod_sort(Relocs.begin(), Relocs.end());
1426
1427 // Dump each literal pointer.
1428 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1429 if (print_addresses) {
1430 if (O->is64Bit())
1431 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1432 else
1433 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1434 }
1435 uint64_t lp;
1436 if (O->is64Bit()) {
1437 memcpy(&lp, sect + i, sizeof(uint64_t));
1438 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1439 sys::swapByteOrder(lp);
1440 } else {
1441 uint32_t li;
1442 memcpy(&li, sect + i, sizeof(uint32_t));
1443 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1444 sys::swapByteOrder(li);
1445 lp = li;
1446 }
1447
1448 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001449 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1450 return P.first == i;
1451 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001452 if (Reloc != Relocs.end()) {
1453 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001454 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1455 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001456 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001457 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001458
1459 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001460 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1461 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1462 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001463 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001464 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001465 continue;
1466 }
1467
1468 uint64_t SectAddress = Sect->getAddress();
1469 uint64_t SectSize = Sect->getSize();
1470
1471 StringRef SectName;
1472 Sect->getName(SectName);
1473 DataRefImpl Ref = Sect->getRawDataRefImpl();
1474 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1475 outs() << SegmentName << ":" << SectName << ":";
1476
1477 uint32_t section_type;
1478 if (O->is64Bit()) {
1479 const MachO::section_64 Sec = O->getSection64(Ref);
1480 section_type = Sec.flags & MachO::SECTION_TYPE;
1481 } else {
1482 const MachO::section Sec = O->getSection(Ref);
1483 section_type = Sec.flags & MachO::SECTION_TYPE;
1484 }
1485
1486 StringRef BytesStr;
1487 Sect->getContents(BytesStr);
1488 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1489
1490 switch (section_type) {
1491 case MachO::S_CSTRING_LITERALS:
1492 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1493 i++) {
1494 DumpCstringChar(Contents[i]);
1495 }
1496 outs() << "\n";
1497 break;
1498 case MachO::S_4BYTE_LITERALS:
1499 float f;
1500 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1501 uint32_t l;
1502 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1503 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1504 sys::swapByteOrder(f);
1505 sys::swapByteOrder(l);
1506 }
1507 DumpLiteral4(l, f);
1508 break;
1509 case MachO::S_8BYTE_LITERALS: {
1510 double d;
1511 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1512 uint32_t l0, l1;
1513 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1514 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1515 sizeof(uint32_t));
1516 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1517 sys::swapByteOrder(f);
1518 sys::swapByteOrder(l0);
1519 sys::swapByteOrder(l1);
1520 }
1521 DumpLiteral8(O, l0, l1, d);
1522 break;
1523 }
1524 case MachO::S_16BYTE_LITERALS: {
1525 uint32_t l0, l1, l2, l3;
1526 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1527 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1528 sizeof(uint32_t));
1529 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1530 sizeof(uint32_t));
1531 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1532 sizeof(uint32_t));
1533 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1534 sys::swapByteOrder(l0);
1535 sys::swapByteOrder(l1);
1536 sys::swapByteOrder(l2);
1537 sys::swapByteOrder(l3);
1538 }
1539 DumpLiteral16(l0, l1, l2, l3);
1540 break;
1541 }
1542 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001543 }
1544}
1545
Kevin Enderby85b7a662018-03-20 20:29:52 +00001546static void DumpInitTermPointerSection(MachOObjectFile *O,
1547 const SectionRef &Section,
1548 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001549 uint32_t sect_size, uint64_t sect_addr,
1550 SymbolAddressMap *AddrMap,
1551 bool verbose) {
1552 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001553 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001554
1555 // Collect the external relocation symbols for the pointers.
1556 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1557 for (const RelocationRef &Reloc : Section.relocations()) {
1558 DataRefImpl Rel;
1559 MachO::any_relocation_info RE;
1560 bool isExtern = false;
1561 Rel = Reloc.getRawDataRefImpl();
1562 RE = O->getRelocation(Rel);
1563 isExtern = O->getPlainRelocationExternal(RE);
1564 if (isExtern) {
1565 uint64_t RelocOffset = Reloc.getOffset();
1566 symbol_iterator RelocSym = Reloc.getSymbol();
1567 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1568 }
1569 }
1570 array_pod_sort(Relocs.begin(), Relocs.end());
1571
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001572 for (uint32_t i = 0; i < sect_size; i += stride) {
1573 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001574 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001575 if (O->is64Bit()) {
1576 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1577 uint64_t pointer_value;
1578 memcpy(&pointer_value, sect + i, stride);
1579 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1580 sys::swapByteOrder(pointer_value);
1581 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001582 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001583 } else {
1584 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1585 uint32_t pointer_value;
1586 memcpy(&pointer_value, sect + i, stride);
1587 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1588 sys::swapByteOrder(pointer_value);
1589 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001590 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001591 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001592 if (verbose) {
1593 // First look for an external relocation entry for this pointer.
1594 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1595 return P.first == i;
1596 });
1597 if (Reloc != Relocs.end()) {
1598 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001599 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
Kevin Enderby85b7a662018-03-20 20:29:52 +00001600 } else {
1601 SymbolName = GuessSymbolName(p, AddrMap);
1602 if (SymbolName)
1603 outs() << " " << SymbolName;
1604 }
1605 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001606 outs() << "\n";
1607 }
1608}
1609
1610static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1611 uint32_t size, uint64_t addr) {
1612 uint32_t cputype = O->getHeader().cputype;
1613 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1614 uint32_t j;
1615 for (uint32_t i = 0; i < size; i += j, addr += j) {
1616 if (O->is64Bit())
1617 outs() << format("%016" PRIx64, addr) << "\t";
1618 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001619 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001620 for (j = 0; j < 16 && i + j < size; j++) {
1621 uint8_t byte_word = *(sect + i + j);
1622 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1623 }
1624 outs() << "\n";
1625 }
1626 } else {
1627 uint32_t j;
1628 for (uint32_t i = 0; i < size; i += j, addr += j) {
1629 if (O->is64Bit())
1630 outs() << format("%016" PRIx64, addr) << "\t";
1631 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001632 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001633 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1634 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001635 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001636 uint32_t long_word;
1637 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1638 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1639 sys::swapByteOrder(long_word);
1640 outs() << format("%08" PRIx32, long_word) << " ";
1641 } else {
1642 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001643 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001644 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1645 }
1646 }
1647 }
1648 outs() << "\n";
1649 }
1650 }
1651}
1652
Kevin Enderby95df54c2015-02-04 01:01:38 +00001653static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1654 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001655static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1656 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001657#ifdef HAVE_LIBXAR
1658static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1659 uint32_t size, bool verbose,
1660 bool PrintXarHeader, bool PrintXarFileHeaders,
1661 std::string XarMemberName);
1662#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001663
1664static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1665 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001666 SymbolAddressMap AddrMap;
1667 if (verbose)
1668 CreateSymbolAddressMap(O, &AddrMap);
1669
Colin LeMahieufcc32762015-07-29 19:08:10 +00001670 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1671 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001672 std::pair<StringRef, StringRef> DumpSegSectName;
1673 DumpSegSectName = DumpSection.split(',');
1674 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001675 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001676 DumpSegName = DumpSegSectName.first;
1677 DumpSectName = DumpSegSectName.second;
1678 } else {
1679 DumpSegName = "";
1680 DumpSectName = DumpSegSectName.first;
1681 }
1682 for (const SectionRef &Section : O->sections()) {
1683 StringRef SectName;
1684 Section.getName(SectName);
1685 DataRefImpl Ref = Section.getRawDataRefImpl();
1686 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1687 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1688 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001689
Kevin Enderby95df54c2015-02-04 01:01:38 +00001690 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001691 if (O->is64Bit()) {
1692 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001693 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001694
1695 } else {
1696 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001697 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001698 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001699 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001700
1701 StringRef BytesStr;
1702 Section.getContents(BytesStr);
1703 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1704 uint32_t sect_size = BytesStr.size();
1705 uint64_t sect_addr = Section.getAddress();
1706
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001707 outs() << "Contents of (" << SegName << "," << SectName
1708 << ") section\n";
1709
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001710 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001711 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1712 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1713 DisassembleMachO(Filename, O, SegName, SectName);
1714 continue;
1715 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001716 if (SegName == "__TEXT" && SectName == "__info_plist") {
1717 outs() << sect;
1718 continue;
1719 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001720 if (SegName == "__OBJC" && SectName == "__protocol") {
1721 DumpProtocolSection(O, sect, sect_size, sect_addr);
1722 continue;
1723 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001724#ifdef HAVE_LIBXAR
1725 if (SegName == "__LLVM" && SectName == "__bundle") {
1726 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1727 ArchiveHeaders, "");
1728 continue;
1729 }
1730#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001731 switch (section_type) {
1732 case MachO::S_REGULAR:
1733 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1734 break;
1735 case MachO::S_ZEROFILL:
1736 outs() << "zerofill section and has no contents in the file\n";
1737 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001738 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001739 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001740 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001741 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001742 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001743 break;
1744 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001745 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001746 break;
1747 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001748 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1749 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001750 case MachO::S_LITERAL_POINTERS:
1751 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001752 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001753 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001754 case MachO::S_MOD_INIT_FUNC_POINTERS:
1755 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001756 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1757 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001758 break;
1759 default:
1760 outs() << "Unknown section type ("
1761 << format("0x%08" PRIx32, section_type) << ")\n";
1762 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1763 break;
1764 }
1765 } else {
1766 if (section_type == MachO::S_ZEROFILL)
1767 outs() << "zerofill section and has no contents in the file\n";
1768 else
1769 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1770 }
1771 }
1772 }
1773 }
1774}
1775
Kevin Enderbycd66be52015-03-11 22:06:32 +00001776static void DumpInfoPlistSectionContents(StringRef Filename,
1777 MachOObjectFile *O) {
1778 for (const SectionRef &Section : O->sections()) {
1779 StringRef SectName;
1780 Section.getName(SectName);
1781 DataRefImpl Ref = Section.getRawDataRefImpl();
1782 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1783 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001784 if (!NoLeadingHeaders)
1785 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001786 StringRef BytesStr;
1787 Section.getContents(BytesStr);
1788 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001789 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001790 return;
1791 }
1792 }
1793}
1794
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001795// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1796// and if it is and there is a list of architecture flags is specified then
1797// check to make sure this Mach-O file is one of those architectures or all
1798// architectures were specified. If not then an error is generated and this
1799// routine returns false. Else it returns true.
1800static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001801 auto *MachO = dyn_cast<MachOObjectFile>(O);
1802
1803 if (!MachO || ArchAll || ArchFlags.empty())
1804 return true;
1805
1806 MachO::mach_header H;
1807 MachO::mach_header_64 H_64;
1808 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001809 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001810 if (MachO->is64Bit()) {
1811 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001812 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1813 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001814 } else {
1815 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001816 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1817 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001818 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001819 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001820 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001821 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001822 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001823 WithColor::error(errs(), "llvm-objdump")
1824 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001825 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001826 }
1827 return true;
1828}
1829
Kevin Enderby0fc11822015-04-01 20:57:01 +00001830static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1831
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001832// ProcessMachO() is passed a single opened Mach-O file, which may be an
1833// archive member and or in a slice of a universal file. It prints the
1834// the file name and header info and then processes it according to the
1835// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001836static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001837 StringRef ArchiveMemberName = StringRef(),
1838 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001839 // If we are doing some processing here on the Mach-O file print the header
1840 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001841 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001842 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1843 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1844 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001845 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001846 if (!NoLeadingHeaders) {
1847 outs() << Name;
1848 if (!ArchiveMemberName.empty())
1849 outs() << '(' << ArchiveMemberName << ')';
1850 if (!ArchitectureName.empty())
1851 outs() << " (architecture " << ArchitectureName << ")";
1852 outs() << ":\n";
1853 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001854 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001855 // To use the report_error() form with an ArchiveName and FileName set
1856 // these up based on what is passed for Name and ArchiveMemberName.
1857 StringRef ArchiveName;
1858 StringRef FileName;
1859 if (!ArchiveMemberName.empty()) {
1860 ArchiveName = Name;
1861 FileName = ArchiveMemberName;
1862 } else {
1863 ArchiveName = StringRef();
1864 FileName = Name;
1865 }
1866
1867 // If we need the symbol table to do the operation then check it here to
1868 // produce a good error message as to where the Mach-O file comes from in
1869 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001870 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001871 if (Error Err = MachOOF->checkSymbolTable())
Fangrui Songe7834bd2019-04-07 08:19:55 +00001872 report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1873
Michael Trent7e660212019-01-15 20:41:30 +00001874 if (DisassembleAll) {
1875 for (const SectionRef &Section : MachOOF->sections()) {
1876 StringRef SectName;
1877 Section.getName(SectName);
1878 if (SectName.equals("__text")) {
1879 DataRefImpl Ref = Section.getRawDataRefImpl();
1880 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1881 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1882 }
1883 }
1884 }
1885 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001886 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001887 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001888 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1889 else
1890 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1891 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001892 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001893 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001894 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001895 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001896 if (LinkOptHints)
1897 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001898 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001899 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001900 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001901 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001902 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001903 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001904 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001905 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001906 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001907 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001908 if (DylibsUsed)
1909 PrintDylibs(MachOOF, false);
1910 if (DylibId)
1911 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001912 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001913 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001914 if (UnwindInfo)
1915 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001916 if (PrivateHeaders) {
1917 printMachOFileHeader(MachOOF);
1918 printMachOLoadCommands(MachOOF);
1919 }
1920 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001921 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001922 if (ObjcMetaData)
1923 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001924 if (ExportsTrie)
1925 printExportsTrie(MachOOF);
1926 if (Rebase)
1927 printRebaseTable(MachOOF);
1928 if (Bind)
1929 printBindTable(MachOOF);
1930 if (LazyBind)
1931 printLazyBindTable(MachOOF);
1932 if (WeakBind)
1933 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001934
1935 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001936 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001937 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001938 DIDumpOptions DumpOpts;
1939 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001940 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001941 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001942}
1943
Kevin Enderby131d1772015-01-09 19:22:37 +00001944// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1945static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1946 outs() << " cputype (" << cputype << ")\n";
1947 outs() << " cpusubtype (" << cpusubtype << ")\n";
1948}
1949
1950// printCPUType() helps print_fat_headers by printing the cputype and
1951// pusubtype (symbolically for the one's it knows about).
1952static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1953 switch (cputype) {
1954 case MachO::CPU_TYPE_I386:
1955 switch (cpusubtype) {
1956 case MachO::CPU_SUBTYPE_I386_ALL:
1957 outs() << " cputype CPU_TYPE_I386\n";
1958 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1959 break;
1960 default:
1961 printUnknownCPUType(cputype, cpusubtype);
1962 break;
1963 }
1964 break;
1965 case MachO::CPU_TYPE_X86_64:
1966 switch (cpusubtype) {
1967 case MachO::CPU_SUBTYPE_X86_64_ALL:
1968 outs() << " cputype CPU_TYPE_X86_64\n";
1969 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1970 break;
1971 case MachO::CPU_SUBTYPE_X86_64_H:
1972 outs() << " cputype CPU_TYPE_X86_64\n";
1973 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1974 break;
1975 default:
1976 printUnknownCPUType(cputype, cpusubtype);
1977 break;
1978 }
1979 break;
1980 case MachO::CPU_TYPE_ARM:
1981 switch (cpusubtype) {
1982 case MachO::CPU_SUBTYPE_ARM_ALL:
1983 outs() << " cputype CPU_TYPE_ARM\n";
1984 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1985 break;
1986 case MachO::CPU_SUBTYPE_ARM_V4T:
1987 outs() << " cputype CPU_TYPE_ARM\n";
1988 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1989 break;
1990 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1991 outs() << " cputype CPU_TYPE_ARM\n";
1992 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1993 break;
1994 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1995 outs() << " cputype CPU_TYPE_ARM\n";
1996 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1997 break;
1998 case MachO::CPU_SUBTYPE_ARM_V6:
1999 outs() << " cputype CPU_TYPE_ARM\n";
2000 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2001 break;
2002 case MachO::CPU_SUBTYPE_ARM_V6M:
2003 outs() << " cputype CPU_TYPE_ARM\n";
2004 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2005 break;
2006 case MachO::CPU_SUBTYPE_ARM_V7:
2007 outs() << " cputype CPU_TYPE_ARM\n";
2008 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2009 break;
2010 case MachO::CPU_SUBTYPE_ARM_V7EM:
2011 outs() << " cputype CPU_TYPE_ARM\n";
2012 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2013 break;
2014 case MachO::CPU_SUBTYPE_ARM_V7K:
2015 outs() << " cputype CPU_TYPE_ARM\n";
2016 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2017 break;
2018 case MachO::CPU_SUBTYPE_ARM_V7M:
2019 outs() << " cputype CPU_TYPE_ARM\n";
2020 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2021 break;
2022 case MachO::CPU_SUBTYPE_ARM_V7S:
2023 outs() << " cputype CPU_TYPE_ARM\n";
2024 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2025 break;
2026 default:
2027 printUnknownCPUType(cputype, cpusubtype);
2028 break;
2029 }
2030 break;
2031 case MachO::CPU_TYPE_ARM64:
2032 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2033 case MachO::CPU_SUBTYPE_ARM64_ALL:
2034 outs() << " cputype CPU_TYPE_ARM64\n";
2035 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2036 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00002037 case MachO::CPU_SUBTYPE_ARM64E:
2038 outs() << " cputype CPU_TYPE_ARM64\n";
2039 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2040 break;
Kevin Enderby131d1772015-01-09 19:22:37 +00002041 default:
2042 printUnknownCPUType(cputype, cpusubtype);
2043 break;
2044 }
2045 break;
2046 default:
2047 printUnknownCPUType(cputype, cpusubtype);
2048 break;
2049 }
2050}
2051
2052static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2053 bool verbose) {
2054 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002055 if (verbose) {
2056 if (UB->getMagic() == MachO::FAT_MAGIC)
2057 outs() << "fat_magic FAT_MAGIC\n";
2058 else // UB->getMagic() == MachO::FAT_MAGIC_64
2059 outs() << "fat_magic FAT_MAGIC_64\n";
2060 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002061 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2062
2063 uint32_t nfat_arch = UB->getNumberOfObjects();
2064 StringRef Buf = UB->getData();
2065 uint64_t size = Buf.size();
2066 uint64_t big_size = sizeof(struct MachO::fat_header) +
2067 nfat_arch * sizeof(struct MachO::fat_arch);
2068 outs() << "nfat_arch " << UB->getNumberOfObjects();
2069 if (nfat_arch == 0)
2070 outs() << " (malformed, contains zero architecture types)\n";
2071 else if (big_size > size)
2072 outs() << " (malformed, architectures past end of file)\n";
2073 else
2074 outs() << "\n";
2075
2076 for (uint32_t i = 0; i < nfat_arch; ++i) {
2077 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2078 uint32_t cputype = OFA.getCPUType();
2079 uint32_t cpusubtype = OFA.getCPUSubType();
2080 outs() << "architecture ";
2081 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2082 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2083 uint32_t other_cputype = other_OFA.getCPUType();
2084 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002085 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002086 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002087 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002088 outs() << "(illegal duplicate architecture) ";
2089 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002090 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002091 }
2092 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002093 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002094 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2095 } else {
2096 outs() << i << "\n";
2097 outs() << " cputype " << cputype << "\n";
2098 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2099 << "\n";
2100 }
2101 if (verbose &&
2102 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2103 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2104 else
2105 outs() << " capabilities "
2106 << format("0x%" PRIx32,
2107 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2108 outs() << " offset " << OFA.getOffset();
2109 if (OFA.getOffset() > size)
2110 outs() << " (past end of file)";
2111 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2112 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2113 outs() << "\n";
2114 outs() << " size " << OFA.getSize();
2115 big_size = OFA.getOffset() + OFA.getSize();
2116 if (big_size > size)
2117 outs() << " (past end of file)";
2118 outs() << "\n";
2119 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2120 << ")\n";
2121 }
2122}
2123
Kevin Enderby6524bd82016-07-19 20:47:07 +00002124static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2125 bool verbose, bool print_offset,
2126 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002127 if (print_offset)
2128 outs() << C.getChildOffset() << "\t";
Fangrui Songe7834bd2019-04-07 08:19:55 +00002129 sys::fs::perms Mode =
2130 unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002131 if (verbose) {
2132 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2133 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2134 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002135 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2136 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2137 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2138 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2139 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2140 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2141 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2142 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2143 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002144 } else {
2145 outs() << format("0%o ", Mode);
2146 }
2147
Fangrui Songe7834bd2019-04-07 08:19:55 +00002148 outs() << format(
2149 "%3d/%-3d %5" PRId64 " ",
2150 unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2151 unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2152 unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
Kevin Enderby13023a12015-01-15 23:19:11 +00002153
2154 StringRef RawLastModified = C.getRawLastModified();
2155 if (verbose) {
2156 unsigned Seconds;
2157 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002158 outs() << "(date: \"" << RawLastModified
2159 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002160 else {
2161 // Since cime(3) returns a 26 character string of the form:
2162 // "Sun Sep 16 01:03:52 1973\n\0"
2163 // just print 24 characters.
2164 time_t t = Seconds;
2165 outs() << format("%.24s ", ctime(&t));
2166 }
2167 } else {
2168 outs() << RawLastModified << " ";
2169 }
2170
2171 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002172 Expected<StringRef> NameOrErr = C.getName();
2173 if (!NameOrErr) {
2174 consumeError(NameOrErr.takeError());
Fangrui Songe7834bd2019-04-07 08:19:55 +00002175 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2176 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002177 } else {
2178 StringRef Name = NameOrErr.get();
2179 outs() << Name << "\n";
2180 }
2181 } else {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002182 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2183 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002184 }
2185}
2186
Kevin Enderby6524bd82016-07-19 20:47:07 +00002187static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2188 bool print_offset,
2189 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002190 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002191 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002192 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2193
Lang Hamesfc209622016-07-14 02:24:01 +00002194 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002195 report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002196}
2197
Dave Lee3fb120f2018-08-03 00:06:38 +00002198static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002199 // Check for -arch all and verifiy the -arch flags are valid.
2200 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2201 if (ArchFlags[i] == "all") {
2202 ArchAll = true;
2203 } else {
2204 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002205 WithColor::error(errs(), "llvm-objdump")
2206 << "unknown architecture named '" + ArchFlags[i] +
2207 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002208 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002209 }
2210 }
2211 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002212 return true;
2213}
2214
2215// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2216// -arch flags selecting just those slices as specified by them and also parses
2217// archive files. Then for each individual Mach-O file ProcessMachO() is
2218// called to process the file based on the command line options.
Fangrui Song523758e2019-04-15 15:31:42 +00002219void parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002220 if (!ValidateArchFlags())
2221 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002222
2223 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002224 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002225 if (!BinaryOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002226 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2227 report_error(std::move(E), Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002228 else
2229 outs() << Filename << ": is not an object file\n";
2230 return;
2231 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002232 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002233
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002234 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2235 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002236 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002237 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2238
Mehdi Amini41af4302016-11-11 04:28:40 +00002239 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002240 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002241 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2242 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002243 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2244 report_error(std::move(E), Filename, C);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002245 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002246 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002247 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2248 if (!checkMachOAndArchFlags(O, Filename))
2249 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002250 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002251 }
2252 }
Lang Hamesfc209622016-07-14 02:24:01 +00002253 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002254 report_error(std::move(Err), Filename);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002255 return;
2256 }
2257 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002258 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002259 return;
2260 }
2261 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2262 if (!checkMachOAndArchFlags(O, Filename))
2263 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002264 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002265 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002266 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002267 WithColor::error(errs(), "llvm-objdump")
2268 << Filename << "': "
2269 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002270 return;
2271 }
2272 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002273}
2274
Fangrui Song523758e2019-04-15 15:31:42 +00002275void parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002276 if (!ValidateArchFlags())
2277 return;
2278
2279 auto Filename = UB->getFileName();
2280
2281 if (UniversalHeaders)
2282 printMachOUniversalHeaders(UB, !NonVerbose);
2283
2284 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002285 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002286 // Look for a slice in the universal binary that matches each ArchFlag.
2287 bool ArchFound;
2288 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2289 ArchFound = false;
2290 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2291 E = UB->end_objects();
2292 I != E; ++I) {
2293 if (ArchFlags[i] == I->getArchFlagName()) {
2294 ArchFound = true;
2295 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2296 I->getAsObjectFile();
2297 std::string ArchitectureName = "";
2298 if (ArchFlags.size() > 1)
2299 ArchitectureName = I->getArchFlagName();
2300 if (ObjOrErr) {
2301 ObjectFile &O = *ObjOrErr.get();
2302 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2303 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002304 } else if (Error E = isNotObjectErrorInvalidFileType(
2305 ObjOrErr.takeError())) {
2306 report_error(std::move(E), Filename, StringRef(), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002307 continue;
2308 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002309 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002310 std::unique_ptr<Archive> &A = *AOrErr;
2311 outs() << "Archive : " << Filename;
2312 if (!ArchitectureName.empty())
2313 outs() << " (architecture " << ArchitectureName << ")";
2314 outs() << "\n";
2315 if (ArchiveHeaders)
2316 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2317 ArchiveMemberOffsets, ArchitectureName);
2318 Error Err = Error::success();
2319 for (auto &C : A->children(Err)) {
2320 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2321 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002322 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2323 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002324 continue;
2325 }
2326 if (MachOObjectFile *O =
2327 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2328 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2329 }
2330 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002331 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002332 } else {
2333 consumeError(AOrErr.takeError());
2334 error("Mach-O universal file: " + Filename + " for " +
2335 "architecture " + StringRef(I->getArchFlagName()) +
2336 " is not a Mach-O file or an archive file");
2337 }
2338 }
2339 }
2340 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002341 WithColor::error(errs(), "llvm-objdump")
2342 << "file: " + Filename + " does not contain "
2343 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002344 return;
2345 }
2346 }
2347 return;
2348 }
2349 // No architecture flags were specified so if this contains a slice that
2350 // matches the host architecture dump only that.
2351 if (!ArchAll) {
2352 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2353 E = UB->end_objects();
2354 I != E; ++I) {
2355 if (MachOObjectFile::getHostArch().getArchName() ==
2356 I->getArchFlagName()) {
2357 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2358 std::string ArchiveName;
2359 ArchiveName.clear();
2360 if (ObjOrErr) {
2361 ObjectFile &O = *ObjOrErr.get();
2362 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2363 ProcessMachO(Filename, MachOOF);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002364 } else if (Error E =
2365 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2366 report_error(std::move(E), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002367 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002368 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002369 std::unique_ptr<Archive> &A = *AOrErr;
2370 outs() << "Archive : " << Filename << "\n";
2371 if (ArchiveHeaders)
2372 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2373 ArchiveMemberOffsets);
2374 Error Err = Error::success();
2375 for (auto &C : A->children(Err)) {
2376 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2377 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002378 if (Error E =
2379 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2380 report_error(std::move(E), Filename, C);
Dave Lee3fb120f2018-08-03 00:06:38 +00002381 continue;
2382 }
2383 if (MachOObjectFile *O =
2384 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2385 ProcessMachO(Filename, O, O->getFileName());
2386 }
2387 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002388 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002389 } else {
2390 consumeError(AOrErr.takeError());
2391 error("Mach-O universal file: " + Filename + " for architecture " +
2392 StringRef(I->getArchFlagName()) +
2393 " is not a Mach-O file or an archive file");
2394 }
2395 return;
2396 }
2397 }
2398 }
2399 // Either all architectures have been specified or none have been specified
2400 // and this does not contain the host architecture so dump all the slices.
2401 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2402 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2403 E = UB->end_objects();
2404 I != E; ++I) {
2405 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2406 std::string ArchitectureName = "";
2407 if (moreThanOneArch)
2408 ArchitectureName = I->getArchFlagName();
2409 if (ObjOrErr) {
2410 ObjectFile &Obj = *ObjOrErr.get();
2411 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2412 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002413 } else if (Error E =
2414 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2415 report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2416 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002417 std::unique_ptr<Archive> &A = *AOrErr;
2418 outs() << "Archive : " << Filename;
2419 if (!ArchitectureName.empty())
2420 outs() << " (architecture " << ArchitectureName << ")";
2421 outs() << "\n";
2422 if (ArchiveHeaders)
2423 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2424 ArchiveMemberOffsets, ArchitectureName);
2425 Error Err = Error::success();
2426 for (auto &C : A->children(Err)) {
2427 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2428 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002429 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2430 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002431 continue;
2432 }
2433 if (MachOObjectFile *O =
2434 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2435 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2436 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2437 ArchitectureName);
2438 }
2439 }
2440 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002441 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002442 } else {
2443 consumeError(AOrErr.takeError());
2444 error("Mach-O universal file: " + Filename + " for architecture " +
2445 StringRef(I->getArchFlagName()) +
2446 " is not a Mach-O file or an archive file");
2447 }
2448 }
2449}
2450
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002451// The block of info used by the Symbolizer call backs.
2452struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002453 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2454 std::vector<SectionRef> *Sections, bool verbose)
2455 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002456 bool verbose;
2457 MachOObjectFile *O;
2458 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002459 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002460 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002461 const char *class_name = nullptr;
2462 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002463 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002464 char *demangled_name = nullptr;
2465 uint64_t adrp_addr = 0;
2466 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002467 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002468 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002469};
2470
2471// SymbolizerGetOpInfo() is the operand information call back function.
2472// This is called to get the symbolic information for operand(s) of an
2473// instruction when it is being done. This routine does this from
2474// the relocation information, symbol table, etc. That block of information
2475// is a pointer to the struct DisassembleInfo that was passed when the
2476// disassembler context was created and passed to back to here when
2477// called back by the disassembler for instruction operands that could have
2478// relocation information. The address of the instruction containing operand is
2479// at the Pc parameter. The immediate value the operand has is passed in
2480// op_info->Value and is at Offset past the start of the instruction and has a
2481// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2482// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2483// names and addends of the symbolic expression to add for the operand. The
2484// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2485// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002486static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2487 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002488 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2489 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002490 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002491
2492 // Make sure all fields returned are zero if we don't set them.
2493 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2494 op_info->Value = value;
2495
2496 // If the TagType is not the value 1 which it code knows about or if no
2497 // verbose symbolic information is wanted then just return 0, indicating no
2498 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002499 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002500 return 0;
2501
2502 unsigned int Arch = info->O->getArch();
2503 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002504 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2505 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002506 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2507 // TODO:
2508 // Search the external relocation entries of a fully linked image
2509 // (if any) for an entry that matches this segment offset.
2510 // uint32_t seg_offset = (Pc + Offset);
2511 return 0;
2512 }
2513 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2514 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002515 uint32_t sect_addr = info->S.getAddress();
2516 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2517 bool reloc_found = false;
2518 DataRefImpl Rel;
2519 MachO::any_relocation_info RE;
2520 bool isExtern = false;
2521 SymbolRef Symbol;
2522 bool r_scattered = false;
2523 uint32_t r_value, pair_r_value, r_type;
2524 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002525 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002526 if (RelocOffset == sect_offset) {
2527 Rel = Reloc.getRawDataRefImpl();
2528 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002529 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002530 r_scattered = info->O->isRelocationScattered(RE);
2531 if (r_scattered) {
2532 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002533 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2534 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2535 DataRefImpl RelNext = Rel;
2536 info->O->moveRelocationNext(RelNext);
2537 MachO::any_relocation_info RENext;
2538 RENext = info->O->getRelocation(RelNext);
2539 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002540 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002541 else
2542 return 0;
2543 }
2544 } else {
2545 isExtern = info->O->getPlainRelocationExternal(RE);
2546 if (isExtern) {
2547 symbol_iterator RelocSym = Reloc.getSymbol();
2548 Symbol = *RelocSym;
2549 }
2550 }
2551 reloc_found = true;
2552 break;
2553 }
2554 }
2555 if (reloc_found && isExtern) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002556 op_info->AddSymbol.Present = 1;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002557 op_info->AddSymbol.Name =
2558 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002559 // For i386 extern relocation entries the value in the instruction is
2560 // the offset from the symbol, and value is already set in op_info->Value.
2561 return 1;
2562 }
2563 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2564 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002565 const char *add = GuessSymbolName(r_value, info->AddrMap);
2566 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002567 uint32_t offset = value - (r_value - pair_r_value);
2568 op_info->AddSymbol.Present = 1;
2569 if (add != nullptr)
2570 op_info->AddSymbol.Name = add;
2571 else
2572 op_info->AddSymbol.Value = r_value;
2573 op_info->SubtractSymbol.Present = 1;
2574 if (sub != nullptr)
2575 op_info->SubtractSymbol.Name = sub;
2576 else
2577 op_info->SubtractSymbol.Value = pair_r_value;
2578 op_info->Value = offset;
2579 return 1;
2580 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002581 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002582 }
2583 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002584 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2585 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002586 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2587 // relocation entries of a linked image (if any) for an entry that matches
2588 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002589 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002590 uint64_t seg_offset = Pc + Offset;
2591 bool reloc_found = false;
2592 DataRefImpl Rel;
2593 MachO::any_relocation_info RE;
2594 bool isExtern = false;
2595 SymbolRef Symbol;
2596 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2597 uint64_t RelocOffset = Reloc.getOffset();
2598 if (RelocOffset == seg_offset) {
2599 Rel = Reloc.getRawDataRefImpl();
2600 RE = info->O->getRelocation(Rel);
2601 // external relocation entries should always be external.
2602 isExtern = info->O->getPlainRelocationExternal(RE);
2603 if (isExtern) {
2604 symbol_iterator RelocSym = Reloc.getSymbol();
2605 Symbol = *RelocSym;
2606 }
2607 reloc_found = true;
2608 break;
2609 }
2610 }
2611 if (reloc_found && isExtern) {
2612 // The Value passed in will be adjusted by the Pc if the instruction
2613 // adds the Pc. But for x86_64 external relocation entries the Value
2614 // is the offset from the external symbol.
2615 if (info->O->getAnyRelocationPCRel(RE))
2616 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002617 const char *name =
2618 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002619 op_info->AddSymbol.Present = 1;
2620 op_info->AddSymbol.Name = name;
2621 return 1;
2622 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002623 return 0;
2624 }
2625 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2626 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002627 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002628 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2629 bool reloc_found = false;
2630 DataRefImpl Rel;
2631 MachO::any_relocation_info RE;
2632 bool isExtern = false;
2633 SymbolRef Symbol;
2634 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002635 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002636 if (RelocOffset == sect_offset) {
2637 Rel = Reloc.getRawDataRefImpl();
2638 RE = info->O->getRelocation(Rel);
2639 // NOTE: Scattered relocations don't exist on x86_64.
2640 isExtern = info->O->getPlainRelocationExternal(RE);
2641 if (isExtern) {
2642 symbol_iterator RelocSym = Reloc.getSymbol();
2643 Symbol = *RelocSym;
2644 }
2645 reloc_found = true;
2646 break;
2647 }
2648 }
2649 if (reloc_found && isExtern) {
2650 // The Value passed in will be adjusted by the Pc if the instruction
2651 // adds the Pc. But for x86_64 external relocation entries the Value
2652 // is the offset from the external symbol.
2653 if (info->O->getAnyRelocationPCRel(RE))
2654 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002655 const char *name =
2656 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002657 unsigned Type = info->O->getAnyRelocationType(RE);
2658 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2659 DataRefImpl RelNext = Rel;
2660 info->O->moveRelocationNext(RelNext);
2661 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2662 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2663 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2664 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2665 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2666 op_info->SubtractSymbol.Present = 1;
2667 op_info->SubtractSymbol.Name = name;
2668 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2669 Symbol = *RelocSymNext;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002670 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002671 }
2672 }
2673 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2674 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2675 op_info->AddSymbol.Present = 1;
2676 op_info->AddSymbol.Name = name;
2677 return 1;
2678 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002679 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002680 }
2681 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002682 if (Offset != 0 || (Size != 4 && Size != 2))
2683 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002684 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2685 // TODO:
2686 // Search the external relocation entries of a fully linked image
2687 // (if any) for an entry that matches this segment offset.
2688 // uint32_t seg_offset = (Pc + Offset);
2689 return 0;
2690 }
2691 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2692 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002693 uint32_t sect_addr = info->S.getAddress();
2694 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002695 DataRefImpl Rel;
2696 MachO::any_relocation_info RE;
2697 bool isExtern = false;
2698 SymbolRef Symbol;
2699 bool r_scattered = false;
2700 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002701 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002702 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2703 uint64_t RelocOffset = Reloc.getOffset();
2704 return RelocOffset == sect_offset;
2705 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002706
2707 if (Reloc == info->S.relocations().end())
2708 return 0;
2709
2710 Rel = Reloc->getRawDataRefImpl();
2711 RE = info->O->getRelocation(Rel);
2712 r_length = info->O->getAnyRelocationLength(RE);
2713 r_scattered = info->O->isRelocationScattered(RE);
2714 if (r_scattered) {
2715 r_value = info->O->getScatteredRelocationValue(RE);
2716 r_type = info->O->getScatteredRelocationType(RE);
2717 } else {
2718 r_type = info->O->getAnyRelocationType(RE);
2719 isExtern = info->O->getPlainRelocationExternal(RE);
2720 if (isExtern) {
2721 symbol_iterator RelocSym = Reloc->getSymbol();
2722 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002723 }
2724 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002725 if (r_type == MachO::ARM_RELOC_HALF ||
2726 r_type == MachO::ARM_RELOC_SECTDIFF ||
2727 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2728 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2729 DataRefImpl RelNext = Rel;
2730 info->O->moveRelocationNext(RelNext);
2731 MachO::any_relocation_info RENext;
2732 RENext = info->O->getRelocation(RelNext);
2733 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2734 if (info->O->isRelocationScattered(RENext))
2735 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2736 }
2737
2738 if (isExtern) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002739 const char *name =
2740 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002741 op_info->AddSymbol.Present = 1;
2742 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002743 switch (r_type) {
2744 case MachO::ARM_RELOC_HALF:
2745 if ((r_length & 0x1) == 1) {
2746 op_info->Value = value << 16 | other_half;
2747 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2748 } else {
2749 op_info->Value = other_half << 16 | value;
2750 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002751 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002752 break;
2753 default:
2754 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002755 }
2756 return 1;
2757 }
2758 // If we have a branch that is not an external relocation entry then
2759 // return 0 so the code in tryAddingSymbolicOperand() can use the
2760 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002761 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002762 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2763 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002764 return 0;
2765
2766 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002767 if (r_type == MachO::ARM_RELOC_HALF ||
2768 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2769 if ((r_length & 0x1) == 1)
2770 value = value << 16 | other_half;
2771 else
2772 value = other_half << 16 | value;
2773 }
2774 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2775 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2776 offset = value - r_value;
2777 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002778 }
2779
David Blaikie33dd45d02015-03-23 18:39:02 +00002780 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002781 if ((r_length & 0x1) == 1)
2782 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2783 else
2784 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002785 const char *add = GuessSymbolName(r_value, info->AddrMap);
2786 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002787 int32_t offset = value - (r_value - pair_r_value);
2788 op_info->AddSymbol.Present = 1;
2789 if (add != nullptr)
2790 op_info->AddSymbol.Name = add;
2791 else
2792 op_info->AddSymbol.Value = r_value;
2793 op_info->SubtractSymbol.Present = 1;
2794 if (sub != nullptr)
2795 op_info->SubtractSymbol.Name = sub;
2796 else
2797 op_info->SubtractSymbol.Value = pair_r_value;
2798 op_info->Value = offset;
2799 return 1;
2800 }
2801
Kevin Enderby930fdc72014-11-06 19:00:13 +00002802 op_info->AddSymbol.Present = 1;
2803 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002804 if (r_type == MachO::ARM_RELOC_HALF) {
2805 if ((r_length & 0x1) == 1)
2806 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2807 else
2808 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002809 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002810 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002811 if (add != nullptr) {
2812 op_info->AddSymbol.Name = add;
2813 return 1;
2814 }
2815 op_info->AddSymbol.Value = value;
2816 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002817 }
2818 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002819 if (Offset != 0 || Size != 4)
2820 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002821 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2822 // TODO:
2823 // Search the external relocation entries of a fully linked image
2824 // (if any) for an entry that matches this segment offset.
2825 // uint64_t seg_offset = (Pc + Offset);
2826 return 0;
2827 }
2828 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2829 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002830 uint64_t sect_addr = info->S.getAddress();
2831 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002832 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002833 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2834 uint64_t RelocOffset = Reloc.getOffset();
2835 return RelocOffset == sect_offset;
2836 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002837
David Blaikie33dd45d02015-03-23 18:39:02 +00002838 if (Reloc == info->S.relocations().end())
2839 return 0;
2840
2841 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2842 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2843 uint32_t r_type = info->O->getAnyRelocationType(RE);
2844 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2845 DataRefImpl RelNext = Rel;
2846 info->O->moveRelocationNext(RelNext);
2847 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2848 if (value == 0) {
2849 value = info->O->getPlainRelocationSymbolNum(RENext);
2850 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002851 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002852 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002853 // NOTE: Scattered relocations don't exist on arm64.
2854 if (!info->O->getPlainRelocationExternal(RE))
2855 return 0;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002856 const char *name =
2857 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2858 .data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002859 op_info->AddSymbol.Present = 1;
2860 op_info->AddSymbol.Name = name;
2861
2862 switch (r_type) {
2863 case MachO::ARM64_RELOC_PAGE21:
2864 /* @page */
2865 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2866 break;
2867 case MachO::ARM64_RELOC_PAGEOFF12:
2868 /* @pageoff */
2869 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2870 break;
2871 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2872 /* @gotpage */
2873 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2874 break;
2875 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2876 /* @gotpageoff */
2877 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2878 break;
2879 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2880 /* @tvlppage is not implemented in llvm-mc */
2881 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2882 break;
2883 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2884 /* @tvlppageoff is not implemented in llvm-mc */
2885 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2886 break;
2887 default:
2888 case MachO::ARM64_RELOC_BRANCH26:
2889 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2890 break;
2891 }
2892 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002893 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002894 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002895}
2896
Kevin Enderbybf246f52014-09-24 23:08:22 +00002897// GuessCstringPointer is passed the address of what might be a pointer to a
2898// literal string in a cstring section. If that address is in a cstring section
2899// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002900static const char *GuessCstringPointer(uint64_t ReferenceValue,
2901 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002902 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002903 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2904 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2905 for (unsigned J = 0; J < Seg.nsects; ++J) {
2906 MachO::section_64 Sec = info->O->getSection64(Load, J);
2907 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2908 if (section_type == MachO::S_CSTRING_LITERALS &&
2909 ReferenceValue >= Sec.addr &&
2910 ReferenceValue < Sec.addr + Sec.size) {
2911 uint64_t sect_offset = ReferenceValue - Sec.addr;
2912 uint64_t object_offset = Sec.offset + sect_offset;
2913 StringRef MachOContents = info->O->getData();
2914 uint64_t object_size = MachOContents.size();
2915 const char *object_addr = (const char *)MachOContents.data();
2916 if (object_offset < object_size) {
2917 const char *name = object_addr + object_offset;
2918 return name;
2919 } else {
2920 return nullptr;
2921 }
2922 }
2923 }
2924 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2925 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2926 for (unsigned J = 0; J < Seg.nsects; ++J) {
2927 MachO::section Sec = info->O->getSection(Load, J);
2928 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2929 if (section_type == MachO::S_CSTRING_LITERALS &&
2930 ReferenceValue >= Sec.addr &&
2931 ReferenceValue < Sec.addr + Sec.size) {
2932 uint64_t sect_offset = ReferenceValue - Sec.addr;
2933 uint64_t object_offset = Sec.offset + sect_offset;
2934 StringRef MachOContents = info->O->getData();
2935 uint64_t object_size = MachOContents.size();
2936 const char *object_addr = (const char *)MachOContents.data();
2937 if (object_offset < object_size) {
2938 const char *name = object_addr + object_offset;
2939 return name;
2940 } else {
2941 return nullptr;
2942 }
2943 }
2944 }
2945 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002946 }
2947 return nullptr;
2948}
2949
Kevin Enderby85974882014-09-26 22:20:44 +00002950// GuessIndirectSymbol returns the name of the indirect symbol for the
2951// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2952// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2953// symbol name being referenced by the stub or pointer.
2954static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2955 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002956 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2957 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002958 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002959 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2960 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2961 for (unsigned J = 0; J < Seg.nsects; ++J) {
2962 MachO::section_64 Sec = info->O->getSection64(Load, J);
2963 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2964 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2965 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2966 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2967 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2968 section_type == MachO::S_SYMBOL_STUBS) &&
2969 ReferenceValue >= Sec.addr &&
2970 ReferenceValue < Sec.addr + Sec.size) {
2971 uint32_t stride;
2972 if (section_type == MachO::S_SYMBOL_STUBS)
2973 stride = Sec.reserved2;
2974 else
2975 stride = 8;
2976 if (stride == 0)
2977 return nullptr;
2978 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2979 if (index < Dysymtab.nindirectsyms) {
2980 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002981 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002982 if (indirect_symbol < Symtab.nsyms) {
2983 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002984 return unwrapOrError(Sym->getName(), info->O->getFileName())
2985 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002986 }
2987 }
2988 }
2989 }
2990 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2991 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2992 for (unsigned J = 0; J < Seg.nsects; ++J) {
2993 MachO::section Sec = info->O->getSection(Load, J);
2994 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2995 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2996 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2997 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2998 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2999 section_type == MachO::S_SYMBOL_STUBS) &&
3000 ReferenceValue >= Sec.addr &&
3001 ReferenceValue < Sec.addr + Sec.size) {
3002 uint32_t stride;
3003 if (section_type == MachO::S_SYMBOL_STUBS)
3004 stride = Sec.reserved2;
3005 else
3006 stride = 4;
3007 if (stride == 0)
3008 return nullptr;
3009 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3010 if (index < Dysymtab.nindirectsyms) {
3011 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003012 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003013 if (indirect_symbol < Symtab.nsyms) {
3014 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00003015 return unwrapOrError(Sym->getName(), info->O->getFileName())
3016 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00003017 }
3018 }
3019 }
3020 }
3021 }
Kevin Enderby85974882014-09-26 22:20:44 +00003022 }
3023 return nullptr;
3024}
3025
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003026// method_reference() is called passing it the ReferenceName that might be
3027// a reference it to an Objective-C method call. If so then it allocates and
3028// assembles a method call string with the values last seen and saved in
3029// the DisassembleInfo's class_name and selector_name fields. This is saved
3030// into the method field of the info and any previous string is free'ed.
3031// Then the class_name field in the info is set to nullptr. The method call
3032// string is set into ReferenceName and ReferenceType is set to
3033// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3034// then both ReferenceType and ReferenceName are left unchanged.
3035static void method_reference(struct DisassembleInfo *info,
3036 uint64_t *ReferenceType,
3037 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003038 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003039 if (*ReferenceName != nullptr) {
3040 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003041 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003042 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003043 info->method = llvm::make_unique<char[]>(
3044 5 + strlen(info->class_name) + strlen(info->selector_name));
3045 char *method = info->method.get();
3046 if (method != nullptr) {
3047 strcpy(method, "+[");
3048 strcat(method, info->class_name);
3049 strcat(method, " ");
3050 strcat(method, info->selector_name);
3051 strcat(method, "]");
3052 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003053 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3054 }
3055 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003056 info->method =
3057 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3058 char *method = info->method.get();
3059 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003060 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003061 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003062 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003063 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003064 else
David Blaikie0e550682018-02-20 18:48:51 +00003065 strcpy(method, "-[r? ");
3066 strcat(method, info->selector_name);
3067 strcat(method, "]");
3068 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003069 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3070 }
3071 }
3072 info->class_name = nullptr;
3073 }
3074 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003075 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003076 info->method =
3077 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3078 char *method = info->method.get();
3079 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003080 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003081 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003082 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003083 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003084 else
David Blaikie0e550682018-02-20 18:48:51 +00003085 strcpy(method, "-[[r? super] ");
3086 strcat(method, info->selector_name);
3087 strcat(method, "]");
3088 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003089 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3090 }
3091 info->class_name = nullptr;
3092 }
3093 }
3094 }
3095}
3096
3097// GuessPointerPointer() is passed the address of what might be a pointer to
3098// a reference to an Objective-C class, selector, message ref or cfstring.
3099// If so the value of the pointer is returned and one of the booleans are set
3100// to true. If not zero is returned and all the booleans are set to false.
3101static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3102 struct DisassembleInfo *info,
3103 bool &classref, bool &selref, bool &msgref,
3104 bool &cfstring) {
3105 classref = false;
3106 selref = false;
3107 msgref = false;
3108 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003109 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003110 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3111 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3112 for (unsigned J = 0; J < Seg.nsects; ++J) {
3113 MachO::section_64 Sec = info->O->getSection64(Load, J);
3114 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3115 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3116 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3117 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3118 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3119 ReferenceValue >= Sec.addr &&
3120 ReferenceValue < Sec.addr + Sec.size) {
3121 uint64_t sect_offset = ReferenceValue - Sec.addr;
3122 uint64_t object_offset = Sec.offset + sect_offset;
3123 StringRef MachOContents = info->O->getData();
3124 uint64_t object_size = MachOContents.size();
3125 const char *object_addr = (const char *)MachOContents.data();
3126 if (object_offset < object_size) {
3127 uint64_t pointer_value;
3128 memcpy(&pointer_value, object_addr + object_offset,
3129 sizeof(uint64_t));
3130 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3131 sys::swapByteOrder(pointer_value);
3132 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3133 selref = true;
3134 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3135 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3136 classref = true;
3137 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3138 ReferenceValue + 8 < Sec.addr + Sec.size) {
3139 msgref = true;
3140 memcpy(&pointer_value, object_addr + object_offset + 8,
3141 sizeof(uint64_t));
3142 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3143 sys::swapByteOrder(pointer_value);
3144 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3145 cfstring = true;
3146 return pointer_value;
3147 } else {
3148 return 0;
3149 }
3150 }
3151 }
3152 }
3153 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003154 }
3155 return 0;
3156}
3157
3158// get_pointer_64 returns a pointer to the bytes in the object file at the
3159// Address from a section in the Mach-O file. And indirectly returns the
3160// offset into the section, number of bytes left in the section past the offset
3161// and which section is was being referenced. If the Address is not in a
3162// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003163static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3164 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003165 DisassembleInfo *info,
3166 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003167 offset = 0;
3168 left = 0;
3169 S = SectionRef();
3170 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3171 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3172 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003173 if (SectSize == 0)
3174 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003175 if (objc_only) {
3176 StringRef SectName;
3177 ((*(info->Sections))[SectIdx]).getName(SectName);
3178 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3179 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3180 if (SegName != "__OBJC" && SectName != "__cstring")
3181 continue;
3182 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003183 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3184 S = (*(info->Sections))[SectIdx];
3185 offset = Address - SectAddress;
3186 left = SectSize - offset;
3187 StringRef SectContents;
3188 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3189 return SectContents.data() + offset;
3190 }
3191 }
3192 return nullptr;
3193}
3194
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003195static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3196 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003197 DisassembleInfo *info,
3198 bool objc_only = false) {
3199 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003200}
3201
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003202// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3203// the symbol indirectly through n_value. Based on the relocation information
3204// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003205// If no relocation information is found and a non-zero ReferenceValue for the
3206// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003207static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3208 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003209 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003210 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003211 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003212 return nullptr;
3213
3214 // See if there is an external relocation entry at the sect_offset.
3215 bool reloc_found = false;
3216 DataRefImpl Rel;
3217 MachO::any_relocation_info RE;
3218 bool isExtern = false;
3219 SymbolRef Symbol;
3220 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003221 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003222 if (RelocOffset == sect_offset) {
3223 Rel = Reloc.getRawDataRefImpl();
3224 RE = info->O->getRelocation(Rel);
3225 if (info->O->isRelocationScattered(RE))
3226 continue;
3227 isExtern = info->O->getPlainRelocationExternal(RE);
3228 if (isExtern) {
3229 symbol_iterator RelocSym = Reloc.getSymbol();
3230 Symbol = *RelocSym;
3231 }
3232 reloc_found = true;
3233 break;
3234 }
3235 }
3236 // If there is an external relocation entry for a symbol in this section
3237 // at this section_offset then use that symbol's value for the n_value
3238 // and return its name.
3239 const char *SymbolName = nullptr;
3240 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003241 n_value = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00003242 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003243 if (!Name.empty()) {
3244 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003245 return SymbolName;
3246 }
3247 }
3248
3249 // TODO: For fully linked images, look through the external relocation
3250 // entries off the dynamic symtab command. For these the r_offset is from the
3251 // start of the first writeable segment in the Mach-O file. So the offset
3252 // to this section from that segment is passed to this routine by the caller,
3253 // as the database_offset. Which is the difference of the section's starting
3254 // address and the first writable segment.
3255 //
3256 // NOTE: need add passing the database_offset to this routine.
3257
Kevin Enderby0fc11822015-04-01 20:57:01 +00003258 // We did not find an external relocation entry so look up the ReferenceValue
3259 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003260 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003261
3262 return SymbolName;
3263}
3264
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003265static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3266 DisassembleInfo *info,
3267 uint32_t ReferenceValue) {
3268 uint64_t n_value64;
3269 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3270}
3271
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003272// These are structs in the Objective-C meta data and read to produce the
3273// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003274// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3275// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003276
3277// The cfstring object in a 64-bit Mach-O file.
3278struct cfstring64_t {
3279 uint64_t isa; // class64_t * (64-bit pointer)
3280 uint64_t flags; // flag bits
3281 uint64_t characters; // char * (64-bit pointer)
3282 uint64_t length; // number of non-NULL characters in above
3283};
3284
3285// The class object in a 64-bit Mach-O file.
3286struct class64_t {
3287 uint64_t isa; // class64_t * (64-bit pointer)
3288 uint64_t superclass; // class64_t * (64-bit pointer)
3289 uint64_t cache; // Cache (64-bit pointer)
3290 uint64_t vtable; // IMP * (64-bit pointer)
3291 uint64_t data; // class_ro64_t * (64-bit pointer)
3292};
3293
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003294struct class32_t {
3295 uint32_t isa; /* class32_t * (32-bit pointer) */
3296 uint32_t superclass; /* class32_t * (32-bit pointer) */
3297 uint32_t cache; /* Cache (32-bit pointer) */
3298 uint32_t vtable; /* IMP * (32-bit pointer) */
3299 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3300};
3301
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003302struct class_ro64_t {
3303 uint32_t flags;
3304 uint32_t instanceStart;
3305 uint32_t instanceSize;
3306 uint32_t reserved;
3307 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3308 uint64_t name; // const char * (64-bit pointer)
3309 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3310 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3311 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3312 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3313 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3314};
3315
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003316struct class_ro32_t {
3317 uint32_t flags;
3318 uint32_t instanceStart;
3319 uint32_t instanceSize;
3320 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3321 uint32_t name; /* const char * (32-bit pointer) */
3322 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3323 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3324 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3325 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3326 uint32_t baseProperties; /* const struct objc_property_list *
3327 (32-bit pointer) */
3328};
3329
3330/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003331#define RO_META (1 << 0)
3332#define RO_ROOT (1 << 1)
3333#define RO_HAS_CXX_STRUCTORS (1 << 2)
3334
3335struct method_list64_t {
3336 uint32_t entsize;
3337 uint32_t count;
3338 /* struct method64_t first; These structures follow inline */
3339};
3340
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003341struct method_list32_t {
3342 uint32_t entsize;
3343 uint32_t count;
3344 /* struct method32_t first; These structures follow inline */
3345};
3346
Kevin Enderby0fc11822015-04-01 20:57:01 +00003347struct method64_t {
3348 uint64_t name; /* SEL (64-bit pointer) */
3349 uint64_t types; /* const char * (64-bit pointer) */
3350 uint64_t imp; /* IMP (64-bit pointer) */
3351};
3352
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003353struct method32_t {
3354 uint32_t name; /* SEL (32-bit pointer) */
3355 uint32_t types; /* const char * (32-bit pointer) */
3356 uint32_t imp; /* IMP (32-bit pointer) */
3357};
3358
Kevin Enderby0fc11822015-04-01 20:57:01 +00003359struct protocol_list64_t {
3360 uint64_t count; /* uintptr_t (a 64-bit value) */
3361 /* struct protocol64_t * list[0]; These pointers follow inline */
3362};
3363
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003364struct protocol_list32_t {
3365 uint32_t count; /* uintptr_t (a 32-bit value) */
3366 /* struct protocol32_t * list[0]; These pointers follow inline */
3367};
3368
Kevin Enderby0fc11822015-04-01 20:57:01 +00003369struct protocol64_t {
3370 uint64_t isa; /* id * (64-bit pointer) */
3371 uint64_t name; /* const char * (64-bit pointer) */
3372 uint64_t protocols; /* struct protocol_list64_t *
3373 (64-bit pointer) */
3374 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3375 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3376 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3377 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3378 uint64_t instanceProperties; /* struct objc_property_list *
3379 (64-bit pointer) */
3380};
3381
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003382struct protocol32_t {
3383 uint32_t isa; /* id * (32-bit pointer) */
3384 uint32_t name; /* const char * (32-bit pointer) */
3385 uint32_t protocols; /* struct protocol_list_t *
3386 (32-bit pointer) */
3387 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3388 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3389 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3390 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3391 uint32_t instanceProperties; /* struct objc_property_list *
3392 (32-bit pointer) */
3393};
3394
Kevin Enderby0fc11822015-04-01 20:57:01 +00003395struct ivar_list64_t {
3396 uint32_t entsize;
3397 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003398 /* struct ivar64_t first; These structures follow inline */
3399};
3400
3401struct ivar_list32_t {
3402 uint32_t entsize;
3403 uint32_t count;
3404 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003405};
3406
3407struct ivar64_t {
3408 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3409 uint64_t name; /* const char * (64-bit pointer) */
3410 uint64_t type; /* const char * (64-bit pointer) */
3411 uint32_t alignment;
3412 uint32_t size;
3413};
3414
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003415struct ivar32_t {
3416 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3417 uint32_t name; /* const char * (32-bit pointer) */
3418 uint32_t type; /* const char * (32-bit pointer) */
3419 uint32_t alignment;
3420 uint32_t size;
3421};
3422
Kevin Enderby0fc11822015-04-01 20:57:01 +00003423struct objc_property_list64 {
3424 uint32_t entsize;
3425 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003426 /* struct objc_property64 first; These structures follow inline */
3427};
3428
3429struct objc_property_list32 {
3430 uint32_t entsize;
3431 uint32_t count;
3432 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003433};
3434
3435struct objc_property64 {
3436 uint64_t name; /* const char * (64-bit pointer) */
3437 uint64_t attributes; /* const char * (64-bit pointer) */
3438};
3439
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003440struct objc_property32 {
3441 uint32_t name; /* const char * (32-bit pointer) */
3442 uint32_t attributes; /* const char * (32-bit pointer) */
3443};
3444
Kevin Enderby0fc11822015-04-01 20:57:01 +00003445struct category64_t {
3446 uint64_t name; /* const char * (64-bit pointer) */
3447 uint64_t cls; /* struct class_t * (64-bit pointer) */
3448 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3449 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3450 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3451 uint64_t instanceProperties; /* struct objc_property_list *
3452 (64-bit pointer) */
3453};
3454
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003455struct category32_t {
3456 uint32_t name; /* const char * (32-bit pointer) */
3457 uint32_t cls; /* struct class_t * (32-bit pointer) */
3458 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3459 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3460 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3461 uint32_t instanceProperties; /* struct objc_property_list *
3462 (32-bit pointer) */
3463};
3464
Kevin Enderby0fc11822015-04-01 20:57:01 +00003465struct objc_image_info64 {
3466 uint32_t version;
3467 uint32_t flags;
3468};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003469struct objc_image_info32 {
3470 uint32_t version;
3471 uint32_t flags;
3472};
Kevin Enderby846c0002015-04-16 17:19:59 +00003473struct imageInfo_t {
3474 uint32_t version;
3475 uint32_t flags;
3476};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003477/* masks for objc_image_info.flags */
3478#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3479#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003480#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3481#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003482
3483struct message_ref64 {
3484 uint64_t imp; /* IMP (64-bit pointer) */
3485 uint64_t sel; /* SEL (64-bit pointer) */
3486};
3487
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003488struct message_ref32 {
3489 uint32_t imp; /* IMP (32-bit pointer) */
3490 uint32_t sel; /* SEL (32-bit pointer) */
3491};
3492
Kevin Enderby846c0002015-04-16 17:19:59 +00003493// Objective-C 1 (32-bit only) meta data structs.
3494
3495struct objc_module_t {
3496 uint32_t version;
3497 uint32_t size;
3498 uint32_t name; /* char * (32-bit pointer) */
3499 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3500};
3501
3502struct objc_symtab_t {
3503 uint32_t sel_ref_cnt;
3504 uint32_t refs; /* SEL * (32-bit pointer) */
3505 uint16_t cls_def_cnt;
3506 uint16_t cat_def_cnt;
3507 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3508};
3509
3510struct objc_class_t {
3511 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3512 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3513 uint32_t name; /* const char * (32-bit pointer) */
3514 int32_t version;
3515 int32_t info;
3516 int32_t instance_size;
3517 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3518 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3519 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3520 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3521};
3522
3523#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3524// class is not a metaclass
3525#define CLS_CLASS 0x1
3526// class is a metaclass
3527#define CLS_META 0x2
3528
3529struct objc_category_t {
3530 uint32_t category_name; /* char * (32-bit pointer) */
3531 uint32_t class_name; /* char * (32-bit pointer) */
3532 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3533 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3534 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3535};
3536
3537struct objc_ivar_t {
3538 uint32_t ivar_name; /* char * (32-bit pointer) */
3539 uint32_t ivar_type; /* char * (32-bit pointer) */
3540 int32_t ivar_offset;
3541};
3542
3543struct objc_ivar_list_t {
3544 int32_t ivar_count;
3545 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3546};
3547
3548struct objc_method_list_t {
3549 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3550 int32_t method_count;
3551 // struct objc_method_t method_list[1]; /* variable length structure */
3552};
3553
3554struct objc_method_t {
3555 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3556 uint32_t method_types; /* char * (32-bit pointer) */
3557 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3558 (32-bit pointer) */
3559};
3560
3561struct objc_protocol_list_t {
3562 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3563 int32_t count;
3564 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3565 // (32-bit pointer) */
3566};
3567
3568struct objc_protocol_t {
3569 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3570 uint32_t protocol_name; /* char * (32-bit pointer) */
3571 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3572 uint32_t instance_methods; /* struct objc_method_description_list *
3573 (32-bit pointer) */
3574 uint32_t class_methods; /* struct objc_method_description_list *
3575 (32-bit pointer) */
3576};
3577
3578struct objc_method_description_list_t {
3579 int32_t count;
3580 // struct objc_method_description_t list[1];
3581};
3582
3583struct objc_method_description_t {
3584 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3585 uint32_t types; /* char * (32-bit pointer) */
3586};
3587
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003588inline void swapStruct(struct cfstring64_t &cfs) {
3589 sys::swapByteOrder(cfs.isa);
3590 sys::swapByteOrder(cfs.flags);
3591 sys::swapByteOrder(cfs.characters);
3592 sys::swapByteOrder(cfs.length);
3593}
3594
3595inline void swapStruct(struct class64_t &c) {
3596 sys::swapByteOrder(c.isa);
3597 sys::swapByteOrder(c.superclass);
3598 sys::swapByteOrder(c.cache);
3599 sys::swapByteOrder(c.vtable);
3600 sys::swapByteOrder(c.data);
3601}
3602
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003603inline void swapStruct(struct class32_t &c) {
3604 sys::swapByteOrder(c.isa);
3605 sys::swapByteOrder(c.superclass);
3606 sys::swapByteOrder(c.cache);
3607 sys::swapByteOrder(c.vtable);
3608 sys::swapByteOrder(c.data);
3609}
3610
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003611inline void swapStruct(struct class_ro64_t &cro) {
3612 sys::swapByteOrder(cro.flags);
3613 sys::swapByteOrder(cro.instanceStart);
3614 sys::swapByteOrder(cro.instanceSize);
3615 sys::swapByteOrder(cro.reserved);
3616 sys::swapByteOrder(cro.ivarLayout);
3617 sys::swapByteOrder(cro.name);
3618 sys::swapByteOrder(cro.baseMethods);
3619 sys::swapByteOrder(cro.baseProtocols);
3620 sys::swapByteOrder(cro.ivars);
3621 sys::swapByteOrder(cro.weakIvarLayout);
3622 sys::swapByteOrder(cro.baseProperties);
3623}
3624
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003625inline void swapStruct(struct class_ro32_t &cro) {
3626 sys::swapByteOrder(cro.flags);
3627 sys::swapByteOrder(cro.instanceStart);
3628 sys::swapByteOrder(cro.instanceSize);
3629 sys::swapByteOrder(cro.ivarLayout);
3630 sys::swapByteOrder(cro.name);
3631 sys::swapByteOrder(cro.baseMethods);
3632 sys::swapByteOrder(cro.baseProtocols);
3633 sys::swapByteOrder(cro.ivars);
3634 sys::swapByteOrder(cro.weakIvarLayout);
3635 sys::swapByteOrder(cro.baseProperties);
3636}
3637
Kevin Enderby0fc11822015-04-01 20:57:01 +00003638inline void swapStruct(struct method_list64_t &ml) {
3639 sys::swapByteOrder(ml.entsize);
3640 sys::swapByteOrder(ml.count);
3641}
3642
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003643inline void swapStruct(struct method_list32_t &ml) {
3644 sys::swapByteOrder(ml.entsize);
3645 sys::swapByteOrder(ml.count);
3646}
3647
Kevin Enderby0fc11822015-04-01 20:57:01 +00003648inline void swapStruct(struct method64_t &m) {
3649 sys::swapByteOrder(m.name);
3650 sys::swapByteOrder(m.types);
3651 sys::swapByteOrder(m.imp);
3652}
3653
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003654inline void swapStruct(struct method32_t &m) {
3655 sys::swapByteOrder(m.name);
3656 sys::swapByteOrder(m.types);
3657 sys::swapByteOrder(m.imp);
3658}
3659
Kevin Enderby0fc11822015-04-01 20:57:01 +00003660inline void swapStruct(struct protocol_list64_t &pl) {
3661 sys::swapByteOrder(pl.count);
3662}
3663
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003664inline void swapStruct(struct protocol_list32_t &pl) {
3665 sys::swapByteOrder(pl.count);
3666}
3667
Kevin Enderby0fc11822015-04-01 20:57:01 +00003668inline void swapStruct(struct protocol64_t &p) {
3669 sys::swapByteOrder(p.isa);
3670 sys::swapByteOrder(p.name);
3671 sys::swapByteOrder(p.protocols);
3672 sys::swapByteOrder(p.instanceMethods);
3673 sys::swapByteOrder(p.classMethods);
3674 sys::swapByteOrder(p.optionalInstanceMethods);
3675 sys::swapByteOrder(p.optionalClassMethods);
3676 sys::swapByteOrder(p.instanceProperties);
3677}
3678
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003679inline void swapStruct(struct protocol32_t &p) {
3680 sys::swapByteOrder(p.isa);
3681 sys::swapByteOrder(p.name);
3682 sys::swapByteOrder(p.protocols);
3683 sys::swapByteOrder(p.instanceMethods);
3684 sys::swapByteOrder(p.classMethods);
3685 sys::swapByteOrder(p.optionalInstanceMethods);
3686 sys::swapByteOrder(p.optionalClassMethods);
3687 sys::swapByteOrder(p.instanceProperties);
3688}
3689
Kevin Enderby0fc11822015-04-01 20:57:01 +00003690inline void swapStruct(struct ivar_list64_t &il) {
3691 sys::swapByteOrder(il.entsize);
3692 sys::swapByteOrder(il.count);
3693}
3694
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003695inline void swapStruct(struct ivar_list32_t &il) {
3696 sys::swapByteOrder(il.entsize);
3697 sys::swapByteOrder(il.count);
3698}
3699
Kevin Enderby0fc11822015-04-01 20:57:01 +00003700inline void swapStruct(struct ivar64_t &i) {
3701 sys::swapByteOrder(i.offset);
3702 sys::swapByteOrder(i.name);
3703 sys::swapByteOrder(i.type);
3704 sys::swapByteOrder(i.alignment);
3705 sys::swapByteOrder(i.size);
3706}
3707
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003708inline void swapStruct(struct ivar32_t &i) {
3709 sys::swapByteOrder(i.offset);
3710 sys::swapByteOrder(i.name);
3711 sys::swapByteOrder(i.type);
3712 sys::swapByteOrder(i.alignment);
3713 sys::swapByteOrder(i.size);
3714}
3715
Kevin Enderby0fc11822015-04-01 20:57:01 +00003716inline void swapStruct(struct objc_property_list64 &pl) {
3717 sys::swapByteOrder(pl.entsize);
3718 sys::swapByteOrder(pl.count);
3719}
3720
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003721inline void swapStruct(struct objc_property_list32 &pl) {
3722 sys::swapByteOrder(pl.entsize);
3723 sys::swapByteOrder(pl.count);
3724}
3725
Kevin Enderby0fc11822015-04-01 20:57:01 +00003726inline void swapStruct(struct objc_property64 &op) {
3727 sys::swapByteOrder(op.name);
3728 sys::swapByteOrder(op.attributes);
3729}
3730
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003731inline void swapStruct(struct objc_property32 &op) {
3732 sys::swapByteOrder(op.name);
3733 sys::swapByteOrder(op.attributes);
3734}
3735
Kevin Enderby0fc11822015-04-01 20:57:01 +00003736inline void swapStruct(struct category64_t &c) {
3737 sys::swapByteOrder(c.name);
3738 sys::swapByteOrder(c.cls);
3739 sys::swapByteOrder(c.instanceMethods);
3740 sys::swapByteOrder(c.classMethods);
3741 sys::swapByteOrder(c.protocols);
3742 sys::swapByteOrder(c.instanceProperties);
3743}
3744
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003745inline void swapStruct(struct category32_t &c) {
3746 sys::swapByteOrder(c.name);
3747 sys::swapByteOrder(c.cls);
3748 sys::swapByteOrder(c.instanceMethods);
3749 sys::swapByteOrder(c.classMethods);
3750 sys::swapByteOrder(c.protocols);
3751 sys::swapByteOrder(c.instanceProperties);
3752}
3753
Kevin Enderby0fc11822015-04-01 20:57:01 +00003754inline void swapStruct(struct objc_image_info64 &o) {
3755 sys::swapByteOrder(o.version);
3756 sys::swapByteOrder(o.flags);
3757}
3758
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003759inline void swapStruct(struct objc_image_info32 &o) {
3760 sys::swapByteOrder(o.version);
3761 sys::swapByteOrder(o.flags);
3762}
3763
Kevin Enderby846c0002015-04-16 17:19:59 +00003764inline void swapStruct(struct imageInfo_t &o) {
3765 sys::swapByteOrder(o.version);
3766 sys::swapByteOrder(o.flags);
3767}
3768
Kevin Enderby0fc11822015-04-01 20:57:01 +00003769inline void swapStruct(struct message_ref64 &mr) {
3770 sys::swapByteOrder(mr.imp);
3771 sys::swapByteOrder(mr.sel);
3772}
3773
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003774inline void swapStruct(struct message_ref32 &mr) {
3775 sys::swapByteOrder(mr.imp);
3776 sys::swapByteOrder(mr.sel);
3777}
3778
Kevin Enderby846c0002015-04-16 17:19:59 +00003779inline void swapStruct(struct objc_module_t &module) {
3780 sys::swapByteOrder(module.version);
3781 sys::swapByteOrder(module.size);
3782 sys::swapByteOrder(module.name);
3783 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003784}
Kevin Enderby846c0002015-04-16 17:19:59 +00003785
3786inline void swapStruct(struct objc_symtab_t &symtab) {
3787 sys::swapByteOrder(symtab.sel_ref_cnt);
3788 sys::swapByteOrder(symtab.refs);
3789 sys::swapByteOrder(symtab.cls_def_cnt);
3790 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003791}
Kevin Enderby846c0002015-04-16 17:19:59 +00003792
3793inline void swapStruct(struct objc_class_t &objc_class) {
3794 sys::swapByteOrder(objc_class.isa);
3795 sys::swapByteOrder(objc_class.super_class);
3796 sys::swapByteOrder(objc_class.name);
3797 sys::swapByteOrder(objc_class.version);
3798 sys::swapByteOrder(objc_class.info);
3799 sys::swapByteOrder(objc_class.instance_size);
3800 sys::swapByteOrder(objc_class.ivars);
3801 sys::swapByteOrder(objc_class.methodLists);
3802 sys::swapByteOrder(objc_class.cache);
3803 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003804}
Kevin Enderby846c0002015-04-16 17:19:59 +00003805
3806inline void swapStruct(struct objc_category_t &objc_category) {
3807 sys::swapByteOrder(objc_category.category_name);
3808 sys::swapByteOrder(objc_category.class_name);
3809 sys::swapByteOrder(objc_category.instance_methods);
3810 sys::swapByteOrder(objc_category.class_methods);
3811 sys::swapByteOrder(objc_category.protocols);
3812}
3813
3814inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3815 sys::swapByteOrder(objc_ivar_list.ivar_count);
3816}
3817
3818inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3819 sys::swapByteOrder(objc_ivar.ivar_name);
3820 sys::swapByteOrder(objc_ivar.ivar_type);
3821 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003822}
Kevin Enderby846c0002015-04-16 17:19:59 +00003823
3824inline void swapStruct(struct objc_method_list_t &method_list) {
3825 sys::swapByteOrder(method_list.obsolete);
3826 sys::swapByteOrder(method_list.method_count);
3827}
3828
3829inline void swapStruct(struct objc_method_t &method) {
3830 sys::swapByteOrder(method.method_name);
3831 sys::swapByteOrder(method.method_types);
3832 sys::swapByteOrder(method.method_imp);
3833}
3834
3835inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3836 sys::swapByteOrder(protocol_list.next);
3837 sys::swapByteOrder(protocol_list.count);
3838}
3839
3840inline void swapStruct(struct objc_protocol_t &protocol) {
3841 sys::swapByteOrder(protocol.isa);
3842 sys::swapByteOrder(protocol.protocol_name);
3843 sys::swapByteOrder(protocol.protocol_list);
3844 sys::swapByteOrder(protocol.instance_methods);
3845 sys::swapByteOrder(protocol.class_methods);
3846}
3847
3848inline void swapStruct(struct objc_method_description_list_t &mdl) {
3849 sys::swapByteOrder(mdl.count);
3850}
3851
3852inline void swapStruct(struct objc_method_description_t &md) {
3853 sys::swapByteOrder(md.name);
3854 sys::swapByteOrder(md.types);
3855}
3856
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003857static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3858 struct DisassembleInfo *info);
3859
3860// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3861// to an Objective-C class and returns the class name. It is also passed the
3862// address of the pointer, so when the pointer is zero as it can be in an .o
3863// file, that is used to look for an external relocation entry with a symbol
3864// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003865static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3866 uint64_t ReferenceValue,
3867 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003868 const char *r;
3869 uint32_t offset, left;
3870 SectionRef S;
3871
3872 // The pointer_value can be 0 in an object file and have a relocation
3873 // entry for the class symbol at the ReferenceValue (the address of the
3874 // pointer).
3875 if (pointer_value == 0) {
3876 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3877 if (r == nullptr || left < sizeof(uint64_t))
3878 return nullptr;
3879 uint64_t n_value;
3880 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3881 if (symbol_name == nullptr)
3882 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003883 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003884 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3885 return class_name + 2;
3886 else
3887 return nullptr;
3888 }
3889
3890 // The case were the pointer_value is non-zero and points to a class defined
3891 // in this Mach-O file.
3892 r = get_pointer_64(pointer_value, offset, left, S, info);
3893 if (r == nullptr || left < sizeof(struct class64_t))
3894 return nullptr;
3895 struct class64_t c;
3896 memcpy(&c, r, sizeof(struct class64_t));
3897 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3898 swapStruct(c);
3899 if (c.data == 0)
3900 return nullptr;
3901 r = get_pointer_64(c.data, offset, left, S, info);
3902 if (r == nullptr || left < sizeof(struct class_ro64_t))
3903 return nullptr;
3904 struct class_ro64_t cro;
3905 memcpy(&cro, r, sizeof(struct class_ro64_t));
3906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3907 swapStruct(cro);
3908 if (cro.name == 0)
3909 return nullptr;
3910 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3911 return name;
3912}
3913
3914// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3915// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003916static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3917 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003918 const char *r, *name;
3919 uint32_t offset, left;
3920 SectionRef S;
3921 struct cfstring64_t cfs;
3922 uint64_t cfs_characters;
3923
3924 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3925 if (r == nullptr || left < sizeof(struct cfstring64_t))
3926 return nullptr;
3927 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3928 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3929 swapStruct(cfs);
3930 if (cfs.characters == 0) {
3931 uint64_t n_value;
3932 const char *symbol_name = get_symbol_64(
3933 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3934 if (symbol_name == nullptr)
3935 return nullptr;
3936 cfs_characters = n_value;
3937 } else
3938 cfs_characters = cfs.characters;
3939 name = get_pointer_64(cfs_characters, offset, left, S, info);
3940
3941 return name;
3942}
3943
3944// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3945// of a pointer to an Objective-C selector reference when the pointer value is
3946// zero as in a .o file and is likely to have a external relocation entry with
3947// who's symbol's n_value is the real pointer to the selector name. If that is
3948// the case the real pointer to the selector name is returned else 0 is
3949// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003950static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3951 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003952 uint32_t offset, left;
3953 SectionRef S;
3954
3955 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3956 if (r == nullptr || left < sizeof(uint64_t))
3957 return 0;
3958 uint64_t n_value;
3959 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3960 if (symbol_name == nullptr)
3961 return 0;
3962 return n_value;
3963}
3964
Kevin Enderby0fc11822015-04-01 20:57:01 +00003965static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3966 const char *sectname) {
3967 for (const SectionRef &Section : O->sections()) {
3968 StringRef SectName;
3969 Section.getName(SectName);
3970 DataRefImpl Ref = Section.getRawDataRefImpl();
3971 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3972 if (SegName == segname && SectName == sectname)
3973 return Section;
3974 }
3975 return SectionRef();
3976}
3977
3978static void
3979walk_pointer_list_64(const char *listname, const SectionRef S,
3980 MachOObjectFile *O, struct DisassembleInfo *info,
3981 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3982 if (S == SectionRef())
3983 return;
3984
3985 StringRef SectName;
3986 S.getName(SectName);
3987 DataRefImpl Ref = S.getRawDataRefImpl();
3988 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3989 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3990
3991 StringRef BytesStr;
3992 S.getContents(BytesStr);
3993 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3994
3995 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3996 uint32_t left = S.getSize() - i;
3997 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3998 uint64_t p = 0;
3999 memcpy(&p, Contents + i, size);
4000 if (i + sizeof(uint64_t) > S.getSize())
4001 outs() << listname << " list pointer extends past end of (" << SegName
4002 << "," << SectName << ") section\n";
4003 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4004
4005 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4006 sys::swapByteOrder(p);
4007
4008 uint64_t n_value = 0;
4009 const char *name = get_symbol_64(i, S, info, n_value, p);
4010 if (name == nullptr)
4011 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4012
4013 if (n_value != 0) {
4014 outs() << format("0x%" PRIx64, n_value);
4015 if (p != 0)
4016 outs() << " + " << format("0x%" PRIx64, p);
4017 } else
4018 outs() << format("0x%" PRIx64, p);
4019 if (name != nullptr)
4020 outs() << " " << name;
4021 outs() << "\n";
4022
4023 p += n_value;
4024 if (func)
4025 func(p, info);
4026 }
4027}
4028
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004029static void
4030walk_pointer_list_32(const char *listname, const SectionRef S,
4031 MachOObjectFile *O, struct DisassembleInfo *info,
4032 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4033 if (S == SectionRef())
4034 return;
4035
4036 StringRef SectName;
4037 S.getName(SectName);
4038 DataRefImpl Ref = S.getRawDataRefImpl();
4039 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4040 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4041
4042 StringRef BytesStr;
4043 S.getContents(BytesStr);
4044 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4045
4046 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4047 uint32_t left = S.getSize() - i;
4048 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4049 uint32_t p = 0;
4050 memcpy(&p, Contents + i, size);
4051 if (i + sizeof(uint32_t) > S.getSize())
4052 outs() << listname << " list pointer extends past end of (" << SegName
4053 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004054 uint32_t Address = S.getAddress() + i;
4055 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004056
4057 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4058 sys::swapByteOrder(p);
4059 outs() << format("0x%" PRIx32, p);
4060
4061 const char *name = get_symbol_32(i, S, info, p);
4062 if (name != nullptr)
4063 outs() << " " << name;
4064 outs() << "\n";
4065
4066 if (func)
4067 func(p, info);
4068 }
4069}
4070
4071static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004072 if (layout_map == nullptr)
4073 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004074 outs() << " layout map: ";
4075 do {
4076 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4077 left--;
4078 layout_map++;
4079 } while (*layout_map != '\0' && left != 0);
4080 outs() << "\n";
4081}
4082
Kevin Enderby0fc11822015-04-01 20:57:01 +00004083static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4084 uint32_t offset, left;
4085 SectionRef S;
4086 const char *layout_map;
4087
4088 if (p == 0)
4089 return;
4090 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004091 print_layout_map(layout_map, left);
4092}
4093
4094static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4095 uint32_t offset, left;
4096 SectionRef S;
4097 const char *layout_map;
4098
4099 if (p == 0)
4100 return;
4101 layout_map = get_pointer_32(p, offset, left, S, info);
4102 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004103}
4104
4105static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4106 const char *indent) {
4107 struct method_list64_t ml;
4108 struct method64_t m;
4109 const char *r;
4110 uint32_t offset, xoffset, left, i;
4111 SectionRef S, xS;
4112 const char *name, *sym_name;
4113 uint64_t n_value;
4114
4115 r = get_pointer_64(p, offset, left, S, info);
4116 if (r == nullptr)
4117 return;
4118 memset(&ml, '\0', sizeof(struct method_list64_t));
4119 if (left < sizeof(struct method_list64_t)) {
4120 memcpy(&ml, r, left);
4121 outs() << " (method_list_t entends past the end of the section)\n";
4122 } else
4123 memcpy(&ml, r, sizeof(struct method_list64_t));
4124 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4125 swapStruct(ml);
4126 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4127 outs() << indent << "\t\t count " << ml.count << "\n";
4128
4129 p += sizeof(struct method_list64_t);
4130 offset += sizeof(struct method_list64_t);
4131 for (i = 0; i < ml.count; i++) {
4132 r = get_pointer_64(p, offset, left, S, info);
4133 if (r == nullptr)
4134 return;
4135 memset(&m, '\0', sizeof(struct method64_t));
4136 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004137 memcpy(&m, r, left);
4138 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004139 } else
4140 memcpy(&m, r, sizeof(struct method64_t));
4141 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4142 swapStruct(m);
4143
4144 outs() << indent << "\t\t name ";
4145 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4146 info, n_value, m.name);
4147 if (n_value != 0) {
4148 if (info->verbose && sym_name != nullptr)
4149 outs() << sym_name;
4150 else
4151 outs() << format("0x%" PRIx64, n_value);
4152 if (m.name != 0)
4153 outs() << " + " << format("0x%" PRIx64, m.name);
4154 } else
4155 outs() << format("0x%" PRIx64, m.name);
4156 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4157 if (name != nullptr)
4158 outs() << format(" %.*s", left, name);
4159 outs() << "\n";
4160
4161 outs() << indent << "\t\t types ";
4162 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4163 info, n_value, m.types);
4164 if (n_value != 0) {
4165 if (info->verbose && sym_name != nullptr)
4166 outs() << sym_name;
4167 else
4168 outs() << format("0x%" PRIx64, n_value);
4169 if (m.types != 0)
4170 outs() << " + " << format("0x%" PRIx64, m.types);
4171 } else
4172 outs() << format("0x%" PRIx64, m.types);
4173 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4174 if (name != nullptr)
4175 outs() << format(" %.*s", left, name);
4176 outs() << "\n";
4177
4178 outs() << indent << "\t\t imp ";
4179 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4180 n_value, m.imp);
4181 if (info->verbose && name == nullptr) {
4182 if (n_value != 0) {
4183 outs() << format("0x%" PRIx64, n_value) << " ";
4184 if (m.imp != 0)
4185 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4186 } else
4187 outs() << format("0x%" PRIx64, m.imp) << " ";
4188 }
4189 if (name != nullptr)
4190 outs() << name;
4191 outs() << "\n";
4192
4193 p += sizeof(struct method64_t);
4194 offset += sizeof(struct method64_t);
4195 }
4196}
4197
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004198static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4199 const char *indent) {
4200 struct method_list32_t ml;
4201 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004202 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004203 uint32_t offset, xoffset, left, i;
4204 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004205
4206 r = get_pointer_32(p, offset, left, S, info);
4207 if (r == nullptr)
4208 return;
4209 memset(&ml, '\0', sizeof(struct method_list32_t));
4210 if (left < sizeof(struct method_list32_t)) {
4211 memcpy(&ml, r, left);
4212 outs() << " (method_list_t entends past the end of the section)\n";
4213 } else
4214 memcpy(&ml, r, sizeof(struct method_list32_t));
4215 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4216 swapStruct(ml);
4217 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4218 outs() << indent << "\t\t count " << ml.count << "\n";
4219
4220 p += sizeof(struct method_list32_t);
4221 offset += sizeof(struct method_list32_t);
4222 for (i = 0; i < ml.count; i++) {
4223 r = get_pointer_32(p, offset, left, S, info);
4224 if (r == nullptr)
4225 return;
4226 memset(&m, '\0', sizeof(struct method32_t));
4227 if (left < sizeof(struct method32_t)) {
4228 memcpy(&ml, r, left);
4229 outs() << indent << " (method_t entends past the end of the section)\n";
4230 } else
4231 memcpy(&m, r, sizeof(struct method32_t));
4232 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4233 swapStruct(m);
4234
4235 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4236 name = get_pointer_32(m.name, xoffset, left, xS, info);
4237 if (name != nullptr)
4238 outs() << format(" %.*s", left, name);
4239 outs() << "\n";
4240
4241 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4242 name = get_pointer_32(m.types, xoffset, left, xS, info);
4243 if (name != nullptr)
4244 outs() << format(" %.*s", left, name);
4245 outs() << "\n";
4246
4247 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4248 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4249 m.imp);
4250 if (name != nullptr)
4251 outs() << " " << name;
4252 outs() << "\n";
4253
4254 p += sizeof(struct method32_t);
4255 offset += sizeof(struct method32_t);
4256 }
4257}
4258
Kevin Enderby846c0002015-04-16 17:19:59 +00004259static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4260 uint32_t offset, left, xleft;
4261 SectionRef S;
4262 struct objc_method_list_t method_list;
4263 struct objc_method_t method;
4264 const char *r, *methods, *name, *SymbolName;
4265 int32_t i;
4266
4267 r = get_pointer_32(p, offset, left, S, info, true);
4268 if (r == nullptr)
4269 return true;
4270
4271 outs() << "\n";
4272 if (left > sizeof(struct objc_method_list_t)) {
4273 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4274 } else {
4275 outs() << "\t\t objc_method_list extends past end of the section\n";
4276 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4277 memcpy(&method_list, r, left);
4278 }
4279 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4280 swapStruct(method_list);
4281
4282 outs() << "\t\t obsolete "
4283 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4284 outs() << "\t\t method_count " << method_list.method_count << "\n";
4285
4286 methods = r + sizeof(struct objc_method_list_t);
4287 for (i = 0; i < method_list.method_count; i++) {
4288 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4289 outs() << "\t\t remaining method's extend past the of the section\n";
4290 break;
4291 }
4292 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4293 sizeof(struct objc_method_t));
4294 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4295 swapStruct(method);
4296
4297 outs() << "\t\t method_name "
4298 << format("0x%08" PRIx32, method.method_name);
4299 if (info->verbose) {
4300 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4301 if (name != nullptr)
4302 outs() << format(" %.*s", xleft, name);
4303 else
4304 outs() << " (not in an __OBJC section)";
4305 }
4306 outs() << "\n";
4307
4308 outs() << "\t\t method_types "
4309 << format("0x%08" PRIx32, method.method_types);
4310 if (info->verbose) {
4311 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4312 if (name != nullptr)
4313 outs() << format(" %.*s", xleft, name);
4314 else
4315 outs() << " (not in an __OBJC section)";
4316 }
4317 outs() << "\n";
4318
4319 outs() << "\t\t method_imp "
4320 << format("0x%08" PRIx32, method.method_imp) << " ";
4321 if (info->verbose) {
4322 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4323 if (SymbolName != nullptr)
4324 outs() << SymbolName;
4325 }
4326 outs() << "\n";
4327 }
4328 return false;
4329}
4330
Kevin Enderby0fc11822015-04-01 20:57:01 +00004331static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4332 struct protocol_list64_t pl;
4333 uint64_t q, n_value;
4334 struct protocol64_t pc;
4335 const char *r;
4336 uint32_t offset, xoffset, left, i;
4337 SectionRef S, xS;
4338 const char *name, *sym_name;
4339
4340 r = get_pointer_64(p, offset, left, S, info);
4341 if (r == nullptr)
4342 return;
4343 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4344 if (left < sizeof(struct protocol_list64_t)) {
4345 memcpy(&pl, r, left);
4346 outs() << " (protocol_list_t entends past the end of the section)\n";
4347 } else
4348 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4349 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4350 swapStruct(pl);
4351 outs() << " count " << pl.count << "\n";
4352
4353 p += sizeof(struct protocol_list64_t);
4354 offset += sizeof(struct protocol_list64_t);
4355 for (i = 0; i < pl.count; i++) {
4356 r = get_pointer_64(p, offset, left, S, info);
4357 if (r == nullptr)
4358 return;
4359 q = 0;
4360 if (left < sizeof(uint64_t)) {
4361 memcpy(&q, r, left);
4362 outs() << " (protocol_t * entends past the end of the section)\n";
4363 } else
4364 memcpy(&q, r, sizeof(uint64_t));
4365 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4366 sys::swapByteOrder(q);
4367
4368 outs() << "\t\t list[" << i << "] ";
4369 sym_name = get_symbol_64(offset, S, info, n_value, q);
4370 if (n_value != 0) {
4371 if (info->verbose && sym_name != nullptr)
4372 outs() << sym_name;
4373 else
4374 outs() << format("0x%" PRIx64, n_value);
4375 if (q != 0)
4376 outs() << " + " << format("0x%" PRIx64, q);
4377 } else
4378 outs() << format("0x%" PRIx64, q);
4379 outs() << " (struct protocol_t *)\n";
4380
4381 r = get_pointer_64(q + n_value, offset, left, S, info);
4382 if (r == nullptr)
4383 return;
4384 memset(&pc, '\0', sizeof(struct protocol64_t));
4385 if (left < sizeof(struct protocol64_t)) {
4386 memcpy(&pc, r, left);
4387 outs() << " (protocol_t entends past the end of the section)\n";
4388 } else
4389 memcpy(&pc, r, sizeof(struct protocol64_t));
4390 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4391 swapStruct(pc);
4392
4393 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4394
4395 outs() << "\t\t\t name ";
4396 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4397 info, n_value, pc.name);
4398 if (n_value != 0) {
4399 if (info->verbose && sym_name != nullptr)
4400 outs() << sym_name;
4401 else
4402 outs() << format("0x%" PRIx64, n_value);
4403 if (pc.name != 0)
4404 outs() << " + " << format("0x%" PRIx64, pc.name);
4405 } else
4406 outs() << format("0x%" PRIx64, pc.name);
4407 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4408 if (name != nullptr)
4409 outs() << format(" %.*s", left, name);
4410 outs() << "\n";
4411
4412 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4413
4414 outs() << "\t\t instanceMethods ";
4415 sym_name =
4416 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4417 S, info, n_value, pc.instanceMethods);
4418 if (n_value != 0) {
4419 if (info->verbose && sym_name != nullptr)
4420 outs() << sym_name;
4421 else
4422 outs() << format("0x%" PRIx64, n_value);
4423 if (pc.instanceMethods != 0)
4424 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4425 } else
4426 outs() << format("0x%" PRIx64, pc.instanceMethods);
4427 outs() << " (struct method_list_t *)\n";
4428 if (pc.instanceMethods + n_value != 0)
4429 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4430
4431 outs() << "\t\t classMethods ";
4432 sym_name =
4433 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4434 info, n_value, pc.classMethods);
4435 if (n_value != 0) {
4436 if (info->verbose && sym_name != nullptr)
4437 outs() << sym_name;
4438 else
4439 outs() << format("0x%" PRIx64, n_value);
4440 if (pc.classMethods != 0)
4441 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4442 } else
4443 outs() << format("0x%" PRIx64, pc.classMethods);
4444 outs() << " (struct method_list_t *)\n";
4445 if (pc.classMethods + n_value != 0)
4446 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4447
4448 outs() << "\t optionalInstanceMethods "
4449 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4450 outs() << "\t optionalClassMethods "
4451 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4452 outs() << "\t instanceProperties "
4453 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4454
4455 p += sizeof(uint64_t);
4456 offset += sizeof(uint64_t);
4457 }
4458}
4459
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004460static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4461 struct protocol_list32_t pl;
4462 uint32_t q;
4463 struct protocol32_t pc;
4464 const char *r;
4465 uint32_t offset, xoffset, left, i;
4466 SectionRef S, xS;
4467 const char *name;
4468
4469 r = get_pointer_32(p, offset, left, S, info);
4470 if (r == nullptr)
4471 return;
4472 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4473 if (left < sizeof(struct protocol_list32_t)) {
4474 memcpy(&pl, r, left);
4475 outs() << " (protocol_list_t entends past the end of the section)\n";
4476 } else
4477 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4478 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4479 swapStruct(pl);
4480 outs() << " count " << pl.count << "\n";
4481
4482 p += sizeof(struct protocol_list32_t);
4483 offset += sizeof(struct protocol_list32_t);
4484 for (i = 0; i < pl.count; i++) {
4485 r = get_pointer_32(p, offset, left, S, info);
4486 if (r == nullptr)
4487 return;
4488 q = 0;
4489 if (left < sizeof(uint32_t)) {
4490 memcpy(&q, r, left);
4491 outs() << " (protocol_t * entends past the end of the section)\n";
4492 } else
4493 memcpy(&q, r, sizeof(uint32_t));
4494 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4495 sys::swapByteOrder(q);
4496 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4497 << " (struct protocol_t *)\n";
4498 r = get_pointer_32(q, offset, left, S, info);
4499 if (r == nullptr)
4500 return;
4501 memset(&pc, '\0', sizeof(struct protocol32_t));
4502 if (left < sizeof(struct protocol32_t)) {
4503 memcpy(&pc, r, left);
4504 outs() << " (protocol_t entends past the end of the section)\n";
4505 } else
4506 memcpy(&pc, r, sizeof(struct protocol32_t));
4507 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4508 swapStruct(pc);
4509 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4510 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4511 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4512 if (name != nullptr)
4513 outs() << format(" %.*s", left, name);
4514 outs() << "\n";
4515 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4516 outs() << "\t\t instanceMethods "
4517 << format("0x%" PRIx32, pc.instanceMethods)
4518 << " (struct method_list_t *)\n";
4519 if (pc.instanceMethods != 0)
4520 print_method_list32_t(pc.instanceMethods, info, "\t");
4521 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4522 << " (struct method_list_t *)\n";
4523 if (pc.classMethods != 0)
4524 print_method_list32_t(pc.classMethods, info, "\t");
4525 outs() << "\t optionalInstanceMethods "
4526 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4527 outs() << "\t optionalClassMethods "
4528 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4529 outs() << "\t instanceProperties "
4530 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4531 p += sizeof(uint32_t);
4532 offset += sizeof(uint32_t);
4533 }
4534}
4535
Kevin Enderby846c0002015-04-16 17:19:59 +00004536static void print_indent(uint32_t indent) {
4537 for (uint32_t i = 0; i < indent;) {
4538 if (indent - i >= 8) {
4539 outs() << "\t";
4540 i += 8;
4541 } else {
4542 for (uint32_t j = i; j < indent; j++)
4543 outs() << " ";
4544 return;
4545 }
4546 }
4547}
4548
4549static bool print_method_description_list(uint32_t p, uint32_t indent,
4550 struct DisassembleInfo *info) {
4551 uint32_t offset, left, xleft;
4552 SectionRef S;
4553 struct objc_method_description_list_t mdl;
4554 struct objc_method_description_t md;
4555 const char *r, *list, *name;
4556 int32_t i;
4557
4558 r = get_pointer_32(p, offset, left, S, info, true);
4559 if (r == nullptr)
4560 return true;
4561
4562 outs() << "\n";
4563 if (left > sizeof(struct objc_method_description_list_t)) {
4564 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4565 } else {
4566 print_indent(indent);
4567 outs() << " objc_method_description_list extends past end of the section\n";
4568 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4569 memcpy(&mdl, r, left);
4570 }
4571 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4572 swapStruct(mdl);
4573
4574 print_indent(indent);
4575 outs() << " count " << mdl.count << "\n";
4576
4577 list = r + sizeof(struct objc_method_description_list_t);
4578 for (i = 0; i < mdl.count; i++) {
4579 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4580 print_indent(indent);
4581 outs() << " remaining list entries extend past the of the section\n";
4582 break;
4583 }
4584 print_indent(indent);
4585 outs() << " list[" << i << "]\n";
4586 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4587 sizeof(struct objc_method_description_t));
4588 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4589 swapStruct(md);
4590
4591 print_indent(indent);
4592 outs() << " name " << format("0x%08" PRIx32, md.name);
4593 if (info->verbose) {
4594 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4595 if (name != nullptr)
4596 outs() << format(" %.*s", xleft, name);
4597 else
4598 outs() << " (not in an __OBJC section)";
4599 }
4600 outs() << "\n";
4601
4602 print_indent(indent);
4603 outs() << " types " << format("0x%08" PRIx32, md.types);
4604 if (info->verbose) {
4605 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4606 if (name != nullptr)
4607 outs() << format(" %.*s", xleft, name);
4608 else
4609 outs() << " (not in an __OBJC section)";
4610 }
4611 outs() << "\n";
4612 }
4613 return false;
4614}
4615
4616static bool print_protocol_list(uint32_t p, uint32_t indent,
4617 struct DisassembleInfo *info);
4618
4619static bool print_protocol(uint32_t p, uint32_t indent,
4620 struct DisassembleInfo *info) {
4621 uint32_t offset, left;
4622 SectionRef S;
4623 struct objc_protocol_t protocol;
4624 const char *r, *name;
4625
4626 r = get_pointer_32(p, offset, left, S, info, true);
4627 if (r == nullptr)
4628 return true;
4629
4630 outs() << "\n";
4631 if (left >= sizeof(struct objc_protocol_t)) {
4632 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4633 } else {
4634 print_indent(indent);
4635 outs() << " Protocol extends past end of the section\n";
4636 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4637 memcpy(&protocol, r, left);
4638 }
4639 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4640 swapStruct(protocol);
4641
4642 print_indent(indent);
4643 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4644 << "\n";
4645
4646 print_indent(indent);
4647 outs() << " protocol_name "
4648 << format("0x%08" PRIx32, protocol.protocol_name);
4649 if (info->verbose) {
4650 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4651 if (name != nullptr)
4652 outs() << format(" %.*s", left, name);
4653 else
4654 outs() << " (not in an __OBJC section)";
4655 }
4656 outs() << "\n";
4657
4658 print_indent(indent);
4659 outs() << " protocol_list "
4660 << format("0x%08" PRIx32, protocol.protocol_list);
4661 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4662 outs() << " (not in an __OBJC section)\n";
4663
4664 print_indent(indent);
4665 outs() << " instance_methods "
4666 << format("0x%08" PRIx32, protocol.instance_methods);
4667 if (print_method_description_list(protocol.instance_methods, indent, info))
4668 outs() << " (not in an __OBJC section)\n";
4669
4670 print_indent(indent);
4671 outs() << " class_methods "
4672 << format("0x%08" PRIx32, protocol.class_methods);
4673 if (print_method_description_list(protocol.class_methods, indent, info))
4674 outs() << " (not in an __OBJC section)\n";
4675
4676 return false;
4677}
4678
4679static bool print_protocol_list(uint32_t p, uint32_t indent,
4680 struct DisassembleInfo *info) {
4681 uint32_t offset, left, l;
4682 SectionRef S;
4683 struct objc_protocol_list_t protocol_list;
4684 const char *r, *list;
4685 int32_t i;
4686
4687 r = get_pointer_32(p, offset, left, S, info, true);
4688 if (r == nullptr)
4689 return true;
4690
4691 outs() << "\n";
4692 if (left > sizeof(struct objc_protocol_list_t)) {
4693 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4694 } else {
4695 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4696 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4697 memcpy(&protocol_list, r, left);
4698 }
4699 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4700 swapStruct(protocol_list);
4701
4702 print_indent(indent);
4703 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4704 << "\n";
4705 print_indent(indent);
4706 outs() << " count " << protocol_list.count << "\n";
4707
4708 list = r + sizeof(struct objc_protocol_list_t);
4709 for (i = 0; i < protocol_list.count; i++) {
4710 if ((i + 1) * sizeof(uint32_t) > left) {
4711 outs() << "\t\t remaining list entries extend past the of the section\n";
4712 break;
4713 }
4714 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4715 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4716 sys::swapByteOrder(l);
4717
4718 print_indent(indent);
4719 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4720 if (print_protocol(l, indent, info))
4721 outs() << "(not in an __OBJC section)\n";
4722 }
4723 return false;
4724}
4725
Kevin Enderby0fc11822015-04-01 20:57:01 +00004726static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4727 struct ivar_list64_t il;
4728 struct ivar64_t i;
4729 const char *r;
4730 uint32_t offset, xoffset, left, j;
4731 SectionRef S, xS;
4732 const char *name, *sym_name, *ivar_offset_p;
4733 uint64_t ivar_offset, n_value;
4734
4735 r = get_pointer_64(p, offset, left, S, info);
4736 if (r == nullptr)
4737 return;
4738 memset(&il, '\0', sizeof(struct ivar_list64_t));
4739 if (left < sizeof(struct ivar_list64_t)) {
4740 memcpy(&il, r, left);
4741 outs() << " (ivar_list_t entends past the end of the section)\n";
4742 } else
4743 memcpy(&il, r, sizeof(struct ivar_list64_t));
4744 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4745 swapStruct(il);
4746 outs() << " entsize " << il.entsize << "\n";
4747 outs() << " count " << il.count << "\n";
4748
4749 p += sizeof(struct ivar_list64_t);
4750 offset += sizeof(struct ivar_list64_t);
4751 for (j = 0; j < il.count; j++) {
4752 r = get_pointer_64(p, offset, left, S, info);
4753 if (r == nullptr)
4754 return;
4755 memset(&i, '\0', sizeof(struct ivar64_t));
4756 if (left < sizeof(struct ivar64_t)) {
4757 memcpy(&i, r, left);
4758 outs() << " (ivar_t entends past the end of the section)\n";
4759 } else
4760 memcpy(&i, r, sizeof(struct ivar64_t));
4761 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4762 swapStruct(i);
4763
4764 outs() << "\t\t\t offset ";
4765 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4766 info, n_value, i.offset);
4767 if (n_value != 0) {
4768 if (info->verbose && sym_name != nullptr)
4769 outs() << sym_name;
4770 else
4771 outs() << format("0x%" PRIx64, n_value);
4772 if (i.offset != 0)
4773 outs() << " + " << format("0x%" PRIx64, i.offset);
4774 } else
4775 outs() << format("0x%" PRIx64, i.offset);
4776 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4777 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4778 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4779 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4780 sys::swapByteOrder(ivar_offset);
4781 outs() << " " << ivar_offset << "\n";
4782 } else
4783 outs() << "\n";
4784
4785 outs() << "\t\t\t name ";
4786 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4787 n_value, i.name);
4788 if (n_value != 0) {
4789 if (info->verbose && sym_name != nullptr)
4790 outs() << sym_name;
4791 else
4792 outs() << format("0x%" PRIx64, n_value);
4793 if (i.name != 0)
4794 outs() << " + " << format("0x%" PRIx64, i.name);
4795 } else
4796 outs() << format("0x%" PRIx64, i.name);
4797 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4798 if (name != nullptr)
4799 outs() << format(" %.*s", left, name);
4800 outs() << "\n";
4801
4802 outs() << "\t\t\t type ";
4803 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4804 n_value, i.name);
4805 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4806 if (n_value != 0) {
4807 if (info->verbose && sym_name != nullptr)
4808 outs() << sym_name;
4809 else
4810 outs() << format("0x%" PRIx64, n_value);
4811 if (i.type != 0)
4812 outs() << " + " << format("0x%" PRIx64, i.type);
4813 } else
4814 outs() << format("0x%" PRIx64, i.type);
4815 if (name != nullptr)
4816 outs() << format(" %.*s", left, name);
4817 outs() << "\n";
4818
4819 outs() << "\t\t\talignment " << i.alignment << "\n";
4820 outs() << "\t\t\t size " << i.size << "\n";
4821
4822 p += sizeof(struct ivar64_t);
4823 offset += sizeof(struct ivar64_t);
4824 }
4825}
4826
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004827static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4828 struct ivar_list32_t il;
4829 struct ivar32_t i;
4830 const char *r;
4831 uint32_t offset, xoffset, left, j;
4832 SectionRef S, xS;
4833 const char *name, *ivar_offset_p;
4834 uint32_t ivar_offset;
4835
4836 r = get_pointer_32(p, offset, left, S, info);
4837 if (r == nullptr)
4838 return;
4839 memset(&il, '\0', sizeof(struct ivar_list32_t));
4840 if (left < sizeof(struct ivar_list32_t)) {
4841 memcpy(&il, r, left);
4842 outs() << " (ivar_list_t entends past the end of the section)\n";
4843 } else
4844 memcpy(&il, r, sizeof(struct ivar_list32_t));
4845 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4846 swapStruct(il);
4847 outs() << " entsize " << il.entsize << "\n";
4848 outs() << " count " << il.count << "\n";
4849
4850 p += sizeof(struct ivar_list32_t);
4851 offset += sizeof(struct ivar_list32_t);
4852 for (j = 0; j < il.count; j++) {
4853 r = get_pointer_32(p, offset, left, S, info);
4854 if (r == nullptr)
4855 return;
4856 memset(&i, '\0', sizeof(struct ivar32_t));
4857 if (left < sizeof(struct ivar32_t)) {
4858 memcpy(&i, r, left);
4859 outs() << " (ivar_t entends past the end of the section)\n";
4860 } else
4861 memcpy(&i, r, sizeof(struct ivar32_t));
4862 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4863 swapStruct(i);
4864
4865 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4866 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4867 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4868 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4869 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4870 sys::swapByteOrder(ivar_offset);
4871 outs() << " " << ivar_offset << "\n";
4872 } else
4873 outs() << "\n";
4874
4875 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4876 name = get_pointer_32(i.name, xoffset, left, xS, info);
4877 if (name != nullptr)
4878 outs() << format(" %.*s", left, name);
4879 outs() << "\n";
4880
4881 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4882 name = get_pointer_32(i.type, xoffset, left, xS, info);
4883 if (name != nullptr)
4884 outs() << format(" %.*s", left, name);
4885 outs() << "\n";
4886
4887 outs() << "\t\t\talignment " << i.alignment << "\n";
4888 outs() << "\t\t\t size " << i.size << "\n";
4889
4890 p += sizeof(struct ivar32_t);
4891 offset += sizeof(struct ivar32_t);
4892 }
4893}
4894
Kevin Enderby0fc11822015-04-01 20:57:01 +00004895static void print_objc_property_list64(uint64_t p,
4896 struct DisassembleInfo *info) {
4897 struct objc_property_list64 opl;
4898 struct objc_property64 op;
4899 const char *r;
4900 uint32_t offset, xoffset, left, j;
4901 SectionRef S, xS;
4902 const char *name, *sym_name;
4903 uint64_t n_value;
4904
4905 r = get_pointer_64(p, offset, left, S, info);
4906 if (r == nullptr)
4907 return;
4908 memset(&opl, '\0', sizeof(struct objc_property_list64));
4909 if (left < sizeof(struct objc_property_list64)) {
4910 memcpy(&opl, r, left);
4911 outs() << " (objc_property_list entends past the end of the section)\n";
4912 } else
4913 memcpy(&opl, r, sizeof(struct objc_property_list64));
4914 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4915 swapStruct(opl);
4916 outs() << " entsize " << opl.entsize << "\n";
4917 outs() << " count " << opl.count << "\n";
4918
4919 p += sizeof(struct objc_property_list64);
4920 offset += sizeof(struct objc_property_list64);
4921 for (j = 0; j < opl.count; j++) {
4922 r = get_pointer_64(p, offset, left, S, info);
4923 if (r == nullptr)
4924 return;
4925 memset(&op, '\0', sizeof(struct objc_property64));
4926 if (left < sizeof(struct objc_property64)) {
4927 memcpy(&op, r, left);
4928 outs() << " (objc_property entends past the end of the section)\n";
4929 } else
4930 memcpy(&op, r, sizeof(struct objc_property64));
4931 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4932 swapStruct(op);
4933
4934 outs() << "\t\t\t name ";
4935 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4936 info, n_value, op.name);
4937 if (n_value != 0) {
4938 if (info->verbose && sym_name != nullptr)
4939 outs() << sym_name;
4940 else
4941 outs() << format("0x%" PRIx64, n_value);
4942 if (op.name != 0)
4943 outs() << " + " << format("0x%" PRIx64, op.name);
4944 } else
4945 outs() << format("0x%" PRIx64, op.name);
4946 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4947 if (name != nullptr)
4948 outs() << format(" %.*s", left, name);
4949 outs() << "\n";
4950
4951 outs() << "\t\t\tattributes ";
4952 sym_name =
4953 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4954 info, n_value, op.attributes);
4955 if (n_value != 0) {
4956 if (info->verbose && sym_name != nullptr)
4957 outs() << sym_name;
4958 else
4959 outs() << format("0x%" PRIx64, n_value);
4960 if (op.attributes != 0)
4961 outs() << " + " << format("0x%" PRIx64, op.attributes);
4962 } else
4963 outs() << format("0x%" PRIx64, op.attributes);
4964 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4965 if (name != nullptr)
4966 outs() << format(" %.*s", left, name);
4967 outs() << "\n";
4968
4969 p += sizeof(struct objc_property64);
4970 offset += sizeof(struct objc_property64);
4971 }
4972}
4973
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004974static void print_objc_property_list32(uint32_t p,
4975 struct DisassembleInfo *info) {
4976 struct objc_property_list32 opl;
4977 struct objc_property32 op;
4978 const char *r;
4979 uint32_t offset, xoffset, left, j;
4980 SectionRef S, xS;
4981 const char *name;
4982
4983 r = get_pointer_32(p, offset, left, S, info);
4984 if (r == nullptr)
4985 return;
4986 memset(&opl, '\0', sizeof(struct objc_property_list32));
4987 if (left < sizeof(struct objc_property_list32)) {
4988 memcpy(&opl, r, left);
4989 outs() << " (objc_property_list entends past the end of the section)\n";
4990 } else
4991 memcpy(&opl, r, sizeof(struct objc_property_list32));
4992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4993 swapStruct(opl);
4994 outs() << " entsize " << opl.entsize << "\n";
4995 outs() << " count " << opl.count << "\n";
4996
4997 p += sizeof(struct objc_property_list32);
4998 offset += sizeof(struct objc_property_list32);
4999 for (j = 0; j < opl.count; j++) {
5000 r = get_pointer_32(p, offset, left, S, info);
5001 if (r == nullptr)
5002 return;
5003 memset(&op, '\0', sizeof(struct objc_property32));
5004 if (left < sizeof(struct objc_property32)) {
5005 memcpy(&op, r, left);
5006 outs() << " (objc_property entends past the end of the section)\n";
5007 } else
5008 memcpy(&op, r, sizeof(struct objc_property32));
5009 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5010 swapStruct(op);
5011
5012 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5013 name = get_pointer_32(op.name, xoffset, left, xS, info);
5014 if (name != nullptr)
5015 outs() << format(" %.*s", left, name);
5016 outs() << "\n";
5017
5018 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5019 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5020 if (name != nullptr)
5021 outs() << format(" %.*s", left, name);
5022 outs() << "\n";
5023
5024 p += sizeof(struct objc_property32);
5025 offset += sizeof(struct objc_property32);
5026 }
5027}
5028
Richard Smith81ff44d2015-10-09 22:09:56 +00005029static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005030 bool &is_meta_class) {
5031 struct class_ro64_t cro;
5032 const char *r;
5033 uint32_t offset, xoffset, left;
5034 SectionRef S, xS;
5035 const char *name, *sym_name;
5036 uint64_t n_value;
5037
5038 r = get_pointer_64(p, offset, left, S, info);
5039 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005040 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005041 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043 swapStruct(cro);
5044 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5045 if (cro.flags & RO_META)
5046 outs() << " RO_META";
5047 if (cro.flags & RO_ROOT)
5048 outs() << " RO_ROOT";
5049 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5050 outs() << " RO_HAS_CXX_STRUCTORS";
5051 outs() << "\n";
5052 outs() << " instanceStart " << cro.instanceStart << "\n";
5053 outs() << " instanceSize " << cro.instanceSize << "\n";
5054 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5055 << "\n";
5056 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5057 << "\n";
5058 print_layout_map64(cro.ivarLayout, info);
5059
5060 outs() << " name ";
5061 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5062 info, n_value, cro.name);
5063 if (n_value != 0) {
5064 if (info->verbose && sym_name != nullptr)
5065 outs() << sym_name;
5066 else
5067 outs() << format("0x%" PRIx64, n_value);
5068 if (cro.name != 0)
5069 outs() << " + " << format("0x%" PRIx64, cro.name);
5070 } else
5071 outs() << format("0x%" PRIx64, cro.name);
5072 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5073 if (name != nullptr)
5074 outs() << format(" %.*s", left, name);
5075 outs() << "\n";
5076
5077 outs() << " baseMethods ";
5078 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5079 S, info, n_value, cro.baseMethods);
5080 if (n_value != 0) {
5081 if (info->verbose && sym_name != nullptr)
5082 outs() << sym_name;
5083 else
5084 outs() << format("0x%" PRIx64, n_value);
5085 if (cro.baseMethods != 0)
5086 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5087 } else
5088 outs() << format("0x%" PRIx64, cro.baseMethods);
5089 outs() << " (struct method_list_t *)\n";
5090 if (cro.baseMethods + n_value != 0)
5091 print_method_list64_t(cro.baseMethods + n_value, info, "");
5092
5093 outs() << " baseProtocols ";
5094 sym_name =
5095 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5096 info, n_value, cro.baseProtocols);
5097 if (n_value != 0) {
5098 if (info->verbose && sym_name != nullptr)
5099 outs() << sym_name;
5100 else
5101 outs() << format("0x%" PRIx64, n_value);
5102 if (cro.baseProtocols != 0)
5103 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5104 } else
5105 outs() << format("0x%" PRIx64, cro.baseProtocols);
5106 outs() << "\n";
5107 if (cro.baseProtocols + n_value != 0)
5108 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5109
5110 outs() << " ivars ";
5111 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005112 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005113 if (n_value != 0) {
5114 if (info->verbose && sym_name != nullptr)
5115 outs() << sym_name;
5116 else
5117 outs() << format("0x%" PRIx64, n_value);
5118 if (cro.ivars != 0)
5119 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5120 } else
5121 outs() << format("0x%" PRIx64, cro.ivars);
5122 outs() << "\n";
5123 if (cro.ivars + n_value != 0)
5124 print_ivar_list64_t(cro.ivars + n_value, info);
5125
5126 outs() << " weakIvarLayout ";
5127 sym_name =
5128 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5129 info, n_value, cro.weakIvarLayout);
5130 if (n_value != 0) {
5131 if (info->verbose && sym_name != nullptr)
5132 outs() << sym_name;
5133 else
5134 outs() << format("0x%" PRIx64, n_value);
5135 if (cro.weakIvarLayout != 0)
5136 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5137 } else
5138 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5139 outs() << "\n";
5140 print_layout_map64(cro.weakIvarLayout + n_value, info);
5141
5142 outs() << " baseProperties ";
5143 sym_name =
5144 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5145 info, n_value, cro.baseProperties);
5146 if (n_value != 0) {
5147 if (info->verbose && sym_name != nullptr)
5148 outs() << sym_name;
5149 else
5150 outs() << format("0x%" PRIx64, n_value);
5151 if (cro.baseProperties != 0)
5152 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5153 } else
5154 outs() << format("0x%" PRIx64, cro.baseProperties);
5155 outs() << "\n";
5156 if (cro.baseProperties + n_value != 0)
5157 print_objc_property_list64(cro.baseProperties + n_value, info);
5158
Rafael Espindolab9091322015-10-24 23:19:10 +00005159 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005160 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005161}
5162
Richard Smith81ff44d2015-10-09 22:09:56 +00005163static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005164 bool &is_meta_class) {
5165 struct class_ro32_t cro;
5166 const char *r;
5167 uint32_t offset, xoffset, left;
5168 SectionRef S, xS;
5169 const char *name;
5170
5171 r = get_pointer_32(p, offset, left, S, info);
5172 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005173 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005174 memset(&cro, '\0', sizeof(struct class_ro32_t));
5175 if (left < sizeof(struct class_ro32_t)) {
5176 memcpy(&cro, r, left);
5177 outs() << " (class_ro_t entends past the end of the section)\n";
5178 } else
5179 memcpy(&cro, r, sizeof(struct class_ro32_t));
5180 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5181 swapStruct(cro);
5182 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5183 if (cro.flags & RO_META)
5184 outs() << " RO_META";
5185 if (cro.flags & RO_ROOT)
5186 outs() << " RO_ROOT";
5187 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5188 outs() << " RO_HAS_CXX_STRUCTORS";
5189 outs() << "\n";
5190 outs() << " instanceStart " << cro.instanceStart << "\n";
5191 outs() << " instanceSize " << cro.instanceSize << "\n";
5192 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5193 << "\n";
5194 print_layout_map32(cro.ivarLayout, info);
5195
5196 outs() << " name " << format("0x%" PRIx32, cro.name);
5197 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5198 if (name != nullptr)
5199 outs() << format(" %.*s", left, name);
5200 outs() << "\n";
5201
5202 outs() << " baseMethods "
5203 << format("0x%" PRIx32, cro.baseMethods)
5204 << " (struct method_list_t *)\n";
5205 if (cro.baseMethods != 0)
5206 print_method_list32_t(cro.baseMethods, info, "");
5207
5208 outs() << " baseProtocols "
5209 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5210 if (cro.baseProtocols != 0)
5211 print_protocol_list32_t(cro.baseProtocols, info);
5212 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5213 << "\n";
5214 if (cro.ivars != 0)
5215 print_ivar_list32_t(cro.ivars, info);
5216 outs() << " weakIvarLayout "
5217 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5218 print_layout_map32(cro.weakIvarLayout, info);
5219 outs() << " baseProperties "
5220 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5221 if (cro.baseProperties != 0)
5222 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005223 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005224 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005225}
5226
Kevin Enderby0fc11822015-04-01 20:57:01 +00005227static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5228 struct class64_t c;
5229 const char *r;
5230 uint32_t offset, left;
5231 SectionRef S;
5232 const char *name;
5233 uint64_t isa_n_value, n_value;
5234
5235 r = get_pointer_64(p, offset, left, S, info);
5236 if (r == nullptr || left < sizeof(struct class64_t))
5237 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005238 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005239 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5240 swapStruct(c);
5241
5242 outs() << " isa " << format("0x%" PRIx64, c.isa);
5243 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5244 isa_n_value, c.isa);
5245 if (name != nullptr)
5246 outs() << " " << name;
5247 outs() << "\n";
5248
5249 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5250 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5251 n_value, c.superclass);
5252 if (name != nullptr)
5253 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005254 else {
5255 name = get_dyld_bind_info_symbolname(S.getAddress() +
5256 offset + offsetof(struct class64_t, superclass), info);
5257 if (name != nullptr)
5258 outs() << " " << name;
5259 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005260 outs() << "\n";
5261
5262 outs() << " cache " << format("0x%" PRIx64, c.cache);
5263 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5264 n_value, c.cache);
5265 if (name != nullptr)
5266 outs() << " " << name;
5267 outs() << "\n";
5268
5269 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5270 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5271 n_value, c.vtable);
5272 if (name != nullptr)
5273 outs() << " " << name;
5274 outs() << "\n";
5275
5276 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5277 n_value, c.data);
5278 outs() << " data ";
5279 if (n_value != 0) {
5280 if (info->verbose && name != nullptr)
5281 outs() << name;
5282 else
5283 outs() << format("0x%" PRIx64, n_value);
5284 if (c.data != 0)
5285 outs() << " + " << format("0x%" PRIx64, c.data);
5286 } else
5287 outs() << format("0x%" PRIx64, c.data);
5288 outs() << " (struct class_ro_t *)";
5289
5290 // This is a Swift class if some of the low bits of the pointer are set.
5291 if ((c.data + n_value) & 0x7)
5292 outs() << " Swift class";
5293 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005294 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005295 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5296 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005297
Kevin Enderbyaac75382015-10-08 16:56:35 +00005298 if (!is_meta_class &&
5299 c.isa + isa_n_value != p &&
5300 c.isa + isa_n_value != 0 &&
5301 info->depth < 100) {
5302 info->depth++;
5303 outs() << "Meta Class\n";
5304 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005305 }
5306}
5307
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005308static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5309 struct class32_t c;
5310 const char *r;
5311 uint32_t offset, left;
5312 SectionRef S;
5313 const char *name;
5314
5315 r = get_pointer_32(p, offset, left, S, info);
5316 if (r == nullptr)
5317 return;
5318 memset(&c, '\0', sizeof(struct class32_t));
5319 if (left < sizeof(struct class32_t)) {
5320 memcpy(&c, r, left);
5321 outs() << " (class_t entends past the end of the section)\n";
5322 } else
5323 memcpy(&c, r, sizeof(struct class32_t));
5324 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5325 swapStruct(c);
5326
5327 outs() << " isa " << format("0x%" PRIx32, c.isa);
5328 name =
5329 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5330 if (name != nullptr)
5331 outs() << " " << name;
5332 outs() << "\n";
5333
5334 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5335 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5336 c.superclass);
5337 if (name != nullptr)
5338 outs() << " " << name;
5339 outs() << "\n";
5340
5341 outs() << " cache " << format("0x%" PRIx32, c.cache);
5342 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5343 c.cache);
5344 if (name != nullptr)
5345 outs() << " " << name;
5346 outs() << "\n";
5347
5348 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5349 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5350 c.vtable);
5351 if (name != nullptr)
5352 outs() << " " << name;
5353 outs() << "\n";
5354
5355 name =
5356 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5357 outs() << " data " << format("0x%" PRIx32, c.data)
5358 << " (struct class_ro_t *)";
5359
5360 // This is a Swift class if some of the low bits of the pointer are set.
5361 if (c.data & 0x3)
5362 outs() << " Swift class";
5363 outs() << "\n";
5364 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005365 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5366 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005367
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005368 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005369 outs() << "Meta Class\n";
5370 print_class32_t(c.isa, info);
5371 }
5372}
5373
Kevin Enderby846c0002015-04-16 17:19:59 +00005374static void print_objc_class_t(struct objc_class_t *objc_class,
5375 struct DisassembleInfo *info) {
5376 uint32_t offset, left, xleft;
5377 const char *name, *p, *ivar_list;
5378 SectionRef S;
5379 int32_t i;
5380 struct objc_ivar_list_t objc_ivar_list;
5381 struct objc_ivar_t ivar;
5382
5383 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5384 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5385 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5386 if (name != nullptr)
5387 outs() << format(" %.*s", left, name);
5388 else
5389 outs() << " (not in an __OBJC section)";
5390 }
5391 outs() << "\n";
5392
5393 outs() << "\t super_class "
5394 << format("0x%08" PRIx32, objc_class->super_class);
5395 if (info->verbose) {
5396 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5397 if (name != nullptr)
5398 outs() << format(" %.*s", left, name);
5399 else
5400 outs() << " (not in an __OBJC section)";
5401 }
5402 outs() << "\n";
5403
5404 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5405 if (info->verbose) {
5406 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5407 if (name != nullptr)
5408 outs() << format(" %.*s", left, name);
5409 else
5410 outs() << " (not in an __OBJC section)";
5411 }
5412 outs() << "\n";
5413
5414 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5415 << "\n";
5416
5417 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5418 if (info->verbose) {
5419 if (CLS_GETINFO(objc_class, CLS_CLASS))
5420 outs() << " CLS_CLASS";
5421 else if (CLS_GETINFO(objc_class, CLS_META))
5422 outs() << " CLS_META";
5423 }
5424 outs() << "\n";
5425
5426 outs() << "\t instance_size "
5427 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5428
5429 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5430 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5431 if (p != nullptr) {
5432 if (left > sizeof(struct objc_ivar_list_t)) {
5433 outs() << "\n";
5434 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5435 } else {
5436 outs() << " (entends past the end of the section)\n";
5437 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5438 memcpy(&objc_ivar_list, p, left);
5439 }
5440 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5441 swapStruct(objc_ivar_list);
5442 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5443 ivar_list = p + sizeof(struct objc_ivar_list_t);
5444 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5445 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5446 outs() << "\t\t remaining ivar's extend past the of the section\n";
5447 break;
5448 }
5449 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5450 sizeof(struct objc_ivar_t));
5451 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5452 swapStruct(ivar);
5453
5454 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5455 if (info->verbose) {
5456 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5457 if (name != nullptr)
5458 outs() << format(" %.*s", xleft, name);
5459 else
5460 outs() << " (not in an __OBJC section)";
5461 }
5462 outs() << "\n";
5463
5464 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5465 if (info->verbose) {
5466 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5467 if (name != nullptr)
5468 outs() << format(" %.*s", xleft, name);
5469 else
5470 outs() << " (not in an __OBJC section)";
5471 }
5472 outs() << "\n";
5473
5474 outs() << "\t\t ivar_offset "
5475 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5476 }
5477 } else {
5478 outs() << " (not in an __OBJC section)\n";
5479 }
5480
5481 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5482 if (print_method_list(objc_class->methodLists, info))
5483 outs() << " (not in an __OBJC section)\n";
5484
5485 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5486 << "\n";
5487
5488 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5489 if (print_protocol_list(objc_class->protocols, 16, info))
5490 outs() << " (not in an __OBJC section)\n";
5491}
5492
5493static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5494 struct DisassembleInfo *info) {
5495 uint32_t offset, left;
5496 const char *name;
5497 SectionRef S;
5498
5499 outs() << "\t category name "
5500 << format("0x%08" PRIx32, objc_category->category_name);
5501 if (info->verbose) {
5502 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5503 true);
5504 if (name != nullptr)
5505 outs() << format(" %.*s", left, name);
5506 else
5507 outs() << " (not in an __OBJC section)";
5508 }
5509 outs() << "\n";
5510
5511 outs() << "\t\t class name "
5512 << format("0x%08" PRIx32, objc_category->class_name);
5513 if (info->verbose) {
5514 name =
5515 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5516 if (name != nullptr)
5517 outs() << format(" %.*s", left, name);
5518 else
5519 outs() << " (not in an __OBJC section)";
5520 }
5521 outs() << "\n";
5522
5523 outs() << "\t instance methods "
5524 << format("0x%08" PRIx32, objc_category->instance_methods);
5525 if (print_method_list(objc_category->instance_methods, info))
5526 outs() << " (not in an __OBJC section)\n";
5527
5528 outs() << "\t class methods "
5529 << format("0x%08" PRIx32, objc_category->class_methods);
5530 if (print_method_list(objc_category->class_methods, info))
5531 outs() << " (not in an __OBJC section)\n";
5532}
5533
Kevin Enderby0fc11822015-04-01 20:57:01 +00005534static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5535 struct category64_t c;
5536 const char *r;
5537 uint32_t offset, xoffset, left;
5538 SectionRef S, xS;
5539 const char *name, *sym_name;
5540 uint64_t n_value;
5541
5542 r = get_pointer_64(p, offset, left, S, info);
5543 if (r == nullptr)
5544 return;
5545 memset(&c, '\0', sizeof(struct category64_t));
5546 if (left < sizeof(struct category64_t)) {
5547 memcpy(&c, r, left);
5548 outs() << " (category_t entends past the end of the section)\n";
5549 } else
5550 memcpy(&c, r, sizeof(struct category64_t));
5551 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5552 swapStruct(c);
5553
5554 outs() << " name ";
5555 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5556 info, n_value, c.name);
5557 if (n_value != 0) {
5558 if (info->verbose && sym_name != nullptr)
5559 outs() << sym_name;
5560 else
5561 outs() << format("0x%" PRIx64, n_value);
5562 if (c.name != 0)
5563 outs() << " + " << format("0x%" PRIx64, c.name);
5564 } else
5565 outs() << format("0x%" PRIx64, c.name);
5566 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5567 if (name != nullptr)
5568 outs() << format(" %.*s", left, name);
5569 outs() << "\n";
5570
5571 outs() << " cls ";
5572 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5573 n_value, c.cls);
5574 if (n_value != 0) {
5575 if (info->verbose && sym_name != nullptr)
5576 outs() << sym_name;
5577 else
5578 outs() << format("0x%" PRIx64, n_value);
5579 if (c.cls != 0)
5580 outs() << " + " << format("0x%" PRIx64, c.cls);
5581 } else
5582 outs() << format("0x%" PRIx64, c.cls);
5583 outs() << "\n";
5584 if (c.cls + n_value != 0)
5585 print_class64_t(c.cls + n_value, info);
5586
5587 outs() << " instanceMethods ";
5588 sym_name =
5589 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5590 info, n_value, c.instanceMethods);
5591 if (n_value != 0) {
5592 if (info->verbose && sym_name != nullptr)
5593 outs() << sym_name;
5594 else
5595 outs() << format("0x%" PRIx64, n_value);
5596 if (c.instanceMethods != 0)
5597 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5598 } else
5599 outs() << format("0x%" PRIx64, c.instanceMethods);
5600 outs() << "\n";
5601 if (c.instanceMethods + n_value != 0)
5602 print_method_list64_t(c.instanceMethods + n_value, info, "");
5603
5604 outs() << " classMethods ";
5605 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5606 S, info, n_value, c.classMethods);
5607 if (n_value != 0) {
5608 if (info->verbose && sym_name != nullptr)
5609 outs() << sym_name;
5610 else
5611 outs() << format("0x%" PRIx64, n_value);
5612 if (c.classMethods != 0)
5613 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5614 } else
5615 outs() << format("0x%" PRIx64, c.classMethods);
5616 outs() << "\n";
5617 if (c.classMethods + n_value != 0)
5618 print_method_list64_t(c.classMethods + n_value, info, "");
5619
5620 outs() << " protocols ";
5621 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5622 info, n_value, c.protocols);
5623 if (n_value != 0) {
5624 if (info->verbose && sym_name != nullptr)
5625 outs() << sym_name;
5626 else
5627 outs() << format("0x%" PRIx64, n_value);
5628 if (c.protocols != 0)
5629 outs() << " + " << format("0x%" PRIx64, c.protocols);
5630 } else
5631 outs() << format("0x%" PRIx64, c.protocols);
5632 outs() << "\n";
5633 if (c.protocols + n_value != 0)
5634 print_protocol_list64_t(c.protocols + n_value, info);
5635
5636 outs() << "instanceProperties ";
5637 sym_name =
5638 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5639 S, info, n_value, c.instanceProperties);
5640 if (n_value != 0) {
5641 if (info->verbose && sym_name != nullptr)
5642 outs() << sym_name;
5643 else
5644 outs() << format("0x%" PRIx64, n_value);
5645 if (c.instanceProperties != 0)
5646 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5647 } else
5648 outs() << format("0x%" PRIx64, c.instanceProperties);
5649 outs() << "\n";
5650 if (c.instanceProperties + n_value != 0)
5651 print_objc_property_list64(c.instanceProperties + n_value, info);
5652}
5653
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005654static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5655 struct category32_t c;
5656 const char *r;
5657 uint32_t offset, left;
5658 SectionRef S, xS;
5659 const char *name;
5660
5661 r = get_pointer_32(p, offset, left, S, info);
5662 if (r == nullptr)
5663 return;
5664 memset(&c, '\0', sizeof(struct category32_t));
5665 if (left < sizeof(struct category32_t)) {
5666 memcpy(&c, r, left);
5667 outs() << " (category_t entends past the end of the section)\n";
5668 } else
5669 memcpy(&c, r, sizeof(struct category32_t));
5670 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5671 swapStruct(c);
5672
5673 outs() << " name " << format("0x%" PRIx32, c.name);
5674 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5675 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005676 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005677 outs() << " " << name;
5678 outs() << "\n";
5679
5680 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5681 if (c.cls != 0)
5682 print_class32_t(c.cls, info);
5683 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5684 << "\n";
5685 if (c.instanceMethods != 0)
5686 print_method_list32_t(c.instanceMethods, info, "");
5687 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5688 << "\n";
5689 if (c.classMethods != 0)
5690 print_method_list32_t(c.classMethods, info, "");
5691 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5692 if (c.protocols != 0)
5693 print_protocol_list32_t(c.protocols, info);
5694 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5695 << "\n";
5696 if (c.instanceProperties != 0)
5697 print_objc_property_list32(c.instanceProperties, info);
5698}
5699
Kevin Enderby0fc11822015-04-01 20:57:01 +00005700static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5701 uint32_t i, left, offset, xoffset;
5702 uint64_t p, n_value;
5703 struct message_ref64 mr;
5704 const char *name, *sym_name;
5705 const char *r;
5706 SectionRef xS;
5707
5708 if (S == SectionRef())
5709 return;
5710
5711 StringRef SectName;
5712 S.getName(SectName);
5713 DataRefImpl Ref = S.getRawDataRefImpl();
5714 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5715 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5716 offset = 0;
5717 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5718 p = S.getAddress() + i;
5719 r = get_pointer_64(p, offset, left, S, info);
5720 if (r == nullptr)
5721 return;
5722 memset(&mr, '\0', sizeof(struct message_ref64));
5723 if (left < sizeof(struct message_ref64)) {
5724 memcpy(&mr, r, left);
5725 outs() << " (message_ref entends past the end of the section)\n";
5726 } else
5727 memcpy(&mr, r, sizeof(struct message_ref64));
5728 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5729 swapStruct(mr);
5730
5731 outs() << " imp ";
5732 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5733 n_value, mr.imp);
5734 if (n_value != 0) {
5735 outs() << format("0x%" PRIx64, n_value) << " ";
5736 if (mr.imp != 0)
5737 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5738 } else
5739 outs() << format("0x%" PRIx64, mr.imp) << " ";
5740 if (name != nullptr)
5741 outs() << " " << name;
5742 outs() << "\n";
5743
5744 outs() << " sel ";
5745 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5746 info, n_value, mr.sel);
5747 if (n_value != 0) {
5748 if (info->verbose && sym_name != nullptr)
5749 outs() << sym_name;
5750 else
5751 outs() << format("0x%" PRIx64, n_value);
5752 if (mr.sel != 0)
5753 outs() << " + " << format("0x%" PRIx64, mr.sel);
5754 } else
5755 outs() << format("0x%" PRIx64, mr.sel);
5756 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5757 if (name != nullptr)
5758 outs() << format(" %.*s", left, name);
5759 outs() << "\n";
5760
5761 offset += sizeof(struct message_ref64);
5762 }
5763}
5764
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005765static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5766 uint32_t i, left, offset, xoffset, p;
5767 struct message_ref32 mr;
5768 const char *name, *r;
5769 SectionRef xS;
5770
5771 if (S == SectionRef())
5772 return;
5773
5774 StringRef SectName;
5775 S.getName(SectName);
5776 DataRefImpl Ref = S.getRawDataRefImpl();
5777 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5778 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5779 offset = 0;
5780 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5781 p = S.getAddress() + i;
5782 r = get_pointer_32(p, offset, left, S, info);
5783 if (r == nullptr)
5784 return;
5785 memset(&mr, '\0', sizeof(struct message_ref32));
5786 if (left < sizeof(struct message_ref32)) {
5787 memcpy(&mr, r, left);
5788 outs() << " (message_ref entends past the end of the section)\n";
5789 } else
5790 memcpy(&mr, r, sizeof(struct message_ref32));
5791 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5792 swapStruct(mr);
5793
5794 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5795 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5796 mr.imp);
5797 if (name != nullptr)
5798 outs() << " " << name;
5799 outs() << "\n";
5800
5801 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5802 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5803 if (name != nullptr)
5804 outs() << " " << name;
5805 outs() << "\n";
5806
5807 offset += sizeof(struct message_ref32);
5808 }
5809}
5810
Kevin Enderby0fc11822015-04-01 20:57:01 +00005811static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5812 uint32_t left, offset, swift_version;
5813 uint64_t p;
5814 struct objc_image_info64 o;
5815 const char *r;
5816
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005817 if (S == SectionRef())
5818 return;
5819
Kevin Enderby0fc11822015-04-01 20:57:01 +00005820 StringRef SectName;
5821 S.getName(SectName);
5822 DataRefImpl Ref = S.getRawDataRefImpl();
5823 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5824 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5825 p = S.getAddress();
5826 r = get_pointer_64(p, offset, left, S, info);
5827 if (r == nullptr)
5828 return;
5829 memset(&o, '\0', sizeof(struct objc_image_info64));
5830 if (left < sizeof(struct objc_image_info64)) {
5831 memcpy(&o, r, left);
5832 outs() << " (objc_image_info entends past the end of the section)\n";
5833 } else
5834 memcpy(&o, r, sizeof(struct objc_image_info64));
5835 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5836 swapStruct(o);
5837 outs() << " version " << o.version << "\n";
5838 outs() << " flags " << format("0x%" PRIx32, o.flags);
5839 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5840 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5841 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5842 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005843 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5844 outs() << " OBJC_IMAGE_IS_SIMULATED";
5845 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5846 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005847 swift_version = (o.flags >> 8) & 0xff;
5848 if (swift_version != 0) {
5849 if (swift_version == 1)
5850 outs() << " Swift 1.0";
5851 else if (swift_version == 2)
5852 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005853 else if(swift_version == 3)
5854 outs() << " Swift 2.0";
5855 else if(swift_version == 4)
5856 outs() << " Swift 3.0";
5857 else if(swift_version == 5)
5858 outs() << " Swift 4.0";
5859 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005860 outs() << " Swift 4.1/Swift 4.2";
5861 else if(swift_version == 7)
5862 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005863 else
5864 outs() << " unknown future Swift version (" << swift_version << ")";
5865 }
5866 outs() << "\n";
5867}
5868
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005869static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5870 uint32_t left, offset, swift_version, p;
5871 struct objc_image_info32 o;
5872 const char *r;
5873
Kevin Enderby19be2512016-04-21 19:49:29 +00005874 if (S == SectionRef())
5875 return;
5876
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005877 StringRef SectName;
5878 S.getName(SectName);
5879 DataRefImpl Ref = S.getRawDataRefImpl();
5880 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5881 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5882 p = S.getAddress();
5883 r = get_pointer_32(p, offset, left, S, info);
5884 if (r == nullptr)
5885 return;
5886 memset(&o, '\0', sizeof(struct objc_image_info32));
5887 if (left < sizeof(struct objc_image_info32)) {
5888 memcpy(&o, r, left);
5889 outs() << " (objc_image_info entends past the end of the section)\n";
5890 } else
5891 memcpy(&o, r, sizeof(struct objc_image_info32));
5892 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5893 swapStruct(o);
5894 outs() << " version " << o.version << "\n";
5895 outs() << " flags " << format("0x%" PRIx32, o.flags);
5896 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5897 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5898 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5899 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5900 swift_version = (o.flags >> 8) & 0xff;
5901 if (swift_version != 0) {
5902 if (swift_version == 1)
5903 outs() << " Swift 1.0";
5904 else if (swift_version == 2)
5905 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005906 else if(swift_version == 3)
5907 outs() << " Swift 2.0";
5908 else if(swift_version == 4)
5909 outs() << " Swift 3.0";
5910 else if(swift_version == 5)
5911 outs() << " Swift 4.0";
5912 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005913 outs() << " Swift 4.1/Swift 4.2";
5914 else if(swift_version == 7)
5915 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005916 else
5917 outs() << " unknown future Swift version (" << swift_version << ")";
5918 }
5919 outs() << "\n";
5920}
5921
Kevin Enderby846c0002015-04-16 17:19:59 +00005922static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5923 uint32_t left, offset, p;
5924 struct imageInfo_t o;
5925 const char *r;
5926
5927 StringRef SectName;
5928 S.getName(SectName);
5929 DataRefImpl Ref = S.getRawDataRefImpl();
5930 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5931 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5932 p = S.getAddress();
5933 r = get_pointer_32(p, offset, left, S, info);
5934 if (r == nullptr)
5935 return;
5936 memset(&o, '\0', sizeof(struct imageInfo_t));
5937 if (left < sizeof(struct imageInfo_t)) {
5938 memcpy(&o, r, left);
5939 outs() << " (imageInfo entends past the end of the section)\n";
5940 } else
5941 memcpy(&o, r, sizeof(struct imageInfo_t));
5942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5943 swapStruct(o);
5944 outs() << " version " << o.version << "\n";
5945 outs() << " flags " << format("0x%" PRIx32, o.flags);
5946 if (o.flags & 0x1)
5947 outs() << " F&C";
5948 if (o.flags & 0x2)
5949 outs() << " GC";
5950 if (o.flags & 0x4)
5951 outs() << " GC-only";
5952 else
5953 outs() << " RR";
5954 outs() << "\n";
5955}
5956
Kevin Enderby0fc11822015-04-01 20:57:01 +00005957static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5958 SymbolAddressMap AddrMap;
5959 if (verbose)
5960 CreateSymbolAddressMap(O, &AddrMap);
5961
5962 std::vector<SectionRef> Sections;
5963 for (const SectionRef &Section : O->sections()) {
5964 StringRef SectName;
5965 Section.getName(SectName);
5966 Sections.push_back(Section);
5967 }
5968
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005969 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005970
Davide Italiano62507042015-12-11 22:27:59 +00005971 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5972 if (CL == SectionRef())
5973 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005974 if (CL == SectionRef())
5975 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5976 if (CL == SectionRef())
5977 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005978 info.S = CL;
5979 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005980
Davide Italiano62507042015-12-11 22:27:59 +00005981 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5982 if (CR == SectionRef())
5983 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005984 if (CR == SectionRef())
5985 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5986 if (CR == SectionRef())
5987 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005988 info.S = CR;
5989 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005990
Davide Italiano62507042015-12-11 22:27:59 +00005991 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5992 if (SR == SectionRef())
5993 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005994 if (SR == SectionRef())
5995 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5996 if (SR == SectionRef())
5997 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005998 info.S = SR;
5999 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006000
Davide Italiano62507042015-12-11 22:27:59 +00006001 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6002 if (CA == SectionRef())
6003 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006004 if (CA == SectionRef())
6005 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6006 if (CA == SectionRef())
6007 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00006008 info.S = CA;
6009 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006010
Davide Italiano62507042015-12-11 22:27:59 +00006011 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6012 if (PL == SectionRef())
6013 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006014 if (PL == SectionRef())
6015 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6016 if (PL == SectionRef())
6017 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00006018 info.S = PL;
6019 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006020
Davide Italiano62507042015-12-11 22:27:59 +00006021 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6022 if (MR == SectionRef())
6023 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006024 if (MR == SectionRef())
6025 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6026 if (MR == SectionRef())
6027 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006028 info.S = MR;
6029 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006030
Davide Italiano62507042015-12-11 22:27:59 +00006031 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6032 if (II == SectionRef())
6033 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006034 if (II == SectionRef())
6035 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6036 if (II == SectionRef())
6037 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006038 info.S = II;
6039 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006040}
6041
6042static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006043 SymbolAddressMap AddrMap;
6044 if (verbose)
6045 CreateSymbolAddressMap(O, &AddrMap);
6046
6047 std::vector<SectionRef> Sections;
6048 for (const SectionRef &Section : O->sections()) {
6049 StringRef SectName;
6050 Section.getName(SectName);
6051 Sections.push_back(Section);
6052 }
6053
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006054 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006055
Kevin Enderby5879a482017-02-09 17:56:26 +00006056 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6057 if (CL == SectionRef())
6058 CL = get_section(O, "__DATA", "__objc_classlist");
6059 if (CL == SectionRef())
6060 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6061 if (CL == SectionRef())
6062 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6063 info.S = CL;
6064 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006065
Kevin Enderby5879a482017-02-09 17:56:26 +00006066 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6067 if (CR == SectionRef())
6068 CR = get_section(O, "__DATA", "__objc_classrefs");
6069 if (CR == SectionRef())
6070 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6071 if (CR == SectionRef())
6072 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6073 info.S = CR;
6074 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006075
Kevin Enderby5879a482017-02-09 17:56:26 +00006076 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6077 if (SR == SectionRef())
6078 SR = get_section(O, "__DATA", "__objc_superrefs");
6079 if (SR == SectionRef())
6080 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6081 if (SR == SectionRef())
6082 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6083 info.S = SR;
6084 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006085
Kevin Enderby5879a482017-02-09 17:56:26 +00006086 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6087 if (CA == SectionRef())
6088 CA = get_section(O, "__DATA", "__objc_catlist");
6089 if (CA == SectionRef())
6090 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6091 if (CA == SectionRef())
6092 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6093 info.S = CA;
6094 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006095
Kevin Enderby5879a482017-02-09 17:56:26 +00006096 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6097 if (PL == SectionRef())
6098 PL = get_section(O, "__DATA", "__objc_protolist");
6099 if (PL == SectionRef())
6100 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6101 if (PL == SectionRef())
6102 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6103 info.S = PL;
6104 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006105
Kevin Enderby5879a482017-02-09 17:56:26 +00006106 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6107 if (MR == SectionRef())
6108 MR = get_section(O, "__DATA", "__objc_msgrefs");
6109 if (MR == SectionRef())
6110 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6111 if (MR == SectionRef())
6112 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6113 info.S = MR;
6114 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006115
Kevin Enderby5879a482017-02-09 17:56:26 +00006116 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6117 if (II == SectionRef())
6118 II = get_section(O, "__DATA", "__objc_imageinfo");
6119 if (II == SectionRef())
6120 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6121 if (II == SectionRef())
6122 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6123 info.S = II;
6124 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006125}
6126
6127static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006128 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6129 const char *r, *name, *defs;
6130 struct objc_module_t module;
6131 SectionRef S, xS;
6132 struct objc_symtab_t symtab;
6133 struct objc_class_t objc_class;
6134 struct objc_category_t objc_category;
6135
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006136 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006137 S = get_section(O, "__OBJC", "__module_info");
6138 if (S == SectionRef())
6139 return false;
6140
6141 SymbolAddressMap AddrMap;
6142 if (verbose)
6143 CreateSymbolAddressMap(O, &AddrMap);
6144
6145 std::vector<SectionRef> Sections;
6146 for (const SectionRef &Section : O->sections()) {
6147 StringRef SectName;
6148 Section.getName(SectName);
6149 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006150 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006151
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006152 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006153
6154 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6155 p = S.getAddress() + i;
6156 r = get_pointer_32(p, offset, left, S, &info, true);
6157 if (r == nullptr)
6158 return true;
6159 memset(&module, '\0', sizeof(struct objc_module_t));
6160 if (left < sizeof(struct objc_module_t)) {
6161 memcpy(&module, r, left);
6162 outs() << " (module extends past end of __module_info section)\n";
6163 } else
6164 memcpy(&module, r, sizeof(struct objc_module_t));
6165 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6166 swapStruct(module);
6167
6168 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6169 outs() << " version " << module.version << "\n";
6170 outs() << " size " << module.size << "\n";
6171 outs() << " name ";
6172 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6173 if (name != nullptr)
6174 outs() << format("%.*s", left, name);
6175 else
6176 outs() << format("0x%08" PRIx32, module.name)
6177 << "(not in an __OBJC section)";
6178 outs() << "\n";
6179
6180 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6181 if (module.symtab == 0 || r == nullptr) {
6182 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6183 << " (not in an __OBJC section)\n";
6184 continue;
6185 }
6186 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6187 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6188 defs_left = 0;
6189 defs = nullptr;
6190 if (left < sizeof(struct objc_symtab_t)) {
6191 memcpy(&symtab, r, left);
6192 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6193 } else {
6194 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6195 if (left > sizeof(struct objc_symtab_t)) {
6196 defs_left = left - sizeof(struct objc_symtab_t);
6197 defs = r + sizeof(struct objc_symtab_t);
6198 }
6199 }
6200 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6201 swapStruct(symtab);
6202
6203 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6204 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6205 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6206 if (r == nullptr)
6207 outs() << " (not in an __OBJC section)";
6208 outs() << "\n";
6209 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6210 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6211 if (symtab.cls_def_cnt > 0)
6212 outs() << "\tClass Definitions\n";
6213 for (j = 0; j < symtab.cls_def_cnt; j++) {
6214 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6215 outs() << "\t(remaining class defs entries entends past the end of the "
6216 << "section)\n";
6217 break;
6218 }
6219 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6220 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6221 sys::swapByteOrder(def);
6222
6223 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6224 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6225 if (r != nullptr) {
6226 if (left > sizeof(struct objc_class_t)) {
6227 outs() << "\n";
6228 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6229 } else {
6230 outs() << " (entends past the end of the section)\n";
6231 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6232 memcpy(&objc_class, r, left);
6233 }
6234 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6235 swapStruct(objc_class);
6236 print_objc_class_t(&objc_class, &info);
6237 } else {
6238 outs() << "(not in an __OBJC section)\n";
6239 }
6240
6241 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6242 outs() << "\tMeta Class";
6243 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6244 if (r != nullptr) {
6245 if (left > sizeof(struct objc_class_t)) {
6246 outs() << "\n";
6247 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6248 } else {
6249 outs() << " (entends past the end of the section)\n";
6250 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6251 memcpy(&objc_class, r, left);
6252 }
6253 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6254 swapStruct(objc_class);
6255 print_objc_class_t(&objc_class, &info);
6256 } else {
6257 outs() << "(not in an __OBJC section)\n";
6258 }
6259 }
6260 }
6261 if (symtab.cat_def_cnt > 0)
6262 outs() << "\tCategory Definitions\n";
6263 for (j = 0; j < symtab.cat_def_cnt; j++) {
6264 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6265 outs() << "\t(remaining category defs entries entends past the end of "
6266 << "the section)\n";
6267 break;
6268 }
6269 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6270 sizeof(uint32_t));
6271 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6272 sys::swapByteOrder(def);
6273
6274 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6275 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6276 << format("0x%08" PRIx32, def);
6277 if (r != nullptr) {
6278 if (left > sizeof(struct objc_category_t)) {
6279 outs() << "\n";
6280 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6281 } else {
6282 outs() << " (entends past the end of the section)\n";
6283 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6284 memcpy(&objc_category, r, left);
6285 }
6286 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6287 swapStruct(objc_category);
6288 print_objc_objc_category_t(&objc_category, &info);
6289 } else {
6290 outs() << "(not in an __OBJC section)\n";
6291 }
6292 }
6293 }
6294 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6295 if (II != SectionRef())
6296 print_image_info(II, &info);
6297
6298 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006299}
6300
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006301static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6302 uint32_t size, uint32_t addr) {
6303 SymbolAddressMap AddrMap;
6304 CreateSymbolAddressMap(O, &AddrMap);
6305
6306 std::vector<SectionRef> Sections;
6307 for (const SectionRef &Section : O->sections()) {
6308 StringRef SectName;
6309 Section.getName(SectName);
6310 Sections.push_back(Section);
6311 }
6312
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006313 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006314
6315 const char *p;
6316 struct objc_protocol_t protocol;
6317 uint32_t left, paddr;
6318 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6319 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6320 left = size - (p - sect);
6321 if (left < sizeof(struct objc_protocol_t)) {
6322 outs() << "Protocol extends past end of __protocol section\n";
6323 memcpy(&protocol, p, left);
6324 } else
6325 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6326 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6327 swapStruct(protocol);
6328 paddr = addr + (p - sect);
6329 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6330 if (print_protocol(paddr, 0, &info))
6331 outs() << "(not in an __OBJC section)\n";
6332 }
6333}
6334
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006335#ifdef HAVE_LIBXAR
6336inline void swapStruct(struct xar_header &xar) {
6337 sys::swapByteOrder(xar.magic);
6338 sys::swapByteOrder(xar.size);
6339 sys::swapByteOrder(xar.version);
6340 sys::swapByteOrder(xar.toc_length_compressed);
6341 sys::swapByteOrder(xar.toc_length_uncompressed);
6342 sys::swapByteOrder(xar.cksum_alg);
6343}
6344
6345static void PrintModeVerbose(uint32_t mode) {
6346 switch(mode & S_IFMT){
6347 case S_IFDIR:
6348 outs() << "d";
6349 break;
6350 case S_IFCHR:
6351 outs() << "c";
6352 break;
6353 case S_IFBLK:
6354 outs() << "b";
6355 break;
6356 case S_IFREG:
6357 outs() << "-";
6358 break;
6359 case S_IFLNK:
6360 outs() << "l";
6361 break;
6362 case S_IFSOCK:
6363 outs() << "s";
6364 break;
6365 default:
6366 outs() << "?";
6367 break;
6368 }
6369
6370 /* owner permissions */
6371 if(mode & S_IREAD)
6372 outs() << "r";
6373 else
6374 outs() << "-";
6375 if(mode & S_IWRITE)
6376 outs() << "w";
6377 else
6378 outs() << "-";
6379 if(mode & S_ISUID)
6380 outs() << "s";
6381 else if(mode & S_IEXEC)
6382 outs() << "x";
6383 else
6384 outs() << "-";
6385
6386 /* group permissions */
6387 if(mode & (S_IREAD >> 3))
6388 outs() << "r";
6389 else
6390 outs() << "-";
6391 if(mode & (S_IWRITE >> 3))
6392 outs() << "w";
6393 else
6394 outs() << "-";
6395 if(mode & S_ISGID)
6396 outs() << "s";
6397 else if(mode & (S_IEXEC >> 3))
6398 outs() << "x";
6399 else
6400 outs() << "-";
6401
6402 /* other permissions */
6403 if(mode & (S_IREAD >> 6))
6404 outs() << "r";
6405 else
6406 outs() << "-";
6407 if(mode & (S_IWRITE >> 6))
6408 outs() << "w";
6409 else
6410 outs() << "-";
6411 if(mode & S_ISVTX)
6412 outs() << "t";
6413 else if(mode & (S_IEXEC >> 6))
6414 outs() << "x";
6415 else
6416 outs() << "-";
6417}
6418
6419static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006420 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006421 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6422 char *endp;
6423 uint32_t mode_value;
6424
Francis Ricci6f942972017-10-06 15:33:28 +00006425 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006426 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006427 WithColor::error(errs(), "llvm-objdump")
6428 << "can't obtain an xar iterator for xar archive " << XarFilename
6429 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006430 return;
6431 }
6432
6433 // Go through the xar's files.
6434 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006435 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006436 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006437 WithColor::error(errs(), "llvm-objdump")
6438 << "can't obtain an xar iterator for xar archive " << XarFilename
6439 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006440 return;
6441 }
6442 type = nullptr;
6443 mode = nullptr;
6444 user = nullptr;
6445 group = nullptr;
6446 size = nullptr;
6447 mtime = nullptr;
6448 name = nullptr;
6449 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006450 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006451 xar_prop_get(xf, key, &val);
6452#if 0 // Useful for debugging.
6453 outs() << "key: " << key << " value: " << val << "\n";
6454#endif
6455 if(strcmp(key, "type") == 0)
6456 type = val;
6457 if(strcmp(key, "mode") == 0)
6458 mode = val;
6459 if(strcmp(key, "user") == 0)
6460 user = val;
6461 if(strcmp(key, "group") == 0)
6462 group = val;
6463 if(strcmp(key, "data/size") == 0)
6464 size = val;
6465 if(strcmp(key, "mtime") == 0)
6466 mtime = val;
6467 if(strcmp(key, "name") == 0)
6468 name = val;
6469 }
6470 if(mode != nullptr){
6471 mode_value = strtoul(mode, &endp, 8);
6472 if(*endp != '\0')
6473 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6474 if(strcmp(type, "file") == 0)
6475 mode_value |= S_IFREG;
6476 PrintModeVerbose(mode_value);
6477 outs() << " ";
6478 }
6479 if(user != nullptr)
6480 outs() << format("%10s/", user);
6481 if(group != nullptr)
6482 outs() << format("%-10s ", group);
6483 if(size != nullptr)
6484 outs() << format("%7s ", size);
6485 if(mtime != nullptr){
6486 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6487 outs() << *m;
6488 if(*m == 'T')
6489 m++;
6490 outs() << " ";
6491 for( ; *m != 'Z' && *m != '\0'; m++)
6492 outs() << *m;
6493 outs() << " ";
6494 }
6495 if(name != nullptr)
6496 outs() << name;
6497 outs() << "\n";
6498 }
6499}
6500
6501static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6502 uint32_t size, bool verbose,
6503 bool PrintXarHeader, bool PrintXarFileHeaders,
6504 std::string XarMemberName) {
6505 if(size < sizeof(struct xar_header)) {
6506 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6507 "of struct xar_header)\n";
6508 return;
6509 }
6510 struct xar_header XarHeader;
6511 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6512 if (sys::IsLittleEndianHost)
6513 swapStruct(XarHeader);
6514 if (PrintXarHeader) {
6515 if (!XarMemberName.empty())
6516 outs() << "In xar member " << XarMemberName << ": ";
6517 else
6518 outs() << "For (__LLVM,__bundle) section: ";
6519 outs() << "xar header\n";
6520 if (XarHeader.magic == XAR_HEADER_MAGIC)
6521 outs() << " magic XAR_HEADER_MAGIC\n";
6522 else
6523 outs() << " magic "
6524 << format_hex(XarHeader.magic, 10, true)
6525 << " (not XAR_HEADER_MAGIC)\n";
6526 outs() << " size " << XarHeader.size << "\n";
6527 outs() << " version " << XarHeader.version << "\n";
6528 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6529 << "\n";
6530 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6531 << "\n";
6532 outs() << " cksum_alg ";
6533 switch (XarHeader.cksum_alg) {
6534 case XAR_CKSUM_NONE:
6535 outs() << "XAR_CKSUM_NONE\n";
6536 break;
6537 case XAR_CKSUM_SHA1:
6538 outs() << "XAR_CKSUM_SHA1\n";
6539 break;
6540 case XAR_CKSUM_MD5:
6541 outs() << "XAR_CKSUM_MD5\n";
6542 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006543#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006544 case XAR_CKSUM_SHA256:
6545 outs() << "XAR_CKSUM_SHA256\n";
6546 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006547#endif
6548#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006549 case XAR_CKSUM_SHA512:
6550 outs() << "XAR_CKSUM_SHA512\n";
6551 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006552#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006553 default:
6554 outs() << XarHeader.cksum_alg << "\n";
6555 }
6556 }
6557
6558 SmallString<128> XarFilename;
6559 int FD;
6560 std::error_code XarEC =
6561 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6562 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006563 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006564 return;
6565 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006566 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006567 raw_fd_ostream &XarOut = XarFile.os();
6568 StringRef XarContents(sect, size);
6569 XarOut << XarContents;
6570 XarOut.close();
6571 if (XarOut.has_error())
6572 return;
6573
Francis Ricci6f942972017-10-06 15:33:28 +00006574 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006575 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006576 WithColor::error(errs(), "llvm-objdump")
6577 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006578 return;
6579 }
6580
6581 SmallString<128> TocFilename;
6582 std::error_code TocEC =
6583 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6584 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006585 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006586 return;
6587 }
6588 xar_serialize(xar, TocFilename.c_str());
6589
6590 if (PrintXarFileHeaders) {
6591 if (!XarMemberName.empty())
6592 outs() << "In xar member " << XarMemberName << ": ";
6593 else
6594 outs() << "For (__LLVM,__bundle) section: ";
6595 outs() << "xar archive files:\n";
6596 PrintXarFilesSummary(XarFilename.c_str(), xar);
6597 }
6598
6599 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6600 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6601 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006602 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006603 return;
6604 }
6605 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6606
6607 if (!XarMemberName.empty())
6608 outs() << "In xar member " << XarMemberName << ": ";
6609 else
6610 outs() << "For (__LLVM,__bundle) section: ";
6611 outs() << "xar table of contents:\n";
6612 outs() << Buffer->getBuffer() << "\n";
6613
6614 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006615 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006616 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006617 WithColor::error(errs(), "llvm-objdump")
6618 << "can't obtain an xar iterator for xar archive "
6619 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006620 return;
6621 }
6622 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6623 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006624 const char *member_name, *member_type, *member_size_string;
6625 size_t member_size;
6626
Francis Ricci6f942972017-10-06 15:33:28 +00006627 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006628 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006629 WithColor::error(errs(), "llvm-objdump")
6630 << "can't obtain an xar iterator for xar archive "
6631 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006632 return;
6633 }
6634 member_name = NULL;
6635 member_type = NULL;
6636 member_size_string = NULL;
6637 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006638 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006639 xar_prop_get(xf, key, &val);
6640#if 0 // Useful for debugging.
6641 outs() << "key: " << key << " value: " << val << "\n";
6642#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006643 if (strcmp(key, "name") == 0)
6644 member_name = val;
6645 if (strcmp(key, "type") == 0)
6646 member_type = val;
6647 if (strcmp(key, "data/size") == 0)
6648 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006649 }
6650 /*
6651 * If we find a file with a name, date/size and type properties
6652 * and with the type being "file" see if that is a xar file.
6653 */
6654 if (member_name != NULL && member_type != NULL &&
6655 strcmp(member_type, "file") == 0 &&
6656 member_size_string != NULL){
6657 // Extract the file into a buffer.
6658 char *endptr;
6659 member_size = strtoul(member_size_string, &endptr, 10);
6660 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006661 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006662 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006663#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006664 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006665#endif
6666 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006667 std::string OldXarMemberName;
6668 // If XarMemberName is already set this is nested. So
6669 // save the old name and create the nested name.
6670 if (!XarMemberName.empty()) {
6671 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006672 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006673 (Twine("[") + XarMemberName + "]" + member_name).str();
6674 } else {
6675 OldXarMemberName = "";
6676 XarMemberName = member_name;
6677 }
6678 // See if this is could be a xar file (nested).
6679 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006680#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006681 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006682#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006683 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006684 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006685 swapStruct(XarHeader);
6686 if (XarHeader.magic == XAR_HEADER_MAGIC)
6687 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006688 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006689 XarMemberName);
6690 }
6691 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006692 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006693 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006694 }
6695 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006696 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006697}
6698#endif // defined(HAVE_LIBXAR)
6699
Kevin Enderby0fc11822015-04-01 20:57:01 +00006700static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6701 if (O->is64Bit())
6702 printObjc2_64bit_MetaData(O, verbose);
6703 else {
6704 MachO::mach_header H;
6705 H = O->getHeader();
6706 if (H.cputype == MachO::CPU_TYPE_ARM)
6707 printObjc2_32bit_MetaData(O, verbose);
6708 else {
6709 // This is the 32-bit non-arm cputype case. Which is normally
6710 // the first Objective-C ABI. But it may be the case of a
6711 // binary for the iOS simulator which is the second Objective-C
6712 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6713 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006714 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006715 printObjc2_32bit_MetaData(O, verbose);
6716 }
6717 }
6718}
6719
Kevin Enderbybf246f52014-09-24 23:08:22 +00006720// GuessLiteralPointer returns a string which for the item in the Mach-O file
6721// for the address passed in as ReferenceValue for printing as a comment with
6722// the instruction and also returns the corresponding type of that item
6723// indirectly through ReferenceType.
6724//
6725// If ReferenceValue is an address of literal cstring then a pointer to the
6726// cstring is returned and ReferenceType is set to
6727// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6728//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006729// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6730// Class ref that name is returned and the ReferenceType is set accordingly.
6731//
6732// Lastly, literals which are Symbol address in a literal pool are looked for
6733// and if found the symbol name is returned and ReferenceType is set to
6734// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6735//
6736// If there is no item in the Mach-O file for the address passed in as
6737// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006738static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6739 uint64_t ReferencePC,
6740 uint64_t *ReferenceType,
6741 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006742 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006743 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6744 uint64_t sect_addr = info->S.getAddress();
6745 uint64_t sect_offset = ReferencePC - sect_addr;
6746 bool reloc_found = false;
6747 DataRefImpl Rel;
6748 MachO::any_relocation_info RE;
6749 bool isExtern = false;
6750 SymbolRef Symbol;
6751 for (const RelocationRef &Reloc : info->S.relocations()) {
6752 uint64_t RelocOffset = Reloc.getOffset();
6753 if (RelocOffset == sect_offset) {
6754 Rel = Reloc.getRawDataRefImpl();
6755 RE = info->O->getRelocation(Rel);
6756 if (info->O->isRelocationScattered(RE))
6757 continue;
6758 isExtern = info->O->getPlainRelocationExternal(RE);
6759 if (isExtern) {
6760 symbol_iterator RelocSym = Reloc.getSymbol();
6761 Symbol = *RelocSym;
6762 }
6763 reloc_found = true;
6764 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006765 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006766 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006767 // If there is an external relocation entry for a symbol in a section
6768 // then used that symbol's value for the value of the reference.
6769 if (reloc_found && isExtern) {
6770 if (info->O->getAnyRelocationPCRel(RE)) {
6771 unsigned Type = info->O->getAnyRelocationType(RE);
6772 if (Type == MachO::X86_64_RELOC_SIGNED) {
6773 ReferenceValue = Symbol.getValue();
6774 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006775 }
6776 }
6777 }
6778
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006779 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6780 // Message refs and Class refs.
6781 bool classref, selref, msgref, cfstring;
6782 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6783 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006784 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006785 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6786 // And the pointer_value in that section is typically zero as it will be
6787 // set by dyld as part of the "bind information".
6788 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6789 if (name != nullptr) {
6790 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006791 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006792 if (class_name != nullptr && class_name[1] == '_' &&
6793 class_name[2] != '\0') {
6794 info->class_name = class_name + 2;
6795 return name;
6796 }
6797 }
6798 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006799
David Blaikie33dd45d02015-03-23 18:39:02 +00006800 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006801 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6802 const char *name =
6803 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6804 if (name != nullptr)
6805 info->class_name = name;
6806 else
6807 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006808 return name;
6809 }
6810
David Blaikie33dd45d02015-03-23 18:39:02 +00006811 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006812 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6813 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6814 return name;
6815 }
6816
David Blaikie33dd45d02015-03-23 18:39:02 +00006817 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006818 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6819
6820 if (pointer_value != 0)
6821 ReferenceValue = pointer_value;
6822
6823 const char *name = GuessCstringPointer(ReferenceValue, info);
6824 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006825 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006826 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6827 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006828 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006829 info->class_name = nullptr;
6830 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6831 info->selector_name = name;
6832 } else
6833 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6834 return name;
6835 }
6836
6837 // Lastly look for an indirect symbol with this ReferenceValue which is in
6838 // a literal pool. If found return that symbol name.
6839 name = GuessIndirectSymbol(ReferenceValue, info);
6840 if (name) {
6841 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6842 return name;
6843 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006844
6845 return nullptr;
6846}
6847
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006848// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006849// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006850// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6851// is created and returns the symbol name that matches the ReferenceValue or
6852// nullptr if none. The ReferenceType is passed in for the IN type of
6853// reference the instruction is making from the values in defined in the header
6854// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6855// Out type and the ReferenceName will also be set which is added as a comment
6856// to the disassembled instruction.
6857//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006858// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006859// returned through ReferenceName and ReferenceType is set to
6860// LLVMDisassembler_ReferenceType_DeMangled_Name .
6861//
6862// When this is called to get a symbol name for a branch target then the
6863// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6864// SymbolValue will be looked for in the indirect symbol table to determine if
6865// it is an address for a symbol stub. If so then the symbol name for that
6866// stub is returned indirectly through ReferenceName and then ReferenceType is
6867// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6868//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006869// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006870// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6871// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6872// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006873// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006874static const char *SymbolizerSymbolLookUp(void *DisInfo,
6875 uint64_t ReferenceValue,
6876 uint64_t *ReferenceType,
6877 uint64_t ReferencePC,
6878 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006879 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006880 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006881 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006882 *ReferenceName = nullptr;
6883 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006884 return nullptr;
6885 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006886
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006887 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006888
Kevin Enderby85974882014-09-26 22:20:44 +00006889 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6890 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006891 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006892 method_reference(info, ReferenceType, ReferenceName);
6893 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6894 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006895 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006896 if (info->demangled_name != nullptr)
6897 free(info->demangled_name);
6898 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006899 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006900 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006901 if (info->demangled_name != nullptr) {
6902 *ReferenceName = info->demangled_name;
6903 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6904 } else
6905 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6906 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006907 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6908 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6909 *ReferenceName =
6910 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006911 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006912 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006913 else
6914 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006915 // If this is arm64 and the reference is an adrp instruction save the
6916 // instruction, passed in ReferenceValue and the address of the instruction
6917 // for use later if we see and add immediate instruction.
6918 } else if (info->O->getArch() == Triple::aarch64 &&
6919 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6920 info->adrp_inst = ReferenceValue;
6921 info->adrp_addr = ReferencePC;
6922 SymbolName = nullptr;
6923 *ReferenceName = nullptr;
6924 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6925 // If this is arm64 and reference is an add immediate instruction and we
6926 // have
6927 // seen an adrp instruction just before it and the adrp's Xd register
6928 // matches
6929 // this add's Xn register reconstruct the value being referenced and look to
6930 // see if it is a literal pointer. Note the add immediate instruction is
6931 // passed in ReferenceValue.
6932 } else if (info->O->getArch() == Triple::aarch64 &&
6933 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6934 ReferencePC - 4 == info->adrp_addr &&
6935 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6936 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6937 uint32_t addxri_inst;
6938 uint64_t adrp_imm, addxri_imm;
6939
6940 adrp_imm =
6941 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6942 if (info->adrp_inst & 0x0200000)
6943 adrp_imm |= 0xfffffffffc000000LL;
6944
6945 addxri_inst = ReferenceValue;
6946 addxri_imm = (addxri_inst >> 10) & 0xfff;
6947 if (((addxri_inst >> 22) & 0x3) == 1)
6948 addxri_imm <<= 12;
6949
6950 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6951 (adrp_imm << 12) + addxri_imm;
6952
6953 *ReferenceName =
6954 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6955 if (*ReferenceName == nullptr)
6956 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6957 // If this is arm64 and the reference is a load register instruction and we
6958 // have seen an adrp instruction just before it and the adrp's Xd register
6959 // matches this add's Xn register reconstruct the value being referenced and
6960 // look to see if it is a literal pointer. Note the load register
6961 // instruction is passed in ReferenceValue.
6962 } else if (info->O->getArch() == Triple::aarch64 &&
6963 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6964 ReferencePC - 4 == info->adrp_addr &&
6965 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6966 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6967 uint32_t ldrxui_inst;
6968 uint64_t adrp_imm, ldrxui_imm;
6969
6970 adrp_imm =
6971 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6972 if (info->adrp_inst & 0x0200000)
6973 adrp_imm |= 0xfffffffffc000000LL;
6974
6975 ldrxui_inst = ReferenceValue;
6976 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6977
6978 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6979 (adrp_imm << 12) + (ldrxui_imm << 3);
6980
6981 *ReferenceName =
6982 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6983 if (*ReferenceName == nullptr)
6984 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6985 }
6986 // If this arm64 and is an load register (PC-relative) instruction the
6987 // ReferenceValue is the PC plus the immediate value.
6988 else if (info->O->getArch() == Triple::aarch64 &&
6989 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6990 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6991 *ReferenceName =
6992 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6993 if (*ReferenceName == nullptr)
6994 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006995 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006996 if (info->demangled_name != nullptr)
6997 free(info->demangled_name);
6998 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006999 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00007000 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007001 if (info->demangled_name != nullptr) {
7002 *ReferenceName = info->demangled_name;
7003 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7004 }
7005 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007006 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007007 *ReferenceName = nullptr;
7008 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7009 }
7010
7011 return SymbolName;
7012}
7013
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007014/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007015/// Each comment in the CommentStream must end with a newline.
7016static void emitComments(raw_svector_ostream &CommentStream,
7017 SmallString<128> &CommentsToEmit,
7018 formatted_raw_ostream &FormattedOS,
7019 const MCAsmInfo &MAI) {
7020 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007021 StringRef Comments = CommentsToEmit.str();
7022 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00007023 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00007024 unsigned CommentColumn = MAI.getCommentColumn();
7025 bool IsFirst = true;
7026 while (!Comments.empty()) {
7027 if (!IsFirst)
7028 FormattedOS << '\n';
7029 // Emit a line of comments.
7030 FormattedOS.PadToColumn(CommentColumn);
7031 size_t Position = Comments.find('\n');
7032 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7033 // Move after the newline character.
7034 Comments = Comments.substr(Position + 1);
7035 IsFirst = false;
7036 }
7037 FormattedOS.flush();
7038
7039 // Tell the comment stream that the vector changed underneath it.
7040 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007041}
7042
Kevin Enderby95df54c2015-02-04 01:01:38 +00007043static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7044 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007045 const char *McpuDefault = nullptr;
7046 const Target *ThumbTarget = nullptr;
7047 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007048 if (!TheTarget) {
7049 // GetTarget prints out stuff.
7050 return;
7051 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007052 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007053 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007054 MachOMCPU = McpuDefault;
7055 else
7056 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007057
Ahmed Charles56440fd2014-03-06 05:51:42 +00007058 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007059 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007060 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007061 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007062
Kevin Enderbyc9595622014-08-06 23:24:41 +00007063 // Package up features to be passed to target/subtarget
7064 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007065 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007066 SubtargetFeatures Features;
7067 for (unsigned i = 0; i != MAttrs.size(); ++i)
7068 Features.AddFeature(MAttrs[i]);
7069 FeaturesStr = Features.getString();
7070 }
7071
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007072 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007073 std::unique_ptr<const MCRegisterInfo> MRI(
7074 TheTarget->createMCRegInfo(TripleName));
7075 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007076 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007077 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007078 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007079 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007080 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007081 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007082 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007083 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007084 std::unique_ptr<MCRelocationInfo> RelInfo(
7085 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7086 if (RelInfo) {
7087 Symbolizer.reset(TheTarget->createMCSymbolizer(
7088 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007089 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007090 DisAsm->setSymbolizer(std::move(Symbolizer));
7091 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007092 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007093 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007094 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007095 // Set the display preference for hex vs. decimal immediates.
7096 IP->setPrintImmHex(PrintImmHex);
7097 // Comment stream and backing vector.
7098 SmallString<128> CommentsToEmit;
7099 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007100 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7101 // if it is done then arm64 comments for string literals don't get printed
7102 // and some constant get printed instead and not setting it causes intel
7103 // (32-bit and 64-bit) comments printed with different spacing before the
7104 // comment causing different diffs with the 'C' disassembler library API.
7105 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007106
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007107 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007108 WithColor::error(errs(), "llvm-objdump")
7109 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007110 return;
7111 }
7112
Tim Northover09ca33e2016-04-22 23:23:31 +00007113 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007114 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7115 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7116 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007117 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007118 std::unique_ptr<MCInstPrinter> ThumbIP;
7119 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007120 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007121 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007122 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007123 if (ThumbTarget) {
7124 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7125 ThumbAsmInfo.reset(
7126 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7127 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007128 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7129 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007130 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7131 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007132 MCContext *PtrThumbCtx = ThumbCtx.get();
7133 ThumbRelInfo.reset(
7134 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7135 if (ThumbRelInfo) {
7136 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7137 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007138 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007139 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7140 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007141 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7142 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007143 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7144 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007145 // Set the display preference for hex vs. decimal immediates.
7146 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007147 }
7148
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007149 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007150 WithColor::error(errs(), "llvm-objdump")
7151 << "couldn't initialize disassembler for target " << ThumbTripleName
7152 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007153 return;
7154 }
7155
Charles Davis8bdfafd2013-09-01 04:28:48 +00007156 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007157
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007158 // FIXME: Using the -cfg command line option, this code used to be able to
7159 // annotate relocations with the referenced symbol's name, and if this was
7160 // inside a __[cf]string section, the data it points to. This is now replaced
7161 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007162 std::vector<SectionRef> Sections;
7163 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007164 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007165 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007166
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007167 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007168 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007169
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007170 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007171 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007172
Kevin Enderby273ae012013-06-06 17:20:50 +00007173 // Build a data in code table that is sorted on by the address of each entry.
7174 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007175 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007176 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007177 else
7178 BaseAddress = BaseSegmentAddress;
7179 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007180 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007181 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007182 uint32_t Offset;
7183 DI->getOffset(Offset);
7184 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7185 }
7186 array_pod_sort(Dices.begin(), Dices.end());
7187
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007188#ifndef NDEBUG
7189 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7190#else
7191 raw_ostream &DebugOut = nulls();
7192#endif
7193
Ahmed Charles56440fd2014-03-06 05:51:42 +00007194 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007195 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007196 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007197 // Try to find debug info and set up the DIContext for it.
7198 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007199 // A separate DSym file path was specified, parse it as a macho file,
7200 // get the sections and supply it to the section name parsing machinery.
7201 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007202 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007203 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007204 if (std::error_code EC = BufOrErr.getError()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007205 report_error(errorCodeToError(EC), DSYMFile);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007206 return;
7207 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007208
Fangrui Songe7834bd2019-04-07 08:19:55 +00007209 std::unique_ptr<MachOObjectFile> DbgObjCheck = unwrapOrError(
7210 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef()),
7211 DSYMFile.getValue());
7212 DbgObj = DbgObjCheck.release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007213 // We need to keep the file alive, because we're replacing DbgObj with it.
7214 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007215 }
7216
Eric Christopher7370b552012-11-12 21:40:38 +00007217 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007218 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007219 }
7220
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007221 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007222 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007223
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007224 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007225 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007226 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7227 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007228
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007229 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007230
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007231 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007232 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007233 continue;
7234
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007235 StringRef BytesStr;
7236 Sections[SectIdx].getContents(BytesStr);
Fangrui Song6a0746a2019-04-07 03:58:42 +00007237 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
Rafael Espindola80291272014-10-08 15:28:58 +00007238 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007239
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007240 bool symbolTableWorked = false;
7241
Kevin Enderbybf246f52014-09-24 23:08:22 +00007242 // Create a map of symbol addresses to symbol names for use by
7243 // the SymbolizerSymbolLookUp() routine.
7244 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007245 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007246 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007247 SymbolRef::Type ST =
7248 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007249 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7250 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007251 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00007252 StringRef SymName =
7253 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007254 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007255 if (!DisSymName.empty() && DisSymName == SymName)
7256 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007257 }
7258 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007259 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007260 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7261 return;
7262 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007263 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007264 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007265 SymbolizerInfo.O = MachOOF;
7266 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007267 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007268 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007269 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007270 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007271 ThumbSymbolizerInfo.O = MachOOF;
7272 ThumbSymbolizerInfo.S = Sections[SectIdx];
7273 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7274 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007275
Kevin Enderby4b627be2016-04-28 20:14:13 +00007276 unsigned int Arch = MachOOF->getArch();
7277
Tim Northoverf203ab52016-07-14 22:13:32 +00007278 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007279 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007280 return;
7281
Kevin Enderbyc138da32017-02-06 18:43:18 +00007282 // If the section has symbols but no symbol at the start of the section
7283 // these are used to make sure the bytes before the first symbol are
7284 // disassembled.
7285 bool FirstSymbol = true;
7286 bool FirstSymbolAtSectionStart = true;
7287
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007288 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007289 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007290 StringRef SymName =
7291 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7292 SymbolRef::Type ST =
7293 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
Kuba Breckade833222015-11-12 09:40:29 +00007294 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007295 continue;
7296
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007297 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007298 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007299 if (!containsSym) {
7300 if (!DisSymName.empty() && DisSymName == SymName) {
7301 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7302 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007303 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007304 continue;
7305 }
7306 // The __mh_execute_header is special and we need to deal with that fact
7307 // this symbol is before the start of the (__TEXT,__text) section and at the
7308 // address of the start of the __TEXT segment. This is because this symbol
7309 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7310 // start of the section in a standard MH_EXECUTE filetype.
7311 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7312 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7313 return;
7314 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007315 // When this code is trying to disassemble a symbol at a time and in the
7316 // case there is only the __mh_execute_header symbol left as in a stripped
7317 // executable, we need to deal with this by ignoring this symbol so the
7318 // whole section is disassembled and this symbol is then not displayed.
7319 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7320 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7321 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007322 continue;
7323
Kevin Enderby6a221752015-03-17 17:10:57 +00007324 // If we are only disassembling one symbol see if this is that symbol.
7325 if (!DisSymName.empty() && DisSymName != SymName)
7326 continue;
7327
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007328 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007329 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007330 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007331 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007332 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007333
Tim Northoverf203ab52016-07-14 22:13:32 +00007334 if (Start > SectSize) {
7335 outs() << "section data ends, " << SymName
7336 << " lies outside valid range\n";
7337 return;
7338 }
7339
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007340 // Stop disassembling either at the beginning of the next symbol or at
7341 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007342 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007343 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007344 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007345 while (Symbols.size() > NextSymIdx) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007346 SymbolRef::Type NextSymType = unwrapOrError(
7347 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
Owen Andersond9243c42011-10-17 21:37:35 +00007348 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007349 containsNextSym =
7350 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007351 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007352 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007353 break;
7354 }
7355 ++NextSymIdx;
7356 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007357
Tim Northoverf203ab52016-07-14 22:13:32 +00007358 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007359 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007360
7361 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007362
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007363 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007364 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7365
7366 // We only need the dedicated Thumb target if there's a real choice
7367 // (i.e. we're not targeting M-class) and the function is Thumb.
7368 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007369
Kevin Enderbyc138da32017-02-06 18:43:18 +00007370 // If we are not specifying a symbol to start disassembly with and this
7371 // is the first symbol in the section but not at the start of the section
7372 // then move the disassembly index to the start of the section and
7373 // don't print the symbol name just yet. This is so the bytes before the
7374 // first symbol are disassembled.
7375 uint64_t SymbolStart = Start;
7376 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7377 FirstSymbolAtSectionStart = false;
7378 Start = 0;
7379 }
7380 else
7381 outs() << SymName << ":\n";
7382
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007383 DILineInfo lastLine;
7384 for (uint64_t Index = Start; Index < End; Index += Size) {
7385 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007386
Kevin Enderbyc138da32017-02-06 18:43:18 +00007387 // If this is the first symbol in the section and it was not at the
7388 // start of the section, see if we are at its Index now and if so print
7389 // the symbol name.
7390 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7391 outs() << SymName << ":\n";
7392
Kevin Enderbybf246f52014-09-24 23:08:22 +00007393 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007394 if (!NoLeadingAddr) {
7395 if (FullLeadingAddr) {
7396 if (MachOOF->is64Bit())
7397 outs() << format("%016" PRIx64, PC);
7398 else
7399 outs() << format("%08" PRIx64, PC);
7400 } else {
7401 outs() << format("%8" PRIx64 ":", PC);
7402 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007403 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007404 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007405 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007406
7407 // Check the data in code table here to see if this is data not an
7408 // instruction to be disassembled.
7409 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007410 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007411 dice_table_iterator DTI =
7412 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7413 compareDiceTableEntries);
7414 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007415 uint16_t Length;
7416 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007417 uint16_t Kind;
7418 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007419 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007420 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7421 (PC == (DTI->first + Length - 1)) && (Length & 1))
7422 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007423 continue;
7424 }
7425
Kevin Enderbybf246f52014-09-24 23:08:22 +00007426 SmallVector<char, 64> AnnotationsBytes;
7427 raw_svector_ostream Annotations(AnnotationsBytes);
7428
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007429 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007430 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007431 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007432 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007433 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007434 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007435 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007436 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007437 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007438 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007439 }
7440 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007441 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007442 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007443 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007444 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007445 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007446 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007447
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007448 // Print debug info.
7449 if (diContext) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00007450 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007451 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007452 if (dli != lastLine && dli.Line != 0)
7453 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7454 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007455 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007456 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007457 outs() << "\n";
7458 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007459 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007460 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007461 outs() << format("\t.byte 0x%02x #bad opcode\n",
7462 *(Bytes.data() + Index) & 0xff);
7463 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007464 } else if (Arch == Triple::aarch64 ||
7465 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007466 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7467 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7468 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7469 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7470 outs() << format("\t.long\t0x%08x\n", opcode);
7471 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007472 } else if (Arch == Triple::arm) {
7473 assert(IsThumb && "ARM mode should have been dealt with above");
7474 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7475 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7476 outs() << format("\t.short\t0x%04x\n", opcode);
7477 Size = 2;
7478 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007479 WithColor::warning(errs(), "llvm-objdump")
7480 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007481 if (Size == 0)
7482 Size = 1; // skip illegible bytes
7483 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007484 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007485 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007486 // Now that we are done disassembled the first symbol set the bool that
7487 // were doing this to false.
7488 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007489 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007490 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007491 // Reading the symbol table didn't work, disassemble the whole section.
7492 uint64_t SectAddress = Sections[SectIdx].getAddress();
7493 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007494 uint64_t InstSize;
7495 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007496 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007497
Kevin Enderbybf246f52014-09-24 23:08:22 +00007498 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007499 SmallVector<char, 64> AnnotationsBytes;
7500 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007501 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007502 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007503 if (!NoLeadingAddr) {
7504 if (FullLeadingAddr) {
7505 if (MachOOF->is64Bit())
7506 outs() << format("%016" PRIx64, PC);
7507 else
7508 outs() << format("%08" PRIx64, PC);
7509 } else {
7510 outs() << format("%8" PRIx64 ":", PC);
7511 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007512 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007513 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007514 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007515 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007516 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007517 StringRef AnnotationsStr = Annotations.str();
7518 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007519 outs() << "\n";
7520 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007521 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007522 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007523 outs() << format("\t.byte 0x%02x #bad opcode\n",
7524 *(Bytes.data() + Index) & 0xff);
7525 InstSize = 1; // skip exactly one illegible byte and move on.
7526 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007527 WithColor::warning(errs(), "llvm-objdump")
7528 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007529 if (InstSize == 0)
7530 InstSize = 1; // skip illegible bytes
7531 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007532 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007533 }
7534 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007535 // The TripleName's need to be reset if we are called again for a different
7536 // archtecture.
7537 TripleName = "";
7538 ThumbTripleName = "";
7539
Kevin Enderby04bf6932014-10-28 23:39:46 +00007540 if (SymbolizerInfo.demangled_name != nullptr)
7541 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007542 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7543 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007544 }
7545}
Tim Northover4bd286a2014-08-01 13:07:19 +00007546
Tim Northover39c70bb2014-08-12 11:52:59 +00007547//===----------------------------------------------------------------------===//
7548// __compact_unwind section dumping
7549//===----------------------------------------------------------------------===//
7550
Tim Northover4bd286a2014-08-01 13:07:19 +00007551namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007552
Tim Northover3a4e1c72018-01-23 13:51:57 +00007553template <typename T>
7554static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007555 using llvm::support::little;
7556 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007557
Tim Northover3a4e1c72018-01-23 13:51:57 +00007558 if (Offset + sizeof(T) > Contents.size()) {
7559 outs() << "warning: attempt to read past end of buffer\n";
7560 return T();
7561 }
7562
7563 uint64_t Val =
7564 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7565 return Val;
7566}
7567
7568template <typename T>
7569static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7570 T Val = read<T>(Contents, Offset);
7571 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007572 return Val;
7573}
Tim Northover39c70bb2014-08-12 11:52:59 +00007574
Tim Northover4bd286a2014-08-01 13:07:19 +00007575struct CompactUnwindEntry {
7576 uint32_t OffsetInSection;
7577
7578 uint64_t FunctionAddr;
7579 uint32_t Length;
7580 uint32_t CompactEncoding;
7581 uint64_t PersonalityAddr;
7582 uint64_t LSDAAddr;
7583
7584 RelocationRef FunctionReloc;
7585 RelocationRef PersonalityReloc;
7586 RelocationRef LSDAReloc;
7587
7588 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007589 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007590 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007591 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007592 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007593 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007594 }
7595
7596private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007597 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7598 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7599 Length = readNext<uint32_t>(Contents, Offset);
7600 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7601 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7602 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007603 }
7604};
7605}
7606
7607/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7608/// and data being relocated, determine the best base Name and Addend to use for
7609/// display purposes.
7610///
7611/// 1. An Extern relocation will directly reference a symbol (and the data is
7612/// then already an addend), so use that.
7613/// 2. Otherwise the data is an offset in the object file's layout; try to find
7614// a symbol before it in the same section, and use the offset from there.
7615/// 3. Finally, if all that fails, fall back to an offset from the start of the
7616/// referenced section.
7617static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7618 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007619 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007620 StringRef &Name, uint64_t &Addend) {
7621 if (Reloc.getSymbol() != Obj->symbol_end()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007622 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007623 Addend = Addr;
7624 return;
7625 }
7626
7627 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007628 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007629
Rafael Espindola80291272014-10-08 15:28:58 +00007630 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007631
7632 auto Sym = Symbols.upper_bound(Addr);
7633 if (Sym == Symbols.begin()) {
7634 // The first symbol in the object is after this reference, the best we can
7635 // do is section-relative notation.
7636 RelocSection.getName(Name);
7637 Addend = Addr - SectionAddr;
7638 return;
7639 }
7640
7641 // Go back one so that SymbolAddress <= Addr.
7642 --Sym;
7643
Fangrui Songe7834bd2019-04-07 08:19:55 +00007644 section_iterator SymSection =
7645 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007646 if (RelocSection == *SymSection) {
7647 // There's a valid symbol in the same section before this reference.
Fangrui Songe7834bd2019-04-07 08:19:55 +00007648 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007649 Addend = Addr - Sym->first;
7650 return;
7651 }
7652
7653 // There is a symbol before this reference, but it's in a different
7654 // section. Probably not helpful to mention it, so use the section name.
7655 RelocSection.getName(Name);
7656 Addend = Addr - SectionAddr;
7657}
7658
7659static void printUnwindRelocDest(const MachOObjectFile *Obj,
7660 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007661 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007662 StringRef Name;
7663 uint64_t Addend;
7664
Rafael Espindola854038e2015-06-26 14:51:16 +00007665 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007666 return;
7667
Tim Northover4bd286a2014-08-01 13:07:19 +00007668 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7669
7670 outs() << Name;
7671 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007672 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007673}
7674
7675static void
7676printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7677 std::map<uint64_t, SymbolRef> &Symbols,
7678 const SectionRef &CompactUnwind) {
7679
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007680 if (!Obj->isLittleEndian()) {
7681 outs() << "Skipping big-endian __compact_unwind section\n";
7682 return;
7683 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007684
7685 bool Is64 = Obj->is64Bit();
7686 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7687 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7688
7689 StringRef Contents;
7690 CompactUnwind.getContents(Contents);
7691
7692 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7693
7694 // First populate the initial raw offsets, encodings and so on from the entry.
7695 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007696 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007697 CompactUnwinds.push_back(Entry);
7698 }
7699
7700 // Next we need to look at the relocations to find out what objects are
7701 // actually being referred to.
7702 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007703 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007704
7705 uint32_t EntryIdx = RelocAddress / EntrySize;
7706 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7707 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7708
7709 if (OffsetInEntry == 0)
7710 Entry.FunctionReloc = Reloc;
7711 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7712 Entry.PersonalityReloc = Reloc;
7713 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7714 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007715 else {
7716 outs() << "Invalid relocation in __compact_unwind section\n";
7717 return;
7718 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007719 }
7720
7721 // Finally, we're ready to print the data we've gathered.
7722 outs() << "Contents of __compact_unwind section:\n";
7723 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007724 outs() << " Entry at offset "
7725 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007726
7727 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007728 outs() << " start: " << format("0x%" PRIx64,
7729 Entry.FunctionAddr) << ' ';
7730 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007731 outs() << '\n';
7732
7733 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007734 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7735 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007736 // 3. The 32-bit compact encoding.
7737 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007738 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007739
7740 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007741 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007742 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007743 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007744 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7745 Entry.PersonalityAddr);
7746 outs() << '\n';
7747 }
7748
7749 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007750 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007751 outs() << " LSDA: " << format("0x%" PRIx64,
7752 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007753 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7754 outs() << '\n';
7755 }
7756 }
7757}
7758
Tim Northover39c70bb2014-08-12 11:52:59 +00007759//===----------------------------------------------------------------------===//
7760// __unwind_info section dumping
7761//===----------------------------------------------------------------------===//
7762
Tim Northover3a4e1c72018-01-23 13:51:57 +00007763static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7764 ptrdiff_t Pos = 0;
7765 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007766 (void)Kind;
7767 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7768
Tim Northover3a4e1c72018-01-23 13:51:57 +00007769 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7770 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007771
Tim Northover3a4e1c72018-01-23 13:51:57 +00007772 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007773 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007774 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7775 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007776
7777 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007778 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7779 << ", "
7780 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007781 }
7782}
7783
7784static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007785 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007786 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007787 ptrdiff_t Pos = 0;
7788 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007789 (void)Kind;
7790 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7791
Tim Northover3a4e1c72018-01-23 13:51:57 +00007792 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7793 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007794
Tim Northover3a4e1c72018-01-23 13:51:57 +00007795 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7796 readNext<uint16_t>(PageData, Pos);
7797 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007798
Tim Northover3a4e1c72018-01-23 13:51:57 +00007799 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007800 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007801 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007802 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7803 uint32_t EncodingIdx = Entry >> 24;
7804
7805 uint32_t Encoding;
7806 if (EncodingIdx < CommonEncodings.size())
7807 Encoding = CommonEncodings[EncodingIdx];
7808 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007809 Encoding = read<uint32_t>(PageEncodings,
7810 sizeof(uint32_t) *
7811 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007812
7813 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007814 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7815 << ", "
7816 << "encoding[" << EncodingIdx
7817 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007818 }
7819}
7820
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007821static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7822 std::map<uint64_t, SymbolRef> &Symbols,
7823 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007824
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007825 if (!Obj->isLittleEndian()) {
7826 outs() << "Skipping big-endian __unwind_info section\n";
7827 return;
7828 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007829
7830 outs() << "Contents of __unwind_info section:\n";
7831
7832 StringRef Contents;
7833 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007834 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007835
7836 //===----------------------------------
7837 // Section header
7838 //===----------------------------------
7839
Tim Northover3a4e1c72018-01-23 13:51:57 +00007840 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007841 outs() << " Version: "
7842 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007843 if (Version != 1) {
7844 outs() << " Skipping section with unknown version\n";
7845 return;
7846 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007847
Tim Northover3a4e1c72018-01-23 13:51:57 +00007848 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007849 outs() << " Common encodings array section offset: "
7850 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007851 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007852 outs() << " Number of common encodings in array: "
7853 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7854
Tim Northover3a4e1c72018-01-23 13:51:57 +00007855 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007856 outs() << " Personality function array section offset: "
7857 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007858 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007859 outs() << " Number of personality functions in array: "
7860 << format("0x%" PRIx32, NumPersonalities) << '\n';
7861
Tim Northover3a4e1c72018-01-23 13:51:57 +00007862 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007863 outs() << " Index array section offset: "
7864 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007865 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007866 outs() << " Number of indices in array: "
7867 << format("0x%" PRIx32, NumIndices) << '\n';
7868
7869 //===----------------------------------
7870 // A shared list of common encodings
7871 //===----------------------------------
7872
7873 // These occupy indices in the range [0, N] whenever an encoding is referenced
7874 // from a compressed 2nd level index table. In practice the linker only
7875 // creates ~128 of these, so that indices are available to embed encodings in
7876 // the 2nd level index.
7877
7878 SmallVector<uint32_t, 64> CommonEncodings;
7879 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007880 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007881 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007882 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007883 CommonEncodings.push_back(Encoding);
7884
7885 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7886 << '\n';
7887 }
7888
Tim Northover39c70bb2014-08-12 11:52:59 +00007889 //===----------------------------------
7890 // Personality functions used in this executable
7891 //===----------------------------------
7892
7893 // There should be only a handful of these (one per source language,
7894 // roughly). Particularly since they only get 2 bits in the compact encoding.
7895
7896 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007897 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007898 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007899 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007900 outs() << " personality[" << i + 1
7901 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7902 }
7903
7904 //===----------------------------------
7905 // The level 1 index entries
7906 //===----------------------------------
7907
7908 // These specify an approximate place to start searching for the more detailed
7909 // information, sorted by PC.
7910
7911 struct IndexEntry {
7912 uint32_t FunctionOffset;
7913 uint32_t SecondLevelPageStart;
7914 uint32_t LSDAStart;
7915 };
7916
7917 SmallVector<IndexEntry, 4> IndexEntries;
7918
7919 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007920 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007921 for (unsigned i = 0; i < NumIndices; ++i) {
7922 IndexEntry Entry;
7923
Tim Northover3a4e1c72018-01-23 13:51:57 +00007924 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7925 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7926 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007927 IndexEntries.push_back(Entry);
7928
7929 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007930 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7931 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007932 << "2nd level page offset="
7933 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007934 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007935 }
7936
Tim Northover39c70bb2014-08-12 11:52:59 +00007937 //===----------------------------------
7938 // Next come the LSDA tables
7939 //===----------------------------------
7940
7941 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7942 // the first top-level index's LSDAOffset to the last (sentinel).
7943
7944 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007945 Pos = IndexEntries[0].LSDAStart;
7946 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7947 int NumLSDAs =
7948 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7949
Tim Northover39c70bb2014-08-12 11:52:59 +00007950 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007951 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7952 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007953 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007954 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7955 << ", "
7956 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007957 }
7958
7959 //===----------------------------------
7960 // Finally, the 2nd level indices
7961 //===----------------------------------
7962
7963 // Generally these are 4K in size, and have 2 possible forms:
7964 // + Regular stores up to 511 entries with disparate encodings
7965 // + Compressed stores up to 1021 entries if few enough compact encoding
7966 // values are used.
7967 outs() << " Second level indices:\n";
7968 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7969 // The final sentinel top-level index has no associated 2nd level page
7970 if (IndexEntries[i].SecondLevelPageStart == 0)
7971 break;
7972
7973 outs() << " Second level index[" << i << "]: "
7974 << "offset in section="
7975 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7976 << ", "
7977 << "base function offset="
7978 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7979
Tim Northover3a4e1c72018-01-23 13:51:57 +00007980 Pos = IndexEntries[i].SecondLevelPageStart;
7981 if (Pos + sizeof(uint32_t) > Contents.size()) {
7982 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7983 continue;
7984 }
7985
7986 uint32_t Kind =
7987 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007988 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007989 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007990 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007991 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7992 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007993 CommonEncodings);
7994 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007995 outs() << " Skipping 2nd level page with unknown kind " << Kind
7996 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007997 }
7998}
7999
Fangrui Song523758e2019-04-15 15:31:42 +00008000void printMachOUnwindInfo(const MachOObjectFile *Obj) {
Tim Northover4bd286a2014-08-01 13:07:19 +00008001 std::map<uint64_t, SymbolRef> Symbols;
8002 for (const SymbolRef &SymRef : Obj->symbols()) {
8003 // Discard any undefined or absolute symbols. They're not going to take part
8004 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00008005 auto SectOrErr = SymRef.getSection();
8006 if (!SectOrErr) {
8007 // TODO: Actually report errors helpfully.
8008 consumeError(SectOrErr.takeError());
8009 continue;
8010 }
8011 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00008012 if (Section == Obj->section_end())
8013 continue;
8014
Rafael Espindoladea00162015-07-03 17:44:18 +00008015 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00008016 Symbols.insert(std::make_pair(Addr, SymRef));
8017 }
8018
8019 for (const SectionRef &Section : Obj->sections()) {
8020 StringRef SectName;
8021 Section.getName(SectName);
8022 if (SectName == "__compact_unwind")
8023 printMachOCompactUnwindSection(Obj, Symbols, Section);
8024 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00008025 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00008026 }
8027}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008028
8029static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8030 uint32_t cpusubtype, uint32_t filetype,
8031 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8032 bool verbose) {
8033 outs() << "Mach header\n";
8034 outs() << " magic cputype cpusubtype caps filetype ncmds "
8035 "sizeofcmds flags\n";
8036 if (verbose) {
8037 if (magic == MachO::MH_MAGIC)
8038 outs() << " MH_MAGIC";
8039 else if (magic == MachO::MH_MAGIC_64)
8040 outs() << "MH_MAGIC_64";
8041 else
8042 outs() << format(" 0x%08" PRIx32, magic);
8043 switch (cputype) {
8044 case MachO::CPU_TYPE_I386:
8045 outs() << " I386";
8046 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8047 case MachO::CPU_SUBTYPE_I386_ALL:
8048 outs() << " ALL";
8049 break;
8050 default:
8051 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8052 break;
8053 }
8054 break;
8055 case MachO::CPU_TYPE_X86_64:
8056 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008057 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8058 case MachO::CPU_SUBTYPE_X86_64_ALL:
8059 outs() << " ALL";
8060 break;
8061 case MachO::CPU_SUBTYPE_X86_64_H:
8062 outs() << " Haswell";
8063 break;
8064 default:
8065 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8066 break;
8067 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008068 break;
8069 case MachO::CPU_TYPE_ARM:
8070 outs() << " ARM";
8071 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8072 case MachO::CPU_SUBTYPE_ARM_ALL:
8073 outs() << " ALL";
8074 break;
8075 case MachO::CPU_SUBTYPE_ARM_V4T:
8076 outs() << " V4T";
8077 break;
8078 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8079 outs() << " V5TEJ";
8080 break;
8081 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8082 outs() << " XSCALE";
8083 break;
8084 case MachO::CPU_SUBTYPE_ARM_V6:
8085 outs() << " V6";
8086 break;
8087 case MachO::CPU_SUBTYPE_ARM_V6M:
8088 outs() << " V6M";
8089 break;
8090 case MachO::CPU_SUBTYPE_ARM_V7:
8091 outs() << " V7";
8092 break;
8093 case MachO::CPU_SUBTYPE_ARM_V7EM:
8094 outs() << " V7EM";
8095 break;
8096 case MachO::CPU_SUBTYPE_ARM_V7K:
8097 outs() << " V7K";
8098 break;
8099 case MachO::CPU_SUBTYPE_ARM_V7M:
8100 outs() << " V7M";
8101 break;
8102 case MachO::CPU_SUBTYPE_ARM_V7S:
8103 outs() << " V7S";
8104 break;
8105 default:
8106 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8107 break;
8108 }
8109 break;
8110 case MachO::CPU_TYPE_ARM64:
8111 outs() << " ARM64";
8112 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8113 case MachO::CPU_SUBTYPE_ARM64_ALL:
8114 outs() << " ALL";
8115 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00008116 case MachO::CPU_SUBTYPE_ARM64E:
8117 outs() << " E";
8118 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008119 default:
8120 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8121 break;
8122 }
8123 break;
8124 case MachO::CPU_TYPE_POWERPC:
8125 outs() << " PPC";
8126 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8127 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8128 outs() << " ALL";
8129 break;
8130 default:
8131 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8132 break;
8133 }
8134 break;
8135 case MachO::CPU_TYPE_POWERPC64:
8136 outs() << " PPC64";
8137 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8138 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8139 outs() << " ALL";
8140 break;
8141 default:
8142 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8143 break;
8144 }
8145 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008146 default:
8147 outs() << format(" %7d", cputype);
8148 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8149 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008150 }
8151 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008152 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008153 } else {
8154 outs() << format(" 0x%02" PRIx32,
8155 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8156 }
8157 switch (filetype) {
8158 case MachO::MH_OBJECT:
8159 outs() << " OBJECT";
8160 break;
8161 case MachO::MH_EXECUTE:
8162 outs() << " EXECUTE";
8163 break;
8164 case MachO::MH_FVMLIB:
8165 outs() << " FVMLIB";
8166 break;
8167 case MachO::MH_CORE:
8168 outs() << " CORE";
8169 break;
8170 case MachO::MH_PRELOAD:
8171 outs() << " PRELOAD";
8172 break;
8173 case MachO::MH_DYLIB:
8174 outs() << " DYLIB";
8175 break;
8176 case MachO::MH_DYLIB_STUB:
8177 outs() << " DYLIB_STUB";
8178 break;
8179 case MachO::MH_DYLINKER:
8180 outs() << " DYLINKER";
8181 break;
8182 case MachO::MH_BUNDLE:
8183 outs() << " BUNDLE";
8184 break;
8185 case MachO::MH_DSYM:
8186 outs() << " DSYM";
8187 break;
8188 case MachO::MH_KEXT_BUNDLE:
8189 outs() << " KEXTBUNDLE";
8190 break;
8191 default:
8192 outs() << format(" %10u", filetype);
8193 break;
8194 }
8195 outs() << format(" %5u", ncmds);
8196 outs() << format(" %10u", sizeofcmds);
8197 uint32_t f = flags;
8198 if (f & MachO::MH_NOUNDEFS) {
8199 outs() << " NOUNDEFS";
8200 f &= ~MachO::MH_NOUNDEFS;
8201 }
8202 if (f & MachO::MH_INCRLINK) {
8203 outs() << " INCRLINK";
8204 f &= ~MachO::MH_INCRLINK;
8205 }
8206 if (f & MachO::MH_DYLDLINK) {
8207 outs() << " DYLDLINK";
8208 f &= ~MachO::MH_DYLDLINK;
8209 }
8210 if (f & MachO::MH_BINDATLOAD) {
8211 outs() << " BINDATLOAD";
8212 f &= ~MachO::MH_BINDATLOAD;
8213 }
8214 if (f & MachO::MH_PREBOUND) {
8215 outs() << " PREBOUND";
8216 f &= ~MachO::MH_PREBOUND;
8217 }
8218 if (f & MachO::MH_SPLIT_SEGS) {
8219 outs() << " SPLIT_SEGS";
8220 f &= ~MachO::MH_SPLIT_SEGS;
8221 }
8222 if (f & MachO::MH_LAZY_INIT) {
8223 outs() << " LAZY_INIT";
8224 f &= ~MachO::MH_LAZY_INIT;
8225 }
8226 if (f & MachO::MH_TWOLEVEL) {
8227 outs() << " TWOLEVEL";
8228 f &= ~MachO::MH_TWOLEVEL;
8229 }
8230 if (f & MachO::MH_FORCE_FLAT) {
8231 outs() << " FORCE_FLAT";
8232 f &= ~MachO::MH_FORCE_FLAT;
8233 }
8234 if (f & MachO::MH_NOMULTIDEFS) {
8235 outs() << " NOMULTIDEFS";
8236 f &= ~MachO::MH_NOMULTIDEFS;
8237 }
8238 if (f & MachO::MH_NOFIXPREBINDING) {
8239 outs() << " NOFIXPREBINDING";
8240 f &= ~MachO::MH_NOFIXPREBINDING;
8241 }
8242 if (f & MachO::MH_PREBINDABLE) {
8243 outs() << " PREBINDABLE";
8244 f &= ~MachO::MH_PREBINDABLE;
8245 }
8246 if (f & MachO::MH_ALLMODSBOUND) {
8247 outs() << " ALLMODSBOUND";
8248 f &= ~MachO::MH_ALLMODSBOUND;
8249 }
8250 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8251 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8252 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8253 }
8254 if (f & MachO::MH_CANONICAL) {
8255 outs() << " CANONICAL";
8256 f &= ~MachO::MH_CANONICAL;
8257 }
8258 if (f & MachO::MH_WEAK_DEFINES) {
8259 outs() << " WEAK_DEFINES";
8260 f &= ~MachO::MH_WEAK_DEFINES;
8261 }
8262 if (f & MachO::MH_BINDS_TO_WEAK) {
8263 outs() << " BINDS_TO_WEAK";
8264 f &= ~MachO::MH_BINDS_TO_WEAK;
8265 }
8266 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8267 outs() << " ALLOW_STACK_EXECUTION";
8268 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8269 }
8270 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8271 outs() << " DEAD_STRIPPABLE_DYLIB";
8272 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8273 }
8274 if (f & MachO::MH_PIE) {
8275 outs() << " PIE";
8276 f &= ~MachO::MH_PIE;
8277 }
8278 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8279 outs() << " NO_REEXPORTED_DYLIBS";
8280 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8281 }
8282 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8283 outs() << " MH_HAS_TLV_DESCRIPTORS";
8284 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8285 }
8286 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8287 outs() << " MH_NO_HEAP_EXECUTION";
8288 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8289 }
8290 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8291 outs() << " APP_EXTENSION_SAFE";
8292 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8293 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008294 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8295 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8296 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8297 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008298 if (f != 0 || flags == 0)
8299 outs() << format(" 0x%08" PRIx32, f);
8300 } else {
8301 outs() << format(" 0x%08" PRIx32, magic);
8302 outs() << format(" %7d", cputype);
8303 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8304 outs() << format(" 0x%02" PRIx32,
8305 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8306 outs() << format(" %10u", filetype);
8307 outs() << format(" %5u", ncmds);
8308 outs() << format(" %10u", sizeofcmds);
8309 outs() << format(" 0x%08" PRIx32, flags);
8310 }
8311 outs() << "\n";
8312}
8313
Kevin Enderby956366c2014-08-29 22:30:52 +00008314static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8315 StringRef SegName, uint64_t vmaddr,
8316 uint64_t vmsize, uint64_t fileoff,
8317 uint64_t filesize, uint32_t maxprot,
8318 uint32_t initprot, uint32_t nsects,
8319 uint32_t flags, uint32_t object_size,
8320 bool verbose) {
8321 uint64_t expected_cmdsize;
8322 if (cmd == MachO::LC_SEGMENT) {
8323 outs() << " cmd LC_SEGMENT\n";
8324 expected_cmdsize = nsects;
8325 expected_cmdsize *= sizeof(struct MachO::section);
8326 expected_cmdsize += sizeof(struct MachO::segment_command);
8327 } else {
8328 outs() << " cmd LC_SEGMENT_64\n";
8329 expected_cmdsize = nsects;
8330 expected_cmdsize *= sizeof(struct MachO::section_64);
8331 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8332 }
8333 outs() << " cmdsize " << cmdsize;
8334 if (cmdsize != expected_cmdsize)
8335 outs() << " Inconsistent size\n";
8336 else
8337 outs() << "\n";
8338 outs() << " segname " << SegName << "\n";
8339 if (cmd == MachO::LC_SEGMENT_64) {
8340 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8341 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8342 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008343 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8344 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008345 }
8346 outs() << " fileoff " << fileoff;
8347 if (fileoff > object_size)
8348 outs() << " (past end of file)\n";
8349 else
8350 outs() << "\n";
8351 outs() << " filesize " << filesize;
8352 if (fileoff + filesize > object_size)
8353 outs() << " (past end of file)\n";
8354 else
8355 outs() << "\n";
8356 if (verbose) {
8357 if ((maxprot &
8358 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8359 MachO::VM_PROT_EXECUTE)) != 0)
8360 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8361 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008362 outs() << " maxprot ";
8363 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8364 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8365 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008366 }
8367 if ((initprot &
8368 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8369 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008370 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008371 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008372 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008373 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8374 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8375 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008376 }
8377 } else {
8378 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8379 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8380 }
8381 outs() << " nsects " << nsects << "\n";
8382 if (verbose) {
8383 outs() << " flags";
8384 if (flags == 0)
8385 outs() << " (none)\n";
8386 else {
8387 if (flags & MachO::SG_HIGHVM) {
8388 outs() << " HIGHVM";
8389 flags &= ~MachO::SG_HIGHVM;
8390 }
8391 if (flags & MachO::SG_FVMLIB) {
8392 outs() << " FVMLIB";
8393 flags &= ~MachO::SG_FVMLIB;
8394 }
8395 if (flags & MachO::SG_NORELOC) {
8396 outs() << " NORELOC";
8397 flags &= ~MachO::SG_NORELOC;
8398 }
8399 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8400 outs() << " PROTECTED_VERSION_1";
8401 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8402 }
8403 if (flags)
8404 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8405 else
8406 outs() << "\n";
8407 }
8408 } else {
8409 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8410 }
8411}
8412
8413static void PrintSection(const char *sectname, const char *segname,
8414 uint64_t addr, uint64_t size, uint32_t offset,
8415 uint32_t align, uint32_t reloff, uint32_t nreloc,
8416 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8417 uint32_t cmd, const char *sg_segname,
8418 uint32_t filetype, uint32_t object_size,
8419 bool verbose) {
8420 outs() << "Section\n";
8421 outs() << " sectname " << format("%.16s\n", sectname);
8422 outs() << " segname " << format("%.16s", segname);
8423 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8424 outs() << " (does not match segment)\n";
8425 else
8426 outs() << "\n";
8427 if (cmd == MachO::LC_SEGMENT_64) {
8428 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8429 outs() << " size " << format("0x%016" PRIx64, size);
8430 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008431 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8432 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008433 }
8434 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8435 outs() << " (past end of file)\n";
8436 else
8437 outs() << "\n";
8438 outs() << " offset " << offset;
8439 if (offset > object_size)
8440 outs() << " (past end of file)\n";
8441 else
8442 outs() << "\n";
8443 uint32_t align_shifted = 1 << align;
8444 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8445 outs() << " reloff " << reloff;
8446 if (reloff > object_size)
8447 outs() << " (past end of file)\n";
8448 else
8449 outs() << "\n";
8450 outs() << " nreloc " << nreloc;
8451 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8452 outs() << " (past end of file)\n";
8453 else
8454 outs() << "\n";
8455 uint32_t section_type = flags & MachO::SECTION_TYPE;
8456 if (verbose) {
8457 outs() << " type";
8458 if (section_type == MachO::S_REGULAR)
8459 outs() << " S_REGULAR\n";
8460 else if (section_type == MachO::S_ZEROFILL)
8461 outs() << " S_ZEROFILL\n";
8462 else if (section_type == MachO::S_CSTRING_LITERALS)
8463 outs() << " S_CSTRING_LITERALS\n";
8464 else if (section_type == MachO::S_4BYTE_LITERALS)
8465 outs() << " S_4BYTE_LITERALS\n";
8466 else if (section_type == MachO::S_8BYTE_LITERALS)
8467 outs() << " S_8BYTE_LITERALS\n";
8468 else if (section_type == MachO::S_16BYTE_LITERALS)
8469 outs() << " S_16BYTE_LITERALS\n";
8470 else if (section_type == MachO::S_LITERAL_POINTERS)
8471 outs() << " S_LITERAL_POINTERS\n";
8472 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8473 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8474 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8475 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8476 else if (section_type == MachO::S_SYMBOL_STUBS)
8477 outs() << " S_SYMBOL_STUBS\n";
8478 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8479 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8480 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8481 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8482 else if (section_type == MachO::S_COALESCED)
8483 outs() << " S_COALESCED\n";
8484 else if (section_type == MachO::S_INTERPOSING)
8485 outs() << " S_INTERPOSING\n";
8486 else if (section_type == MachO::S_DTRACE_DOF)
8487 outs() << " S_DTRACE_DOF\n";
8488 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8489 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8490 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8491 outs() << " S_THREAD_LOCAL_REGULAR\n";
8492 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8493 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8494 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8495 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8496 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8497 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8498 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8499 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8500 else
8501 outs() << format("0x%08" PRIx32, section_type) << "\n";
8502 outs() << "attributes";
8503 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8504 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8505 outs() << " PURE_INSTRUCTIONS";
8506 if (section_attributes & MachO::S_ATTR_NO_TOC)
8507 outs() << " NO_TOC";
8508 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8509 outs() << " STRIP_STATIC_SYMS";
8510 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8511 outs() << " NO_DEAD_STRIP";
8512 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8513 outs() << " LIVE_SUPPORT";
8514 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8515 outs() << " SELF_MODIFYING_CODE";
8516 if (section_attributes & MachO::S_ATTR_DEBUG)
8517 outs() << " DEBUG";
8518 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8519 outs() << " SOME_INSTRUCTIONS";
8520 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8521 outs() << " EXT_RELOC";
8522 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8523 outs() << " LOC_RELOC";
8524 if (section_attributes == 0)
8525 outs() << " (none)";
8526 outs() << "\n";
8527 } else
8528 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8529 outs() << " reserved1 " << reserved1;
8530 if (section_type == MachO::S_SYMBOL_STUBS ||
8531 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8532 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8533 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8534 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8535 outs() << " (index into indirect symbol table)\n";
8536 else
8537 outs() << "\n";
8538 outs() << " reserved2 " << reserved2;
8539 if (section_type == MachO::S_SYMBOL_STUBS)
8540 outs() << " (size of stubs)\n";
8541 else
8542 outs() << "\n";
8543}
8544
David Majnemer73cc6ff2014-11-13 19:48:56 +00008545static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008546 uint32_t object_size) {
8547 outs() << " cmd LC_SYMTAB\n";
8548 outs() << " cmdsize " << st.cmdsize;
8549 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8550 outs() << " Incorrect size\n";
8551 else
8552 outs() << "\n";
8553 outs() << " symoff " << st.symoff;
8554 if (st.symoff > object_size)
8555 outs() << " (past end of file)\n";
8556 else
8557 outs() << "\n";
8558 outs() << " nsyms " << st.nsyms;
8559 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008560 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008561 big_size = st.nsyms;
8562 big_size *= sizeof(struct MachO::nlist_64);
8563 big_size += st.symoff;
8564 if (big_size > object_size)
8565 outs() << " (past end of file)\n";
8566 else
8567 outs() << "\n";
8568 } else {
8569 big_size = st.nsyms;
8570 big_size *= sizeof(struct MachO::nlist);
8571 big_size += st.symoff;
8572 if (big_size > object_size)
8573 outs() << " (past end of file)\n";
8574 else
8575 outs() << "\n";
8576 }
8577 outs() << " stroff " << st.stroff;
8578 if (st.stroff > object_size)
8579 outs() << " (past end of file)\n";
8580 else
8581 outs() << "\n";
8582 outs() << " strsize " << st.strsize;
8583 big_size = st.stroff;
8584 big_size += st.strsize;
8585 if (big_size > object_size)
8586 outs() << " (past end of file)\n";
8587 else
8588 outs() << "\n";
8589}
8590
8591static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8592 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008593 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008594 outs() << " cmd LC_DYSYMTAB\n";
8595 outs() << " cmdsize " << dyst.cmdsize;
8596 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8597 outs() << " Incorrect size\n";
8598 else
8599 outs() << "\n";
8600 outs() << " ilocalsym " << dyst.ilocalsym;
8601 if (dyst.ilocalsym > nsyms)
8602 outs() << " (greater than the number of symbols)\n";
8603 else
8604 outs() << "\n";
8605 outs() << " nlocalsym " << dyst.nlocalsym;
8606 uint64_t big_size;
8607 big_size = dyst.ilocalsym;
8608 big_size += dyst.nlocalsym;
8609 if (big_size > nsyms)
8610 outs() << " (past the end of the symbol table)\n";
8611 else
8612 outs() << "\n";
8613 outs() << " iextdefsym " << dyst.iextdefsym;
8614 if (dyst.iextdefsym > nsyms)
8615 outs() << " (greater than the number of symbols)\n";
8616 else
8617 outs() << "\n";
8618 outs() << " nextdefsym " << dyst.nextdefsym;
8619 big_size = dyst.iextdefsym;
8620 big_size += dyst.nextdefsym;
8621 if (big_size > nsyms)
8622 outs() << " (past the end of the symbol table)\n";
8623 else
8624 outs() << "\n";
8625 outs() << " iundefsym " << dyst.iundefsym;
8626 if (dyst.iundefsym > nsyms)
8627 outs() << " (greater than the number of symbols)\n";
8628 else
8629 outs() << "\n";
8630 outs() << " nundefsym " << dyst.nundefsym;
8631 big_size = dyst.iundefsym;
8632 big_size += dyst.nundefsym;
8633 if (big_size > nsyms)
8634 outs() << " (past the end of the symbol table)\n";
8635 else
8636 outs() << "\n";
8637 outs() << " tocoff " << dyst.tocoff;
8638 if (dyst.tocoff > object_size)
8639 outs() << " (past end of file)\n";
8640 else
8641 outs() << "\n";
8642 outs() << " ntoc " << dyst.ntoc;
8643 big_size = dyst.ntoc;
8644 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8645 big_size += dyst.tocoff;
8646 if (big_size > object_size)
8647 outs() << " (past end of file)\n";
8648 else
8649 outs() << "\n";
8650 outs() << " modtaboff " << dyst.modtaboff;
8651 if (dyst.modtaboff > object_size)
8652 outs() << " (past end of file)\n";
8653 else
8654 outs() << "\n";
8655 outs() << " nmodtab " << dyst.nmodtab;
8656 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008657 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008658 modtabend = dyst.nmodtab;
8659 modtabend *= sizeof(struct MachO::dylib_module_64);
8660 modtabend += dyst.modtaboff;
8661 } else {
8662 modtabend = dyst.nmodtab;
8663 modtabend *= sizeof(struct MachO::dylib_module);
8664 modtabend += dyst.modtaboff;
8665 }
8666 if (modtabend > object_size)
8667 outs() << " (past end of file)\n";
8668 else
8669 outs() << "\n";
8670 outs() << " extrefsymoff " << dyst.extrefsymoff;
8671 if (dyst.extrefsymoff > object_size)
8672 outs() << " (past end of file)\n";
8673 else
8674 outs() << "\n";
8675 outs() << " nextrefsyms " << dyst.nextrefsyms;
8676 big_size = dyst.nextrefsyms;
8677 big_size *= sizeof(struct MachO::dylib_reference);
8678 big_size += dyst.extrefsymoff;
8679 if (big_size > object_size)
8680 outs() << " (past end of file)\n";
8681 else
8682 outs() << "\n";
8683 outs() << " indirectsymoff " << dyst.indirectsymoff;
8684 if (dyst.indirectsymoff > object_size)
8685 outs() << " (past end of file)\n";
8686 else
8687 outs() << "\n";
8688 outs() << " nindirectsyms " << dyst.nindirectsyms;
8689 big_size = dyst.nindirectsyms;
8690 big_size *= sizeof(uint32_t);
8691 big_size += dyst.indirectsymoff;
8692 if (big_size > object_size)
8693 outs() << " (past end of file)\n";
8694 else
8695 outs() << "\n";
8696 outs() << " extreloff " << dyst.extreloff;
8697 if (dyst.extreloff > object_size)
8698 outs() << " (past end of file)\n";
8699 else
8700 outs() << "\n";
8701 outs() << " nextrel " << dyst.nextrel;
8702 big_size = dyst.nextrel;
8703 big_size *= sizeof(struct MachO::relocation_info);
8704 big_size += dyst.extreloff;
8705 if (big_size > object_size)
8706 outs() << " (past end of file)\n";
8707 else
8708 outs() << "\n";
8709 outs() << " locreloff " << dyst.locreloff;
8710 if (dyst.locreloff > object_size)
8711 outs() << " (past end of file)\n";
8712 else
8713 outs() << "\n";
8714 outs() << " nlocrel " << dyst.nlocrel;
8715 big_size = dyst.nlocrel;
8716 big_size *= sizeof(struct MachO::relocation_info);
8717 big_size += dyst.locreloff;
8718 if (big_size > object_size)
8719 outs() << " (past end of file)\n";
8720 else
8721 outs() << "\n";
8722}
8723
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008724static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8725 uint32_t object_size) {
8726 if (dc.cmd == MachO::LC_DYLD_INFO)
8727 outs() << " cmd LC_DYLD_INFO\n";
8728 else
8729 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8730 outs() << " cmdsize " << dc.cmdsize;
8731 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8732 outs() << " Incorrect size\n";
8733 else
8734 outs() << "\n";
8735 outs() << " rebase_off " << dc.rebase_off;
8736 if (dc.rebase_off > object_size)
8737 outs() << " (past end of file)\n";
8738 else
8739 outs() << "\n";
8740 outs() << " rebase_size " << dc.rebase_size;
8741 uint64_t big_size;
8742 big_size = dc.rebase_off;
8743 big_size += dc.rebase_size;
8744 if (big_size > object_size)
8745 outs() << " (past end of file)\n";
8746 else
8747 outs() << "\n";
8748 outs() << " bind_off " << dc.bind_off;
8749 if (dc.bind_off > object_size)
8750 outs() << " (past end of file)\n";
8751 else
8752 outs() << "\n";
8753 outs() << " bind_size " << dc.bind_size;
8754 big_size = dc.bind_off;
8755 big_size += dc.bind_size;
8756 if (big_size > object_size)
8757 outs() << " (past end of file)\n";
8758 else
8759 outs() << "\n";
8760 outs() << " weak_bind_off " << dc.weak_bind_off;
8761 if (dc.weak_bind_off > object_size)
8762 outs() << " (past end of file)\n";
8763 else
8764 outs() << "\n";
8765 outs() << " weak_bind_size " << dc.weak_bind_size;
8766 big_size = dc.weak_bind_off;
8767 big_size += dc.weak_bind_size;
8768 if (big_size > object_size)
8769 outs() << " (past end of file)\n";
8770 else
8771 outs() << "\n";
8772 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8773 if (dc.lazy_bind_off > object_size)
8774 outs() << " (past end of file)\n";
8775 else
8776 outs() << "\n";
8777 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8778 big_size = dc.lazy_bind_off;
8779 big_size += dc.lazy_bind_size;
8780 if (big_size > object_size)
8781 outs() << " (past end of file)\n";
8782 else
8783 outs() << "\n";
8784 outs() << " export_off " << dc.export_off;
8785 if (dc.export_off > object_size)
8786 outs() << " (past end of file)\n";
8787 else
8788 outs() << "\n";
8789 outs() << " export_size " << dc.export_size;
8790 big_size = dc.export_off;
8791 big_size += dc.export_size;
8792 if (big_size > object_size)
8793 outs() << " (past end of file)\n";
8794 else
8795 outs() << "\n";
8796}
8797
8798static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8799 const char *Ptr) {
8800 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8801 outs() << " cmd LC_ID_DYLINKER\n";
8802 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8803 outs() << " cmd LC_LOAD_DYLINKER\n";
8804 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8805 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8806 else
8807 outs() << " cmd ?(" << dyld.cmd << ")\n";
8808 outs() << " cmdsize " << dyld.cmdsize;
8809 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8810 outs() << " Incorrect size\n";
8811 else
8812 outs() << "\n";
8813 if (dyld.name >= dyld.cmdsize)
8814 outs() << " name ?(bad offset " << dyld.name << ")\n";
8815 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008816 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008817 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8818 }
8819}
8820
8821static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8822 outs() << " cmd LC_UUID\n";
8823 outs() << " cmdsize " << uuid.cmdsize;
8824 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8825 outs() << " Incorrect size\n";
8826 else
8827 outs() << "\n";
8828 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008829 for (int i = 0; i < 16; ++i) {
8830 outs() << format("%02" PRIX32, uuid.uuid[i]);
8831 if (i == 3 || i == 5 || i == 7 || i == 9)
8832 outs() << "-";
8833 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008834 outs() << "\n";
8835}
8836
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008837static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008838 outs() << " cmd LC_RPATH\n";
8839 outs() << " cmdsize " << rpath.cmdsize;
8840 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8841 outs() << " Incorrect size\n";
8842 else
8843 outs() << "\n";
8844 if (rpath.path >= rpath.cmdsize)
8845 outs() << " path ?(bad offset " << rpath.path << ")\n";
8846 else {
8847 const char *P = (const char *)(Ptr) + rpath.path;
8848 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8849 }
8850}
8851
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008852static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008853 StringRef LoadCmdName;
8854 switch (vd.cmd) {
8855 case MachO::LC_VERSION_MIN_MACOSX:
8856 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8857 break;
8858 case MachO::LC_VERSION_MIN_IPHONEOS:
8859 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8860 break;
8861 case MachO::LC_VERSION_MIN_TVOS:
8862 LoadCmdName = "LC_VERSION_MIN_TVOS";
8863 break;
8864 case MachO::LC_VERSION_MIN_WATCHOS:
8865 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8866 break;
8867 default:
8868 llvm_unreachable("Unknown version min load command");
8869 }
8870
8871 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008872 outs() << " cmdsize " << vd.cmdsize;
8873 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8874 outs() << " Incorrect size\n";
8875 else
8876 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008877 outs() << " version "
8878 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8879 << MachOObjectFile::getVersionMinMinor(vd, false);
8880 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8881 if (Update != 0)
8882 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008883 outs() << "\n";
8884 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008885 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008886 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008887 outs() << " sdk "
8888 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8889 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008890 }
Davide Italiano56baef32015-08-26 12:26:11 +00008891 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8892 if (Update != 0)
8893 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008894 outs() << "\n";
8895}
8896
Kevin Enderbya4579c42017-01-19 17:36:31 +00008897static void PrintNoteLoadCommand(MachO::note_command Nt) {
8898 outs() << " cmd LC_NOTE\n";
8899 outs() << " cmdsize " << Nt.cmdsize;
8900 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8901 outs() << " Incorrect size\n";
8902 else
8903 outs() << "\n";
8904 const char *d = Nt.data_owner;
8905 outs() << "data_owner " << format("%.16s\n", d);
8906 outs() << " offset " << Nt.offset << "\n";
8907 outs() << " size " << Nt.size << "\n";
8908}
8909
Steven Wu5b54a422017-01-23 20:07:55 +00008910static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8911 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8912 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8913 << "\n";
8914}
8915
8916static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8917 MachO::build_version_command bd) {
8918 outs() << " cmd LC_BUILD_VERSION\n";
8919 outs() << " cmdsize " << bd.cmdsize;
8920 if (bd.cmdsize !=
8921 sizeof(struct MachO::build_version_command) +
8922 bd.ntools * sizeof(struct MachO::build_tool_version))
8923 outs() << " Incorrect size\n";
8924 else
8925 outs() << "\n";
8926 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8927 << "\n";
8928 if (bd.sdk)
8929 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8930 << "\n";
8931 else
8932 outs() << " sdk n/a\n";
8933 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8934 << "\n";
8935 outs() << " ntools " << bd.ntools << "\n";
8936 for (unsigned i = 0; i < bd.ntools; ++i) {
8937 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8938 PrintBuildToolVersion(bv);
8939 }
8940}
8941
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008942static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8943 outs() << " cmd LC_SOURCE_VERSION\n";
8944 outs() << " cmdsize " << sd.cmdsize;
8945 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8946 outs() << " Incorrect size\n";
8947 else
8948 outs() << "\n";
8949 uint64_t a = (sd.version >> 40) & 0xffffff;
8950 uint64_t b = (sd.version >> 30) & 0x3ff;
8951 uint64_t c = (sd.version >> 20) & 0x3ff;
8952 uint64_t d = (sd.version >> 10) & 0x3ff;
8953 uint64_t e = sd.version & 0x3ff;
8954 outs() << " version " << a << "." << b;
8955 if (e != 0)
8956 outs() << "." << c << "." << d << "." << e;
8957 else if (d != 0)
8958 outs() << "." << c << "." << d;
8959 else if (c != 0)
8960 outs() << "." << c;
8961 outs() << "\n";
8962}
8963
8964static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8965 outs() << " cmd LC_MAIN\n";
8966 outs() << " cmdsize " << ep.cmdsize;
8967 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8968 outs() << " Incorrect size\n";
8969 else
8970 outs() << "\n";
8971 outs() << " entryoff " << ep.entryoff << "\n";
8972 outs() << " stacksize " << ep.stacksize << "\n";
8973}
8974
Kevin Enderby0804f4672014-12-16 23:25:52 +00008975static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8976 uint32_t object_size) {
8977 outs() << " cmd LC_ENCRYPTION_INFO\n";
8978 outs() << " cmdsize " << ec.cmdsize;
8979 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8980 outs() << " Incorrect size\n";
8981 else
8982 outs() << "\n";
8983 outs() << " cryptoff " << ec.cryptoff;
8984 if (ec.cryptoff > object_size)
8985 outs() << " (past end of file)\n";
8986 else
8987 outs() << "\n";
8988 outs() << " cryptsize " << ec.cryptsize;
8989 if (ec.cryptsize > object_size)
8990 outs() << " (past end of file)\n";
8991 else
8992 outs() << "\n";
8993 outs() << " cryptid " << ec.cryptid << "\n";
8994}
8995
Kevin Enderby57538292014-12-17 01:01:30 +00008996static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008997 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008998 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8999 outs() << " cmdsize " << ec.cmdsize;
9000 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9001 outs() << " Incorrect size\n";
9002 else
9003 outs() << "\n";
9004 outs() << " cryptoff " << ec.cryptoff;
9005 if (ec.cryptoff > object_size)
9006 outs() << " (past end of file)\n";
9007 else
9008 outs() << "\n";
9009 outs() << " cryptsize " << ec.cryptsize;
9010 if (ec.cryptsize > object_size)
9011 outs() << " (past end of file)\n";
9012 else
9013 outs() << "\n";
9014 outs() << " cryptid " << ec.cryptid << "\n";
9015 outs() << " pad " << ec.pad << "\n";
9016}
9017
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009018static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9019 const char *Ptr) {
9020 outs() << " cmd LC_LINKER_OPTION\n";
9021 outs() << " cmdsize " << lo.cmdsize;
9022 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9023 outs() << " Incorrect size\n";
9024 else
9025 outs() << "\n";
9026 outs() << " count " << lo.count << "\n";
9027 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9028 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9029 uint32_t i = 0;
9030 while (left > 0) {
9031 while (*string == '\0' && left > 0) {
9032 string++;
9033 left--;
9034 }
9035 if (left > 0) {
9036 i++;
9037 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009038 uint32_t NullPos = StringRef(string, left).find('\0');
9039 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009040 string += len;
9041 left -= len;
9042 }
9043 }
9044 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009045 outs() << " count " << lo.count << " does not match number of strings "
9046 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009047}
9048
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009049static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9050 const char *Ptr) {
9051 outs() << " cmd LC_SUB_FRAMEWORK\n";
9052 outs() << " cmdsize " << sub.cmdsize;
9053 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9054 outs() << " Incorrect size\n";
9055 else
9056 outs() << "\n";
9057 if (sub.umbrella < sub.cmdsize) {
9058 const char *P = Ptr + sub.umbrella;
9059 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9060 } else {
9061 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9062 }
9063}
9064
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009065static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9066 const char *Ptr) {
9067 outs() << " cmd LC_SUB_UMBRELLA\n";
9068 outs() << " cmdsize " << sub.cmdsize;
9069 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9070 outs() << " Incorrect size\n";
9071 else
9072 outs() << "\n";
9073 if (sub.sub_umbrella < sub.cmdsize) {
9074 const char *P = Ptr + sub.sub_umbrella;
9075 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9076 } else {
9077 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9078 }
9079}
9080
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009081static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009082 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009083 outs() << " cmd LC_SUB_LIBRARY\n";
9084 outs() << " cmdsize " << sub.cmdsize;
9085 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9086 outs() << " Incorrect size\n";
9087 else
9088 outs() << "\n";
9089 if (sub.sub_library < sub.cmdsize) {
9090 const char *P = Ptr + sub.sub_library;
9091 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9092 } else {
9093 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9094 }
9095}
9096
Kevin Enderby186eac32014-12-19 21:06:24 +00009097static void PrintSubClientCommand(MachO::sub_client_command sub,
9098 const char *Ptr) {
9099 outs() << " cmd LC_SUB_CLIENT\n";
9100 outs() << " cmdsize " << sub.cmdsize;
9101 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9102 outs() << " Incorrect size\n";
9103 else
9104 outs() << "\n";
9105 if (sub.client < sub.cmdsize) {
9106 const char *P = Ptr + sub.client;
9107 outs() << " client " << P << " (offset " << sub.client << ")\n";
9108 } else {
9109 outs() << " client ?(bad offset " << sub.client << ")\n";
9110 }
9111}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009112
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009113static void PrintRoutinesCommand(MachO::routines_command r) {
9114 outs() << " cmd LC_ROUTINES\n";
9115 outs() << " cmdsize " << r.cmdsize;
9116 if (r.cmdsize != sizeof(struct MachO::routines_command))
9117 outs() << " Incorrect size\n";
9118 else
9119 outs() << "\n";
9120 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9121 outs() << " init_module " << r.init_module << "\n";
9122 outs() << " reserved1 " << r.reserved1 << "\n";
9123 outs() << " reserved2 " << r.reserved2 << "\n";
9124 outs() << " reserved3 " << r.reserved3 << "\n";
9125 outs() << " reserved4 " << r.reserved4 << "\n";
9126 outs() << " reserved5 " << r.reserved5 << "\n";
9127 outs() << " reserved6 " << r.reserved6 << "\n";
9128}
9129
9130static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9131 outs() << " cmd LC_ROUTINES_64\n";
9132 outs() << " cmdsize " << r.cmdsize;
9133 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9134 outs() << " Incorrect size\n";
9135 else
9136 outs() << "\n";
9137 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9138 outs() << " init_module " << r.init_module << "\n";
9139 outs() << " reserved1 " << r.reserved1 << "\n";
9140 outs() << " reserved2 " << r.reserved2 << "\n";
9141 outs() << " reserved3 " << r.reserved3 << "\n";
9142 outs() << " reserved4 " << r.reserved4 << "\n";
9143 outs() << " reserved5 " << r.reserved5 << "\n";
9144 outs() << " reserved6 " << r.reserved6 << "\n";
9145}
9146
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009147static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9148 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9149 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9150 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9151 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9152 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9153 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9154 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9155 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9156 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9157 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9158 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9159 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9160 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9161 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9162 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9163 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9164}
9165
Kevin Enderby48ef5342014-12-23 22:56:39 +00009166static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9167 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9168 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9169 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9170 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9171 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9172 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9173 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9174 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9175 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9176 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9177 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9178 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9179 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9180 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9181 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9182 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9183 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9184 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9185 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9186 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9187 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9188}
9189
Kevin Enderby227df342014-12-23 23:43:59 +00009190static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009191 uint32_t f;
9192 outs() << "\t mmst_reg ";
9193 for (f = 0; f < 10; f++)
9194 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9195 outs() << "\n";
9196 outs() << "\t mmst_rsrv ";
9197 for (f = 0; f < 6; f++)
9198 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9199 outs() << "\n";
9200}
9201
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009202static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009203 uint32_t f;
9204 outs() << "\t xmm_reg ";
9205 for (f = 0; f < 16; f++)
9206 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9207 outs() << "\n";
9208}
9209
9210static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9211 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9212 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9213 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9214 outs() << " denorm " << fpu.fpu_fcw.denorm;
9215 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9216 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9217 outs() << " undfl " << fpu.fpu_fcw.undfl;
9218 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9219 outs() << "\t\t pc ";
9220 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9221 outs() << "FP_PREC_24B ";
9222 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9223 outs() << "FP_PREC_53B ";
9224 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9225 outs() << "FP_PREC_64B ";
9226 else
9227 outs() << fpu.fpu_fcw.pc << " ";
9228 outs() << "rc ";
9229 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9230 outs() << "FP_RND_NEAR ";
9231 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9232 outs() << "FP_RND_DOWN ";
9233 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9234 outs() << "FP_RND_UP ";
9235 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009236 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009237 outs() << "\n";
9238 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9239 outs() << " denorm " << fpu.fpu_fsw.denorm;
9240 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9241 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9242 outs() << " undfl " << fpu.fpu_fsw.undfl;
9243 outs() << " precis " << fpu.fpu_fsw.precis;
9244 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9245 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9246 outs() << " c0 " << fpu.fpu_fsw.c0;
9247 outs() << " c1 " << fpu.fpu_fsw.c1;
9248 outs() << " c2 " << fpu.fpu_fsw.c2;
9249 outs() << " tos " << fpu.fpu_fsw.tos;
9250 outs() << " c3 " << fpu.fpu_fsw.c3;
9251 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9252 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9253 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9254 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9255 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9256 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9257 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9258 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9259 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9260 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9261 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9262 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9263 outs() << "\n";
9264 outs() << "\t fpu_stmm0:\n";
9265 Print_mmst_reg(fpu.fpu_stmm0);
9266 outs() << "\t fpu_stmm1:\n";
9267 Print_mmst_reg(fpu.fpu_stmm1);
9268 outs() << "\t fpu_stmm2:\n";
9269 Print_mmst_reg(fpu.fpu_stmm2);
9270 outs() << "\t fpu_stmm3:\n";
9271 Print_mmst_reg(fpu.fpu_stmm3);
9272 outs() << "\t fpu_stmm4:\n";
9273 Print_mmst_reg(fpu.fpu_stmm4);
9274 outs() << "\t fpu_stmm5:\n";
9275 Print_mmst_reg(fpu.fpu_stmm5);
9276 outs() << "\t fpu_stmm6:\n";
9277 Print_mmst_reg(fpu.fpu_stmm6);
9278 outs() << "\t fpu_stmm7:\n";
9279 Print_mmst_reg(fpu.fpu_stmm7);
9280 outs() << "\t fpu_xmm0:\n";
9281 Print_xmm_reg(fpu.fpu_xmm0);
9282 outs() << "\t fpu_xmm1:\n";
9283 Print_xmm_reg(fpu.fpu_xmm1);
9284 outs() << "\t fpu_xmm2:\n";
9285 Print_xmm_reg(fpu.fpu_xmm2);
9286 outs() << "\t fpu_xmm3:\n";
9287 Print_xmm_reg(fpu.fpu_xmm3);
9288 outs() << "\t fpu_xmm4:\n";
9289 Print_xmm_reg(fpu.fpu_xmm4);
9290 outs() << "\t fpu_xmm5:\n";
9291 Print_xmm_reg(fpu.fpu_xmm5);
9292 outs() << "\t fpu_xmm6:\n";
9293 Print_xmm_reg(fpu.fpu_xmm6);
9294 outs() << "\t fpu_xmm7:\n";
9295 Print_xmm_reg(fpu.fpu_xmm7);
9296 outs() << "\t fpu_xmm8:\n";
9297 Print_xmm_reg(fpu.fpu_xmm8);
9298 outs() << "\t fpu_xmm9:\n";
9299 Print_xmm_reg(fpu.fpu_xmm9);
9300 outs() << "\t fpu_xmm10:\n";
9301 Print_xmm_reg(fpu.fpu_xmm10);
9302 outs() << "\t fpu_xmm11:\n";
9303 Print_xmm_reg(fpu.fpu_xmm11);
9304 outs() << "\t fpu_xmm12:\n";
9305 Print_xmm_reg(fpu.fpu_xmm12);
9306 outs() << "\t fpu_xmm13:\n";
9307 Print_xmm_reg(fpu.fpu_xmm13);
9308 outs() << "\t fpu_xmm14:\n";
9309 Print_xmm_reg(fpu.fpu_xmm14);
9310 outs() << "\t fpu_xmm15:\n";
9311 Print_xmm_reg(fpu.fpu_xmm15);
9312 outs() << "\t fpu_rsrv4:\n";
9313 for (uint32_t f = 0; f < 6; f++) {
9314 outs() << "\t ";
9315 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009316 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009317 outs() << "\n";
9318 }
9319 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9320 outs() << "\n";
9321}
9322
9323static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9324 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9325 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9326 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9327}
9328
Kevin Enderby41c9c002016-10-21 18:22:35 +00009329static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9330 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9331 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9332 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9333 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9334 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9335 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9336 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9337 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9338 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9339 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9340 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9341 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9342 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9343 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9344 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9345 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9346 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9347}
9348
Kevin Enderby7747cb52016-11-03 20:51:28 +00009349static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9350 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9351 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9352 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9353 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9354 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9355 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9356 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9357 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9358 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9359 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9360 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9361 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9362 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9363 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9364 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9365 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9366 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9367 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9368 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9369 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9370 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9371 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9372 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9373 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9374 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9375 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9376 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9377 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9378 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9379 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9380 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9381 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9382 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9383 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9384}
9385
Kevin Enderby48ef5342014-12-23 22:56:39 +00009386static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9387 bool isLittleEndian, uint32_t cputype) {
9388 if (t.cmd == MachO::LC_THREAD)
9389 outs() << " cmd LC_THREAD\n";
9390 else if (t.cmd == MachO::LC_UNIXTHREAD)
9391 outs() << " cmd LC_UNIXTHREAD\n";
9392 else
9393 outs() << " cmd " << t.cmd << " (unknown)\n";
9394 outs() << " cmdsize " << t.cmdsize;
9395 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9396 outs() << " Incorrect size\n";
9397 else
9398 outs() << "\n";
9399
9400 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9401 const char *end = Ptr + t.cmdsize;
9402 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009403 if (cputype == MachO::CPU_TYPE_I386) {
9404 while (begin < end) {
9405 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9406 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9407 begin += sizeof(uint32_t);
9408 } else {
9409 flavor = 0;
9410 begin = end;
9411 }
9412 if (isLittleEndian != sys::IsLittleEndianHost)
9413 sys::swapByteOrder(flavor);
9414 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9415 memcpy((char *)&count, begin, sizeof(uint32_t));
9416 begin += sizeof(uint32_t);
9417 } else {
9418 count = 0;
9419 begin = end;
9420 }
9421 if (isLittleEndian != sys::IsLittleEndianHost)
9422 sys::swapByteOrder(count);
9423 if (flavor == MachO::x86_THREAD_STATE32) {
9424 outs() << " flavor i386_THREAD_STATE\n";
9425 if (count == MachO::x86_THREAD_STATE32_COUNT)
9426 outs() << " count i386_THREAD_STATE_COUNT\n";
9427 else
9428 outs() << " count " << count
9429 << " (not x86_THREAD_STATE32_COUNT)\n";
9430 MachO::x86_thread_state32_t cpu32;
9431 left = end - begin;
9432 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9433 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9434 begin += sizeof(MachO::x86_thread_state32_t);
9435 } else {
9436 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9437 memcpy(&cpu32, begin, left);
9438 begin += left;
9439 }
9440 if (isLittleEndian != sys::IsLittleEndianHost)
9441 swapStruct(cpu32);
9442 Print_x86_thread_state32_t(cpu32);
9443 } else if (flavor == MachO::x86_THREAD_STATE) {
9444 outs() << " flavor x86_THREAD_STATE\n";
9445 if (count == MachO::x86_THREAD_STATE_COUNT)
9446 outs() << " count x86_THREAD_STATE_COUNT\n";
9447 else
9448 outs() << " count " << count
9449 << " (not x86_THREAD_STATE_COUNT)\n";
9450 struct MachO::x86_thread_state_t ts;
9451 left = end - begin;
9452 if (left >= sizeof(MachO::x86_thread_state_t)) {
9453 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9454 begin += sizeof(MachO::x86_thread_state_t);
9455 } else {
9456 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9457 memcpy(&ts, begin, left);
9458 begin += left;
9459 }
9460 if (isLittleEndian != sys::IsLittleEndianHost)
9461 swapStruct(ts);
9462 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9463 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9464 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9465 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9466 else
9467 outs() << "tsh.count " << ts.tsh.count
9468 << " (not x86_THREAD_STATE32_COUNT\n";
9469 Print_x86_thread_state32_t(ts.uts.ts32);
9470 } else {
9471 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9472 << ts.tsh.count << "\n";
9473 }
9474 } else {
9475 outs() << " flavor " << flavor << " (unknown)\n";
9476 outs() << " count " << count << "\n";
9477 outs() << " state (unknown)\n";
9478 begin += count * sizeof(uint32_t);
9479 }
9480 }
9481 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009482 while (begin < end) {
9483 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9484 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9485 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009486 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009487 flavor = 0;
9488 begin = end;
9489 }
9490 if (isLittleEndian != sys::IsLittleEndianHost)
9491 sys::swapByteOrder(flavor);
9492 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9493 memcpy((char *)&count, begin, sizeof(uint32_t));
9494 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009495 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009496 count = 0;
9497 begin = end;
9498 }
9499 if (isLittleEndian != sys::IsLittleEndianHost)
9500 sys::swapByteOrder(count);
9501 if (flavor == MachO::x86_THREAD_STATE64) {
9502 outs() << " flavor x86_THREAD_STATE64\n";
9503 if (count == MachO::x86_THREAD_STATE64_COUNT)
9504 outs() << " count x86_THREAD_STATE64_COUNT\n";
9505 else
9506 outs() << " count " << count
9507 << " (not x86_THREAD_STATE64_COUNT)\n";
9508 MachO::x86_thread_state64_t cpu64;
9509 left = end - begin;
9510 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9511 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9512 begin += sizeof(MachO::x86_thread_state64_t);
9513 } else {
9514 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9515 memcpy(&cpu64, begin, left);
9516 begin += left;
9517 }
9518 if (isLittleEndian != sys::IsLittleEndianHost)
9519 swapStruct(cpu64);
9520 Print_x86_thread_state64_t(cpu64);
9521 } else if (flavor == MachO::x86_THREAD_STATE) {
9522 outs() << " flavor x86_THREAD_STATE\n";
9523 if (count == MachO::x86_THREAD_STATE_COUNT)
9524 outs() << " count x86_THREAD_STATE_COUNT\n";
9525 else
9526 outs() << " count " << count
9527 << " (not x86_THREAD_STATE_COUNT)\n";
9528 struct MachO::x86_thread_state_t ts;
9529 left = end - begin;
9530 if (left >= sizeof(MachO::x86_thread_state_t)) {
9531 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9532 begin += sizeof(MachO::x86_thread_state_t);
9533 } else {
9534 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9535 memcpy(&ts, begin, left);
9536 begin += left;
9537 }
9538 if (isLittleEndian != sys::IsLittleEndianHost)
9539 swapStruct(ts);
9540 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9541 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9542 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9543 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9544 else
9545 outs() << "tsh.count " << ts.tsh.count
9546 << " (not x86_THREAD_STATE64_COUNT\n";
9547 Print_x86_thread_state64_t(ts.uts.ts64);
9548 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009549 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9550 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009551 }
9552 } else if (flavor == MachO::x86_FLOAT_STATE) {
9553 outs() << " flavor x86_FLOAT_STATE\n";
9554 if (count == MachO::x86_FLOAT_STATE_COUNT)
9555 outs() << " count x86_FLOAT_STATE_COUNT\n";
9556 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009557 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009558 struct MachO::x86_float_state_t fs;
9559 left = end - begin;
9560 if (left >= sizeof(MachO::x86_float_state_t)) {
9561 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9562 begin += sizeof(MachO::x86_float_state_t);
9563 } else {
9564 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9565 memcpy(&fs, begin, left);
9566 begin += left;
9567 }
9568 if (isLittleEndian != sys::IsLittleEndianHost)
9569 swapStruct(fs);
9570 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9571 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009572 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009573 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9574 else
9575 outs() << "fsh.count " << fs.fsh.count
9576 << " (not x86_FLOAT_STATE64_COUNT\n";
9577 Print_x86_float_state_t(fs.ufs.fs64);
9578 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009579 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9580 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009581 }
9582 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9583 outs() << " flavor x86_EXCEPTION_STATE\n";
9584 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9585 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9586 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009587 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009588 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9589 struct MachO::x86_exception_state_t es;
9590 left = end - begin;
9591 if (left >= sizeof(MachO::x86_exception_state_t)) {
9592 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9593 begin += sizeof(MachO::x86_exception_state_t);
9594 } else {
9595 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9596 memcpy(&es, begin, left);
9597 begin += left;
9598 }
9599 if (isLittleEndian != sys::IsLittleEndianHost)
9600 swapStruct(es);
9601 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9602 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009603 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009604 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9605 else
9606 outs() << "\t esh.count " << es.esh.count
9607 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9608 Print_x86_exception_state_t(es.ues.es64);
9609 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009610 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9611 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009612 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009613 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9614 outs() << " flavor x86_EXCEPTION_STATE64\n";
9615 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9616 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9617 else
9618 outs() << " count " << count
9619 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9620 struct MachO::x86_exception_state64_t es64;
9621 left = end - begin;
9622 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9623 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9624 begin += sizeof(MachO::x86_exception_state64_t);
9625 } else {
9626 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9627 memcpy(&es64, begin, left);
9628 begin += left;
9629 }
9630 if (isLittleEndian != sys::IsLittleEndianHost)
9631 swapStruct(es64);
9632 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009633 } else {
9634 outs() << " flavor " << flavor << " (unknown)\n";
9635 outs() << " count " << count << "\n";
9636 outs() << " state (unknown)\n";
9637 begin += count * sizeof(uint32_t);
9638 }
9639 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009640 } else if (cputype == MachO::CPU_TYPE_ARM) {
9641 while (begin < end) {
9642 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9643 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9644 begin += sizeof(uint32_t);
9645 } else {
9646 flavor = 0;
9647 begin = end;
9648 }
9649 if (isLittleEndian != sys::IsLittleEndianHost)
9650 sys::swapByteOrder(flavor);
9651 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9652 memcpy((char *)&count, begin, sizeof(uint32_t));
9653 begin += sizeof(uint32_t);
9654 } else {
9655 count = 0;
9656 begin = end;
9657 }
9658 if (isLittleEndian != sys::IsLittleEndianHost)
9659 sys::swapByteOrder(count);
9660 if (flavor == MachO::ARM_THREAD_STATE) {
9661 outs() << " flavor ARM_THREAD_STATE\n";
9662 if (count == MachO::ARM_THREAD_STATE_COUNT)
9663 outs() << " count ARM_THREAD_STATE_COUNT\n";
9664 else
9665 outs() << " count " << count
9666 << " (not ARM_THREAD_STATE_COUNT)\n";
9667 MachO::arm_thread_state32_t cpu32;
9668 left = end - begin;
9669 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9670 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9671 begin += sizeof(MachO::arm_thread_state32_t);
9672 } else {
9673 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9674 memcpy(&cpu32, begin, left);
9675 begin += left;
9676 }
9677 if (isLittleEndian != sys::IsLittleEndianHost)
9678 swapStruct(cpu32);
9679 Print_arm_thread_state32_t(cpu32);
9680 } else {
9681 outs() << " flavor " << flavor << " (unknown)\n";
9682 outs() << " count " << count << "\n";
9683 outs() << " state (unknown)\n";
9684 begin += count * sizeof(uint32_t);
9685 }
9686 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009687 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9688 while (begin < end) {
9689 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9690 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9691 begin += sizeof(uint32_t);
9692 } else {
9693 flavor = 0;
9694 begin = end;
9695 }
9696 if (isLittleEndian != sys::IsLittleEndianHost)
9697 sys::swapByteOrder(flavor);
9698 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9699 memcpy((char *)&count, begin, sizeof(uint32_t));
9700 begin += sizeof(uint32_t);
9701 } else {
9702 count = 0;
9703 begin = end;
9704 }
9705 if (isLittleEndian != sys::IsLittleEndianHost)
9706 sys::swapByteOrder(count);
9707 if (flavor == MachO::ARM_THREAD_STATE64) {
9708 outs() << " flavor ARM_THREAD_STATE64\n";
9709 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9710 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9711 else
9712 outs() << " count " << count
9713 << " (not ARM_THREAD_STATE64_COUNT)\n";
9714 MachO::arm_thread_state64_t cpu64;
9715 left = end - begin;
9716 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9717 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9718 begin += sizeof(MachO::arm_thread_state64_t);
9719 } else {
9720 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9721 memcpy(&cpu64, begin, left);
9722 begin += left;
9723 }
9724 if (isLittleEndian != sys::IsLittleEndianHost)
9725 swapStruct(cpu64);
9726 Print_arm_thread_state64_t(cpu64);
9727 } else {
9728 outs() << " flavor " << flavor << " (unknown)\n";
9729 outs() << " count " << count << "\n";
9730 outs() << " state (unknown)\n";
9731 begin += count * sizeof(uint32_t);
9732 }
9733 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009734 } else {
9735 while (begin < end) {
9736 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9737 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9738 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009739 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009740 flavor = 0;
9741 begin = end;
9742 }
9743 if (isLittleEndian != sys::IsLittleEndianHost)
9744 sys::swapByteOrder(flavor);
9745 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9746 memcpy((char *)&count, begin, sizeof(uint32_t));
9747 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009748 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009749 count = 0;
9750 begin = end;
9751 }
9752 if (isLittleEndian != sys::IsLittleEndianHost)
9753 sys::swapByteOrder(count);
9754 outs() << " flavor " << flavor << "\n";
9755 outs() << " count " << count << "\n";
9756 outs() << " state (Unknown cputype/cpusubtype)\n";
9757 begin += count * sizeof(uint32_t);
9758 }
9759 }
9760}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009761
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009762static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9763 if (dl.cmd == MachO::LC_ID_DYLIB)
9764 outs() << " cmd LC_ID_DYLIB\n";
9765 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9766 outs() << " cmd LC_LOAD_DYLIB\n";
9767 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9768 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9769 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9770 outs() << " cmd LC_REEXPORT_DYLIB\n";
9771 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9772 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9773 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9774 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9775 else
9776 outs() << " cmd " << dl.cmd << " (unknown)\n";
9777 outs() << " cmdsize " << dl.cmdsize;
9778 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9779 outs() << " Incorrect size\n";
9780 else
9781 outs() << "\n";
9782 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009783 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009784 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9785 } else {
9786 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9787 }
9788 outs() << " time stamp " << dl.dylib.timestamp << " ";
9789 time_t t = dl.dylib.timestamp;
9790 outs() << ctime(&t);
9791 outs() << " current version ";
9792 if (dl.dylib.current_version == 0xffffffff)
9793 outs() << "n/a\n";
9794 else
9795 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9796 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9797 << (dl.dylib.current_version & 0xff) << "\n";
9798 outs() << "compatibility version ";
9799 if (dl.dylib.compatibility_version == 0xffffffff)
9800 outs() << "n/a\n";
9801 else
9802 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9803 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9804 << (dl.dylib.compatibility_version & 0xff) << "\n";
9805}
9806
9807static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9808 uint32_t object_size) {
9809 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009810 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009811 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9812 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9813 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9814 outs() << " cmd LC_FUNCTION_STARTS\n";
9815 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9816 outs() << " cmd LC_DATA_IN_CODE\n";
9817 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9818 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9819 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9820 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9821 else
9822 outs() << " cmd " << ld.cmd << " (?)\n";
9823 outs() << " cmdsize " << ld.cmdsize;
9824 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9825 outs() << " Incorrect size\n";
9826 else
9827 outs() << "\n";
9828 outs() << " dataoff " << ld.dataoff;
9829 if (ld.dataoff > object_size)
9830 outs() << " (past end of file)\n";
9831 else
9832 outs() << "\n";
9833 outs() << " datasize " << ld.datasize;
9834 uint64_t big_size = ld.dataoff;
9835 big_size += ld.datasize;
9836 if (big_size > object_size)
9837 outs() << " (past end of file)\n";
9838 else
9839 outs() << "\n";
9840}
9841
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009842static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9843 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009844 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009845 unsigned Index = 0;
9846 for (const auto &Command : Obj->load_commands()) {
9847 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009848 if (Command.C.cmd == MachO::LC_SEGMENT) {
9849 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9850 const char *sg_segname = SLC.segname;
9851 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9852 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9853 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9854 verbose);
9855 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009856 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009857 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9858 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9859 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9860 }
9861 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9862 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9863 const char *sg_segname = SLC_64.segname;
9864 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9865 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9866 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9867 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9868 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9869 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9870 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9871 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9872 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9873 sg_segname, filetype, Buf.size(), verbose);
9874 }
9875 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9876 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009877 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009878 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9879 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9880 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009881 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9882 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009883 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9884 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9885 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9886 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9887 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9888 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9889 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9890 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9891 PrintDyldLoadCommand(Dyld, Command.Ptr);
9892 } else if (Command.C.cmd == MachO::LC_UUID) {
9893 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9894 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009895 } else if (Command.C.cmd == MachO::LC_RPATH) {
9896 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9897 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009898 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009899 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9900 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9901 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009902 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9903 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009904 } else if (Command.C.cmd == MachO::LC_NOTE) {
9905 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9906 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009907 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9908 MachO::build_version_command Bv =
9909 Obj->getBuildVersionLoadCommand(Command);
9910 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009911 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9912 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9913 PrintSourceVersionCommand(Sd);
9914 } else if (Command.C.cmd == MachO::LC_MAIN) {
9915 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9916 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009917 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009918 MachO::encryption_info_command Ei =
9919 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009920 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009921 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009922 MachO::encryption_info_command_64 Ei =
9923 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009924 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009925 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009926 MachO::linker_option_command Lo =
9927 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009928 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009929 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9930 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9931 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009932 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9933 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9934 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009935 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9936 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9937 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009938 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9939 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9940 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009941 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9942 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9943 PrintRoutinesCommand(Rc);
9944 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9945 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9946 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009947 } else if (Command.C.cmd == MachO::LC_THREAD ||
9948 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9949 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9950 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009951 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9952 Command.C.cmd == MachO::LC_ID_DYLIB ||
9953 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9954 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9955 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9956 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009957 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9958 PrintDylibCommand(Dl, Command.Ptr);
9959 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9960 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9961 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9962 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9963 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9964 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9965 MachO::linkedit_data_command Ld =
9966 Obj->getLinkeditDataLoadCommand(Command);
9967 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009968 } else {
9969 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9970 << ")\n";
9971 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9972 // TODO: get and print the raw bytes of the load command.
9973 }
9974 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009975 }
9976}
9977
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009978static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009979 if (Obj->is64Bit()) {
9980 MachO::mach_header_64 H_64;
9981 H_64 = Obj->getHeader64();
9982 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9983 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9984 } else {
9985 MachO::mach_header H;
9986 H = Obj->getHeader();
9987 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9988 H.sizeofcmds, H.flags, verbose);
9989 }
9990}
9991
Fangrui Song523758e2019-04-15 15:31:42 +00009992void printMachOFileHeader(const object::ObjectFile *Obj) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009993 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009994 PrintMachHeader(file, !NonVerbose);
9995}
9996
Fangrui Song523758e2019-04-15 15:31:42 +00009997void printMachOLoadCommands(const object::ObjectFile *Obj) {
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009998 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009999 uint32_t filetype = 0;
10000 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010001 if (file->is64Bit()) {
10002 MachO::mach_header_64 H_64;
10003 H_64 = file->getHeader64();
10004 filetype = H_64.filetype;
10005 cputype = H_64.cputype;
10006 } else {
10007 MachO::mach_header H;
10008 H = file->getHeader();
10009 filetype = H.filetype;
10010 cputype = H.cputype;
10011 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010012 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010013}
Nick Kledzikd04bc352014-08-30 00:20:14 +000010014
10015//===----------------------------------------------------------------------===//
10016// export trie dumping
10017//===----------------------------------------------------------------------===//
10018
Fangrui Song523758e2019-04-15 15:31:42 +000010019void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010020 uint64_t BaseSegmentAddress = 0;
10021 for (const auto &Command : Obj->load_commands()) {
10022 if (Command.C.cmd == MachO::LC_SEGMENT) {
10023 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10024 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10025 BaseSegmentAddress = Seg.vmaddr;
10026 break;
10027 }
10028 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10029 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10030 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10031 BaseSegmentAddress = Seg.vmaddr;
10032 break;
10033 }
10034 }
10035 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010036 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010037 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010038 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010039 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10040 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10041 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10042 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10043 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10044 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10045 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10046 if (ReExport)
10047 outs() << "[re-export] ";
10048 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010049 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010050 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010051 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010052 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010053 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010054 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010055 if (WeakDef) {
10056 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010057 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010058 }
10059 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010060 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010061 outs() << ", ";
10062 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010063 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010064 }
10065 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010066 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010067 outs() << ", ";
10068 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010069 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010070 }
10071 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010072 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010073 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010074 outs() << format("resolver=0x%08llX", Entry.other());
10075 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010076 }
10077 outs() << "]";
10078 }
10079 if (ReExport) {
10080 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010081 int Ordinal = Entry.other() - 1;
10082 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10083 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010084 outs() << " (from " << DylibName << ")";
10085 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010086 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010087 }
10088 outs() << "\n";
10089 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010090 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010091 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikd04bc352014-08-30 00:20:14 +000010092}
Nick Kledzikac431442014-09-12 21:34:15 +000010093
Nick Kledzikac431442014-09-12 21:34:15 +000010094//===----------------------------------------------------------------------===//
10095// rebase table dumping
10096//===----------------------------------------------------------------------===//
10097
Fangrui Song523758e2019-04-15 15:31:42 +000010098void printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010099 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010100 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010101 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010102 StringRef SegmentName = Entry.segmentName();
10103 StringRef SectionName = Entry.sectionName();
10104 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010105
10106 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010107 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10108 SegmentName.str().c_str(), SectionName.str().c_str(),
10109 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010110 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010111 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010112 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikac431442014-09-12 21:34:15 +000010113}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010114
10115static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10116 StringRef DylibName;
10117 switch (Ordinal) {
10118 case MachO::BIND_SPECIAL_DYLIB_SELF:
10119 return "this-image";
10120 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10121 return "main-executable";
10122 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10123 return "flat-namespace";
10124 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010125 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010126 std::error_code EC =
10127 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010128 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010129 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010130 return DylibName;
10131 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010132 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010133 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010134}
10135
10136//===----------------------------------------------------------------------===//
10137// bind table dumping
10138//===----------------------------------------------------------------------===//
10139
Fangrui Song523758e2019-04-15 15:31:42 +000010140void printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010141 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010142 outs() << "segment section address type "
10143 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010144 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010145 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010146 StringRef SegmentName = Entry.segmentName();
10147 StringRef SectionName = Entry.sectionName();
10148 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010149
10150 // Table lines look like:
10151 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010152 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010153 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010154 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010155 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010156 << left_justify(SectionName, 18) << " "
10157 << format_hex(Address, 10, true) << " "
10158 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010159 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010160 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010161 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010162 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010163 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010164 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010165}
10166
10167//===----------------------------------------------------------------------===//
10168// lazy bind table dumping
10169//===----------------------------------------------------------------------===//
10170
Fangrui Song523758e2019-04-15 15:31:42 +000010171void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010172 outs() << "segment section address "
10173 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010174 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010175 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010176 StringRef SegmentName = Entry.segmentName();
10177 StringRef SectionName = Entry.sectionName();
10178 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010179
10180 // Table lines look like:
10181 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010182 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010183 << left_justify(SectionName, 18) << " "
10184 << format_hex(Address, 10, true) << " "
10185 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010186 << Entry.symbolName() << "\n";
10187 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010188 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010189 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010190}
10191
Nick Kledzik56ebef42014-09-16 01:41:51 +000010192//===----------------------------------------------------------------------===//
10193// weak bind table dumping
10194//===----------------------------------------------------------------------===//
10195
Fangrui Song523758e2019-04-15 15:31:42 +000010196void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010197 outs() << "segment section address "
10198 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010199 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010200 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010201 // Strong symbols don't have a location to update.
10202 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010203 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010204 << Entry.symbolName() << "\n";
10205 continue;
10206 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010207 StringRef SegmentName = Entry.segmentName();
10208 StringRef SectionName = Entry.sectionName();
10209 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010210
10211 // Table lines look like:
10212 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010213 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010214 << left_justify(SectionName, 18) << " "
10215 << format_hex(Address, 10, true) << " "
10216 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010217 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10218 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010219 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010220 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010221 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010222}
10223
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010224// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10225// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10226// information for that address. If the address is found its binding symbol
10227// name is returned. If not nullptr is returned.
10228static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10229 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010230 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010231 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010232 Error Err = Error::success();
Fangrui Song523758e2019-04-15 15:31:42 +000010233 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010234 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010235 StringRef name = Entry.symbolName();
10236 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010237 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010238 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010239 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010240 report_error(std::move(Err), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010241 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010242 auto name = info->bindtable->lookup(ReferenceValue);
10243 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010244}
Michael Trent1854ecc2017-12-05 07:50:00 +000010245
Fangrui Song523758e2019-04-15 15:31:42 +000010246void printLazyBindTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010247 outs() << "Lazy bind table:\n";
10248 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10249 printMachOLazyBindTable(MachO);
10250 else
10251 WithColor::error()
10252 << "This operation is only currently supported "
10253 "for Mach-O executable files.\n";
10254}
10255
Fangrui Song523758e2019-04-15 15:31:42 +000010256void printWeakBindTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010257 outs() << "Weak bind table:\n";
10258 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10259 printMachOWeakBindTable(MachO);
10260 else
10261 WithColor::error()
10262 << "This operation is only currently supported "
10263 "for Mach-O executable files.\n";
10264}
10265
Fangrui Song523758e2019-04-15 15:31:42 +000010266void printExportsTrie(const ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010267 outs() << "Exports trie:\n";
10268 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10269 printMachOExportsTrie(MachO);
10270 else
10271 WithColor::error()
10272 << "This operation is only currently supported "
10273 "for Mach-O executable files.\n";
10274}
10275
Fangrui Song523758e2019-04-15 15:31:42 +000010276void printRebaseTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010277 outs() << "Rebase table:\n";
10278 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10279 printMachORebaseTable(MachO);
10280 else
10281 WithColor::error()
10282 << "This operation is only currently supported "
10283 "for Mach-O executable files.\n";
10284}
10285
Fangrui Song523758e2019-04-15 15:31:42 +000010286void printBindTable(ObjectFile *o) {
Fangrui Song9d812f42019-04-15 15:00:10 +000010287 outs() << "Bind table:\n";
10288 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10289 printMachOBindTable(MachO);
10290 else
10291 WithColor::error()
10292 << "This operation is only currently supported "
10293 "for Mach-O executable files.\n";
10294}
Fangrui Song523758e2019-04-15 15:31:42 +000010295} // namespace llvm