blob: 6577b3ab7fd6dc8cedecbf0bc698f839df63741b [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
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
Fangrui Song9d812f42019-04-15 15:00:10 +000061namespace llvm {
62
63extern cl::opt<bool> ArchiveHeaders;
64extern cl::opt<bool> Disassemble;
65extern cl::opt<bool> DisassembleAll;
66extern cl::opt<DIDumpType> DwarfDumpType;
67extern cl::list<std::string> FilterSections;
68extern cl::list<std::string> MAttrs;
69extern cl::opt<std::string> MCPU;
70extern cl::opt<bool> NoShowRawInsn;
71extern cl::opt<bool> NoLeadingAddr;
72extern cl::opt<bool> PrintImmHex;
73extern cl::opt<bool> PrivateHeaders;
74extern cl::opt<bool> Relocations;
75extern cl::opt<bool> SectionHeaders;
76extern cl::opt<bool> SectionContents;
77extern cl::opt<bool> SymbolTable;
78extern cl::opt<std::string> TripleName;
79extern cl::opt<bool> UnwindInfo;
80
81cl::opt<bool>
82 FirstPrivateHeader("private-header",
83 cl::desc("Display only the first format specific file "
84 "header"));
85
86cl::opt<bool> ExportsTrie("exports-trie",
87 cl::desc("Display mach-o exported symbols"));
88
89cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"));
90
91cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"));
92
93cl::opt<bool> LazyBind("lazy-bind",
94 cl::desc("Display mach-o lazy binding info"));
95
96cl::opt<bool> WeakBind("weak-bind",
97 cl::desc("Display mach-o weak binding info"));
98
Benjamin Kramer43a772e2011-09-19 17:56:04 +000099static cl::opt<bool>
Matthew Voss0f436772019-02-19 19:46:08 +0000100 UseDbg("g", cl::Grouping,
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000101 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000102
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000103static cl::opt<std::string> DSYMFile("dsym",
104 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000105
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000106static cl::opt<bool> FullLeadingAddr("full-leading-addr",
107 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +0000108
Kevin Enderbyf9d60f02016-11-29 21:43:40 +0000109static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
110 cl::desc("Print no leading headers"));
111
Fangrui Song9d812f42019-04-15 15:00:10 +0000112cl::opt<bool> UniversalHeaders("universal-headers",
113 cl::desc("Print Mach-O universal headers "
114 "(requires -macho)"));
Kevin Enderby13023a12015-01-15 23:19:11 +0000115
Kevin Enderby131d1772015-01-09 19:22:37 +0000116cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +0000117 ArchiveMemberOffsets("archive-member-offsets",
118 cl::desc("Print the offset to each archive member for "
119 "Mach-O archives (requires -macho and "
120 "-archive-headers)"));
121
Fangrui Song9d812f42019-04-15 15:00:10 +0000122cl::opt<bool> IndirectSymbols("indirect-symbols",
123 cl::desc("Print indirect symbol table for Mach-O "
124 "objects (requires -macho)"));
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000125
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000126cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000127 DataInCode("data-in-code",
128 cl::desc("Print the data in code table for Mach-O objects "
129 "(requires -macho)"));
130
131cl::opt<bool> LinkOptHints("link-opt-hints",
132 cl::desc("Print the linker optimization hints for "
133 "Mach-O objects (requires -macho)"));
134
135cl::opt<bool> InfoPlist("info-plist",
136 cl::desc("Print the info plist section as strings for "
137 "Mach-O objects (requires -macho)"));
138
139cl::opt<bool> DylibsUsed("dylibs-used",
140 cl::desc("Print the shared libraries used for linked "
141 "Mach-O files (requires -macho)"));
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000142
Kevin Enderby9a509442015-01-27 21:28:24 +0000143cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000144 DylibId("dylib-id",
145 cl::desc("Print the shared library's id for the dylib Mach-O "
146 "file (requires -macho)"));
Kevin Enderby9a509442015-01-27 21:28:24 +0000147
Kevin Enderbycd66be52015-03-11 22:06:32 +0000148cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000149 NonVerbose("non-verbose",
150 cl::desc("Print the info for Mach-O objects in "
151 "non-verbose or numeric form (requires -macho)"));
Kevin Enderbycd66be52015-03-11 22:06:32 +0000152
Kevin Enderbyf0640752015-03-13 17:56:32 +0000153cl::opt<bool>
Fangrui Song9d812f42019-04-15 15:00:10 +0000154 ObjcMetaData("objc-meta-data",
155 cl::desc("Print the Objective-C runtime meta data for "
156 "Mach-O files (requires -macho)"));
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000157
Fangrui Song9d812f42019-04-15 15:00:10 +0000158cl::opt<std::string> DisSymName(
Kevin Enderby6a221752015-03-17 17:10:57 +0000159 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000160 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000161
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000162static cl::opt<bool> NoSymbolicOperands(
163 "no-symbolic-operands",
164 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
165
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000166static cl::list<std::string>
167 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
168 cl::ZeroOrMore);
Fangrui Song9d812f42019-04-15 15:00:10 +0000169} // namespace llvm
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000170
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000171bool ArchAll = false;
172
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000173static std::string ThumbTripleName;
174
175static const Target *GetTarget(const MachOObjectFile *MachOObj,
176 const char **McpuDefault,
177 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000178 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000179 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000180 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000181 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000182 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000183 }
184
185 if (TT.getArch() == Triple::arm) {
186 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
187 // that support ARM are also capable of Thumb mode.
188 llvm::Triple ThumbTriple = TT;
189 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
190 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000191 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000192 }
193
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000194 // Get the target specific parser.
195 std::string Error;
196 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000197 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000198 return TheTarget;
199
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000200 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
201 if (*ThumbTarget)
202 return TheTarget;
203
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000204 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000205 if (!TheTarget)
206 errs() << TripleName;
207 else
208 errs() << ThumbTripleName;
209 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000210 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000211}
212
Owen Andersond9243c42011-10-17 21:37:35 +0000213struct SymbolSorter {
214 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000215 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000216 if (!ATypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000217 report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000218 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000219 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000220 if (!BTypeOrErr)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000221 report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000222 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000223 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
224 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000225 return AAddr < BAddr;
226 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000227};
228
Kevin Enderby273ae012013-06-06 17:20:50 +0000229// Types for the storted data in code table that is built before disassembly
230// and the predicate function to sort them.
231typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
232typedef std::vector<DiceTableEntry> DiceTable;
233typedef DiceTable::iterator dice_table_iterator;
234
Francis Ricci195a66f2017-10-06 15:54:20 +0000235#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000236namespace {
237struct ScopedXarFile {
238 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000239 ScopedXarFile(const char *filename, int32_t flags)
240 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000241 ~ScopedXarFile() {
242 if (xar)
243 xar_close(xar);
244 }
245 ScopedXarFile(const ScopedXarFile &) = delete;
246 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
247 operator xar_t() { return xar; }
248};
249
250struct ScopedXarIter {
251 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000252 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000253 ~ScopedXarIter() {
254 if (iter)
255 xar_iter_free(iter);
256 }
257 ScopedXarIter(const ScopedXarIter &) = delete;
258 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
259 operator xar_iter_t() { return iter; }
260};
261} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000262#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000263
Kevin Enderby930fdc72014-11-06 19:00:13 +0000264// This is used to search for a data in code table entry for the PC being
265// disassembled. The j parameter has the PC in j.first. A single data in code
266// table entry can cover many bytes for each of its Kind's. So if the offset,
267// aka the i.first value, of the data in code table entry plus its Length
268// covers the PC being searched for this will return true. If not it will
269// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000270static bool compareDiceTableEntries(const DiceTableEntry &i,
271 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000272 uint16_t Length;
273 i.second.getLength(Length);
274
275 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000276}
277
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000278static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 unsigned short Kind) {
280 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000281
282 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000284 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000285 if (Length >= 4) {
286 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000287 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000288 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000289 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 Size = 4;
291 } else if (Length >= 2) {
292 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000293 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000294 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000295 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000296 Size = 2;
297 } else {
298 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000299 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 Value = bytes[0];
301 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000302 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000303 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000304 if (Kind == MachO::DICE_KIND_DATA)
305 outs() << "\t@ KIND_DATA\n";
306 else
307 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000308 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000309 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000310 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000311 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000312 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000313 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
314 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000315 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000316 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000317 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000318 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000319 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000320 outs() << "\t.short " << format("%5u", Value & 0xffff)
321 << "\t@ KIND_JUMP_TABLE16\n";
322 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000323 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000324 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000325 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
326 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000327 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000328 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000329 outs() << "\t.long " << Value;
330 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
331 outs() << "\t@ KIND_JUMP_TABLE32\n";
332 else
333 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
334 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000335 break;
336 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000337 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000338}
339
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000340static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000341 std::vector<SectionRef> &Sections,
342 std::vector<SymbolRef> &Symbols,
343 SmallVectorImpl<uint64_t> &FoundFns,
344 uint64_t &BaseSegmentAddress) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000345 const StringRef FileName = MachOObj->getFileName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000346 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000347 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
348 if (!SymName.startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000349 Symbols.push_back(Symbol);
350 }
Owen Andersond9243c42011-10-17 21:37:35 +0000351
Alexey Samsonov48803e52014-03-13 14:37:36 +0000352 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000353 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000354 Section.getName(SectName);
355 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000356 }
357
Kevin Enderby273ae012013-06-06 17:20:50 +0000358 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000359 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000360 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000361 // We found a function starts segment, parse the addresses for later
362 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000363 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000364 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000365
Charles Davis8bdfafd2013-09-01 04:28:48 +0000366 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000367 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
368 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000369 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000370 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000371 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000372 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000373 }
374 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000375 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000376}
377
George Rimarc1964882019-01-18 11:33:26 +0000378static void printRelocationTargetName(const MachOObjectFile *O,
379 const MachO::any_relocation_info &RE,
380 raw_string_ostream &Fmt) {
381 // Target of a scattered relocation is an address. In the interest of
382 // generating pretty output, scan through the symbol table looking for a
383 // symbol that aligns with that address. If we find one, print it.
384 // Otherwise, we just print the hex address of the target.
Fangrui Songe7834bd2019-04-07 08:19:55 +0000385 const StringRef FileName = O->getFileName();
George Rimarc1964882019-01-18 11:33:26 +0000386 if (O->isRelocationScattered(RE)) {
387 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
388
389 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000390 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
391 if (Addr != Val)
George Rimarc1964882019-01-18 11:33:26 +0000392 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000393 Fmt << unwrapOrError(Symbol.getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000394 return;
395 }
396
397 // If we couldn't find a symbol that this relocation refers to, try
398 // to find a section beginning instead.
399 for (const SectionRef &Section : ToolSectionFilter(*O)) {
George Rimarc1964882019-01-18 11:33:26 +0000400 StringRef Name;
401 uint64_t Addr = Section.getAddress();
402 if (Addr != Val)
403 continue;
Fangrui Song3f209682019-04-09 05:41:24 +0000404 if (std::error_code EC = Section.getName(Name))
405 report_error(errorCodeToError(EC), O->getFileName());
George Rimarc1964882019-01-18 11:33:26 +0000406 Fmt << Name;
407 return;
408 }
409
410 Fmt << format("0x%x", Val);
411 return;
412 }
413
414 StringRef S;
415 bool isExtern = O->getPlainRelocationExternal(RE);
416 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
417
418 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
419 Fmt << format("0x%0" PRIx64, Val);
420 return;
421 }
422
423 if (isExtern) {
424 symbol_iterator SI = O->symbol_begin();
425 advance(SI, Val);
Fangrui Songe7834bd2019-04-07 08:19:55 +0000426 S = unwrapOrError(SI->getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000427 } else {
428 section_iterator SI = O->section_begin();
429 // Adjust for the fact that sections are 1-indexed.
430 if (Val == 0) {
431 Fmt << "0 (?,?)";
432 return;
433 }
434 uint32_t I = Val - 1;
435 while (I != 0 && SI != O->section_end()) {
436 --I;
437 advance(SI, 1);
438 }
439 if (SI == O->section_end())
440 Fmt << Val << " (?,?)";
441 else
442 SI->getName(S);
443 }
444
445 Fmt << S;
446}
447
Fangrui Songf67de6c2019-04-08 16:24:08 +0000448Error llvm::getMachORelocationValueString(const MachOObjectFile *Obj,
449 const RelocationRef &RelRef,
450 SmallVectorImpl<char> &Result) {
George Rimarc1964882019-01-18 11:33:26 +0000451 DataRefImpl Rel = RelRef.getRawDataRefImpl();
452 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
453
454 unsigned Arch = Obj->getArch();
455
456 std::string FmtBuf;
457 raw_string_ostream Fmt(FmtBuf);
458 unsigned Type = Obj->getAnyRelocationType(RE);
459 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
460
461 // Determine any addends that should be displayed with the relocation.
462 // These require decoding the relocation type, which is triple-specific.
463
464 // X86_64 has entirely custom relocation types.
465 if (Arch == Triple::x86_64) {
466 switch (Type) {
467 case MachO::X86_64_RELOC_GOT_LOAD:
468 case MachO::X86_64_RELOC_GOT: {
469 printRelocationTargetName(Obj, RE, Fmt);
470 Fmt << "@GOT";
471 if (IsPCRel)
472 Fmt << "PCREL";
473 break;
474 }
475 case MachO::X86_64_RELOC_SUBTRACTOR: {
476 DataRefImpl RelNext = Rel;
477 Obj->moveRelocationNext(RelNext);
478 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
479
480 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
481 // X86_64_RELOC_UNSIGNED.
482 // NOTE: Scattered relocations don't exist on x86_64.
483 unsigned RType = Obj->getAnyRelocationType(RENext);
484 if (RType != MachO::X86_64_RELOC_UNSIGNED)
485 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
486 "X86_64_RELOC_SUBTRACTOR.");
487
488 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
489 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
490 printRelocationTargetName(Obj, RENext, Fmt);
491 Fmt << "-";
492 printRelocationTargetName(Obj, RE, Fmt);
493 break;
494 }
495 case MachO::X86_64_RELOC_TLV:
496 printRelocationTargetName(Obj, RE, Fmt);
497 Fmt << "@TLV";
498 if (IsPCRel)
499 Fmt << "P";
500 break;
501 case MachO::X86_64_RELOC_SIGNED_1:
502 printRelocationTargetName(Obj, RE, Fmt);
503 Fmt << "-1";
504 break;
505 case MachO::X86_64_RELOC_SIGNED_2:
506 printRelocationTargetName(Obj, RE, Fmt);
507 Fmt << "-2";
508 break;
509 case MachO::X86_64_RELOC_SIGNED_4:
510 printRelocationTargetName(Obj, RE, Fmt);
511 Fmt << "-4";
512 break;
513 default:
514 printRelocationTargetName(Obj, RE, Fmt);
515 break;
516 }
517 // X86 and ARM share some relocation types in common.
518 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
519 Arch == Triple::ppc) {
520 // Generic relocation types...
521 switch (Type) {
522 case MachO::GENERIC_RELOC_PAIR: // prints no info
Fangrui Songf67de6c2019-04-08 16:24:08 +0000523 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000524 case MachO::GENERIC_RELOC_SECTDIFF: {
525 DataRefImpl RelNext = Rel;
526 Obj->moveRelocationNext(RelNext);
527 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
528
529 // X86 sect diff's must be followed by a relocation of type
530 // GENERIC_RELOC_PAIR.
531 unsigned RType = Obj->getAnyRelocationType(RENext);
532
533 if (RType != MachO::GENERIC_RELOC_PAIR)
534 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
535 "GENERIC_RELOC_SECTDIFF.");
536
537 printRelocationTargetName(Obj, RE, Fmt);
538 Fmt << "-";
539 printRelocationTargetName(Obj, RENext, Fmt);
540 break;
541 }
542 }
543
544 if (Arch == Triple::x86 || Arch == Triple::ppc) {
545 switch (Type) {
546 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
547 DataRefImpl RelNext = Rel;
548 Obj->moveRelocationNext(RelNext);
549 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
550
551 // X86 sect diff's must be followed by a relocation of type
552 // GENERIC_RELOC_PAIR.
553 unsigned RType = Obj->getAnyRelocationType(RENext);
554 if (RType != MachO::GENERIC_RELOC_PAIR)
555 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
556 "GENERIC_RELOC_LOCAL_SECTDIFF.");
557
558 printRelocationTargetName(Obj, RE, Fmt);
559 Fmt << "-";
560 printRelocationTargetName(Obj, RENext, Fmt);
561 break;
562 }
563 case MachO::GENERIC_RELOC_TLV: {
564 printRelocationTargetName(Obj, RE, Fmt);
565 Fmt << "@TLV";
566 if (IsPCRel)
567 Fmt << "P";
568 break;
569 }
570 default:
571 printRelocationTargetName(Obj, RE, Fmt);
572 }
573 } else { // ARM-specific relocations
574 switch (Type) {
575 case MachO::ARM_RELOC_HALF:
576 case MachO::ARM_RELOC_HALF_SECTDIFF: {
577 // Half relocations steal a bit from the length field to encode
578 // whether this is an upper16 or a lower16 relocation.
579 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
580
581 if (isUpper)
582 Fmt << ":upper16:(";
583 else
584 Fmt << ":lower16:(";
585 printRelocationTargetName(Obj, RE, Fmt);
586
587 DataRefImpl RelNext = Rel;
588 Obj->moveRelocationNext(RelNext);
589 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
590
591 // ARM half relocs must be followed by a relocation of type
592 // ARM_RELOC_PAIR.
593 unsigned RType = Obj->getAnyRelocationType(RENext);
594 if (RType != MachO::ARM_RELOC_PAIR)
595 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
596 "ARM_RELOC_HALF");
597
598 // NOTE: The half of the target virtual address is stashed in the
599 // address field of the secondary relocation, but we can't reverse
600 // engineer the constant offset from it without decoding the movw/movt
601 // instruction to find the other half in its immediate field.
602
603 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
604 // symbol/section pointer of the follow-on relocation.
605 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
606 Fmt << "-";
607 printRelocationTargetName(Obj, RENext, Fmt);
608 }
609
610 Fmt << ")";
611 break;
612 }
613 default: {
614 printRelocationTargetName(Obj, RE, Fmt);
615 }
616 }
617 }
618 } else
619 printRelocationTargetName(Obj, RE, Fmt);
620
621 Fmt.flush();
622 Result.append(FmtBuf.begin(), FmtBuf.end());
Fangrui Songf67de6c2019-04-08 16:24:08 +0000623 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000624}
625
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000626static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
627 uint32_t n, uint32_t count,
628 uint32_t stride, uint64_t addr) {
629 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
630 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
631 if (n > nindirectsyms)
632 outs() << " (entries start past the end of the indirect symbol "
633 "table) (reserved1 field greater than the table size)";
634 else if (n + count > nindirectsyms)
635 outs() << " (entries extends past the end of the indirect symbol "
636 "table)";
637 outs() << "\n";
638 uint32_t cputype = O->getHeader().cputype;
639 if (cputype & MachO::CPU_ARCH_ABI64)
640 outs() << "address index";
641 else
642 outs() << "address index";
643 if (verbose)
644 outs() << " name\n";
645 else
646 outs() << "\n";
647 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
648 if (cputype & MachO::CPU_ARCH_ABI64)
649 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
650 else
Tim Northover43978372016-04-26 18:29:16 +0000651 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000652 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
653 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
654 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
655 outs() << "LOCAL\n";
656 continue;
657 }
658 if (indirect_symbol ==
659 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
660 outs() << "LOCAL ABSOLUTE\n";
661 continue;
662 }
663 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
664 outs() << "ABSOLUTE\n";
665 continue;
666 }
667 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000668 if (verbose) {
669 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
670 if (indirect_symbol < Symtab.nsyms) {
671 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
672 SymbolRef Symbol = *Sym;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000673 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
Kevin Enderbyf0640752015-03-13 17:56:32 +0000674 } else {
675 outs() << "?";
676 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000677 }
678 outs() << "\n";
679 }
680}
681
682static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000683 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000684 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
685 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
686 for (unsigned J = 0; J < Seg.nsects; ++J) {
687 MachO::section_64 Sec = O->getSection64(Load, J);
688 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
689 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
690 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
691 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
692 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
693 section_type == MachO::S_SYMBOL_STUBS) {
694 uint32_t stride;
695 if (section_type == MachO::S_SYMBOL_STUBS)
696 stride = Sec.reserved2;
697 else
698 stride = 8;
699 if (stride == 0) {
700 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
701 << Sec.sectname << ") "
702 << "(size of stubs in reserved2 field is zero)\n";
703 continue;
704 }
705 uint32_t count = Sec.size / stride;
706 outs() << "Indirect symbols for (" << Sec.segname << ","
707 << Sec.sectname << ") " << count << " entries";
708 uint32_t n = Sec.reserved1;
709 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
710 }
711 }
712 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
713 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
714 for (unsigned J = 0; J < Seg.nsects; ++J) {
715 MachO::section Sec = O->getSection(Load, J);
716 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
717 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
718 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
719 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
720 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
721 section_type == MachO::S_SYMBOL_STUBS) {
722 uint32_t stride;
723 if (section_type == MachO::S_SYMBOL_STUBS)
724 stride = Sec.reserved2;
725 else
726 stride = 4;
727 if (stride == 0) {
728 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
729 << Sec.sectname << ") "
730 << "(size of stubs in reserved2 field is zero)\n";
731 continue;
732 }
733 uint32_t count = Sec.size / stride;
734 outs() << "Indirect symbols for (" << Sec.segname << ","
735 << Sec.sectname << ") " << count << " entries";
736 uint32_t n = Sec.reserved1;
737 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
738 }
739 }
740 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000741 }
742}
743
Michael Trenta1703b12017-12-15 17:57:40 +0000744static void PrintRType(const uint64_t cputype, const unsigned r_type) {
745 static char const *generic_r_types[] = {
746 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
747 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
748 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
749 };
750 static char const *x86_64_r_types[] = {
751 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
752 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
753 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
754 };
755 static char const *arm_r_types[] = {
756 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
757 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
758 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
759 };
760 static char const *arm64_r_types[] = {
761 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
762 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
763 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
764 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000765
Michael Trenta1703b12017-12-15 17:57:40 +0000766 if (r_type > 0xf){
767 outs() << format("%-7u", r_type) << " ";
768 return;
769 }
770 switch (cputype) {
771 case MachO::CPU_TYPE_I386:
772 outs() << generic_r_types[r_type];
773 break;
774 case MachO::CPU_TYPE_X86_64:
775 outs() << x86_64_r_types[r_type];
776 break;
777 case MachO::CPU_TYPE_ARM:
778 outs() << arm_r_types[r_type];
779 break;
780 case MachO::CPU_TYPE_ARM64:
781 outs() << arm64_r_types[r_type];
782 break;
783 default:
784 outs() << format("%-7u ", r_type);
785 }
786}
787
788static void PrintRLength(const uint64_t cputype, const unsigned r_type,
789 const unsigned r_length, const bool previous_arm_half){
790 if (cputype == MachO::CPU_TYPE_ARM &&
791 (r_type == llvm::MachO::ARM_RELOC_HALF ||
792 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
793 previous_arm_half == true)) {
794 if ((r_length & 0x1) == 0)
795 outs() << "lo/";
796 else
797 outs() << "hi/";
798 if ((r_length & 0x1) == 0)
799 outs() << "arm ";
800 else
801 outs() << "thm ";
802 } else {
803 switch (r_length) {
804 case 0:
805 outs() << "byte ";
806 break;
807 case 1:
808 outs() << "word ";
809 break;
810 case 2:
811 outs() << "long ";
812 break;
813 case 3:
814 if (cputype == MachO::CPU_TYPE_X86_64)
815 outs() << "quad ";
816 else
817 outs() << format("?(%2d) ", r_length);
818 break;
819 default:
820 outs() << format("?(%2d) ", r_length);
821 }
822 }
823}
824
825static void PrintRelocationEntries(const MachOObjectFile *O,
826 const relocation_iterator Begin,
827 const relocation_iterator End,
828 const uint64_t cputype,
829 const bool verbose) {
830 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
831 bool previous_arm_half = false;
832 bool previous_sectdiff = false;
833 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000834
Michael Trenta1703b12017-12-15 17:57:40 +0000835 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
836 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
837 const MachO::any_relocation_info RE = O->getRelocation(Rel);
838 const unsigned r_type = O->getAnyRelocationType(RE);
839 const bool r_scattered = O->isRelocationScattered(RE);
840 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
841 const unsigned r_length = O->getAnyRelocationLength(RE);
842 const unsigned r_address = O->getAnyRelocationAddress(RE);
843 const bool r_extern = (r_scattered ? false :
844 O->getPlainRelocationExternal(RE));
845 const uint32_t r_value = (r_scattered ?
846 O->getScatteredRelocationValue(RE) : 0);
847 const unsigned r_symbolnum = (r_scattered ? 0 :
848 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000849
Michael Trenta1703b12017-12-15 17:57:40 +0000850 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
851 if (verbose) {
852 // scattered: address
853 if ((cputype == MachO::CPU_TYPE_I386 &&
854 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
855 (cputype == MachO::CPU_TYPE_ARM &&
856 r_type == llvm::MachO::ARM_RELOC_PAIR))
857 outs() << " ";
858 else
859 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000860
Michael Trenta1703b12017-12-15 17:57:40 +0000861 // scattered: pcrel
862 if (r_pcrel)
863 outs() << "True ";
864 else
865 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000866
Michael Trenta1703b12017-12-15 17:57:40 +0000867 // scattered: length
868 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000869
Michael Trenta1703b12017-12-15 17:57:40 +0000870 // scattered: extern & type
871 outs() << "n/a ";
872 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000873
Michael Trenta1703b12017-12-15 17:57:40 +0000874 // scattered: scattered & value
875 outs() << format("True 0x%08x", (unsigned int)r_value);
876 if (previous_sectdiff == false) {
877 if ((cputype == MachO::CPU_TYPE_ARM &&
878 r_type == llvm::MachO::ARM_RELOC_PAIR))
879 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
880 }
881 else if (cputype == MachO::CPU_TYPE_ARM &&
882 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
883 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
884 if ((cputype == MachO::CPU_TYPE_I386 &&
885 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
886 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
887 (cputype == MachO::CPU_TYPE_ARM &&
888 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
889 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
890 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
891 previous_sectdiff = true;
892 sectdiff_r_type = r_type;
893 }
894 else {
895 previous_sectdiff = false;
896 sectdiff_r_type = 0;
897 }
898 if (cputype == MachO::CPU_TYPE_ARM &&
899 (r_type == llvm::MachO::ARM_RELOC_HALF ||
900 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
901 previous_arm_half = true;
902 else
903 previous_arm_half = false;
904 outs() << "\n";
905 }
906 else {
907 // scattered: address pcrel length extern type scattered value
908 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
909 (unsigned int)r_address, r_pcrel, r_length, r_type,
910 (unsigned int)r_value);
911 }
912 }
913 else {
914 if (verbose) {
915 // plain: address
916 if (cputype == MachO::CPU_TYPE_ARM &&
917 r_type == llvm::MachO::ARM_RELOC_PAIR)
918 outs() << " ";
919 else
920 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000921
Michael Trenta1703b12017-12-15 17:57:40 +0000922 // plain: pcrel
923 if (r_pcrel)
924 outs() << "True ";
925 else
926 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000927
Michael Trenta1703b12017-12-15 17:57:40 +0000928 // plain: length
929 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000930
Michael Trenta1703b12017-12-15 17:57:40 +0000931 if (r_extern) {
932 // plain: extern & type & scattered
933 outs() << "True ";
934 PrintRType(cputype, r_type);
935 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000936
Michael Trenta1703b12017-12-15 17:57:40 +0000937 // plain: symbolnum/value
938 if (r_symbolnum > Symtab.nsyms)
939 outs() << format("?(%d)\n", r_symbolnum);
940 else {
941 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
942 Expected<StringRef> SymNameNext = Symbol.getName();
943 const char *name = NULL;
944 if (SymNameNext)
945 name = SymNameNext->data();
946 if (name == NULL)
947 outs() << format("?(%d)\n", r_symbolnum);
948 else
949 outs() << name << "\n";
950 }
951 }
952 else {
953 // plain: extern & type & scattered
954 outs() << "False ";
955 PrintRType(cputype, r_type);
956 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000957
Michael Trenta1703b12017-12-15 17:57:40 +0000958 // plain: symbolnum/value
959 if (cputype == MachO::CPU_TYPE_ARM &&
960 r_type == llvm::MachO::ARM_RELOC_PAIR)
961 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
962 else if (cputype == MachO::CPU_TYPE_ARM64 &&
963 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
964 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
965 else {
966 outs() << format("%d ", r_symbolnum);
967 if (r_symbolnum == llvm::MachO::R_ABS)
968 outs() << "R_ABS\n";
969 else {
970 // in this case, r_symbolnum is actually a 1-based section number
971 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
972 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
973 llvm::object::DataRefImpl DRI;
974 DRI.d.a = r_symbolnum-1;
975 StringRef SegName = O->getSectionFinalSegmentName(DRI);
976 StringRef SectName;
977 if (O->getSectionName(DRI, SectName))
978 outs() << "(?,?)\n";
979 else
980 outs() << "(" << SegName << "," << SectName << ")\n";
981 }
982 else {
983 outs() << "(?,?)\n";
984 }
985 }
986 }
987 }
988 if (cputype == MachO::CPU_TYPE_ARM &&
989 (r_type == llvm::MachO::ARM_RELOC_HALF ||
990 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
991 previous_arm_half = true;
992 else
993 previous_arm_half = false;
994 }
995 else {
996 // plain: address pcrel length extern type scattered symbolnum/section
997 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
998 (unsigned int)r_address, r_pcrel, r_length, r_extern,
999 r_type, r_symbolnum);
1000 }
1001 }
1002 }
1003}
1004
1005static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1006 const uint64_t cputype = O->getHeader().cputype;
1007 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1008 if (Dysymtab.nextrel != 0) {
1009 outs() << "External relocation information " << Dysymtab.nextrel
1010 << " entries";
1011 outs() << "\naddress pcrel length extern type scattered "
1012 "symbolnum/value\n";
1013 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1014 verbose);
1015 }
1016 if (Dysymtab.nlocrel != 0) {
1017 outs() << format("Local relocation information %u entries",
1018 Dysymtab.nlocrel);
1019 outs() << "\naddress pcrel length extern type scattered "
1020 "symbolnum/value\n";
1021 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1022 verbose);
1023 }
1024 for (const auto &Load : O->load_commands()) {
1025 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1026 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1027 for (unsigned J = 0; J < Seg.nsects; ++J) {
1028 const MachO::section_64 Sec = O->getSection64(Load, J);
1029 if (Sec.nreloc != 0) {
1030 DataRefImpl DRI;
1031 DRI.d.a = J;
1032 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1033 StringRef SectName;
1034 if (O->getSectionName(DRI, SectName))
1035 outs() << "Relocation information (" << SegName << ",?) "
1036 << format("%u entries", Sec.nreloc);
1037 else
1038 outs() << "Relocation information (" << SegName << ","
1039 << SectName << format(") %u entries", Sec.nreloc);
1040 outs() << "\naddress pcrel length extern type scattered "
1041 "symbolnum/value\n";
1042 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1043 O->section_rel_end(DRI), cputype, verbose);
1044 }
1045 }
1046 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1047 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1048 for (unsigned J = 0; J < Seg.nsects; ++J) {
1049 const MachO::section Sec = O->getSection(Load, J);
1050 if (Sec.nreloc != 0) {
1051 DataRefImpl DRI;
1052 DRI.d.a = J;
1053 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1054 StringRef SectName;
1055 if (O->getSectionName(DRI, SectName))
1056 outs() << "Relocation information (" << SegName << ",?) "
1057 << format("%u entries", Sec.nreloc);
1058 else
1059 outs() << "Relocation information (" << SegName << ","
1060 << SectName << format(") %u entries", Sec.nreloc);
1061 outs() << "\naddress pcrel length extern type scattered "
1062 "symbolnum/value\n";
1063 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1064 O->section_rel_end(DRI), cputype, verbose);
1065 }
1066 }
1067 }
1068 }
1069}
1070
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001071static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1072 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1073 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1074 outs() << "Data in code table (" << nentries << " entries)\n";
1075 outs() << "offset length kind\n";
1076 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1077 ++DI) {
1078 uint32_t Offset;
1079 DI->getOffset(Offset);
1080 outs() << format("0x%08" PRIx32, Offset) << " ";
1081 uint16_t Length;
1082 DI->getLength(Length);
1083 outs() << format("%6u", Length) << " ";
1084 uint16_t Kind;
1085 DI->getKind(Kind);
1086 if (verbose) {
1087 switch (Kind) {
1088 case MachO::DICE_KIND_DATA:
1089 outs() << "DATA";
1090 break;
1091 case MachO::DICE_KIND_JUMP_TABLE8:
1092 outs() << "JUMP_TABLE8";
1093 break;
1094 case MachO::DICE_KIND_JUMP_TABLE16:
1095 outs() << "JUMP_TABLE16";
1096 break;
1097 case MachO::DICE_KIND_JUMP_TABLE32:
1098 outs() << "JUMP_TABLE32";
1099 break;
1100 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1101 outs() << "ABS_JUMP_TABLE32";
1102 break;
1103 default:
1104 outs() << format("0x%04" PRIx32, Kind);
1105 break;
1106 }
1107 } else
1108 outs() << format("0x%04" PRIx32, Kind);
1109 outs() << "\n";
1110 }
1111}
1112
Kevin Enderby9a509442015-01-27 21:28:24 +00001113static void PrintLinkOptHints(MachOObjectFile *O) {
1114 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1115 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1116 uint32_t nloh = LohLC.datasize;
1117 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1118 for (uint32_t i = 0; i < nloh;) {
1119 unsigned n;
1120 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1121 i += n;
1122 outs() << " identifier " << identifier << " ";
1123 if (i >= nloh)
1124 return;
1125 switch (identifier) {
1126 case 1:
1127 outs() << "AdrpAdrp\n";
1128 break;
1129 case 2:
1130 outs() << "AdrpLdr\n";
1131 break;
1132 case 3:
1133 outs() << "AdrpAddLdr\n";
1134 break;
1135 case 4:
1136 outs() << "AdrpLdrGotLdr\n";
1137 break;
1138 case 5:
1139 outs() << "AdrpAddStr\n";
1140 break;
1141 case 6:
1142 outs() << "AdrpLdrGotStr\n";
1143 break;
1144 case 7:
1145 outs() << "AdrpAdd\n";
1146 break;
1147 case 8:
1148 outs() << "AdrpLdrGot\n";
1149 break;
1150 default:
1151 outs() << "Unknown identifier value\n";
1152 break;
1153 }
1154 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1155 i += n;
1156 outs() << " narguments " << narguments << "\n";
1157 if (i >= nloh)
1158 return;
1159
1160 for (uint32_t j = 0; j < narguments; j++) {
1161 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1162 i += n;
1163 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1164 if (i >= nloh)
1165 return;
1166 }
1167 }
1168}
1169
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001170static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001171 unsigned Index = 0;
1172 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001173 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1174 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1175 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1176 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1177 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1178 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1179 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1180 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1181 if (dl.dylib.name < dl.cmdsize) {
1182 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1183 if (JustId)
1184 outs() << p << "\n";
1185 else {
1186 outs() << "\t" << p;
1187 outs() << " (compatibility version "
1188 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1189 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1190 << (dl.dylib.compatibility_version & 0xff) << ",";
1191 outs() << " current version "
1192 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1193 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1194 << (dl.dylib.current_version & 0xff) << ")\n";
1195 }
1196 } else {
1197 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1198 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1199 outs() << "LC_ID_DYLIB ";
1200 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1201 outs() << "LC_LOAD_DYLIB ";
1202 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1203 outs() << "LC_LOAD_WEAK_DYLIB ";
1204 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1205 outs() << "LC_LAZY_LOAD_DYLIB ";
1206 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1207 outs() << "LC_REEXPORT_DYLIB ";
1208 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1209 outs() << "LC_LOAD_UPWARD_DYLIB ";
1210 else
1211 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001212 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001213 }
1214 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001215 }
1216}
1217
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001218typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1219
1220static void CreateSymbolAddressMap(MachOObjectFile *O,
1221 SymbolAddressMap *AddrMap) {
1222 // Create a map of symbol addresses to symbol names.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001223 const StringRef FileName = O->getFileName();
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001224 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001225 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001226 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1227 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001228 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001229 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
Kevin Enderby846c0002015-04-16 17:19:59 +00001230 if (!SymName.startswith(".objc"))
1231 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001232 }
1233 }
1234}
1235
1236// GuessSymbolName is passed the address of what might be a symbol and a
1237// pointer to the SymbolAddressMap. It returns the name of a symbol
1238// with that address or nullptr if no symbol is found with that address.
1239static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1240 const char *SymbolName = nullptr;
1241 // A DenseMap can't lookup up some values.
1242 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1243 StringRef name = AddrMap->lookup(value);
1244 if (!name.empty())
1245 SymbolName = name.data();
1246 }
1247 return SymbolName;
1248}
1249
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001250static void DumpCstringChar(const char c) {
1251 char p[2];
1252 p[0] = c;
1253 p[1] = '\0';
1254 outs().write_escaped(p);
1255}
1256
Kevin Enderby10ba0412015-02-04 21:38:42 +00001257static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1258 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001259 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001260 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001261 if (print_addresses) {
1262 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001263 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001264 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001265 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001266 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001267 for (; i < sect_size && sect[i] != '\0'; i++)
1268 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001269 if (i < sect_size && sect[i] == '\0')
1270 outs() << "\n";
1271 }
1272}
1273
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001274static void DumpLiteral4(uint32_t l, float f) {
1275 outs() << format("0x%08" PRIx32, l);
1276 if ((l & 0x7f800000) != 0x7f800000)
1277 outs() << format(" (%.16e)\n", f);
1278 else {
1279 if (l == 0x7f800000)
1280 outs() << " (+Infinity)\n";
1281 else if (l == 0xff800000)
1282 outs() << " (-Infinity)\n";
1283 else if ((l & 0x00400000) == 0x00400000)
1284 outs() << " (non-signaling Not-a-Number)\n";
1285 else
1286 outs() << " (signaling Not-a-Number)\n";
1287 }
1288}
1289
1290static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1291 uint32_t sect_size, uint64_t sect_addr,
1292 bool print_addresses) {
1293 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1294 if (print_addresses) {
1295 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001296 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001297 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001298 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001299 }
1300 float f;
1301 memcpy(&f, sect + i, sizeof(float));
1302 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1303 sys::swapByteOrder(f);
1304 uint32_t l;
1305 memcpy(&l, sect + i, sizeof(uint32_t));
1306 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1307 sys::swapByteOrder(l);
1308 DumpLiteral4(l, f);
1309 }
1310}
1311
1312static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1313 double d) {
1314 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1315 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001316 Hi = (O->isLittleEndian()) ? l1 : l0;
1317 Lo = (O->isLittleEndian()) ? l0 : l1;
1318
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001319 // Hi is the high word, so this is equivalent to if(isfinite(d))
1320 if ((Hi & 0x7ff00000) != 0x7ff00000)
1321 outs() << format(" (%.16e)\n", d);
1322 else {
1323 if (Hi == 0x7ff00000 && Lo == 0)
1324 outs() << " (+Infinity)\n";
1325 else if (Hi == 0xfff00000 && Lo == 0)
1326 outs() << " (-Infinity)\n";
1327 else if ((Hi & 0x00080000) == 0x00080000)
1328 outs() << " (non-signaling Not-a-Number)\n";
1329 else
1330 outs() << " (signaling Not-a-Number)\n";
1331 }
1332}
1333
1334static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1335 uint32_t sect_size, uint64_t sect_addr,
1336 bool print_addresses) {
1337 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1338 if (print_addresses) {
1339 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001340 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001341 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001342 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001343 }
1344 double d;
1345 memcpy(&d, sect + i, sizeof(double));
1346 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1347 sys::swapByteOrder(d);
1348 uint32_t l0, l1;
1349 memcpy(&l0, sect + i, sizeof(uint32_t));
1350 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1351 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1352 sys::swapByteOrder(l0);
1353 sys::swapByteOrder(l1);
1354 }
1355 DumpLiteral8(O, l0, l1, d);
1356 }
1357}
1358
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001359static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1360 outs() << format("0x%08" PRIx32, l0) << " ";
1361 outs() << format("0x%08" PRIx32, l1) << " ";
1362 outs() << format("0x%08" PRIx32, l2) << " ";
1363 outs() << format("0x%08" PRIx32, l3) << "\n";
1364}
1365
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001366static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1367 uint32_t sect_size, uint64_t sect_addr,
1368 bool print_addresses) {
1369 for (uint32_t i = 0; i < sect_size; i += 16) {
1370 if (print_addresses) {
1371 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001372 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001373 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001374 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001375 }
1376 uint32_t l0, l1, l2, l3;
1377 memcpy(&l0, sect + i, sizeof(uint32_t));
1378 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1379 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1380 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1381 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1382 sys::swapByteOrder(l0);
1383 sys::swapByteOrder(l1);
1384 sys::swapByteOrder(l2);
1385 sys::swapByteOrder(l3);
1386 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001387 DumpLiteral16(l0, l1, l2, l3);
1388 }
1389}
1390
1391static void DumpLiteralPointerSection(MachOObjectFile *O,
1392 const SectionRef &Section,
1393 const char *sect, uint32_t sect_size,
1394 uint64_t sect_addr,
1395 bool print_addresses) {
1396 // Collect the literal sections in this Mach-O file.
1397 std::vector<SectionRef> LiteralSections;
1398 for (const SectionRef &Section : O->sections()) {
1399 DataRefImpl Ref = Section.getRawDataRefImpl();
1400 uint32_t section_type;
1401 if (O->is64Bit()) {
1402 const MachO::section_64 Sec = O->getSection64(Ref);
1403 section_type = Sec.flags & MachO::SECTION_TYPE;
1404 } else {
1405 const MachO::section Sec = O->getSection(Ref);
1406 section_type = Sec.flags & MachO::SECTION_TYPE;
1407 }
1408 if (section_type == MachO::S_CSTRING_LITERALS ||
1409 section_type == MachO::S_4BYTE_LITERALS ||
1410 section_type == MachO::S_8BYTE_LITERALS ||
1411 section_type == MachO::S_16BYTE_LITERALS)
1412 LiteralSections.push_back(Section);
1413 }
1414
1415 // Set the size of the literal pointer.
1416 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1417
Eric Christopher572e03a2015-06-19 01:53:21 +00001418 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001419 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1420 for (const RelocationRef &Reloc : Section.relocations()) {
1421 DataRefImpl Rel;
1422 MachO::any_relocation_info RE;
1423 bool isExtern = false;
1424 Rel = Reloc.getRawDataRefImpl();
1425 RE = O->getRelocation(Rel);
1426 isExtern = O->getPlainRelocationExternal(RE);
1427 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001428 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001429 symbol_iterator RelocSym = Reloc.getSymbol();
1430 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1431 }
1432 }
1433 array_pod_sort(Relocs.begin(), Relocs.end());
1434
1435 // Dump each literal pointer.
1436 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1437 if (print_addresses) {
1438 if (O->is64Bit())
1439 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1440 else
1441 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1442 }
1443 uint64_t lp;
1444 if (O->is64Bit()) {
1445 memcpy(&lp, sect + i, sizeof(uint64_t));
1446 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1447 sys::swapByteOrder(lp);
1448 } else {
1449 uint32_t li;
1450 memcpy(&li, sect + i, sizeof(uint32_t));
1451 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1452 sys::swapByteOrder(li);
1453 lp = li;
1454 }
1455
1456 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001457 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1458 return P.first == i;
1459 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001460 if (Reloc != Relocs.end()) {
1461 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001462 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1463 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001464 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001465 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001466
1467 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001468 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1469 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1470 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001471 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001472 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001473 continue;
1474 }
1475
1476 uint64_t SectAddress = Sect->getAddress();
1477 uint64_t SectSize = Sect->getSize();
1478
1479 StringRef SectName;
1480 Sect->getName(SectName);
1481 DataRefImpl Ref = Sect->getRawDataRefImpl();
1482 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1483 outs() << SegmentName << ":" << SectName << ":";
1484
1485 uint32_t section_type;
1486 if (O->is64Bit()) {
1487 const MachO::section_64 Sec = O->getSection64(Ref);
1488 section_type = Sec.flags & MachO::SECTION_TYPE;
1489 } else {
1490 const MachO::section Sec = O->getSection(Ref);
1491 section_type = Sec.flags & MachO::SECTION_TYPE;
1492 }
1493
1494 StringRef BytesStr;
1495 Sect->getContents(BytesStr);
1496 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1497
1498 switch (section_type) {
1499 case MachO::S_CSTRING_LITERALS:
1500 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1501 i++) {
1502 DumpCstringChar(Contents[i]);
1503 }
1504 outs() << "\n";
1505 break;
1506 case MachO::S_4BYTE_LITERALS:
1507 float f;
1508 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1509 uint32_t l;
1510 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1511 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1512 sys::swapByteOrder(f);
1513 sys::swapByteOrder(l);
1514 }
1515 DumpLiteral4(l, f);
1516 break;
1517 case MachO::S_8BYTE_LITERALS: {
1518 double d;
1519 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1520 uint32_t l0, l1;
1521 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1522 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1523 sizeof(uint32_t));
1524 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1525 sys::swapByteOrder(f);
1526 sys::swapByteOrder(l0);
1527 sys::swapByteOrder(l1);
1528 }
1529 DumpLiteral8(O, l0, l1, d);
1530 break;
1531 }
1532 case MachO::S_16BYTE_LITERALS: {
1533 uint32_t l0, l1, l2, l3;
1534 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1535 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1536 sizeof(uint32_t));
1537 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1538 sizeof(uint32_t));
1539 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1540 sizeof(uint32_t));
1541 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1542 sys::swapByteOrder(l0);
1543 sys::swapByteOrder(l1);
1544 sys::swapByteOrder(l2);
1545 sys::swapByteOrder(l3);
1546 }
1547 DumpLiteral16(l0, l1, l2, l3);
1548 break;
1549 }
1550 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001551 }
1552}
1553
Kevin Enderby85b7a662018-03-20 20:29:52 +00001554static void DumpInitTermPointerSection(MachOObjectFile *O,
1555 const SectionRef &Section,
1556 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001557 uint32_t sect_size, uint64_t sect_addr,
1558 SymbolAddressMap *AddrMap,
1559 bool verbose) {
1560 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001561 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001562
1563 // Collect the external relocation symbols for the pointers.
1564 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1565 for (const RelocationRef &Reloc : Section.relocations()) {
1566 DataRefImpl Rel;
1567 MachO::any_relocation_info RE;
1568 bool isExtern = false;
1569 Rel = Reloc.getRawDataRefImpl();
1570 RE = O->getRelocation(Rel);
1571 isExtern = O->getPlainRelocationExternal(RE);
1572 if (isExtern) {
1573 uint64_t RelocOffset = Reloc.getOffset();
1574 symbol_iterator RelocSym = Reloc.getSymbol();
1575 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1576 }
1577 }
1578 array_pod_sort(Relocs.begin(), Relocs.end());
1579
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001580 for (uint32_t i = 0; i < sect_size; i += stride) {
1581 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001582 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001583 if (O->is64Bit()) {
1584 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1585 uint64_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%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001590 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001591 } else {
1592 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1593 uint32_t pointer_value;
1594 memcpy(&pointer_value, sect + i, stride);
1595 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1596 sys::swapByteOrder(pointer_value);
1597 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001598 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001599 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001600 if (verbose) {
1601 // First look for an external relocation entry for this pointer.
1602 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1603 return P.first == i;
1604 });
1605 if (Reloc != Relocs.end()) {
1606 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001607 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
Kevin Enderby85b7a662018-03-20 20:29:52 +00001608 } else {
1609 SymbolName = GuessSymbolName(p, AddrMap);
1610 if (SymbolName)
1611 outs() << " " << SymbolName;
1612 }
1613 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001614 outs() << "\n";
1615 }
1616}
1617
1618static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1619 uint32_t size, uint64_t addr) {
1620 uint32_t cputype = O->getHeader().cputype;
1621 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1622 uint32_t j;
1623 for (uint32_t i = 0; i < size; i += j, addr += j) {
1624 if (O->is64Bit())
1625 outs() << format("%016" PRIx64, addr) << "\t";
1626 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001627 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001628 for (j = 0; j < 16 && i + j < size; j++) {
1629 uint8_t byte_word = *(sect + i + j);
1630 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1631 }
1632 outs() << "\n";
1633 }
1634 } else {
1635 uint32_t j;
1636 for (uint32_t i = 0; i < size; i += j, addr += j) {
1637 if (O->is64Bit())
1638 outs() << format("%016" PRIx64, addr) << "\t";
1639 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001640 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001641 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1642 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001643 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001644 uint32_t long_word;
1645 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1646 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1647 sys::swapByteOrder(long_word);
1648 outs() << format("%08" PRIx32, long_word) << " ";
1649 } else {
1650 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001651 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001652 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1653 }
1654 }
1655 }
1656 outs() << "\n";
1657 }
1658 }
1659}
1660
Kevin Enderby95df54c2015-02-04 01:01:38 +00001661static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1662 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001663static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1664 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001665#ifdef HAVE_LIBXAR
1666static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1667 uint32_t size, bool verbose,
1668 bool PrintXarHeader, bool PrintXarFileHeaders,
1669 std::string XarMemberName);
1670#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001671
1672static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1673 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001674 SymbolAddressMap AddrMap;
1675 if (verbose)
1676 CreateSymbolAddressMap(O, &AddrMap);
1677
Colin LeMahieufcc32762015-07-29 19:08:10 +00001678 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1679 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001680 std::pair<StringRef, StringRef> DumpSegSectName;
1681 DumpSegSectName = DumpSection.split(',');
1682 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001683 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001684 DumpSegName = DumpSegSectName.first;
1685 DumpSectName = DumpSegSectName.second;
1686 } else {
1687 DumpSegName = "";
1688 DumpSectName = DumpSegSectName.first;
1689 }
1690 for (const SectionRef &Section : O->sections()) {
1691 StringRef SectName;
1692 Section.getName(SectName);
1693 DataRefImpl Ref = Section.getRawDataRefImpl();
1694 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1695 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1696 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001697
Kevin Enderby95df54c2015-02-04 01:01:38 +00001698 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001699 if (O->is64Bit()) {
1700 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001701 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001702
1703 } else {
1704 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001705 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001706 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001707 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001708
1709 StringRef BytesStr;
1710 Section.getContents(BytesStr);
1711 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1712 uint32_t sect_size = BytesStr.size();
1713 uint64_t sect_addr = Section.getAddress();
1714
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001715 outs() << "Contents of (" << SegName << "," << SectName
1716 << ") section\n";
1717
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001718 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001719 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1720 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1721 DisassembleMachO(Filename, O, SegName, SectName);
1722 continue;
1723 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001724 if (SegName == "__TEXT" && SectName == "__info_plist") {
1725 outs() << sect;
1726 continue;
1727 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001728 if (SegName == "__OBJC" && SectName == "__protocol") {
1729 DumpProtocolSection(O, sect, sect_size, sect_addr);
1730 continue;
1731 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001732#ifdef HAVE_LIBXAR
1733 if (SegName == "__LLVM" && SectName == "__bundle") {
1734 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1735 ArchiveHeaders, "");
1736 continue;
1737 }
1738#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001739 switch (section_type) {
1740 case MachO::S_REGULAR:
1741 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1742 break;
1743 case MachO::S_ZEROFILL:
1744 outs() << "zerofill section and has no contents in the file\n";
1745 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001746 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001747 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001748 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001749 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001750 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001751 break;
1752 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001753 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001754 break;
1755 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001756 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1757 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001758 case MachO::S_LITERAL_POINTERS:
1759 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001760 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001761 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001762 case MachO::S_MOD_INIT_FUNC_POINTERS:
1763 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001764 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1765 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001766 break;
1767 default:
1768 outs() << "Unknown section type ("
1769 << format("0x%08" PRIx32, section_type) << ")\n";
1770 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1771 break;
1772 }
1773 } else {
1774 if (section_type == MachO::S_ZEROFILL)
1775 outs() << "zerofill section and has no contents in the file\n";
1776 else
1777 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1778 }
1779 }
1780 }
1781 }
1782}
1783
Kevin Enderbycd66be52015-03-11 22:06:32 +00001784static void DumpInfoPlistSectionContents(StringRef Filename,
1785 MachOObjectFile *O) {
1786 for (const SectionRef &Section : O->sections()) {
1787 StringRef SectName;
1788 Section.getName(SectName);
1789 DataRefImpl Ref = Section.getRawDataRefImpl();
1790 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1791 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001792 if (!NoLeadingHeaders)
1793 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001794 StringRef BytesStr;
1795 Section.getContents(BytesStr);
1796 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001797 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001798 return;
1799 }
1800 }
1801}
1802
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001803// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1804// and if it is and there is a list of architecture flags is specified then
1805// check to make sure this Mach-O file is one of those architectures or all
1806// architectures were specified. If not then an error is generated and this
1807// routine returns false. Else it returns true.
1808static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001809 auto *MachO = dyn_cast<MachOObjectFile>(O);
1810
1811 if (!MachO || ArchAll || ArchFlags.empty())
1812 return true;
1813
1814 MachO::mach_header H;
1815 MachO::mach_header_64 H_64;
1816 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001817 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001818 if (MachO->is64Bit()) {
1819 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001820 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1821 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001822 } else {
1823 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001824 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1825 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001826 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001827 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001828 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001829 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001830 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001831 WithColor::error(errs(), "llvm-objdump")
1832 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001833 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001834 }
1835 return true;
1836}
1837
Kevin Enderby0fc11822015-04-01 20:57:01 +00001838static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1839
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001840// ProcessMachO() is passed a single opened Mach-O file, which may be an
1841// archive member and or in a slice of a universal file. It prints the
1842// the file name and header info and then processes it according to the
1843// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001844static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001845 StringRef ArchiveMemberName = StringRef(),
1846 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001847 // If we are doing some processing here on the Mach-O file print the header
1848 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001849 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001850 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1851 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1852 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001853 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001854 if (!NoLeadingHeaders) {
1855 outs() << Name;
1856 if (!ArchiveMemberName.empty())
1857 outs() << '(' << ArchiveMemberName << ')';
1858 if (!ArchitectureName.empty())
1859 outs() << " (architecture " << ArchitectureName << ")";
1860 outs() << ":\n";
1861 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001862 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001863 // To use the report_error() form with an ArchiveName and FileName set
1864 // these up based on what is passed for Name and ArchiveMemberName.
1865 StringRef ArchiveName;
1866 StringRef FileName;
1867 if (!ArchiveMemberName.empty()) {
1868 ArchiveName = Name;
1869 FileName = ArchiveMemberName;
1870 } else {
1871 ArchiveName = StringRef();
1872 FileName = Name;
1873 }
1874
1875 // If we need the symbol table to do the operation then check it here to
1876 // produce a good error message as to where the Mach-O file comes from in
1877 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001878 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001879 if (Error Err = MachOOF->checkSymbolTable())
Fangrui Songe7834bd2019-04-07 08:19:55 +00001880 report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1881
Michael Trent7e660212019-01-15 20:41:30 +00001882 if (DisassembleAll) {
1883 for (const SectionRef &Section : MachOOF->sections()) {
1884 StringRef SectName;
1885 Section.getName(SectName);
1886 if (SectName.equals("__text")) {
1887 DataRefImpl Ref = Section.getRawDataRefImpl();
1888 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1889 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1890 }
1891 }
1892 }
1893 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001894 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001895 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001896 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1897 else
1898 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1899 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001900 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001901 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001902 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001903 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001904 if (LinkOptHints)
1905 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001906 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001907 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001908 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001909 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001910 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001911 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001912 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001913 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001914 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001915 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001916 if (DylibsUsed)
1917 PrintDylibs(MachOOF, false);
1918 if (DylibId)
1919 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001920 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001921 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001922 if (UnwindInfo)
1923 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001924 if (PrivateHeaders) {
1925 printMachOFileHeader(MachOOF);
1926 printMachOLoadCommands(MachOOF);
1927 }
1928 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001929 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001930 if (ObjcMetaData)
1931 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001932 if (ExportsTrie)
1933 printExportsTrie(MachOOF);
1934 if (Rebase)
1935 printRebaseTable(MachOOF);
1936 if (Bind)
1937 printBindTable(MachOOF);
1938 if (LazyBind)
1939 printLazyBindTable(MachOOF);
1940 if (WeakBind)
1941 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001942
1943 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001944 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001945 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001946 DIDumpOptions DumpOpts;
1947 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001948 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001949 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001950}
1951
Kevin Enderby131d1772015-01-09 19:22:37 +00001952// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1953static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1954 outs() << " cputype (" << cputype << ")\n";
1955 outs() << " cpusubtype (" << cpusubtype << ")\n";
1956}
1957
1958// printCPUType() helps print_fat_headers by printing the cputype and
1959// pusubtype (symbolically for the one's it knows about).
1960static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1961 switch (cputype) {
1962 case MachO::CPU_TYPE_I386:
1963 switch (cpusubtype) {
1964 case MachO::CPU_SUBTYPE_I386_ALL:
1965 outs() << " cputype CPU_TYPE_I386\n";
1966 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1967 break;
1968 default:
1969 printUnknownCPUType(cputype, cpusubtype);
1970 break;
1971 }
1972 break;
1973 case MachO::CPU_TYPE_X86_64:
1974 switch (cpusubtype) {
1975 case MachO::CPU_SUBTYPE_X86_64_ALL:
1976 outs() << " cputype CPU_TYPE_X86_64\n";
1977 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1978 break;
1979 case MachO::CPU_SUBTYPE_X86_64_H:
1980 outs() << " cputype CPU_TYPE_X86_64\n";
1981 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1982 break;
1983 default:
1984 printUnknownCPUType(cputype, cpusubtype);
1985 break;
1986 }
1987 break;
1988 case MachO::CPU_TYPE_ARM:
1989 switch (cpusubtype) {
1990 case MachO::CPU_SUBTYPE_ARM_ALL:
1991 outs() << " cputype CPU_TYPE_ARM\n";
1992 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1993 break;
1994 case MachO::CPU_SUBTYPE_ARM_V4T:
1995 outs() << " cputype CPU_TYPE_ARM\n";
1996 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1997 break;
1998 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1999 outs() << " cputype CPU_TYPE_ARM\n";
2000 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2001 break;
2002 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2003 outs() << " cputype CPU_TYPE_ARM\n";
2004 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2005 break;
2006 case MachO::CPU_SUBTYPE_ARM_V6:
2007 outs() << " cputype CPU_TYPE_ARM\n";
2008 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2009 break;
2010 case MachO::CPU_SUBTYPE_ARM_V6M:
2011 outs() << " cputype CPU_TYPE_ARM\n";
2012 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2013 break;
2014 case MachO::CPU_SUBTYPE_ARM_V7:
2015 outs() << " cputype CPU_TYPE_ARM\n";
2016 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2017 break;
2018 case MachO::CPU_SUBTYPE_ARM_V7EM:
2019 outs() << " cputype CPU_TYPE_ARM\n";
2020 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2021 break;
2022 case MachO::CPU_SUBTYPE_ARM_V7K:
2023 outs() << " cputype CPU_TYPE_ARM\n";
2024 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2025 break;
2026 case MachO::CPU_SUBTYPE_ARM_V7M:
2027 outs() << " cputype CPU_TYPE_ARM\n";
2028 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2029 break;
2030 case MachO::CPU_SUBTYPE_ARM_V7S:
2031 outs() << " cputype CPU_TYPE_ARM\n";
2032 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2033 break;
2034 default:
2035 printUnknownCPUType(cputype, cpusubtype);
2036 break;
2037 }
2038 break;
2039 case MachO::CPU_TYPE_ARM64:
2040 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2041 case MachO::CPU_SUBTYPE_ARM64_ALL:
2042 outs() << " cputype CPU_TYPE_ARM64\n";
2043 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2044 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00002045 case MachO::CPU_SUBTYPE_ARM64E:
2046 outs() << " cputype CPU_TYPE_ARM64\n";
2047 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2048 break;
Kevin Enderby131d1772015-01-09 19:22:37 +00002049 default:
2050 printUnknownCPUType(cputype, cpusubtype);
2051 break;
2052 }
2053 break;
2054 default:
2055 printUnknownCPUType(cputype, cpusubtype);
2056 break;
2057 }
2058}
2059
2060static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2061 bool verbose) {
2062 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002063 if (verbose) {
2064 if (UB->getMagic() == MachO::FAT_MAGIC)
2065 outs() << "fat_magic FAT_MAGIC\n";
2066 else // UB->getMagic() == MachO::FAT_MAGIC_64
2067 outs() << "fat_magic FAT_MAGIC_64\n";
2068 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002069 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2070
2071 uint32_t nfat_arch = UB->getNumberOfObjects();
2072 StringRef Buf = UB->getData();
2073 uint64_t size = Buf.size();
2074 uint64_t big_size = sizeof(struct MachO::fat_header) +
2075 nfat_arch * sizeof(struct MachO::fat_arch);
2076 outs() << "nfat_arch " << UB->getNumberOfObjects();
2077 if (nfat_arch == 0)
2078 outs() << " (malformed, contains zero architecture types)\n";
2079 else if (big_size > size)
2080 outs() << " (malformed, architectures past end of file)\n";
2081 else
2082 outs() << "\n";
2083
2084 for (uint32_t i = 0; i < nfat_arch; ++i) {
2085 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2086 uint32_t cputype = OFA.getCPUType();
2087 uint32_t cpusubtype = OFA.getCPUSubType();
2088 outs() << "architecture ";
2089 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2090 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2091 uint32_t other_cputype = other_OFA.getCPUType();
2092 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002093 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002094 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002095 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002096 outs() << "(illegal duplicate architecture) ";
2097 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002098 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002099 }
2100 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002101 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002102 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2103 } else {
2104 outs() << i << "\n";
2105 outs() << " cputype " << cputype << "\n";
2106 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2107 << "\n";
2108 }
2109 if (verbose &&
2110 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2111 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2112 else
2113 outs() << " capabilities "
2114 << format("0x%" PRIx32,
2115 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2116 outs() << " offset " << OFA.getOffset();
2117 if (OFA.getOffset() > size)
2118 outs() << " (past end of file)";
2119 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2120 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2121 outs() << "\n";
2122 outs() << " size " << OFA.getSize();
2123 big_size = OFA.getOffset() + OFA.getSize();
2124 if (big_size > size)
2125 outs() << " (past end of file)";
2126 outs() << "\n";
2127 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2128 << ")\n";
2129 }
2130}
2131
Kevin Enderby6524bd82016-07-19 20:47:07 +00002132static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2133 bool verbose, bool print_offset,
2134 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002135 if (print_offset)
2136 outs() << C.getChildOffset() << "\t";
Fangrui Songe7834bd2019-04-07 08:19:55 +00002137 sys::fs::perms Mode =
2138 unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002139 if (verbose) {
2140 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2141 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2142 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002143 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2144 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2145 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2146 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2147 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2148 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2149 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2150 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2151 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002152 } else {
2153 outs() << format("0%o ", Mode);
2154 }
2155
Fangrui Songe7834bd2019-04-07 08:19:55 +00002156 outs() << format(
2157 "%3d/%-3d %5" PRId64 " ",
2158 unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2159 unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2160 unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
Kevin Enderby13023a12015-01-15 23:19:11 +00002161
2162 StringRef RawLastModified = C.getRawLastModified();
2163 if (verbose) {
2164 unsigned Seconds;
2165 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002166 outs() << "(date: \"" << RawLastModified
2167 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002168 else {
2169 // Since cime(3) returns a 26 character string of the form:
2170 // "Sun Sep 16 01:03:52 1973\n\0"
2171 // just print 24 characters.
2172 time_t t = Seconds;
2173 outs() << format("%.24s ", ctime(&t));
2174 }
2175 } else {
2176 outs() << RawLastModified << " ";
2177 }
2178
2179 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002180 Expected<StringRef> NameOrErr = C.getName();
2181 if (!NameOrErr) {
2182 consumeError(NameOrErr.takeError());
Fangrui Songe7834bd2019-04-07 08:19:55 +00002183 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2184 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002185 } else {
2186 StringRef Name = NameOrErr.get();
2187 outs() << Name << "\n";
2188 }
2189 } else {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002190 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2191 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002192 }
2193}
2194
Kevin Enderby6524bd82016-07-19 20:47:07 +00002195static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2196 bool print_offset,
2197 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002198 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002199 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002200 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2201
Lang Hamesfc209622016-07-14 02:24:01 +00002202 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002203 report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002204}
2205
Dave Lee3fb120f2018-08-03 00:06:38 +00002206static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002207 // Check for -arch all and verifiy the -arch flags are valid.
2208 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2209 if (ArchFlags[i] == "all") {
2210 ArchAll = true;
2211 } else {
2212 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002213 WithColor::error(errs(), "llvm-objdump")
2214 << "unknown architecture named '" + ArchFlags[i] +
2215 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002216 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002217 }
2218 }
2219 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002220 return true;
2221}
2222
2223// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2224// -arch flags selecting just those slices as specified by them and also parses
2225// archive files. Then for each individual Mach-O file ProcessMachO() is
2226// called to process the file based on the command line options.
George Rimar73a27232019-01-15 09:19:18 +00002227void llvm::parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002228 if (!ValidateArchFlags())
2229 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002230
2231 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002232 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002233 if (!BinaryOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002234 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2235 report_error(std::move(E), Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002236 else
2237 outs() << Filename << ": is not an object file\n";
2238 return;
2239 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002240 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002241
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002242 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2243 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002244 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002245 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2246
Mehdi Amini41af4302016-11-11 04:28:40 +00002247 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002248 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002249 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2250 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002251 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2252 report_error(std::move(E), Filename, C);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002253 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002254 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002255 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2256 if (!checkMachOAndArchFlags(O, Filename))
2257 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002258 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002259 }
2260 }
Lang Hamesfc209622016-07-14 02:24:01 +00002261 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002262 report_error(std::move(Err), Filename);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002263 return;
2264 }
2265 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002266 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002267 return;
2268 }
2269 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2270 if (!checkMachOAndArchFlags(O, Filename))
2271 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002272 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002273 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002274 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002275 WithColor::error(errs(), "llvm-objdump")
2276 << Filename << "': "
2277 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002278 return;
2279 }
2280 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002281}
2282
George Rimar73a27232019-01-15 09:19:18 +00002283void llvm::parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002284 if (!ValidateArchFlags())
2285 return;
2286
2287 auto Filename = UB->getFileName();
2288
2289 if (UniversalHeaders)
2290 printMachOUniversalHeaders(UB, !NonVerbose);
2291
2292 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002293 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002294 // Look for a slice in the universal binary that matches each ArchFlag.
2295 bool ArchFound;
2296 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2297 ArchFound = false;
2298 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2299 E = UB->end_objects();
2300 I != E; ++I) {
2301 if (ArchFlags[i] == I->getArchFlagName()) {
2302 ArchFound = true;
2303 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2304 I->getAsObjectFile();
2305 std::string ArchitectureName = "";
2306 if (ArchFlags.size() > 1)
2307 ArchitectureName = I->getArchFlagName();
2308 if (ObjOrErr) {
2309 ObjectFile &O = *ObjOrErr.get();
2310 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2311 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002312 } else if (Error E = isNotObjectErrorInvalidFileType(
2313 ObjOrErr.takeError())) {
2314 report_error(std::move(E), Filename, StringRef(), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002315 continue;
2316 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002317 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002318 std::unique_ptr<Archive> &A = *AOrErr;
2319 outs() << "Archive : " << Filename;
2320 if (!ArchitectureName.empty())
2321 outs() << " (architecture " << ArchitectureName << ")";
2322 outs() << "\n";
2323 if (ArchiveHeaders)
2324 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2325 ArchiveMemberOffsets, ArchitectureName);
2326 Error Err = Error::success();
2327 for (auto &C : A->children(Err)) {
2328 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2329 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002330 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2331 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002332 continue;
2333 }
2334 if (MachOObjectFile *O =
2335 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2336 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2337 }
2338 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002339 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002340 } else {
2341 consumeError(AOrErr.takeError());
2342 error("Mach-O universal file: " + Filename + " for " +
2343 "architecture " + StringRef(I->getArchFlagName()) +
2344 " is not a Mach-O file or an archive file");
2345 }
2346 }
2347 }
2348 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002349 WithColor::error(errs(), "llvm-objdump")
2350 << "file: " + Filename + " does not contain "
2351 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002352 return;
2353 }
2354 }
2355 return;
2356 }
2357 // No architecture flags were specified so if this contains a slice that
2358 // matches the host architecture dump only that.
2359 if (!ArchAll) {
2360 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2361 E = UB->end_objects();
2362 I != E; ++I) {
2363 if (MachOObjectFile::getHostArch().getArchName() ==
2364 I->getArchFlagName()) {
2365 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2366 std::string ArchiveName;
2367 ArchiveName.clear();
2368 if (ObjOrErr) {
2369 ObjectFile &O = *ObjOrErr.get();
2370 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2371 ProcessMachO(Filename, MachOOF);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002372 } else if (Error E =
2373 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2374 report_error(std::move(E), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002375 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002376 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002377 std::unique_ptr<Archive> &A = *AOrErr;
2378 outs() << "Archive : " << Filename << "\n";
2379 if (ArchiveHeaders)
2380 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2381 ArchiveMemberOffsets);
2382 Error Err = Error::success();
2383 for (auto &C : A->children(Err)) {
2384 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2385 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002386 if (Error E =
2387 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2388 report_error(std::move(E), Filename, C);
Dave Lee3fb120f2018-08-03 00:06:38 +00002389 continue;
2390 }
2391 if (MachOObjectFile *O =
2392 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2393 ProcessMachO(Filename, O, O->getFileName());
2394 }
2395 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002396 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002397 } else {
2398 consumeError(AOrErr.takeError());
2399 error("Mach-O universal file: " + Filename + " for architecture " +
2400 StringRef(I->getArchFlagName()) +
2401 " is not a Mach-O file or an archive file");
2402 }
2403 return;
2404 }
2405 }
2406 }
2407 // Either all architectures have been specified or none have been specified
2408 // and this does not contain the host architecture so dump all the slices.
2409 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2410 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2411 E = UB->end_objects();
2412 I != E; ++I) {
2413 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2414 std::string ArchitectureName = "";
2415 if (moreThanOneArch)
2416 ArchitectureName = I->getArchFlagName();
2417 if (ObjOrErr) {
2418 ObjectFile &Obj = *ObjOrErr.get();
2419 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2420 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002421 } else if (Error E =
2422 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2423 report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2424 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002425 std::unique_ptr<Archive> &A = *AOrErr;
2426 outs() << "Archive : " << Filename;
2427 if (!ArchitectureName.empty())
2428 outs() << " (architecture " << ArchitectureName << ")";
2429 outs() << "\n";
2430 if (ArchiveHeaders)
2431 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2432 ArchiveMemberOffsets, ArchitectureName);
2433 Error Err = Error::success();
2434 for (auto &C : A->children(Err)) {
2435 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2436 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002437 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2438 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002439 continue;
2440 }
2441 if (MachOObjectFile *O =
2442 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2443 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2444 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2445 ArchitectureName);
2446 }
2447 }
2448 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002449 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002450 } else {
2451 consumeError(AOrErr.takeError());
2452 error("Mach-O universal file: " + Filename + " for architecture " +
2453 StringRef(I->getArchFlagName()) +
2454 " is not a Mach-O file or an archive file");
2455 }
2456 }
2457}
2458
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002459// The block of info used by the Symbolizer call backs.
2460struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002461 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2462 std::vector<SectionRef> *Sections, bool verbose)
2463 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002464 bool verbose;
2465 MachOObjectFile *O;
2466 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002467 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002468 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002469 const char *class_name = nullptr;
2470 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002471 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002472 char *demangled_name = nullptr;
2473 uint64_t adrp_addr = 0;
2474 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002475 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002476 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002477};
2478
2479// SymbolizerGetOpInfo() is the operand information call back function.
2480// This is called to get the symbolic information for operand(s) of an
2481// instruction when it is being done. This routine does this from
2482// the relocation information, symbol table, etc. That block of information
2483// is a pointer to the struct DisassembleInfo that was passed when the
2484// disassembler context was created and passed to back to here when
2485// called back by the disassembler for instruction operands that could have
2486// relocation information. The address of the instruction containing operand is
2487// at the Pc parameter. The immediate value the operand has is passed in
2488// op_info->Value and is at Offset past the start of the instruction and has a
2489// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2490// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2491// names and addends of the symbolic expression to add for the operand. The
2492// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2493// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002494static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2495 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002496 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2497 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002498 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002499
2500 // Make sure all fields returned are zero if we don't set them.
2501 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2502 op_info->Value = value;
2503
2504 // If the TagType is not the value 1 which it code knows about or if no
2505 // verbose symbolic information is wanted then just return 0, indicating no
2506 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002507 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002508 return 0;
2509
2510 unsigned int Arch = info->O->getArch();
2511 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002512 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2513 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002514 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2515 // TODO:
2516 // Search the external relocation entries of a fully linked image
2517 // (if any) for an entry that matches this segment offset.
2518 // uint32_t seg_offset = (Pc + Offset);
2519 return 0;
2520 }
2521 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2522 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002523 uint32_t sect_addr = info->S.getAddress();
2524 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2525 bool reloc_found = false;
2526 DataRefImpl Rel;
2527 MachO::any_relocation_info RE;
2528 bool isExtern = false;
2529 SymbolRef Symbol;
2530 bool r_scattered = false;
2531 uint32_t r_value, pair_r_value, r_type;
2532 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002533 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002534 if (RelocOffset == sect_offset) {
2535 Rel = Reloc.getRawDataRefImpl();
2536 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002537 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002538 r_scattered = info->O->isRelocationScattered(RE);
2539 if (r_scattered) {
2540 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002541 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2542 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2543 DataRefImpl RelNext = Rel;
2544 info->O->moveRelocationNext(RelNext);
2545 MachO::any_relocation_info RENext;
2546 RENext = info->O->getRelocation(RelNext);
2547 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002548 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002549 else
2550 return 0;
2551 }
2552 } else {
2553 isExtern = info->O->getPlainRelocationExternal(RE);
2554 if (isExtern) {
2555 symbol_iterator RelocSym = Reloc.getSymbol();
2556 Symbol = *RelocSym;
2557 }
2558 }
2559 reloc_found = true;
2560 break;
2561 }
2562 }
2563 if (reloc_found && isExtern) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002564 op_info->AddSymbol.Present = 1;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002565 op_info->AddSymbol.Name =
2566 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002567 // For i386 extern relocation entries the value in the instruction is
2568 // the offset from the symbol, and value is already set in op_info->Value.
2569 return 1;
2570 }
2571 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2572 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002573 const char *add = GuessSymbolName(r_value, info->AddrMap);
2574 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002575 uint32_t offset = value - (r_value - pair_r_value);
2576 op_info->AddSymbol.Present = 1;
2577 if (add != nullptr)
2578 op_info->AddSymbol.Name = add;
2579 else
2580 op_info->AddSymbol.Value = r_value;
2581 op_info->SubtractSymbol.Present = 1;
2582 if (sub != nullptr)
2583 op_info->SubtractSymbol.Name = sub;
2584 else
2585 op_info->SubtractSymbol.Value = pair_r_value;
2586 op_info->Value = offset;
2587 return 1;
2588 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002589 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002590 }
2591 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002592 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2593 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002594 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2595 // relocation entries of a linked image (if any) for an entry that matches
2596 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002597 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002598 uint64_t seg_offset = Pc + Offset;
2599 bool reloc_found = false;
2600 DataRefImpl Rel;
2601 MachO::any_relocation_info RE;
2602 bool isExtern = false;
2603 SymbolRef Symbol;
2604 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2605 uint64_t RelocOffset = Reloc.getOffset();
2606 if (RelocOffset == seg_offset) {
2607 Rel = Reloc.getRawDataRefImpl();
2608 RE = info->O->getRelocation(Rel);
2609 // external relocation entries should always be external.
2610 isExtern = info->O->getPlainRelocationExternal(RE);
2611 if (isExtern) {
2612 symbol_iterator RelocSym = Reloc.getSymbol();
2613 Symbol = *RelocSym;
2614 }
2615 reloc_found = true;
2616 break;
2617 }
2618 }
2619 if (reloc_found && isExtern) {
2620 // The Value passed in will be adjusted by the Pc if the instruction
2621 // adds the Pc. But for x86_64 external relocation entries the Value
2622 // is the offset from the external symbol.
2623 if (info->O->getAnyRelocationPCRel(RE))
2624 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002625 const char *name =
2626 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002627 op_info->AddSymbol.Present = 1;
2628 op_info->AddSymbol.Name = name;
2629 return 1;
2630 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002631 return 0;
2632 }
2633 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2634 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002635 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002636 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2637 bool reloc_found = false;
2638 DataRefImpl Rel;
2639 MachO::any_relocation_info RE;
2640 bool isExtern = false;
2641 SymbolRef Symbol;
2642 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002643 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002644 if (RelocOffset == sect_offset) {
2645 Rel = Reloc.getRawDataRefImpl();
2646 RE = info->O->getRelocation(Rel);
2647 // NOTE: Scattered relocations don't exist on x86_64.
2648 isExtern = info->O->getPlainRelocationExternal(RE);
2649 if (isExtern) {
2650 symbol_iterator RelocSym = Reloc.getSymbol();
2651 Symbol = *RelocSym;
2652 }
2653 reloc_found = true;
2654 break;
2655 }
2656 }
2657 if (reloc_found && isExtern) {
2658 // The Value passed in will be adjusted by the Pc if the instruction
2659 // adds the Pc. But for x86_64 external relocation entries the Value
2660 // is the offset from the external symbol.
2661 if (info->O->getAnyRelocationPCRel(RE))
2662 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002663 const char *name =
2664 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002665 unsigned Type = info->O->getAnyRelocationType(RE);
2666 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2667 DataRefImpl RelNext = Rel;
2668 info->O->moveRelocationNext(RelNext);
2669 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2670 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2671 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2672 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2673 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2674 op_info->SubtractSymbol.Present = 1;
2675 op_info->SubtractSymbol.Name = name;
2676 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2677 Symbol = *RelocSymNext;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002678 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002679 }
2680 }
2681 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2682 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2683 op_info->AddSymbol.Present = 1;
2684 op_info->AddSymbol.Name = name;
2685 return 1;
2686 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002687 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002688 }
2689 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002690 if (Offset != 0 || (Size != 4 && Size != 2))
2691 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002692 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2693 // TODO:
2694 // Search the external relocation entries of a fully linked image
2695 // (if any) for an entry that matches this segment offset.
2696 // uint32_t seg_offset = (Pc + Offset);
2697 return 0;
2698 }
2699 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2700 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002701 uint32_t sect_addr = info->S.getAddress();
2702 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002703 DataRefImpl Rel;
2704 MachO::any_relocation_info RE;
2705 bool isExtern = false;
2706 SymbolRef Symbol;
2707 bool r_scattered = false;
2708 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002709 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002710 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2711 uint64_t RelocOffset = Reloc.getOffset();
2712 return RelocOffset == sect_offset;
2713 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002714
2715 if (Reloc == info->S.relocations().end())
2716 return 0;
2717
2718 Rel = Reloc->getRawDataRefImpl();
2719 RE = info->O->getRelocation(Rel);
2720 r_length = info->O->getAnyRelocationLength(RE);
2721 r_scattered = info->O->isRelocationScattered(RE);
2722 if (r_scattered) {
2723 r_value = info->O->getScatteredRelocationValue(RE);
2724 r_type = info->O->getScatteredRelocationType(RE);
2725 } else {
2726 r_type = info->O->getAnyRelocationType(RE);
2727 isExtern = info->O->getPlainRelocationExternal(RE);
2728 if (isExtern) {
2729 symbol_iterator RelocSym = Reloc->getSymbol();
2730 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002731 }
2732 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002733 if (r_type == MachO::ARM_RELOC_HALF ||
2734 r_type == MachO::ARM_RELOC_SECTDIFF ||
2735 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2736 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2737 DataRefImpl RelNext = Rel;
2738 info->O->moveRelocationNext(RelNext);
2739 MachO::any_relocation_info RENext;
2740 RENext = info->O->getRelocation(RelNext);
2741 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2742 if (info->O->isRelocationScattered(RENext))
2743 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2744 }
2745
2746 if (isExtern) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002747 const char *name =
2748 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002749 op_info->AddSymbol.Present = 1;
2750 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002751 switch (r_type) {
2752 case MachO::ARM_RELOC_HALF:
2753 if ((r_length & 0x1) == 1) {
2754 op_info->Value = value << 16 | other_half;
2755 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2756 } else {
2757 op_info->Value = other_half << 16 | value;
2758 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002759 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002760 break;
2761 default:
2762 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002763 }
2764 return 1;
2765 }
2766 // If we have a branch that is not an external relocation entry then
2767 // return 0 so the code in tryAddingSymbolicOperand() can use the
2768 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002769 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002770 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2771 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002772 return 0;
2773
2774 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002775 if (r_type == MachO::ARM_RELOC_HALF ||
2776 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2777 if ((r_length & 0x1) == 1)
2778 value = value << 16 | other_half;
2779 else
2780 value = other_half << 16 | value;
2781 }
2782 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2783 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2784 offset = value - r_value;
2785 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002786 }
2787
David Blaikie33dd45d02015-03-23 18:39:02 +00002788 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002789 if ((r_length & 0x1) == 1)
2790 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2791 else
2792 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002793 const char *add = GuessSymbolName(r_value, info->AddrMap);
2794 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002795 int32_t offset = value - (r_value - pair_r_value);
2796 op_info->AddSymbol.Present = 1;
2797 if (add != nullptr)
2798 op_info->AddSymbol.Name = add;
2799 else
2800 op_info->AddSymbol.Value = r_value;
2801 op_info->SubtractSymbol.Present = 1;
2802 if (sub != nullptr)
2803 op_info->SubtractSymbol.Name = sub;
2804 else
2805 op_info->SubtractSymbol.Value = pair_r_value;
2806 op_info->Value = offset;
2807 return 1;
2808 }
2809
Kevin Enderby930fdc72014-11-06 19:00:13 +00002810 op_info->AddSymbol.Present = 1;
2811 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002812 if (r_type == MachO::ARM_RELOC_HALF) {
2813 if ((r_length & 0x1) == 1)
2814 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2815 else
2816 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002817 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002818 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002819 if (add != nullptr) {
2820 op_info->AddSymbol.Name = add;
2821 return 1;
2822 }
2823 op_info->AddSymbol.Value = value;
2824 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002825 }
2826 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002827 if (Offset != 0 || Size != 4)
2828 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002829 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2830 // TODO:
2831 // Search the external relocation entries of a fully linked image
2832 // (if any) for an entry that matches this segment offset.
2833 // uint64_t seg_offset = (Pc + Offset);
2834 return 0;
2835 }
2836 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2837 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002838 uint64_t sect_addr = info->S.getAddress();
2839 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002840 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002841 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2842 uint64_t RelocOffset = Reloc.getOffset();
2843 return RelocOffset == sect_offset;
2844 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002845
David Blaikie33dd45d02015-03-23 18:39:02 +00002846 if (Reloc == info->S.relocations().end())
2847 return 0;
2848
2849 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2850 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2851 uint32_t r_type = info->O->getAnyRelocationType(RE);
2852 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2853 DataRefImpl RelNext = Rel;
2854 info->O->moveRelocationNext(RelNext);
2855 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2856 if (value == 0) {
2857 value = info->O->getPlainRelocationSymbolNum(RENext);
2858 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002859 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002860 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002861 // NOTE: Scattered relocations don't exist on arm64.
2862 if (!info->O->getPlainRelocationExternal(RE))
2863 return 0;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002864 const char *name =
2865 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2866 .data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002867 op_info->AddSymbol.Present = 1;
2868 op_info->AddSymbol.Name = name;
2869
2870 switch (r_type) {
2871 case MachO::ARM64_RELOC_PAGE21:
2872 /* @page */
2873 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2874 break;
2875 case MachO::ARM64_RELOC_PAGEOFF12:
2876 /* @pageoff */
2877 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2878 break;
2879 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2880 /* @gotpage */
2881 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2882 break;
2883 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2884 /* @gotpageoff */
2885 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2886 break;
2887 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2888 /* @tvlppage is not implemented in llvm-mc */
2889 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2890 break;
2891 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2892 /* @tvlppageoff is not implemented in llvm-mc */
2893 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2894 break;
2895 default:
2896 case MachO::ARM64_RELOC_BRANCH26:
2897 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2898 break;
2899 }
2900 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002901 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002902 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002903}
2904
Kevin Enderbybf246f52014-09-24 23:08:22 +00002905// GuessCstringPointer is passed the address of what might be a pointer to a
2906// literal string in a cstring section. If that address is in a cstring section
2907// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002908static const char *GuessCstringPointer(uint64_t ReferenceValue,
2909 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002910 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002911 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2912 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2913 for (unsigned J = 0; J < Seg.nsects; ++J) {
2914 MachO::section_64 Sec = info->O->getSection64(Load, J);
2915 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2916 if (section_type == MachO::S_CSTRING_LITERALS &&
2917 ReferenceValue >= Sec.addr &&
2918 ReferenceValue < Sec.addr + Sec.size) {
2919 uint64_t sect_offset = ReferenceValue - Sec.addr;
2920 uint64_t object_offset = Sec.offset + sect_offset;
2921 StringRef MachOContents = info->O->getData();
2922 uint64_t object_size = MachOContents.size();
2923 const char *object_addr = (const char *)MachOContents.data();
2924 if (object_offset < object_size) {
2925 const char *name = object_addr + object_offset;
2926 return name;
2927 } else {
2928 return nullptr;
2929 }
2930 }
2931 }
2932 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2933 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2934 for (unsigned J = 0; J < Seg.nsects; ++J) {
2935 MachO::section Sec = info->O->getSection(Load, J);
2936 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2937 if (section_type == MachO::S_CSTRING_LITERALS &&
2938 ReferenceValue >= Sec.addr &&
2939 ReferenceValue < Sec.addr + Sec.size) {
2940 uint64_t sect_offset = ReferenceValue - Sec.addr;
2941 uint64_t object_offset = Sec.offset + sect_offset;
2942 StringRef MachOContents = info->O->getData();
2943 uint64_t object_size = MachOContents.size();
2944 const char *object_addr = (const char *)MachOContents.data();
2945 if (object_offset < object_size) {
2946 const char *name = object_addr + object_offset;
2947 return name;
2948 } else {
2949 return nullptr;
2950 }
2951 }
2952 }
2953 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002954 }
2955 return nullptr;
2956}
2957
Kevin Enderby85974882014-09-26 22:20:44 +00002958// GuessIndirectSymbol returns the name of the indirect symbol for the
2959// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2960// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2961// symbol name being referenced by the stub or pointer.
2962static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2963 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002964 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2965 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002966 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002967 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2968 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2969 for (unsigned J = 0; J < Seg.nsects; ++J) {
2970 MachO::section_64 Sec = info->O->getSection64(Load, J);
2971 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2972 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2973 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2974 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2975 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2976 section_type == MachO::S_SYMBOL_STUBS) &&
2977 ReferenceValue >= Sec.addr &&
2978 ReferenceValue < Sec.addr + Sec.size) {
2979 uint32_t stride;
2980 if (section_type == MachO::S_SYMBOL_STUBS)
2981 stride = Sec.reserved2;
2982 else
2983 stride = 8;
2984 if (stride == 0)
2985 return nullptr;
2986 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2987 if (index < Dysymtab.nindirectsyms) {
2988 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002989 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002990 if (indirect_symbol < Symtab.nsyms) {
2991 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002992 return unwrapOrError(Sym->getName(), info->O->getFileName())
2993 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002994 }
2995 }
2996 }
2997 }
2998 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2999 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3000 for (unsigned J = 0; J < Seg.nsects; ++J) {
3001 MachO::section Sec = info->O->getSection(Load, J);
3002 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3003 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3004 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3005 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3006 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3007 section_type == MachO::S_SYMBOL_STUBS) &&
3008 ReferenceValue >= Sec.addr &&
3009 ReferenceValue < Sec.addr + Sec.size) {
3010 uint32_t stride;
3011 if (section_type == MachO::S_SYMBOL_STUBS)
3012 stride = Sec.reserved2;
3013 else
3014 stride = 4;
3015 if (stride == 0)
3016 return nullptr;
3017 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3018 if (index < Dysymtab.nindirectsyms) {
3019 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003020 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003021 if (indirect_symbol < Symtab.nsyms) {
3022 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00003023 return unwrapOrError(Sym->getName(), info->O->getFileName())
3024 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00003025 }
3026 }
3027 }
3028 }
3029 }
Kevin Enderby85974882014-09-26 22:20:44 +00003030 }
3031 return nullptr;
3032}
3033
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003034// method_reference() is called passing it the ReferenceName that might be
3035// a reference it to an Objective-C method call. If so then it allocates and
3036// assembles a method call string with the values last seen and saved in
3037// the DisassembleInfo's class_name and selector_name fields. This is saved
3038// into the method field of the info and any previous string is free'ed.
3039// Then the class_name field in the info is set to nullptr. The method call
3040// string is set into ReferenceName and ReferenceType is set to
3041// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3042// then both ReferenceType and ReferenceName are left unchanged.
3043static void method_reference(struct DisassembleInfo *info,
3044 uint64_t *ReferenceType,
3045 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003046 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003047 if (*ReferenceName != nullptr) {
3048 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003049 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003050 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003051 info->method = llvm::make_unique<char[]>(
3052 5 + strlen(info->class_name) + strlen(info->selector_name));
3053 char *method = info->method.get();
3054 if (method != nullptr) {
3055 strcpy(method, "+[");
3056 strcat(method, info->class_name);
3057 strcat(method, " ");
3058 strcat(method, info->selector_name);
3059 strcat(method, "]");
3060 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003061 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3062 }
3063 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003064 info->method =
3065 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3066 char *method = info->method.get();
3067 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003068 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003069 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003070 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003071 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003072 else
David Blaikie0e550682018-02-20 18:48:51 +00003073 strcpy(method, "-[r? ");
3074 strcat(method, info->selector_name);
3075 strcat(method, "]");
3076 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003077 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3078 }
3079 }
3080 info->class_name = nullptr;
3081 }
3082 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003083 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003084 info->method =
3085 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3086 char *method = info->method.get();
3087 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003088 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003089 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003090 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003091 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003092 else
David Blaikie0e550682018-02-20 18:48:51 +00003093 strcpy(method, "-[[r? super] ");
3094 strcat(method, info->selector_name);
3095 strcat(method, "]");
3096 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003097 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3098 }
3099 info->class_name = nullptr;
3100 }
3101 }
3102 }
3103}
3104
3105// GuessPointerPointer() is passed the address of what might be a pointer to
3106// a reference to an Objective-C class, selector, message ref or cfstring.
3107// If so the value of the pointer is returned and one of the booleans are set
3108// to true. If not zero is returned and all the booleans are set to false.
3109static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3110 struct DisassembleInfo *info,
3111 bool &classref, bool &selref, bool &msgref,
3112 bool &cfstring) {
3113 classref = false;
3114 selref = false;
3115 msgref = false;
3116 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003117 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003118 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3119 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3120 for (unsigned J = 0; J < Seg.nsects; ++J) {
3121 MachO::section_64 Sec = info->O->getSection64(Load, J);
3122 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3123 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3124 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3125 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3126 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3127 ReferenceValue >= Sec.addr &&
3128 ReferenceValue < Sec.addr + Sec.size) {
3129 uint64_t sect_offset = ReferenceValue - Sec.addr;
3130 uint64_t object_offset = Sec.offset + sect_offset;
3131 StringRef MachOContents = info->O->getData();
3132 uint64_t object_size = MachOContents.size();
3133 const char *object_addr = (const char *)MachOContents.data();
3134 if (object_offset < object_size) {
3135 uint64_t pointer_value;
3136 memcpy(&pointer_value, object_addr + object_offset,
3137 sizeof(uint64_t));
3138 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3139 sys::swapByteOrder(pointer_value);
3140 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3141 selref = true;
3142 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3143 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3144 classref = true;
3145 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3146 ReferenceValue + 8 < Sec.addr + Sec.size) {
3147 msgref = true;
3148 memcpy(&pointer_value, object_addr + object_offset + 8,
3149 sizeof(uint64_t));
3150 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3151 sys::swapByteOrder(pointer_value);
3152 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3153 cfstring = true;
3154 return pointer_value;
3155 } else {
3156 return 0;
3157 }
3158 }
3159 }
3160 }
3161 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003162 }
3163 return 0;
3164}
3165
3166// get_pointer_64 returns a pointer to the bytes in the object file at the
3167// Address from a section in the Mach-O file. And indirectly returns the
3168// offset into the section, number of bytes left in the section past the offset
3169// and which section is was being referenced. If the Address is not in a
3170// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003171static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3172 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003173 DisassembleInfo *info,
3174 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003175 offset = 0;
3176 left = 0;
3177 S = SectionRef();
3178 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3179 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3180 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003181 if (SectSize == 0)
3182 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003183 if (objc_only) {
3184 StringRef SectName;
3185 ((*(info->Sections))[SectIdx]).getName(SectName);
3186 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3187 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3188 if (SegName != "__OBJC" && SectName != "__cstring")
3189 continue;
3190 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003191 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3192 S = (*(info->Sections))[SectIdx];
3193 offset = Address - SectAddress;
3194 left = SectSize - offset;
3195 StringRef SectContents;
3196 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3197 return SectContents.data() + offset;
3198 }
3199 }
3200 return nullptr;
3201}
3202
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003203static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3204 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003205 DisassembleInfo *info,
3206 bool objc_only = false) {
3207 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003208}
3209
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003210// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3211// the symbol indirectly through n_value. Based on the relocation information
3212// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003213// If no relocation information is found and a non-zero ReferenceValue for the
3214// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003215static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3216 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003217 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003218 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003219 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003220 return nullptr;
3221
3222 // See if there is an external relocation entry at the sect_offset.
3223 bool reloc_found = false;
3224 DataRefImpl Rel;
3225 MachO::any_relocation_info RE;
3226 bool isExtern = false;
3227 SymbolRef Symbol;
3228 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003229 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003230 if (RelocOffset == sect_offset) {
3231 Rel = Reloc.getRawDataRefImpl();
3232 RE = info->O->getRelocation(Rel);
3233 if (info->O->isRelocationScattered(RE))
3234 continue;
3235 isExtern = info->O->getPlainRelocationExternal(RE);
3236 if (isExtern) {
3237 symbol_iterator RelocSym = Reloc.getSymbol();
3238 Symbol = *RelocSym;
3239 }
3240 reloc_found = true;
3241 break;
3242 }
3243 }
3244 // If there is an external relocation entry for a symbol in this section
3245 // at this section_offset then use that symbol's value for the n_value
3246 // and return its name.
3247 const char *SymbolName = nullptr;
3248 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003249 n_value = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00003250 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003251 if (!Name.empty()) {
3252 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003253 return SymbolName;
3254 }
3255 }
3256
3257 // TODO: For fully linked images, look through the external relocation
3258 // entries off the dynamic symtab command. For these the r_offset is from the
3259 // start of the first writeable segment in the Mach-O file. So the offset
3260 // to this section from that segment is passed to this routine by the caller,
3261 // as the database_offset. Which is the difference of the section's starting
3262 // address and the first writable segment.
3263 //
3264 // NOTE: need add passing the database_offset to this routine.
3265
Kevin Enderby0fc11822015-04-01 20:57:01 +00003266 // We did not find an external relocation entry so look up the ReferenceValue
3267 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003268 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003269
3270 return SymbolName;
3271}
3272
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003273static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3274 DisassembleInfo *info,
3275 uint32_t ReferenceValue) {
3276 uint64_t n_value64;
3277 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3278}
3279
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003280// These are structs in the Objective-C meta data and read to produce the
3281// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003282// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3283// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003284
3285// The cfstring object in a 64-bit Mach-O file.
3286struct cfstring64_t {
3287 uint64_t isa; // class64_t * (64-bit pointer)
3288 uint64_t flags; // flag bits
3289 uint64_t characters; // char * (64-bit pointer)
3290 uint64_t length; // number of non-NULL characters in above
3291};
3292
3293// The class object in a 64-bit Mach-O file.
3294struct class64_t {
3295 uint64_t isa; // class64_t * (64-bit pointer)
3296 uint64_t superclass; // class64_t * (64-bit pointer)
3297 uint64_t cache; // Cache (64-bit pointer)
3298 uint64_t vtable; // IMP * (64-bit pointer)
3299 uint64_t data; // class_ro64_t * (64-bit pointer)
3300};
3301
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003302struct class32_t {
3303 uint32_t isa; /* class32_t * (32-bit pointer) */
3304 uint32_t superclass; /* class32_t * (32-bit pointer) */
3305 uint32_t cache; /* Cache (32-bit pointer) */
3306 uint32_t vtable; /* IMP * (32-bit pointer) */
3307 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3308};
3309
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003310struct class_ro64_t {
3311 uint32_t flags;
3312 uint32_t instanceStart;
3313 uint32_t instanceSize;
3314 uint32_t reserved;
3315 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3316 uint64_t name; // const char * (64-bit pointer)
3317 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3318 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3319 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3320 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3321 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3322};
3323
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003324struct class_ro32_t {
3325 uint32_t flags;
3326 uint32_t instanceStart;
3327 uint32_t instanceSize;
3328 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3329 uint32_t name; /* const char * (32-bit pointer) */
3330 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3331 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3332 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3333 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3334 uint32_t baseProperties; /* const struct objc_property_list *
3335 (32-bit pointer) */
3336};
3337
3338/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003339#define RO_META (1 << 0)
3340#define RO_ROOT (1 << 1)
3341#define RO_HAS_CXX_STRUCTORS (1 << 2)
3342
3343struct method_list64_t {
3344 uint32_t entsize;
3345 uint32_t count;
3346 /* struct method64_t first; These structures follow inline */
3347};
3348
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003349struct method_list32_t {
3350 uint32_t entsize;
3351 uint32_t count;
3352 /* struct method32_t first; These structures follow inline */
3353};
3354
Kevin Enderby0fc11822015-04-01 20:57:01 +00003355struct method64_t {
3356 uint64_t name; /* SEL (64-bit pointer) */
3357 uint64_t types; /* const char * (64-bit pointer) */
3358 uint64_t imp; /* IMP (64-bit pointer) */
3359};
3360
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003361struct method32_t {
3362 uint32_t name; /* SEL (32-bit pointer) */
3363 uint32_t types; /* const char * (32-bit pointer) */
3364 uint32_t imp; /* IMP (32-bit pointer) */
3365};
3366
Kevin Enderby0fc11822015-04-01 20:57:01 +00003367struct protocol_list64_t {
3368 uint64_t count; /* uintptr_t (a 64-bit value) */
3369 /* struct protocol64_t * list[0]; These pointers follow inline */
3370};
3371
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003372struct protocol_list32_t {
3373 uint32_t count; /* uintptr_t (a 32-bit value) */
3374 /* struct protocol32_t * list[0]; These pointers follow inline */
3375};
3376
Kevin Enderby0fc11822015-04-01 20:57:01 +00003377struct protocol64_t {
3378 uint64_t isa; /* id * (64-bit pointer) */
3379 uint64_t name; /* const char * (64-bit pointer) */
3380 uint64_t protocols; /* struct protocol_list64_t *
3381 (64-bit pointer) */
3382 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3383 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3384 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3385 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3386 uint64_t instanceProperties; /* struct objc_property_list *
3387 (64-bit pointer) */
3388};
3389
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003390struct protocol32_t {
3391 uint32_t isa; /* id * (32-bit pointer) */
3392 uint32_t name; /* const char * (32-bit pointer) */
3393 uint32_t protocols; /* struct protocol_list_t *
3394 (32-bit pointer) */
3395 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3396 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3397 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3398 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3399 uint32_t instanceProperties; /* struct objc_property_list *
3400 (32-bit pointer) */
3401};
3402
Kevin Enderby0fc11822015-04-01 20:57:01 +00003403struct ivar_list64_t {
3404 uint32_t entsize;
3405 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003406 /* struct ivar64_t first; These structures follow inline */
3407};
3408
3409struct ivar_list32_t {
3410 uint32_t entsize;
3411 uint32_t count;
3412 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003413};
3414
3415struct ivar64_t {
3416 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3417 uint64_t name; /* const char * (64-bit pointer) */
3418 uint64_t type; /* const char * (64-bit pointer) */
3419 uint32_t alignment;
3420 uint32_t size;
3421};
3422
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003423struct ivar32_t {
3424 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3425 uint32_t name; /* const char * (32-bit pointer) */
3426 uint32_t type; /* const char * (32-bit pointer) */
3427 uint32_t alignment;
3428 uint32_t size;
3429};
3430
Kevin Enderby0fc11822015-04-01 20:57:01 +00003431struct objc_property_list64 {
3432 uint32_t entsize;
3433 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003434 /* struct objc_property64 first; These structures follow inline */
3435};
3436
3437struct objc_property_list32 {
3438 uint32_t entsize;
3439 uint32_t count;
3440 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003441};
3442
3443struct objc_property64 {
3444 uint64_t name; /* const char * (64-bit pointer) */
3445 uint64_t attributes; /* const char * (64-bit pointer) */
3446};
3447
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003448struct objc_property32 {
3449 uint32_t name; /* const char * (32-bit pointer) */
3450 uint32_t attributes; /* const char * (32-bit pointer) */
3451};
3452
Kevin Enderby0fc11822015-04-01 20:57:01 +00003453struct category64_t {
3454 uint64_t name; /* const char * (64-bit pointer) */
3455 uint64_t cls; /* struct class_t * (64-bit pointer) */
3456 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3457 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3458 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3459 uint64_t instanceProperties; /* struct objc_property_list *
3460 (64-bit pointer) */
3461};
3462
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003463struct category32_t {
3464 uint32_t name; /* const char * (32-bit pointer) */
3465 uint32_t cls; /* struct class_t * (32-bit pointer) */
3466 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3467 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3468 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3469 uint32_t instanceProperties; /* struct objc_property_list *
3470 (32-bit pointer) */
3471};
3472
Kevin Enderby0fc11822015-04-01 20:57:01 +00003473struct objc_image_info64 {
3474 uint32_t version;
3475 uint32_t flags;
3476};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003477struct objc_image_info32 {
3478 uint32_t version;
3479 uint32_t flags;
3480};
Kevin Enderby846c0002015-04-16 17:19:59 +00003481struct imageInfo_t {
3482 uint32_t version;
3483 uint32_t flags;
3484};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003485/* masks for objc_image_info.flags */
3486#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3487#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003488#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3489#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003490
3491struct message_ref64 {
3492 uint64_t imp; /* IMP (64-bit pointer) */
3493 uint64_t sel; /* SEL (64-bit pointer) */
3494};
3495
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003496struct message_ref32 {
3497 uint32_t imp; /* IMP (32-bit pointer) */
3498 uint32_t sel; /* SEL (32-bit pointer) */
3499};
3500
Kevin Enderby846c0002015-04-16 17:19:59 +00003501// Objective-C 1 (32-bit only) meta data structs.
3502
3503struct objc_module_t {
3504 uint32_t version;
3505 uint32_t size;
3506 uint32_t name; /* char * (32-bit pointer) */
3507 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3508};
3509
3510struct objc_symtab_t {
3511 uint32_t sel_ref_cnt;
3512 uint32_t refs; /* SEL * (32-bit pointer) */
3513 uint16_t cls_def_cnt;
3514 uint16_t cat_def_cnt;
3515 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3516};
3517
3518struct objc_class_t {
3519 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3520 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3521 uint32_t name; /* const char * (32-bit pointer) */
3522 int32_t version;
3523 int32_t info;
3524 int32_t instance_size;
3525 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3526 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3527 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3528 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3529};
3530
3531#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3532// class is not a metaclass
3533#define CLS_CLASS 0x1
3534// class is a metaclass
3535#define CLS_META 0x2
3536
3537struct objc_category_t {
3538 uint32_t category_name; /* char * (32-bit pointer) */
3539 uint32_t class_name; /* char * (32-bit pointer) */
3540 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3541 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3542 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3543};
3544
3545struct objc_ivar_t {
3546 uint32_t ivar_name; /* char * (32-bit pointer) */
3547 uint32_t ivar_type; /* char * (32-bit pointer) */
3548 int32_t ivar_offset;
3549};
3550
3551struct objc_ivar_list_t {
3552 int32_t ivar_count;
3553 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3554};
3555
3556struct objc_method_list_t {
3557 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3558 int32_t method_count;
3559 // struct objc_method_t method_list[1]; /* variable length structure */
3560};
3561
3562struct objc_method_t {
3563 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3564 uint32_t method_types; /* char * (32-bit pointer) */
3565 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3566 (32-bit pointer) */
3567};
3568
3569struct objc_protocol_list_t {
3570 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3571 int32_t count;
3572 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3573 // (32-bit pointer) */
3574};
3575
3576struct objc_protocol_t {
3577 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3578 uint32_t protocol_name; /* char * (32-bit pointer) */
3579 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3580 uint32_t instance_methods; /* struct objc_method_description_list *
3581 (32-bit pointer) */
3582 uint32_t class_methods; /* struct objc_method_description_list *
3583 (32-bit pointer) */
3584};
3585
3586struct objc_method_description_list_t {
3587 int32_t count;
3588 // struct objc_method_description_t list[1];
3589};
3590
3591struct objc_method_description_t {
3592 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3593 uint32_t types; /* char * (32-bit pointer) */
3594};
3595
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003596inline void swapStruct(struct cfstring64_t &cfs) {
3597 sys::swapByteOrder(cfs.isa);
3598 sys::swapByteOrder(cfs.flags);
3599 sys::swapByteOrder(cfs.characters);
3600 sys::swapByteOrder(cfs.length);
3601}
3602
3603inline void swapStruct(struct class64_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 Enderby28c1c1b2015-04-06 17:47:03 +00003611inline void swapStruct(struct class32_t &c) {
3612 sys::swapByteOrder(c.isa);
3613 sys::swapByteOrder(c.superclass);
3614 sys::swapByteOrder(c.cache);
3615 sys::swapByteOrder(c.vtable);
3616 sys::swapByteOrder(c.data);
3617}
3618
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003619inline void swapStruct(struct class_ro64_t &cro) {
3620 sys::swapByteOrder(cro.flags);
3621 sys::swapByteOrder(cro.instanceStart);
3622 sys::swapByteOrder(cro.instanceSize);
3623 sys::swapByteOrder(cro.reserved);
3624 sys::swapByteOrder(cro.ivarLayout);
3625 sys::swapByteOrder(cro.name);
3626 sys::swapByteOrder(cro.baseMethods);
3627 sys::swapByteOrder(cro.baseProtocols);
3628 sys::swapByteOrder(cro.ivars);
3629 sys::swapByteOrder(cro.weakIvarLayout);
3630 sys::swapByteOrder(cro.baseProperties);
3631}
3632
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003633inline void swapStruct(struct class_ro32_t &cro) {
3634 sys::swapByteOrder(cro.flags);
3635 sys::swapByteOrder(cro.instanceStart);
3636 sys::swapByteOrder(cro.instanceSize);
3637 sys::swapByteOrder(cro.ivarLayout);
3638 sys::swapByteOrder(cro.name);
3639 sys::swapByteOrder(cro.baseMethods);
3640 sys::swapByteOrder(cro.baseProtocols);
3641 sys::swapByteOrder(cro.ivars);
3642 sys::swapByteOrder(cro.weakIvarLayout);
3643 sys::swapByteOrder(cro.baseProperties);
3644}
3645
Kevin Enderby0fc11822015-04-01 20:57:01 +00003646inline void swapStruct(struct method_list64_t &ml) {
3647 sys::swapByteOrder(ml.entsize);
3648 sys::swapByteOrder(ml.count);
3649}
3650
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003651inline void swapStruct(struct method_list32_t &ml) {
3652 sys::swapByteOrder(ml.entsize);
3653 sys::swapByteOrder(ml.count);
3654}
3655
Kevin Enderby0fc11822015-04-01 20:57:01 +00003656inline void swapStruct(struct method64_t &m) {
3657 sys::swapByteOrder(m.name);
3658 sys::swapByteOrder(m.types);
3659 sys::swapByteOrder(m.imp);
3660}
3661
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003662inline void swapStruct(struct method32_t &m) {
3663 sys::swapByteOrder(m.name);
3664 sys::swapByteOrder(m.types);
3665 sys::swapByteOrder(m.imp);
3666}
3667
Kevin Enderby0fc11822015-04-01 20:57:01 +00003668inline void swapStruct(struct protocol_list64_t &pl) {
3669 sys::swapByteOrder(pl.count);
3670}
3671
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003672inline void swapStruct(struct protocol_list32_t &pl) {
3673 sys::swapByteOrder(pl.count);
3674}
3675
Kevin Enderby0fc11822015-04-01 20:57:01 +00003676inline void swapStruct(struct protocol64_t &p) {
3677 sys::swapByteOrder(p.isa);
3678 sys::swapByteOrder(p.name);
3679 sys::swapByteOrder(p.protocols);
3680 sys::swapByteOrder(p.instanceMethods);
3681 sys::swapByteOrder(p.classMethods);
3682 sys::swapByteOrder(p.optionalInstanceMethods);
3683 sys::swapByteOrder(p.optionalClassMethods);
3684 sys::swapByteOrder(p.instanceProperties);
3685}
3686
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003687inline void swapStruct(struct protocol32_t &p) {
3688 sys::swapByteOrder(p.isa);
3689 sys::swapByteOrder(p.name);
3690 sys::swapByteOrder(p.protocols);
3691 sys::swapByteOrder(p.instanceMethods);
3692 sys::swapByteOrder(p.classMethods);
3693 sys::swapByteOrder(p.optionalInstanceMethods);
3694 sys::swapByteOrder(p.optionalClassMethods);
3695 sys::swapByteOrder(p.instanceProperties);
3696}
3697
Kevin Enderby0fc11822015-04-01 20:57:01 +00003698inline void swapStruct(struct ivar_list64_t &il) {
3699 sys::swapByteOrder(il.entsize);
3700 sys::swapByteOrder(il.count);
3701}
3702
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003703inline void swapStruct(struct ivar_list32_t &il) {
3704 sys::swapByteOrder(il.entsize);
3705 sys::swapByteOrder(il.count);
3706}
3707
Kevin Enderby0fc11822015-04-01 20:57:01 +00003708inline void swapStruct(struct ivar64_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 Enderby28c1c1b2015-04-06 17:47:03 +00003716inline void swapStruct(struct ivar32_t &i) {
3717 sys::swapByteOrder(i.offset);
3718 sys::swapByteOrder(i.name);
3719 sys::swapByteOrder(i.type);
3720 sys::swapByteOrder(i.alignment);
3721 sys::swapByteOrder(i.size);
3722}
3723
Kevin Enderby0fc11822015-04-01 20:57:01 +00003724inline void swapStruct(struct objc_property_list64 &pl) {
3725 sys::swapByteOrder(pl.entsize);
3726 sys::swapByteOrder(pl.count);
3727}
3728
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003729inline void swapStruct(struct objc_property_list32 &pl) {
3730 sys::swapByteOrder(pl.entsize);
3731 sys::swapByteOrder(pl.count);
3732}
3733
Kevin Enderby0fc11822015-04-01 20:57:01 +00003734inline void swapStruct(struct objc_property64 &op) {
3735 sys::swapByteOrder(op.name);
3736 sys::swapByteOrder(op.attributes);
3737}
3738
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003739inline void swapStruct(struct objc_property32 &op) {
3740 sys::swapByteOrder(op.name);
3741 sys::swapByteOrder(op.attributes);
3742}
3743
Kevin Enderby0fc11822015-04-01 20:57:01 +00003744inline void swapStruct(struct category64_t &c) {
3745 sys::swapByteOrder(c.name);
3746 sys::swapByteOrder(c.cls);
3747 sys::swapByteOrder(c.instanceMethods);
3748 sys::swapByteOrder(c.classMethods);
3749 sys::swapByteOrder(c.protocols);
3750 sys::swapByteOrder(c.instanceProperties);
3751}
3752
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003753inline void swapStruct(struct category32_t &c) {
3754 sys::swapByteOrder(c.name);
3755 sys::swapByteOrder(c.cls);
3756 sys::swapByteOrder(c.instanceMethods);
3757 sys::swapByteOrder(c.classMethods);
3758 sys::swapByteOrder(c.protocols);
3759 sys::swapByteOrder(c.instanceProperties);
3760}
3761
Kevin Enderby0fc11822015-04-01 20:57:01 +00003762inline void swapStruct(struct objc_image_info64 &o) {
3763 sys::swapByteOrder(o.version);
3764 sys::swapByteOrder(o.flags);
3765}
3766
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003767inline void swapStruct(struct objc_image_info32 &o) {
3768 sys::swapByteOrder(o.version);
3769 sys::swapByteOrder(o.flags);
3770}
3771
Kevin Enderby846c0002015-04-16 17:19:59 +00003772inline void swapStruct(struct imageInfo_t &o) {
3773 sys::swapByteOrder(o.version);
3774 sys::swapByteOrder(o.flags);
3775}
3776
Kevin Enderby0fc11822015-04-01 20:57:01 +00003777inline void swapStruct(struct message_ref64 &mr) {
3778 sys::swapByteOrder(mr.imp);
3779 sys::swapByteOrder(mr.sel);
3780}
3781
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003782inline void swapStruct(struct message_ref32 &mr) {
3783 sys::swapByteOrder(mr.imp);
3784 sys::swapByteOrder(mr.sel);
3785}
3786
Kevin Enderby846c0002015-04-16 17:19:59 +00003787inline void swapStruct(struct objc_module_t &module) {
3788 sys::swapByteOrder(module.version);
3789 sys::swapByteOrder(module.size);
3790 sys::swapByteOrder(module.name);
3791 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003792}
Kevin Enderby846c0002015-04-16 17:19:59 +00003793
3794inline void swapStruct(struct objc_symtab_t &symtab) {
3795 sys::swapByteOrder(symtab.sel_ref_cnt);
3796 sys::swapByteOrder(symtab.refs);
3797 sys::swapByteOrder(symtab.cls_def_cnt);
3798 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003799}
Kevin Enderby846c0002015-04-16 17:19:59 +00003800
3801inline void swapStruct(struct objc_class_t &objc_class) {
3802 sys::swapByteOrder(objc_class.isa);
3803 sys::swapByteOrder(objc_class.super_class);
3804 sys::swapByteOrder(objc_class.name);
3805 sys::swapByteOrder(objc_class.version);
3806 sys::swapByteOrder(objc_class.info);
3807 sys::swapByteOrder(objc_class.instance_size);
3808 sys::swapByteOrder(objc_class.ivars);
3809 sys::swapByteOrder(objc_class.methodLists);
3810 sys::swapByteOrder(objc_class.cache);
3811 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003812}
Kevin Enderby846c0002015-04-16 17:19:59 +00003813
3814inline void swapStruct(struct objc_category_t &objc_category) {
3815 sys::swapByteOrder(objc_category.category_name);
3816 sys::swapByteOrder(objc_category.class_name);
3817 sys::swapByteOrder(objc_category.instance_methods);
3818 sys::swapByteOrder(objc_category.class_methods);
3819 sys::swapByteOrder(objc_category.protocols);
3820}
3821
3822inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3823 sys::swapByteOrder(objc_ivar_list.ivar_count);
3824}
3825
3826inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3827 sys::swapByteOrder(objc_ivar.ivar_name);
3828 sys::swapByteOrder(objc_ivar.ivar_type);
3829 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003830}
Kevin Enderby846c0002015-04-16 17:19:59 +00003831
3832inline void swapStruct(struct objc_method_list_t &method_list) {
3833 sys::swapByteOrder(method_list.obsolete);
3834 sys::swapByteOrder(method_list.method_count);
3835}
3836
3837inline void swapStruct(struct objc_method_t &method) {
3838 sys::swapByteOrder(method.method_name);
3839 sys::swapByteOrder(method.method_types);
3840 sys::swapByteOrder(method.method_imp);
3841}
3842
3843inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3844 sys::swapByteOrder(protocol_list.next);
3845 sys::swapByteOrder(protocol_list.count);
3846}
3847
3848inline void swapStruct(struct objc_protocol_t &protocol) {
3849 sys::swapByteOrder(protocol.isa);
3850 sys::swapByteOrder(protocol.protocol_name);
3851 sys::swapByteOrder(protocol.protocol_list);
3852 sys::swapByteOrder(protocol.instance_methods);
3853 sys::swapByteOrder(protocol.class_methods);
3854}
3855
3856inline void swapStruct(struct objc_method_description_list_t &mdl) {
3857 sys::swapByteOrder(mdl.count);
3858}
3859
3860inline void swapStruct(struct objc_method_description_t &md) {
3861 sys::swapByteOrder(md.name);
3862 sys::swapByteOrder(md.types);
3863}
3864
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003865static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3866 struct DisassembleInfo *info);
3867
3868// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3869// to an Objective-C class and returns the class name. It is also passed the
3870// address of the pointer, so when the pointer is zero as it can be in an .o
3871// file, that is used to look for an external relocation entry with a symbol
3872// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003873static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3874 uint64_t ReferenceValue,
3875 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003876 const char *r;
3877 uint32_t offset, left;
3878 SectionRef S;
3879
3880 // The pointer_value can be 0 in an object file and have a relocation
3881 // entry for the class symbol at the ReferenceValue (the address of the
3882 // pointer).
3883 if (pointer_value == 0) {
3884 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3885 if (r == nullptr || left < sizeof(uint64_t))
3886 return nullptr;
3887 uint64_t n_value;
3888 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3889 if (symbol_name == nullptr)
3890 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003891 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003892 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3893 return class_name + 2;
3894 else
3895 return nullptr;
3896 }
3897
3898 // The case were the pointer_value is non-zero and points to a class defined
3899 // in this Mach-O file.
3900 r = get_pointer_64(pointer_value, offset, left, S, info);
3901 if (r == nullptr || left < sizeof(struct class64_t))
3902 return nullptr;
3903 struct class64_t c;
3904 memcpy(&c, r, sizeof(struct class64_t));
3905 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3906 swapStruct(c);
3907 if (c.data == 0)
3908 return nullptr;
3909 r = get_pointer_64(c.data, offset, left, S, info);
3910 if (r == nullptr || left < sizeof(struct class_ro64_t))
3911 return nullptr;
3912 struct class_ro64_t cro;
3913 memcpy(&cro, r, sizeof(struct class_ro64_t));
3914 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3915 swapStruct(cro);
3916 if (cro.name == 0)
3917 return nullptr;
3918 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3919 return name;
3920}
3921
3922// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3923// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003924static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3925 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003926 const char *r, *name;
3927 uint32_t offset, left;
3928 SectionRef S;
3929 struct cfstring64_t cfs;
3930 uint64_t cfs_characters;
3931
3932 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3933 if (r == nullptr || left < sizeof(struct cfstring64_t))
3934 return nullptr;
3935 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3936 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3937 swapStruct(cfs);
3938 if (cfs.characters == 0) {
3939 uint64_t n_value;
3940 const char *symbol_name = get_symbol_64(
3941 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3942 if (symbol_name == nullptr)
3943 return nullptr;
3944 cfs_characters = n_value;
3945 } else
3946 cfs_characters = cfs.characters;
3947 name = get_pointer_64(cfs_characters, offset, left, S, info);
3948
3949 return name;
3950}
3951
3952// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3953// of a pointer to an Objective-C selector reference when the pointer value is
3954// zero as in a .o file and is likely to have a external relocation entry with
3955// who's symbol's n_value is the real pointer to the selector name. If that is
3956// the case the real pointer to the selector name is returned else 0 is
3957// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003958static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3959 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003960 uint32_t offset, left;
3961 SectionRef S;
3962
3963 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3964 if (r == nullptr || left < sizeof(uint64_t))
3965 return 0;
3966 uint64_t n_value;
3967 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3968 if (symbol_name == nullptr)
3969 return 0;
3970 return n_value;
3971}
3972
Kevin Enderby0fc11822015-04-01 20:57:01 +00003973static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3974 const char *sectname) {
3975 for (const SectionRef &Section : O->sections()) {
3976 StringRef SectName;
3977 Section.getName(SectName);
3978 DataRefImpl Ref = Section.getRawDataRefImpl();
3979 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3980 if (SegName == segname && SectName == sectname)
3981 return Section;
3982 }
3983 return SectionRef();
3984}
3985
3986static void
3987walk_pointer_list_64(const char *listname, const SectionRef S,
3988 MachOObjectFile *O, struct DisassembleInfo *info,
3989 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3990 if (S == SectionRef())
3991 return;
3992
3993 StringRef SectName;
3994 S.getName(SectName);
3995 DataRefImpl Ref = S.getRawDataRefImpl();
3996 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3997 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3998
3999 StringRef BytesStr;
4000 S.getContents(BytesStr);
4001 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4002
4003 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4004 uint32_t left = S.getSize() - i;
4005 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4006 uint64_t p = 0;
4007 memcpy(&p, Contents + i, size);
4008 if (i + sizeof(uint64_t) > S.getSize())
4009 outs() << listname << " list pointer extends past end of (" << SegName
4010 << "," << SectName << ") section\n";
4011 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4012
4013 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4014 sys::swapByteOrder(p);
4015
4016 uint64_t n_value = 0;
4017 const char *name = get_symbol_64(i, S, info, n_value, p);
4018 if (name == nullptr)
4019 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4020
4021 if (n_value != 0) {
4022 outs() << format("0x%" PRIx64, n_value);
4023 if (p != 0)
4024 outs() << " + " << format("0x%" PRIx64, p);
4025 } else
4026 outs() << format("0x%" PRIx64, p);
4027 if (name != nullptr)
4028 outs() << " " << name;
4029 outs() << "\n";
4030
4031 p += n_value;
4032 if (func)
4033 func(p, info);
4034 }
4035}
4036
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004037static void
4038walk_pointer_list_32(const char *listname, const SectionRef S,
4039 MachOObjectFile *O, struct DisassembleInfo *info,
4040 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4041 if (S == SectionRef())
4042 return;
4043
4044 StringRef SectName;
4045 S.getName(SectName);
4046 DataRefImpl Ref = S.getRawDataRefImpl();
4047 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4048 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4049
4050 StringRef BytesStr;
4051 S.getContents(BytesStr);
4052 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4053
4054 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4055 uint32_t left = S.getSize() - i;
4056 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4057 uint32_t p = 0;
4058 memcpy(&p, Contents + i, size);
4059 if (i + sizeof(uint32_t) > S.getSize())
4060 outs() << listname << " list pointer extends past end of (" << SegName
4061 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004062 uint32_t Address = S.getAddress() + i;
4063 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004064
4065 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4066 sys::swapByteOrder(p);
4067 outs() << format("0x%" PRIx32, p);
4068
4069 const char *name = get_symbol_32(i, S, info, p);
4070 if (name != nullptr)
4071 outs() << " " << name;
4072 outs() << "\n";
4073
4074 if (func)
4075 func(p, info);
4076 }
4077}
4078
4079static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004080 if (layout_map == nullptr)
4081 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004082 outs() << " layout map: ";
4083 do {
4084 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4085 left--;
4086 layout_map++;
4087 } while (*layout_map != '\0' && left != 0);
4088 outs() << "\n";
4089}
4090
Kevin Enderby0fc11822015-04-01 20:57:01 +00004091static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4092 uint32_t offset, left;
4093 SectionRef S;
4094 const char *layout_map;
4095
4096 if (p == 0)
4097 return;
4098 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004099 print_layout_map(layout_map, left);
4100}
4101
4102static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4103 uint32_t offset, left;
4104 SectionRef S;
4105 const char *layout_map;
4106
4107 if (p == 0)
4108 return;
4109 layout_map = get_pointer_32(p, offset, left, S, info);
4110 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004111}
4112
4113static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4114 const char *indent) {
4115 struct method_list64_t ml;
4116 struct method64_t m;
4117 const char *r;
4118 uint32_t offset, xoffset, left, i;
4119 SectionRef S, xS;
4120 const char *name, *sym_name;
4121 uint64_t n_value;
4122
4123 r = get_pointer_64(p, offset, left, S, info);
4124 if (r == nullptr)
4125 return;
4126 memset(&ml, '\0', sizeof(struct method_list64_t));
4127 if (left < sizeof(struct method_list64_t)) {
4128 memcpy(&ml, r, left);
4129 outs() << " (method_list_t entends past the end of the section)\n";
4130 } else
4131 memcpy(&ml, r, sizeof(struct method_list64_t));
4132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4133 swapStruct(ml);
4134 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4135 outs() << indent << "\t\t count " << ml.count << "\n";
4136
4137 p += sizeof(struct method_list64_t);
4138 offset += sizeof(struct method_list64_t);
4139 for (i = 0; i < ml.count; i++) {
4140 r = get_pointer_64(p, offset, left, S, info);
4141 if (r == nullptr)
4142 return;
4143 memset(&m, '\0', sizeof(struct method64_t));
4144 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004145 memcpy(&m, r, left);
4146 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004147 } else
4148 memcpy(&m, r, sizeof(struct method64_t));
4149 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4150 swapStruct(m);
4151
4152 outs() << indent << "\t\t name ";
4153 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4154 info, n_value, m.name);
4155 if (n_value != 0) {
4156 if (info->verbose && sym_name != nullptr)
4157 outs() << sym_name;
4158 else
4159 outs() << format("0x%" PRIx64, n_value);
4160 if (m.name != 0)
4161 outs() << " + " << format("0x%" PRIx64, m.name);
4162 } else
4163 outs() << format("0x%" PRIx64, m.name);
4164 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4165 if (name != nullptr)
4166 outs() << format(" %.*s", left, name);
4167 outs() << "\n";
4168
4169 outs() << indent << "\t\t types ";
4170 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4171 info, n_value, m.types);
4172 if (n_value != 0) {
4173 if (info->verbose && sym_name != nullptr)
4174 outs() << sym_name;
4175 else
4176 outs() << format("0x%" PRIx64, n_value);
4177 if (m.types != 0)
4178 outs() << " + " << format("0x%" PRIx64, m.types);
4179 } else
4180 outs() << format("0x%" PRIx64, m.types);
4181 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4182 if (name != nullptr)
4183 outs() << format(" %.*s", left, name);
4184 outs() << "\n";
4185
4186 outs() << indent << "\t\t imp ";
4187 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4188 n_value, m.imp);
4189 if (info->verbose && name == nullptr) {
4190 if (n_value != 0) {
4191 outs() << format("0x%" PRIx64, n_value) << " ";
4192 if (m.imp != 0)
4193 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4194 } else
4195 outs() << format("0x%" PRIx64, m.imp) << " ";
4196 }
4197 if (name != nullptr)
4198 outs() << name;
4199 outs() << "\n";
4200
4201 p += sizeof(struct method64_t);
4202 offset += sizeof(struct method64_t);
4203 }
4204}
4205
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004206static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4207 const char *indent) {
4208 struct method_list32_t ml;
4209 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004210 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004211 uint32_t offset, xoffset, left, i;
4212 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004213
4214 r = get_pointer_32(p, offset, left, S, info);
4215 if (r == nullptr)
4216 return;
4217 memset(&ml, '\0', sizeof(struct method_list32_t));
4218 if (left < sizeof(struct method_list32_t)) {
4219 memcpy(&ml, r, left);
4220 outs() << " (method_list_t entends past the end of the section)\n";
4221 } else
4222 memcpy(&ml, r, sizeof(struct method_list32_t));
4223 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4224 swapStruct(ml);
4225 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4226 outs() << indent << "\t\t count " << ml.count << "\n";
4227
4228 p += sizeof(struct method_list32_t);
4229 offset += sizeof(struct method_list32_t);
4230 for (i = 0; i < ml.count; i++) {
4231 r = get_pointer_32(p, offset, left, S, info);
4232 if (r == nullptr)
4233 return;
4234 memset(&m, '\0', sizeof(struct method32_t));
4235 if (left < sizeof(struct method32_t)) {
4236 memcpy(&ml, r, left);
4237 outs() << indent << " (method_t entends past the end of the section)\n";
4238 } else
4239 memcpy(&m, r, sizeof(struct method32_t));
4240 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4241 swapStruct(m);
4242
4243 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4244 name = get_pointer_32(m.name, xoffset, left, xS, info);
4245 if (name != nullptr)
4246 outs() << format(" %.*s", left, name);
4247 outs() << "\n";
4248
4249 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4250 name = get_pointer_32(m.types, xoffset, left, xS, info);
4251 if (name != nullptr)
4252 outs() << format(" %.*s", left, name);
4253 outs() << "\n";
4254
4255 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4256 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4257 m.imp);
4258 if (name != nullptr)
4259 outs() << " " << name;
4260 outs() << "\n";
4261
4262 p += sizeof(struct method32_t);
4263 offset += sizeof(struct method32_t);
4264 }
4265}
4266
Kevin Enderby846c0002015-04-16 17:19:59 +00004267static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4268 uint32_t offset, left, xleft;
4269 SectionRef S;
4270 struct objc_method_list_t method_list;
4271 struct objc_method_t method;
4272 const char *r, *methods, *name, *SymbolName;
4273 int32_t i;
4274
4275 r = get_pointer_32(p, offset, left, S, info, true);
4276 if (r == nullptr)
4277 return true;
4278
4279 outs() << "\n";
4280 if (left > sizeof(struct objc_method_list_t)) {
4281 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4282 } else {
4283 outs() << "\t\t objc_method_list extends past end of the section\n";
4284 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4285 memcpy(&method_list, r, left);
4286 }
4287 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4288 swapStruct(method_list);
4289
4290 outs() << "\t\t obsolete "
4291 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4292 outs() << "\t\t method_count " << method_list.method_count << "\n";
4293
4294 methods = r + sizeof(struct objc_method_list_t);
4295 for (i = 0; i < method_list.method_count; i++) {
4296 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4297 outs() << "\t\t remaining method's extend past the of the section\n";
4298 break;
4299 }
4300 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4301 sizeof(struct objc_method_t));
4302 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4303 swapStruct(method);
4304
4305 outs() << "\t\t method_name "
4306 << format("0x%08" PRIx32, method.method_name);
4307 if (info->verbose) {
4308 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4309 if (name != nullptr)
4310 outs() << format(" %.*s", xleft, name);
4311 else
4312 outs() << " (not in an __OBJC section)";
4313 }
4314 outs() << "\n";
4315
4316 outs() << "\t\t method_types "
4317 << format("0x%08" PRIx32, method.method_types);
4318 if (info->verbose) {
4319 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4320 if (name != nullptr)
4321 outs() << format(" %.*s", xleft, name);
4322 else
4323 outs() << " (not in an __OBJC section)";
4324 }
4325 outs() << "\n";
4326
4327 outs() << "\t\t method_imp "
4328 << format("0x%08" PRIx32, method.method_imp) << " ";
4329 if (info->verbose) {
4330 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4331 if (SymbolName != nullptr)
4332 outs() << SymbolName;
4333 }
4334 outs() << "\n";
4335 }
4336 return false;
4337}
4338
Kevin Enderby0fc11822015-04-01 20:57:01 +00004339static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4340 struct protocol_list64_t pl;
4341 uint64_t q, n_value;
4342 struct protocol64_t pc;
4343 const char *r;
4344 uint32_t offset, xoffset, left, i;
4345 SectionRef S, xS;
4346 const char *name, *sym_name;
4347
4348 r = get_pointer_64(p, offset, left, S, info);
4349 if (r == nullptr)
4350 return;
4351 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4352 if (left < sizeof(struct protocol_list64_t)) {
4353 memcpy(&pl, r, left);
4354 outs() << " (protocol_list_t entends past the end of the section)\n";
4355 } else
4356 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4357 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4358 swapStruct(pl);
4359 outs() << " count " << pl.count << "\n";
4360
4361 p += sizeof(struct protocol_list64_t);
4362 offset += sizeof(struct protocol_list64_t);
4363 for (i = 0; i < pl.count; i++) {
4364 r = get_pointer_64(p, offset, left, S, info);
4365 if (r == nullptr)
4366 return;
4367 q = 0;
4368 if (left < sizeof(uint64_t)) {
4369 memcpy(&q, r, left);
4370 outs() << " (protocol_t * entends past the end of the section)\n";
4371 } else
4372 memcpy(&q, r, sizeof(uint64_t));
4373 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4374 sys::swapByteOrder(q);
4375
4376 outs() << "\t\t list[" << i << "] ";
4377 sym_name = get_symbol_64(offset, S, info, n_value, q);
4378 if (n_value != 0) {
4379 if (info->verbose && sym_name != nullptr)
4380 outs() << sym_name;
4381 else
4382 outs() << format("0x%" PRIx64, n_value);
4383 if (q != 0)
4384 outs() << " + " << format("0x%" PRIx64, q);
4385 } else
4386 outs() << format("0x%" PRIx64, q);
4387 outs() << " (struct protocol_t *)\n";
4388
4389 r = get_pointer_64(q + n_value, offset, left, S, info);
4390 if (r == nullptr)
4391 return;
4392 memset(&pc, '\0', sizeof(struct protocol64_t));
4393 if (left < sizeof(struct protocol64_t)) {
4394 memcpy(&pc, r, left);
4395 outs() << " (protocol_t entends past the end of the section)\n";
4396 } else
4397 memcpy(&pc, r, sizeof(struct protocol64_t));
4398 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4399 swapStruct(pc);
4400
4401 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4402
4403 outs() << "\t\t\t name ";
4404 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4405 info, n_value, pc.name);
4406 if (n_value != 0) {
4407 if (info->verbose && sym_name != nullptr)
4408 outs() << sym_name;
4409 else
4410 outs() << format("0x%" PRIx64, n_value);
4411 if (pc.name != 0)
4412 outs() << " + " << format("0x%" PRIx64, pc.name);
4413 } else
4414 outs() << format("0x%" PRIx64, pc.name);
4415 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4416 if (name != nullptr)
4417 outs() << format(" %.*s", left, name);
4418 outs() << "\n";
4419
4420 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4421
4422 outs() << "\t\t instanceMethods ";
4423 sym_name =
4424 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4425 S, info, n_value, pc.instanceMethods);
4426 if (n_value != 0) {
4427 if (info->verbose && sym_name != nullptr)
4428 outs() << sym_name;
4429 else
4430 outs() << format("0x%" PRIx64, n_value);
4431 if (pc.instanceMethods != 0)
4432 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4433 } else
4434 outs() << format("0x%" PRIx64, pc.instanceMethods);
4435 outs() << " (struct method_list_t *)\n";
4436 if (pc.instanceMethods + n_value != 0)
4437 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4438
4439 outs() << "\t\t classMethods ";
4440 sym_name =
4441 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4442 info, n_value, pc.classMethods);
4443 if (n_value != 0) {
4444 if (info->verbose && sym_name != nullptr)
4445 outs() << sym_name;
4446 else
4447 outs() << format("0x%" PRIx64, n_value);
4448 if (pc.classMethods != 0)
4449 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4450 } else
4451 outs() << format("0x%" PRIx64, pc.classMethods);
4452 outs() << " (struct method_list_t *)\n";
4453 if (pc.classMethods + n_value != 0)
4454 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4455
4456 outs() << "\t optionalInstanceMethods "
4457 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4458 outs() << "\t optionalClassMethods "
4459 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4460 outs() << "\t instanceProperties "
4461 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4462
4463 p += sizeof(uint64_t);
4464 offset += sizeof(uint64_t);
4465 }
4466}
4467
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004468static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4469 struct protocol_list32_t pl;
4470 uint32_t q;
4471 struct protocol32_t pc;
4472 const char *r;
4473 uint32_t offset, xoffset, left, i;
4474 SectionRef S, xS;
4475 const char *name;
4476
4477 r = get_pointer_32(p, offset, left, S, info);
4478 if (r == nullptr)
4479 return;
4480 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4481 if (left < sizeof(struct protocol_list32_t)) {
4482 memcpy(&pl, r, left);
4483 outs() << " (protocol_list_t entends past the end of the section)\n";
4484 } else
4485 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4486 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4487 swapStruct(pl);
4488 outs() << " count " << pl.count << "\n";
4489
4490 p += sizeof(struct protocol_list32_t);
4491 offset += sizeof(struct protocol_list32_t);
4492 for (i = 0; i < pl.count; i++) {
4493 r = get_pointer_32(p, offset, left, S, info);
4494 if (r == nullptr)
4495 return;
4496 q = 0;
4497 if (left < sizeof(uint32_t)) {
4498 memcpy(&q, r, left);
4499 outs() << " (protocol_t * entends past the end of the section)\n";
4500 } else
4501 memcpy(&q, r, sizeof(uint32_t));
4502 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4503 sys::swapByteOrder(q);
4504 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4505 << " (struct protocol_t *)\n";
4506 r = get_pointer_32(q, offset, left, S, info);
4507 if (r == nullptr)
4508 return;
4509 memset(&pc, '\0', sizeof(struct protocol32_t));
4510 if (left < sizeof(struct protocol32_t)) {
4511 memcpy(&pc, r, left);
4512 outs() << " (protocol_t entends past the end of the section)\n";
4513 } else
4514 memcpy(&pc, r, sizeof(struct protocol32_t));
4515 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4516 swapStruct(pc);
4517 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4518 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4519 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4520 if (name != nullptr)
4521 outs() << format(" %.*s", left, name);
4522 outs() << "\n";
4523 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4524 outs() << "\t\t instanceMethods "
4525 << format("0x%" PRIx32, pc.instanceMethods)
4526 << " (struct method_list_t *)\n";
4527 if (pc.instanceMethods != 0)
4528 print_method_list32_t(pc.instanceMethods, info, "\t");
4529 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4530 << " (struct method_list_t *)\n";
4531 if (pc.classMethods != 0)
4532 print_method_list32_t(pc.classMethods, info, "\t");
4533 outs() << "\t optionalInstanceMethods "
4534 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4535 outs() << "\t optionalClassMethods "
4536 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4537 outs() << "\t instanceProperties "
4538 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4539 p += sizeof(uint32_t);
4540 offset += sizeof(uint32_t);
4541 }
4542}
4543
Kevin Enderby846c0002015-04-16 17:19:59 +00004544static void print_indent(uint32_t indent) {
4545 for (uint32_t i = 0; i < indent;) {
4546 if (indent - i >= 8) {
4547 outs() << "\t";
4548 i += 8;
4549 } else {
4550 for (uint32_t j = i; j < indent; j++)
4551 outs() << " ";
4552 return;
4553 }
4554 }
4555}
4556
4557static bool print_method_description_list(uint32_t p, uint32_t indent,
4558 struct DisassembleInfo *info) {
4559 uint32_t offset, left, xleft;
4560 SectionRef S;
4561 struct objc_method_description_list_t mdl;
4562 struct objc_method_description_t md;
4563 const char *r, *list, *name;
4564 int32_t i;
4565
4566 r = get_pointer_32(p, offset, left, S, info, true);
4567 if (r == nullptr)
4568 return true;
4569
4570 outs() << "\n";
4571 if (left > sizeof(struct objc_method_description_list_t)) {
4572 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4573 } else {
4574 print_indent(indent);
4575 outs() << " objc_method_description_list extends past end of the section\n";
4576 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4577 memcpy(&mdl, r, left);
4578 }
4579 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4580 swapStruct(mdl);
4581
4582 print_indent(indent);
4583 outs() << " count " << mdl.count << "\n";
4584
4585 list = r + sizeof(struct objc_method_description_list_t);
4586 for (i = 0; i < mdl.count; i++) {
4587 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4588 print_indent(indent);
4589 outs() << " remaining list entries extend past the of the section\n";
4590 break;
4591 }
4592 print_indent(indent);
4593 outs() << " list[" << i << "]\n";
4594 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4595 sizeof(struct objc_method_description_t));
4596 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4597 swapStruct(md);
4598
4599 print_indent(indent);
4600 outs() << " name " << format("0x%08" PRIx32, md.name);
4601 if (info->verbose) {
4602 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4603 if (name != nullptr)
4604 outs() << format(" %.*s", xleft, name);
4605 else
4606 outs() << " (not in an __OBJC section)";
4607 }
4608 outs() << "\n";
4609
4610 print_indent(indent);
4611 outs() << " types " << format("0x%08" PRIx32, md.types);
4612 if (info->verbose) {
4613 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4614 if (name != nullptr)
4615 outs() << format(" %.*s", xleft, name);
4616 else
4617 outs() << " (not in an __OBJC section)";
4618 }
4619 outs() << "\n";
4620 }
4621 return false;
4622}
4623
4624static bool print_protocol_list(uint32_t p, uint32_t indent,
4625 struct DisassembleInfo *info);
4626
4627static bool print_protocol(uint32_t p, uint32_t indent,
4628 struct DisassembleInfo *info) {
4629 uint32_t offset, left;
4630 SectionRef S;
4631 struct objc_protocol_t protocol;
4632 const char *r, *name;
4633
4634 r = get_pointer_32(p, offset, left, S, info, true);
4635 if (r == nullptr)
4636 return true;
4637
4638 outs() << "\n";
4639 if (left >= sizeof(struct objc_protocol_t)) {
4640 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4641 } else {
4642 print_indent(indent);
4643 outs() << " Protocol extends past end of the section\n";
4644 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4645 memcpy(&protocol, r, left);
4646 }
4647 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4648 swapStruct(protocol);
4649
4650 print_indent(indent);
4651 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4652 << "\n";
4653
4654 print_indent(indent);
4655 outs() << " protocol_name "
4656 << format("0x%08" PRIx32, protocol.protocol_name);
4657 if (info->verbose) {
4658 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4659 if (name != nullptr)
4660 outs() << format(" %.*s", left, name);
4661 else
4662 outs() << " (not in an __OBJC section)";
4663 }
4664 outs() << "\n";
4665
4666 print_indent(indent);
4667 outs() << " protocol_list "
4668 << format("0x%08" PRIx32, protocol.protocol_list);
4669 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4670 outs() << " (not in an __OBJC section)\n";
4671
4672 print_indent(indent);
4673 outs() << " instance_methods "
4674 << format("0x%08" PRIx32, protocol.instance_methods);
4675 if (print_method_description_list(protocol.instance_methods, indent, info))
4676 outs() << " (not in an __OBJC section)\n";
4677
4678 print_indent(indent);
4679 outs() << " class_methods "
4680 << format("0x%08" PRIx32, protocol.class_methods);
4681 if (print_method_description_list(protocol.class_methods, indent, info))
4682 outs() << " (not in an __OBJC section)\n";
4683
4684 return false;
4685}
4686
4687static bool print_protocol_list(uint32_t p, uint32_t indent,
4688 struct DisassembleInfo *info) {
4689 uint32_t offset, left, l;
4690 SectionRef S;
4691 struct objc_protocol_list_t protocol_list;
4692 const char *r, *list;
4693 int32_t i;
4694
4695 r = get_pointer_32(p, offset, left, S, info, true);
4696 if (r == nullptr)
4697 return true;
4698
4699 outs() << "\n";
4700 if (left > sizeof(struct objc_protocol_list_t)) {
4701 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4702 } else {
4703 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4704 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4705 memcpy(&protocol_list, r, left);
4706 }
4707 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4708 swapStruct(protocol_list);
4709
4710 print_indent(indent);
4711 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4712 << "\n";
4713 print_indent(indent);
4714 outs() << " count " << protocol_list.count << "\n";
4715
4716 list = r + sizeof(struct objc_protocol_list_t);
4717 for (i = 0; i < protocol_list.count; i++) {
4718 if ((i + 1) * sizeof(uint32_t) > left) {
4719 outs() << "\t\t remaining list entries extend past the of the section\n";
4720 break;
4721 }
4722 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4723 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4724 sys::swapByteOrder(l);
4725
4726 print_indent(indent);
4727 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4728 if (print_protocol(l, indent, info))
4729 outs() << "(not in an __OBJC section)\n";
4730 }
4731 return false;
4732}
4733
Kevin Enderby0fc11822015-04-01 20:57:01 +00004734static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4735 struct ivar_list64_t il;
4736 struct ivar64_t i;
4737 const char *r;
4738 uint32_t offset, xoffset, left, j;
4739 SectionRef S, xS;
4740 const char *name, *sym_name, *ivar_offset_p;
4741 uint64_t ivar_offset, n_value;
4742
4743 r = get_pointer_64(p, offset, left, S, info);
4744 if (r == nullptr)
4745 return;
4746 memset(&il, '\0', sizeof(struct ivar_list64_t));
4747 if (left < sizeof(struct ivar_list64_t)) {
4748 memcpy(&il, r, left);
4749 outs() << " (ivar_list_t entends past the end of the section)\n";
4750 } else
4751 memcpy(&il, r, sizeof(struct ivar_list64_t));
4752 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4753 swapStruct(il);
4754 outs() << " entsize " << il.entsize << "\n";
4755 outs() << " count " << il.count << "\n";
4756
4757 p += sizeof(struct ivar_list64_t);
4758 offset += sizeof(struct ivar_list64_t);
4759 for (j = 0; j < il.count; j++) {
4760 r = get_pointer_64(p, offset, left, S, info);
4761 if (r == nullptr)
4762 return;
4763 memset(&i, '\0', sizeof(struct ivar64_t));
4764 if (left < sizeof(struct ivar64_t)) {
4765 memcpy(&i, r, left);
4766 outs() << " (ivar_t entends past the end of the section)\n";
4767 } else
4768 memcpy(&i, r, sizeof(struct ivar64_t));
4769 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4770 swapStruct(i);
4771
4772 outs() << "\t\t\t offset ";
4773 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4774 info, n_value, i.offset);
4775 if (n_value != 0) {
4776 if (info->verbose && sym_name != nullptr)
4777 outs() << sym_name;
4778 else
4779 outs() << format("0x%" PRIx64, n_value);
4780 if (i.offset != 0)
4781 outs() << " + " << format("0x%" PRIx64, i.offset);
4782 } else
4783 outs() << format("0x%" PRIx64, i.offset);
4784 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4785 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4786 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4787 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4788 sys::swapByteOrder(ivar_offset);
4789 outs() << " " << ivar_offset << "\n";
4790 } else
4791 outs() << "\n";
4792
4793 outs() << "\t\t\t name ";
4794 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4795 n_value, i.name);
4796 if (n_value != 0) {
4797 if (info->verbose && sym_name != nullptr)
4798 outs() << sym_name;
4799 else
4800 outs() << format("0x%" PRIx64, n_value);
4801 if (i.name != 0)
4802 outs() << " + " << format("0x%" PRIx64, i.name);
4803 } else
4804 outs() << format("0x%" PRIx64, i.name);
4805 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4806 if (name != nullptr)
4807 outs() << format(" %.*s", left, name);
4808 outs() << "\n";
4809
4810 outs() << "\t\t\t type ";
4811 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4812 n_value, i.name);
4813 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4814 if (n_value != 0) {
4815 if (info->verbose && sym_name != nullptr)
4816 outs() << sym_name;
4817 else
4818 outs() << format("0x%" PRIx64, n_value);
4819 if (i.type != 0)
4820 outs() << " + " << format("0x%" PRIx64, i.type);
4821 } else
4822 outs() << format("0x%" PRIx64, i.type);
4823 if (name != nullptr)
4824 outs() << format(" %.*s", left, name);
4825 outs() << "\n";
4826
4827 outs() << "\t\t\talignment " << i.alignment << "\n";
4828 outs() << "\t\t\t size " << i.size << "\n";
4829
4830 p += sizeof(struct ivar64_t);
4831 offset += sizeof(struct ivar64_t);
4832 }
4833}
4834
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004835static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4836 struct ivar_list32_t il;
4837 struct ivar32_t i;
4838 const char *r;
4839 uint32_t offset, xoffset, left, j;
4840 SectionRef S, xS;
4841 const char *name, *ivar_offset_p;
4842 uint32_t ivar_offset;
4843
4844 r = get_pointer_32(p, offset, left, S, info);
4845 if (r == nullptr)
4846 return;
4847 memset(&il, '\0', sizeof(struct ivar_list32_t));
4848 if (left < sizeof(struct ivar_list32_t)) {
4849 memcpy(&il, r, left);
4850 outs() << " (ivar_list_t entends past the end of the section)\n";
4851 } else
4852 memcpy(&il, r, sizeof(struct ivar_list32_t));
4853 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4854 swapStruct(il);
4855 outs() << " entsize " << il.entsize << "\n";
4856 outs() << " count " << il.count << "\n";
4857
4858 p += sizeof(struct ivar_list32_t);
4859 offset += sizeof(struct ivar_list32_t);
4860 for (j = 0; j < il.count; j++) {
4861 r = get_pointer_32(p, offset, left, S, info);
4862 if (r == nullptr)
4863 return;
4864 memset(&i, '\0', sizeof(struct ivar32_t));
4865 if (left < sizeof(struct ivar32_t)) {
4866 memcpy(&i, r, left);
4867 outs() << " (ivar_t entends past the end of the section)\n";
4868 } else
4869 memcpy(&i, r, sizeof(struct ivar32_t));
4870 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4871 swapStruct(i);
4872
4873 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4874 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4875 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4876 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4877 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4878 sys::swapByteOrder(ivar_offset);
4879 outs() << " " << ivar_offset << "\n";
4880 } else
4881 outs() << "\n";
4882
4883 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4884 name = get_pointer_32(i.name, xoffset, left, xS, info);
4885 if (name != nullptr)
4886 outs() << format(" %.*s", left, name);
4887 outs() << "\n";
4888
4889 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4890 name = get_pointer_32(i.type, xoffset, left, xS, info);
4891 if (name != nullptr)
4892 outs() << format(" %.*s", left, name);
4893 outs() << "\n";
4894
4895 outs() << "\t\t\talignment " << i.alignment << "\n";
4896 outs() << "\t\t\t size " << i.size << "\n";
4897
4898 p += sizeof(struct ivar32_t);
4899 offset += sizeof(struct ivar32_t);
4900 }
4901}
4902
Kevin Enderby0fc11822015-04-01 20:57:01 +00004903static void print_objc_property_list64(uint64_t p,
4904 struct DisassembleInfo *info) {
4905 struct objc_property_list64 opl;
4906 struct objc_property64 op;
4907 const char *r;
4908 uint32_t offset, xoffset, left, j;
4909 SectionRef S, xS;
4910 const char *name, *sym_name;
4911 uint64_t n_value;
4912
4913 r = get_pointer_64(p, offset, left, S, info);
4914 if (r == nullptr)
4915 return;
4916 memset(&opl, '\0', sizeof(struct objc_property_list64));
4917 if (left < sizeof(struct objc_property_list64)) {
4918 memcpy(&opl, r, left);
4919 outs() << " (objc_property_list entends past the end of the section)\n";
4920 } else
4921 memcpy(&opl, r, sizeof(struct objc_property_list64));
4922 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4923 swapStruct(opl);
4924 outs() << " entsize " << opl.entsize << "\n";
4925 outs() << " count " << opl.count << "\n";
4926
4927 p += sizeof(struct objc_property_list64);
4928 offset += sizeof(struct objc_property_list64);
4929 for (j = 0; j < opl.count; j++) {
4930 r = get_pointer_64(p, offset, left, S, info);
4931 if (r == nullptr)
4932 return;
4933 memset(&op, '\0', sizeof(struct objc_property64));
4934 if (left < sizeof(struct objc_property64)) {
4935 memcpy(&op, r, left);
4936 outs() << " (objc_property entends past the end of the section)\n";
4937 } else
4938 memcpy(&op, r, sizeof(struct objc_property64));
4939 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4940 swapStruct(op);
4941
4942 outs() << "\t\t\t name ";
4943 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4944 info, n_value, op.name);
4945 if (n_value != 0) {
4946 if (info->verbose && sym_name != nullptr)
4947 outs() << sym_name;
4948 else
4949 outs() << format("0x%" PRIx64, n_value);
4950 if (op.name != 0)
4951 outs() << " + " << format("0x%" PRIx64, op.name);
4952 } else
4953 outs() << format("0x%" PRIx64, op.name);
4954 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4955 if (name != nullptr)
4956 outs() << format(" %.*s", left, name);
4957 outs() << "\n";
4958
4959 outs() << "\t\t\tattributes ";
4960 sym_name =
4961 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4962 info, n_value, op.attributes);
4963 if (n_value != 0) {
4964 if (info->verbose && sym_name != nullptr)
4965 outs() << sym_name;
4966 else
4967 outs() << format("0x%" PRIx64, n_value);
4968 if (op.attributes != 0)
4969 outs() << " + " << format("0x%" PRIx64, op.attributes);
4970 } else
4971 outs() << format("0x%" PRIx64, op.attributes);
4972 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4973 if (name != nullptr)
4974 outs() << format(" %.*s", left, name);
4975 outs() << "\n";
4976
4977 p += sizeof(struct objc_property64);
4978 offset += sizeof(struct objc_property64);
4979 }
4980}
4981
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004982static void print_objc_property_list32(uint32_t p,
4983 struct DisassembleInfo *info) {
4984 struct objc_property_list32 opl;
4985 struct objc_property32 op;
4986 const char *r;
4987 uint32_t offset, xoffset, left, j;
4988 SectionRef S, xS;
4989 const char *name;
4990
4991 r = get_pointer_32(p, offset, left, S, info);
4992 if (r == nullptr)
4993 return;
4994 memset(&opl, '\0', sizeof(struct objc_property_list32));
4995 if (left < sizeof(struct objc_property_list32)) {
4996 memcpy(&opl, r, left);
4997 outs() << " (objc_property_list entends past the end of the section)\n";
4998 } else
4999 memcpy(&opl, r, sizeof(struct objc_property_list32));
5000 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5001 swapStruct(opl);
5002 outs() << " entsize " << opl.entsize << "\n";
5003 outs() << " count " << opl.count << "\n";
5004
5005 p += sizeof(struct objc_property_list32);
5006 offset += sizeof(struct objc_property_list32);
5007 for (j = 0; j < opl.count; j++) {
5008 r = get_pointer_32(p, offset, left, S, info);
5009 if (r == nullptr)
5010 return;
5011 memset(&op, '\0', sizeof(struct objc_property32));
5012 if (left < sizeof(struct objc_property32)) {
5013 memcpy(&op, r, left);
5014 outs() << " (objc_property entends past the end of the section)\n";
5015 } else
5016 memcpy(&op, r, sizeof(struct objc_property32));
5017 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5018 swapStruct(op);
5019
5020 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5021 name = get_pointer_32(op.name, xoffset, left, xS, info);
5022 if (name != nullptr)
5023 outs() << format(" %.*s", left, name);
5024 outs() << "\n";
5025
5026 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5027 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5028 if (name != nullptr)
5029 outs() << format(" %.*s", left, name);
5030 outs() << "\n";
5031
5032 p += sizeof(struct objc_property32);
5033 offset += sizeof(struct objc_property32);
5034 }
5035}
5036
Richard Smith81ff44d2015-10-09 22:09:56 +00005037static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005038 bool &is_meta_class) {
5039 struct class_ro64_t cro;
5040 const char *r;
5041 uint32_t offset, xoffset, left;
5042 SectionRef S, xS;
5043 const char *name, *sym_name;
5044 uint64_t n_value;
5045
5046 r = get_pointer_64(p, offset, left, S, info);
5047 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005048 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005049 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005050 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5051 swapStruct(cro);
5052 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5053 if (cro.flags & RO_META)
5054 outs() << " RO_META";
5055 if (cro.flags & RO_ROOT)
5056 outs() << " RO_ROOT";
5057 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5058 outs() << " RO_HAS_CXX_STRUCTORS";
5059 outs() << "\n";
5060 outs() << " instanceStart " << cro.instanceStart << "\n";
5061 outs() << " instanceSize " << cro.instanceSize << "\n";
5062 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5063 << "\n";
5064 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5065 << "\n";
5066 print_layout_map64(cro.ivarLayout, info);
5067
5068 outs() << " name ";
5069 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5070 info, n_value, cro.name);
5071 if (n_value != 0) {
5072 if (info->verbose && sym_name != nullptr)
5073 outs() << sym_name;
5074 else
5075 outs() << format("0x%" PRIx64, n_value);
5076 if (cro.name != 0)
5077 outs() << " + " << format("0x%" PRIx64, cro.name);
5078 } else
5079 outs() << format("0x%" PRIx64, cro.name);
5080 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5081 if (name != nullptr)
5082 outs() << format(" %.*s", left, name);
5083 outs() << "\n";
5084
5085 outs() << " baseMethods ";
5086 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5087 S, info, n_value, cro.baseMethods);
5088 if (n_value != 0) {
5089 if (info->verbose && sym_name != nullptr)
5090 outs() << sym_name;
5091 else
5092 outs() << format("0x%" PRIx64, n_value);
5093 if (cro.baseMethods != 0)
5094 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5095 } else
5096 outs() << format("0x%" PRIx64, cro.baseMethods);
5097 outs() << " (struct method_list_t *)\n";
5098 if (cro.baseMethods + n_value != 0)
5099 print_method_list64_t(cro.baseMethods + n_value, info, "");
5100
5101 outs() << " baseProtocols ";
5102 sym_name =
5103 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5104 info, n_value, cro.baseProtocols);
5105 if (n_value != 0) {
5106 if (info->verbose && sym_name != nullptr)
5107 outs() << sym_name;
5108 else
5109 outs() << format("0x%" PRIx64, n_value);
5110 if (cro.baseProtocols != 0)
5111 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5112 } else
5113 outs() << format("0x%" PRIx64, cro.baseProtocols);
5114 outs() << "\n";
5115 if (cro.baseProtocols + n_value != 0)
5116 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5117
5118 outs() << " ivars ";
5119 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005120 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005121 if (n_value != 0) {
5122 if (info->verbose && sym_name != nullptr)
5123 outs() << sym_name;
5124 else
5125 outs() << format("0x%" PRIx64, n_value);
5126 if (cro.ivars != 0)
5127 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5128 } else
5129 outs() << format("0x%" PRIx64, cro.ivars);
5130 outs() << "\n";
5131 if (cro.ivars + n_value != 0)
5132 print_ivar_list64_t(cro.ivars + n_value, info);
5133
5134 outs() << " weakIvarLayout ";
5135 sym_name =
5136 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5137 info, n_value, cro.weakIvarLayout);
5138 if (n_value != 0) {
5139 if (info->verbose && sym_name != nullptr)
5140 outs() << sym_name;
5141 else
5142 outs() << format("0x%" PRIx64, n_value);
5143 if (cro.weakIvarLayout != 0)
5144 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5145 } else
5146 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5147 outs() << "\n";
5148 print_layout_map64(cro.weakIvarLayout + n_value, info);
5149
5150 outs() << " baseProperties ";
5151 sym_name =
5152 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5153 info, n_value, cro.baseProperties);
5154 if (n_value != 0) {
5155 if (info->verbose && sym_name != nullptr)
5156 outs() << sym_name;
5157 else
5158 outs() << format("0x%" PRIx64, n_value);
5159 if (cro.baseProperties != 0)
5160 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5161 } else
5162 outs() << format("0x%" PRIx64, cro.baseProperties);
5163 outs() << "\n";
5164 if (cro.baseProperties + n_value != 0)
5165 print_objc_property_list64(cro.baseProperties + n_value, info);
5166
Rafael Espindolab9091322015-10-24 23:19:10 +00005167 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005168 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005169}
5170
Richard Smith81ff44d2015-10-09 22:09:56 +00005171static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005172 bool &is_meta_class) {
5173 struct class_ro32_t cro;
5174 const char *r;
5175 uint32_t offset, xoffset, left;
5176 SectionRef S, xS;
5177 const char *name;
5178
5179 r = get_pointer_32(p, offset, left, S, info);
5180 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005181 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005182 memset(&cro, '\0', sizeof(struct class_ro32_t));
5183 if (left < sizeof(struct class_ro32_t)) {
5184 memcpy(&cro, r, left);
5185 outs() << " (class_ro_t entends past the end of the section)\n";
5186 } else
5187 memcpy(&cro, r, sizeof(struct class_ro32_t));
5188 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5189 swapStruct(cro);
5190 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5191 if (cro.flags & RO_META)
5192 outs() << " RO_META";
5193 if (cro.flags & RO_ROOT)
5194 outs() << " RO_ROOT";
5195 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5196 outs() << " RO_HAS_CXX_STRUCTORS";
5197 outs() << "\n";
5198 outs() << " instanceStart " << cro.instanceStart << "\n";
5199 outs() << " instanceSize " << cro.instanceSize << "\n";
5200 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5201 << "\n";
5202 print_layout_map32(cro.ivarLayout, info);
5203
5204 outs() << " name " << format("0x%" PRIx32, cro.name);
5205 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5206 if (name != nullptr)
5207 outs() << format(" %.*s", left, name);
5208 outs() << "\n";
5209
5210 outs() << " baseMethods "
5211 << format("0x%" PRIx32, cro.baseMethods)
5212 << " (struct method_list_t *)\n";
5213 if (cro.baseMethods != 0)
5214 print_method_list32_t(cro.baseMethods, info, "");
5215
5216 outs() << " baseProtocols "
5217 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5218 if (cro.baseProtocols != 0)
5219 print_protocol_list32_t(cro.baseProtocols, info);
5220 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5221 << "\n";
5222 if (cro.ivars != 0)
5223 print_ivar_list32_t(cro.ivars, info);
5224 outs() << " weakIvarLayout "
5225 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5226 print_layout_map32(cro.weakIvarLayout, info);
5227 outs() << " baseProperties "
5228 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5229 if (cro.baseProperties != 0)
5230 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005231 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005232 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005233}
5234
Kevin Enderby0fc11822015-04-01 20:57:01 +00005235static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5236 struct class64_t c;
5237 const char *r;
5238 uint32_t offset, left;
5239 SectionRef S;
5240 const char *name;
5241 uint64_t isa_n_value, n_value;
5242
5243 r = get_pointer_64(p, offset, left, S, info);
5244 if (r == nullptr || left < sizeof(struct class64_t))
5245 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005246 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005247 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5248 swapStruct(c);
5249
5250 outs() << " isa " << format("0x%" PRIx64, c.isa);
5251 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5252 isa_n_value, c.isa);
5253 if (name != nullptr)
5254 outs() << " " << name;
5255 outs() << "\n";
5256
5257 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5258 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5259 n_value, c.superclass);
5260 if (name != nullptr)
5261 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005262 else {
5263 name = get_dyld_bind_info_symbolname(S.getAddress() +
5264 offset + offsetof(struct class64_t, superclass), info);
5265 if (name != nullptr)
5266 outs() << " " << name;
5267 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005268 outs() << "\n";
5269
5270 outs() << " cache " << format("0x%" PRIx64, c.cache);
5271 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5272 n_value, c.cache);
5273 if (name != nullptr)
5274 outs() << " " << name;
5275 outs() << "\n";
5276
5277 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5278 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5279 n_value, c.vtable);
5280 if (name != nullptr)
5281 outs() << " " << name;
5282 outs() << "\n";
5283
5284 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5285 n_value, c.data);
5286 outs() << " data ";
5287 if (n_value != 0) {
5288 if (info->verbose && name != nullptr)
5289 outs() << name;
5290 else
5291 outs() << format("0x%" PRIx64, n_value);
5292 if (c.data != 0)
5293 outs() << " + " << format("0x%" PRIx64, c.data);
5294 } else
5295 outs() << format("0x%" PRIx64, c.data);
5296 outs() << " (struct class_ro_t *)";
5297
5298 // This is a Swift class if some of the low bits of the pointer are set.
5299 if ((c.data + n_value) & 0x7)
5300 outs() << " Swift class";
5301 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005302 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005303 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5304 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005305
Kevin Enderbyaac75382015-10-08 16:56:35 +00005306 if (!is_meta_class &&
5307 c.isa + isa_n_value != p &&
5308 c.isa + isa_n_value != 0 &&
5309 info->depth < 100) {
5310 info->depth++;
5311 outs() << "Meta Class\n";
5312 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005313 }
5314}
5315
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005316static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5317 struct class32_t c;
5318 const char *r;
5319 uint32_t offset, left;
5320 SectionRef S;
5321 const char *name;
5322
5323 r = get_pointer_32(p, offset, left, S, info);
5324 if (r == nullptr)
5325 return;
5326 memset(&c, '\0', sizeof(struct class32_t));
5327 if (left < sizeof(struct class32_t)) {
5328 memcpy(&c, r, left);
5329 outs() << " (class_t entends past the end of the section)\n";
5330 } else
5331 memcpy(&c, r, sizeof(struct class32_t));
5332 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5333 swapStruct(c);
5334
5335 outs() << " isa " << format("0x%" PRIx32, c.isa);
5336 name =
5337 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5338 if (name != nullptr)
5339 outs() << " " << name;
5340 outs() << "\n";
5341
5342 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5343 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5344 c.superclass);
5345 if (name != nullptr)
5346 outs() << " " << name;
5347 outs() << "\n";
5348
5349 outs() << " cache " << format("0x%" PRIx32, c.cache);
5350 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5351 c.cache);
5352 if (name != nullptr)
5353 outs() << " " << name;
5354 outs() << "\n";
5355
5356 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5357 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5358 c.vtable);
5359 if (name != nullptr)
5360 outs() << " " << name;
5361 outs() << "\n";
5362
5363 name =
5364 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5365 outs() << " data " << format("0x%" PRIx32, c.data)
5366 << " (struct class_ro_t *)";
5367
5368 // This is a Swift class if some of the low bits of the pointer are set.
5369 if (c.data & 0x3)
5370 outs() << " Swift class";
5371 outs() << "\n";
5372 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005373 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5374 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005375
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005376 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005377 outs() << "Meta Class\n";
5378 print_class32_t(c.isa, info);
5379 }
5380}
5381
Kevin Enderby846c0002015-04-16 17:19:59 +00005382static void print_objc_class_t(struct objc_class_t *objc_class,
5383 struct DisassembleInfo *info) {
5384 uint32_t offset, left, xleft;
5385 const char *name, *p, *ivar_list;
5386 SectionRef S;
5387 int32_t i;
5388 struct objc_ivar_list_t objc_ivar_list;
5389 struct objc_ivar_t ivar;
5390
5391 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5392 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5393 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5394 if (name != nullptr)
5395 outs() << format(" %.*s", left, name);
5396 else
5397 outs() << " (not in an __OBJC section)";
5398 }
5399 outs() << "\n";
5400
5401 outs() << "\t super_class "
5402 << format("0x%08" PRIx32, objc_class->super_class);
5403 if (info->verbose) {
5404 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5405 if (name != nullptr)
5406 outs() << format(" %.*s", left, name);
5407 else
5408 outs() << " (not in an __OBJC section)";
5409 }
5410 outs() << "\n";
5411
5412 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5413 if (info->verbose) {
5414 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5415 if (name != nullptr)
5416 outs() << format(" %.*s", left, name);
5417 else
5418 outs() << " (not in an __OBJC section)";
5419 }
5420 outs() << "\n";
5421
5422 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5423 << "\n";
5424
5425 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5426 if (info->verbose) {
5427 if (CLS_GETINFO(objc_class, CLS_CLASS))
5428 outs() << " CLS_CLASS";
5429 else if (CLS_GETINFO(objc_class, CLS_META))
5430 outs() << " CLS_META";
5431 }
5432 outs() << "\n";
5433
5434 outs() << "\t instance_size "
5435 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5436
5437 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5438 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5439 if (p != nullptr) {
5440 if (left > sizeof(struct objc_ivar_list_t)) {
5441 outs() << "\n";
5442 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5443 } else {
5444 outs() << " (entends past the end of the section)\n";
5445 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5446 memcpy(&objc_ivar_list, p, left);
5447 }
5448 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5449 swapStruct(objc_ivar_list);
5450 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5451 ivar_list = p + sizeof(struct objc_ivar_list_t);
5452 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5453 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5454 outs() << "\t\t remaining ivar's extend past the of the section\n";
5455 break;
5456 }
5457 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5458 sizeof(struct objc_ivar_t));
5459 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5460 swapStruct(ivar);
5461
5462 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5463 if (info->verbose) {
5464 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5465 if (name != nullptr)
5466 outs() << format(" %.*s", xleft, name);
5467 else
5468 outs() << " (not in an __OBJC section)";
5469 }
5470 outs() << "\n";
5471
5472 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5473 if (info->verbose) {
5474 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5475 if (name != nullptr)
5476 outs() << format(" %.*s", xleft, name);
5477 else
5478 outs() << " (not in an __OBJC section)";
5479 }
5480 outs() << "\n";
5481
5482 outs() << "\t\t ivar_offset "
5483 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5484 }
5485 } else {
5486 outs() << " (not in an __OBJC section)\n";
5487 }
5488
5489 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5490 if (print_method_list(objc_class->methodLists, info))
5491 outs() << " (not in an __OBJC section)\n";
5492
5493 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5494 << "\n";
5495
5496 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5497 if (print_protocol_list(objc_class->protocols, 16, info))
5498 outs() << " (not in an __OBJC section)\n";
5499}
5500
5501static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5502 struct DisassembleInfo *info) {
5503 uint32_t offset, left;
5504 const char *name;
5505 SectionRef S;
5506
5507 outs() << "\t category name "
5508 << format("0x%08" PRIx32, objc_category->category_name);
5509 if (info->verbose) {
5510 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5511 true);
5512 if (name != nullptr)
5513 outs() << format(" %.*s", left, name);
5514 else
5515 outs() << " (not in an __OBJC section)";
5516 }
5517 outs() << "\n";
5518
5519 outs() << "\t\t class name "
5520 << format("0x%08" PRIx32, objc_category->class_name);
5521 if (info->verbose) {
5522 name =
5523 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5524 if (name != nullptr)
5525 outs() << format(" %.*s", left, name);
5526 else
5527 outs() << " (not in an __OBJC section)";
5528 }
5529 outs() << "\n";
5530
5531 outs() << "\t instance methods "
5532 << format("0x%08" PRIx32, objc_category->instance_methods);
5533 if (print_method_list(objc_category->instance_methods, info))
5534 outs() << " (not in an __OBJC section)\n";
5535
5536 outs() << "\t class methods "
5537 << format("0x%08" PRIx32, objc_category->class_methods);
5538 if (print_method_list(objc_category->class_methods, info))
5539 outs() << " (not in an __OBJC section)\n";
5540}
5541
Kevin Enderby0fc11822015-04-01 20:57:01 +00005542static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5543 struct category64_t c;
5544 const char *r;
5545 uint32_t offset, xoffset, left;
5546 SectionRef S, xS;
5547 const char *name, *sym_name;
5548 uint64_t n_value;
5549
5550 r = get_pointer_64(p, offset, left, S, info);
5551 if (r == nullptr)
5552 return;
5553 memset(&c, '\0', sizeof(struct category64_t));
5554 if (left < sizeof(struct category64_t)) {
5555 memcpy(&c, r, left);
5556 outs() << " (category_t entends past the end of the section)\n";
5557 } else
5558 memcpy(&c, r, sizeof(struct category64_t));
5559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5560 swapStruct(c);
5561
5562 outs() << " name ";
5563 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5564 info, n_value, c.name);
5565 if (n_value != 0) {
5566 if (info->verbose && sym_name != nullptr)
5567 outs() << sym_name;
5568 else
5569 outs() << format("0x%" PRIx64, n_value);
5570 if (c.name != 0)
5571 outs() << " + " << format("0x%" PRIx64, c.name);
5572 } else
5573 outs() << format("0x%" PRIx64, c.name);
5574 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5575 if (name != nullptr)
5576 outs() << format(" %.*s", left, name);
5577 outs() << "\n";
5578
5579 outs() << " cls ";
5580 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5581 n_value, c.cls);
5582 if (n_value != 0) {
5583 if (info->verbose && sym_name != nullptr)
5584 outs() << sym_name;
5585 else
5586 outs() << format("0x%" PRIx64, n_value);
5587 if (c.cls != 0)
5588 outs() << " + " << format("0x%" PRIx64, c.cls);
5589 } else
5590 outs() << format("0x%" PRIx64, c.cls);
5591 outs() << "\n";
5592 if (c.cls + n_value != 0)
5593 print_class64_t(c.cls + n_value, info);
5594
5595 outs() << " instanceMethods ";
5596 sym_name =
5597 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5598 info, n_value, c.instanceMethods);
5599 if (n_value != 0) {
5600 if (info->verbose && sym_name != nullptr)
5601 outs() << sym_name;
5602 else
5603 outs() << format("0x%" PRIx64, n_value);
5604 if (c.instanceMethods != 0)
5605 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5606 } else
5607 outs() << format("0x%" PRIx64, c.instanceMethods);
5608 outs() << "\n";
5609 if (c.instanceMethods + n_value != 0)
5610 print_method_list64_t(c.instanceMethods + n_value, info, "");
5611
5612 outs() << " classMethods ";
5613 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5614 S, info, n_value, c.classMethods);
5615 if (n_value != 0) {
5616 if (info->verbose && sym_name != nullptr)
5617 outs() << sym_name;
5618 else
5619 outs() << format("0x%" PRIx64, n_value);
5620 if (c.classMethods != 0)
5621 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5622 } else
5623 outs() << format("0x%" PRIx64, c.classMethods);
5624 outs() << "\n";
5625 if (c.classMethods + n_value != 0)
5626 print_method_list64_t(c.classMethods + n_value, info, "");
5627
5628 outs() << " protocols ";
5629 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5630 info, n_value, c.protocols);
5631 if (n_value != 0) {
5632 if (info->verbose && sym_name != nullptr)
5633 outs() << sym_name;
5634 else
5635 outs() << format("0x%" PRIx64, n_value);
5636 if (c.protocols != 0)
5637 outs() << " + " << format("0x%" PRIx64, c.protocols);
5638 } else
5639 outs() << format("0x%" PRIx64, c.protocols);
5640 outs() << "\n";
5641 if (c.protocols + n_value != 0)
5642 print_protocol_list64_t(c.protocols + n_value, info);
5643
5644 outs() << "instanceProperties ";
5645 sym_name =
5646 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5647 S, info, n_value, c.instanceProperties);
5648 if (n_value != 0) {
5649 if (info->verbose && sym_name != nullptr)
5650 outs() << sym_name;
5651 else
5652 outs() << format("0x%" PRIx64, n_value);
5653 if (c.instanceProperties != 0)
5654 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5655 } else
5656 outs() << format("0x%" PRIx64, c.instanceProperties);
5657 outs() << "\n";
5658 if (c.instanceProperties + n_value != 0)
5659 print_objc_property_list64(c.instanceProperties + n_value, info);
5660}
5661
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005662static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5663 struct category32_t c;
5664 const char *r;
5665 uint32_t offset, left;
5666 SectionRef S, xS;
5667 const char *name;
5668
5669 r = get_pointer_32(p, offset, left, S, info);
5670 if (r == nullptr)
5671 return;
5672 memset(&c, '\0', sizeof(struct category32_t));
5673 if (left < sizeof(struct category32_t)) {
5674 memcpy(&c, r, left);
5675 outs() << " (category_t entends past the end of the section)\n";
5676 } else
5677 memcpy(&c, r, sizeof(struct category32_t));
5678 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5679 swapStruct(c);
5680
5681 outs() << " name " << format("0x%" PRIx32, c.name);
5682 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5683 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005684 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005685 outs() << " " << name;
5686 outs() << "\n";
5687
5688 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5689 if (c.cls != 0)
5690 print_class32_t(c.cls, info);
5691 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5692 << "\n";
5693 if (c.instanceMethods != 0)
5694 print_method_list32_t(c.instanceMethods, info, "");
5695 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5696 << "\n";
5697 if (c.classMethods != 0)
5698 print_method_list32_t(c.classMethods, info, "");
5699 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5700 if (c.protocols != 0)
5701 print_protocol_list32_t(c.protocols, info);
5702 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5703 << "\n";
5704 if (c.instanceProperties != 0)
5705 print_objc_property_list32(c.instanceProperties, info);
5706}
5707
Kevin Enderby0fc11822015-04-01 20:57:01 +00005708static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5709 uint32_t i, left, offset, xoffset;
5710 uint64_t p, n_value;
5711 struct message_ref64 mr;
5712 const char *name, *sym_name;
5713 const char *r;
5714 SectionRef xS;
5715
5716 if (S == SectionRef())
5717 return;
5718
5719 StringRef SectName;
5720 S.getName(SectName);
5721 DataRefImpl Ref = S.getRawDataRefImpl();
5722 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5723 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5724 offset = 0;
5725 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5726 p = S.getAddress() + i;
5727 r = get_pointer_64(p, offset, left, S, info);
5728 if (r == nullptr)
5729 return;
5730 memset(&mr, '\0', sizeof(struct message_ref64));
5731 if (left < sizeof(struct message_ref64)) {
5732 memcpy(&mr, r, left);
5733 outs() << " (message_ref entends past the end of the section)\n";
5734 } else
5735 memcpy(&mr, r, sizeof(struct message_ref64));
5736 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5737 swapStruct(mr);
5738
5739 outs() << " imp ";
5740 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5741 n_value, mr.imp);
5742 if (n_value != 0) {
5743 outs() << format("0x%" PRIx64, n_value) << " ";
5744 if (mr.imp != 0)
5745 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5746 } else
5747 outs() << format("0x%" PRIx64, mr.imp) << " ";
5748 if (name != nullptr)
5749 outs() << " " << name;
5750 outs() << "\n";
5751
5752 outs() << " sel ";
5753 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5754 info, n_value, mr.sel);
5755 if (n_value != 0) {
5756 if (info->verbose && sym_name != nullptr)
5757 outs() << sym_name;
5758 else
5759 outs() << format("0x%" PRIx64, n_value);
5760 if (mr.sel != 0)
5761 outs() << " + " << format("0x%" PRIx64, mr.sel);
5762 } else
5763 outs() << format("0x%" PRIx64, mr.sel);
5764 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5765 if (name != nullptr)
5766 outs() << format(" %.*s", left, name);
5767 outs() << "\n";
5768
5769 offset += sizeof(struct message_ref64);
5770 }
5771}
5772
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005773static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5774 uint32_t i, left, offset, xoffset, p;
5775 struct message_ref32 mr;
5776 const char *name, *r;
5777 SectionRef xS;
5778
5779 if (S == SectionRef())
5780 return;
5781
5782 StringRef SectName;
5783 S.getName(SectName);
5784 DataRefImpl Ref = S.getRawDataRefImpl();
5785 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5786 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5787 offset = 0;
5788 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5789 p = S.getAddress() + i;
5790 r = get_pointer_32(p, offset, left, S, info);
5791 if (r == nullptr)
5792 return;
5793 memset(&mr, '\0', sizeof(struct message_ref32));
5794 if (left < sizeof(struct message_ref32)) {
5795 memcpy(&mr, r, left);
5796 outs() << " (message_ref entends past the end of the section)\n";
5797 } else
5798 memcpy(&mr, r, sizeof(struct message_ref32));
5799 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5800 swapStruct(mr);
5801
5802 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5803 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5804 mr.imp);
5805 if (name != nullptr)
5806 outs() << " " << name;
5807 outs() << "\n";
5808
5809 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5810 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5811 if (name != nullptr)
5812 outs() << " " << name;
5813 outs() << "\n";
5814
5815 offset += sizeof(struct message_ref32);
5816 }
5817}
5818
Kevin Enderby0fc11822015-04-01 20:57:01 +00005819static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5820 uint32_t left, offset, swift_version;
5821 uint64_t p;
5822 struct objc_image_info64 o;
5823 const char *r;
5824
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005825 if (S == SectionRef())
5826 return;
5827
Kevin Enderby0fc11822015-04-01 20:57:01 +00005828 StringRef SectName;
5829 S.getName(SectName);
5830 DataRefImpl Ref = S.getRawDataRefImpl();
5831 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5832 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5833 p = S.getAddress();
5834 r = get_pointer_64(p, offset, left, S, info);
5835 if (r == nullptr)
5836 return;
5837 memset(&o, '\0', sizeof(struct objc_image_info64));
5838 if (left < sizeof(struct objc_image_info64)) {
5839 memcpy(&o, r, left);
5840 outs() << " (objc_image_info entends past the end of the section)\n";
5841 } else
5842 memcpy(&o, r, sizeof(struct objc_image_info64));
5843 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5844 swapStruct(o);
5845 outs() << " version " << o.version << "\n";
5846 outs() << " flags " << format("0x%" PRIx32, o.flags);
5847 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5848 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5849 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5850 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005851 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5852 outs() << " OBJC_IMAGE_IS_SIMULATED";
5853 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5854 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005855 swift_version = (o.flags >> 8) & 0xff;
5856 if (swift_version != 0) {
5857 if (swift_version == 1)
5858 outs() << " Swift 1.0";
5859 else if (swift_version == 2)
5860 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005861 else if(swift_version == 3)
5862 outs() << " Swift 2.0";
5863 else if(swift_version == 4)
5864 outs() << " Swift 3.0";
5865 else if(swift_version == 5)
5866 outs() << " Swift 4.0";
5867 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005868 outs() << " Swift 4.1/Swift 4.2";
5869 else if(swift_version == 7)
5870 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005871 else
5872 outs() << " unknown future Swift version (" << swift_version << ")";
5873 }
5874 outs() << "\n";
5875}
5876
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005877static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5878 uint32_t left, offset, swift_version, p;
5879 struct objc_image_info32 o;
5880 const char *r;
5881
Kevin Enderby19be2512016-04-21 19:49:29 +00005882 if (S == SectionRef())
5883 return;
5884
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005885 StringRef SectName;
5886 S.getName(SectName);
5887 DataRefImpl Ref = S.getRawDataRefImpl();
5888 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5889 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5890 p = S.getAddress();
5891 r = get_pointer_32(p, offset, left, S, info);
5892 if (r == nullptr)
5893 return;
5894 memset(&o, '\0', sizeof(struct objc_image_info32));
5895 if (left < sizeof(struct objc_image_info32)) {
5896 memcpy(&o, r, left);
5897 outs() << " (objc_image_info entends past the end of the section)\n";
5898 } else
5899 memcpy(&o, r, sizeof(struct objc_image_info32));
5900 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5901 swapStruct(o);
5902 outs() << " version " << o.version << "\n";
5903 outs() << " flags " << format("0x%" PRIx32, o.flags);
5904 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5905 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5906 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5907 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5908 swift_version = (o.flags >> 8) & 0xff;
5909 if (swift_version != 0) {
5910 if (swift_version == 1)
5911 outs() << " Swift 1.0";
5912 else if (swift_version == 2)
5913 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005914 else if(swift_version == 3)
5915 outs() << " Swift 2.0";
5916 else if(swift_version == 4)
5917 outs() << " Swift 3.0";
5918 else if(swift_version == 5)
5919 outs() << " Swift 4.0";
5920 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005921 outs() << " Swift 4.1/Swift 4.2";
5922 else if(swift_version == 7)
5923 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005924 else
5925 outs() << " unknown future Swift version (" << swift_version << ")";
5926 }
5927 outs() << "\n";
5928}
5929
Kevin Enderby846c0002015-04-16 17:19:59 +00005930static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5931 uint32_t left, offset, p;
5932 struct imageInfo_t o;
5933 const char *r;
5934
5935 StringRef SectName;
5936 S.getName(SectName);
5937 DataRefImpl Ref = S.getRawDataRefImpl();
5938 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5939 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5940 p = S.getAddress();
5941 r = get_pointer_32(p, offset, left, S, info);
5942 if (r == nullptr)
5943 return;
5944 memset(&o, '\0', sizeof(struct imageInfo_t));
5945 if (left < sizeof(struct imageInfo_t)) {
5946 memcpy(&o, r, left);
5947 outs() << " (imageInfo entends past the end of the section)\n";
5948 } else
5949 memcpy(&o, r, sizeof(struct imageInfo_t));
5950 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5951 swapStruct(o);
5952 outs() << " version " << o.version << "\n";
5953 outs() << " flags " << format("0x%" PRIx32, o.flags);
5954 if (o.flags & 0x1)
5955 outs() << " F&C";
5956 if (o.flags & 0x2)
5957 outs() << " GC";
5958 if (o.flags & 0x4)
5959 outs() << " GC-only";
5960 else
5961 outs() << " RR";
5962 outs() << "\n";
5963}
5964
Kevin Enderby0fc11822015-04-01 20:57:01 +00005965static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5966 SymbolAddressMap AddrMap;
5967 if (verbose)
5968 CreateSymbolAddressMap(O, &AddrMap);
5969
5970 std::vector<SectionRef> Sections;
5971 for (const SectionRef &Section : O->sections()) {
5972 StringRef SectName;
5973 Section.getName(SectName);
5974 Sections.push_back(Section);
5975 }
5976
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005977 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005978
Davide Italiano62507042015-12-11 22:27:59 +00005979 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5980 if (CL == SectionRef())
5981 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005982 if (CL == SectionRef())
5983 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5984 if (CL == SectionRef())
5985 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005986 info.S = CL;
5987 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005988
Davide Italiano62507042015-12-11 22:27:59 +00005989 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5990 if (CR == SectionRef())
5991 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005992 if (CR == SectionRef())
5993 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5994 if (CR == SectionRef())
5995 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005996 info.S = CR;
5997 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005998
Davide Italiano62507042015-12-11 22:27:59 +00005999 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6000 if (SR == SectionRef())
6001 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006002 if (SR == SectionRef())
6003 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6004 if (SR == SectionRef())
6005 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006006 info.S = SR;
6007 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006008
Davide Italiano62507042015-12-11 22:27:59 +00006009 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6010 if (CA == SectionRef())
6011 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006012 if (CA == SectionRef())
6013 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6014 if (CA == SectionRef())
6015 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00006016 info.S = CA;
6017 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006018
Davide Italiano62507042015-12-11 22:27:59 +00006019 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6020 if (PL == SectionRef())
6021 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006022 if (PL == SectionRef())
6023 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6024 if (PL == SectionRef())
6025 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00006026 info.S = PL;
6027 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006028
Davide Italiano62507042015-12-11 22:27:59 +00006029 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6030 if (MR == SectionRef())
6031 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006032 if (MR == SectionRef())
6033 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6034 if (MR == SectionRef())
6035 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006036 info.S = MR;
6037 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006038
Davide Italiano62507042015-12-11 22:27:59 +00006039 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6040 if (II == SectionRef())
6041 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006042 if (II == SectionRef())
6043 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6044 if (II == SectionRef())
6045 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006046 info.S = II;
6047 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006048}
6049
6050static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006051 SymbolAddressMap AddrMap;
6052 if (verbose)
6053 CreateSymbolAddressMap(O, &AddrMap);
6054
6055 std::vector<SectionRef> Sections;
6056 for (const SectionRef &Section : O->sections()) {
6057 StringRef SectName;
6058 Section.getName(SectName);
6059 Sections.push_back(Section);
6060 }
6061
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006062 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006063
Kevin Enderby5879a482017-02-09 17:56:26 +00006064 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6065 if (CL == SectionRef())
6066 CL = get_section(O, "__DATA", "__objc_classlist");
6067 if (CL == SectionRef())
6068 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6069 if (CL == SectionRef())
6070 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6071 info.S = CL;
6072 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006073
Kevin Enderby5879a482017-02-09 17:56:26 +00006074 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6075 if (CR == SectionRef())
6076 CR = get_section(O, "__DATA", "__objc_classrefs");
6077 if (CR == SectionRef())
6078 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6079 if (CR == SectionRef())
6080 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6081 info.S = CR;
6082 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006083
Kevin Enderby5879a482017-02-09 17:56:26 +00006084 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6085 if (SR == SectionRef())
6086 SR = get_section(O, "__DATA", "__objc_superrefs");
6087 if (SR == SectionRef())
6088 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6089 if (SR == SectionRef())
6090 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6091 info.S = SR;
6092 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006093
Kevin Enderby5879a482017-02-09 17:56:26 +00006094 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6095 if (CA == SectionRef())
6096 CA = get_section(O, "__DATA", "__objc_catlist");
6097 if (CA == SectionRef())
6098 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6099 if (CA == SectionRef())
6100 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6101 info.S = CA;
6102 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006103
Kevin Enderby5879a482017-02-09 17:56:26 +00006104 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6105 if (PL == SectionRef())
6106 PL = get_section(O, "__DATA", "__objc_protolist");
6107 if (PL == SectionRef())
6108 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6109 if (PL == SectionRef())
6110 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6111 info.S = PL;
6112 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006113
Kevin Enderby5879a482017-02-09 17:56:26 +00006114 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6115 if (MR == SectionRef())
6116 MR = get_section(O, "__DATA", "__objc_msgrefs");
6117 if (MR == SectionRef())
6118 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6119 if (MR == SectionRef())
6120 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6121 info.S = MR;
6122 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006123
Kevin Enderby5879a482017-02-09 17:56:26 +00006124 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6125 if (II == SectionRef())
6126 II = get_section(O, "__DATA", "__objc_imageinfo");
6127 if (II == SectionRef())
6128 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6129 if (II == SectionRef())
6130 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6131 info.S = II;
6132 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006133}
6134
6135static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006136 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6137 const char *r, *name, *defs;
6138 struct objc_module_t module;
6139 SectionRef S, xS;
6140 struct objc_symtab_t symtab;
6141 struct objc_class_t objc_class;
6142 struct objc_category_t objc_category;
6143
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006144 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006145 S = get_section(O, "__OBJC", "__module_info");
6146 if (S == SectionRef())
6147 return false;
6148
6149 SymbolAddressMap AddrMap;
6150 if (verbose)
6151 CreateSymbolAddressMap(O, &AddrMap);
6152
6153 std::vector<SectionRef> Sections;
6154 for (const SectionRef &Section : O->sections()) {
6155 StringRef SectName;
6156 Section.getName(SectName);
6157 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006158 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006159
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006160 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006161
6162 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6163 p = S.getAddress() + i;
6164 r = get_pointer_32(p, offset, left, S, &info, true);
6165 if (r == nullptr)
6166 return true;
6167 memset(&module, '\0', sizeof(struct objc_module_t));
6168 if (left < sizeof(struct objc_module_t)) {
6169 memcpy(&module, r, left);
6170 outs() << " (module extends past end of __module_info section)\n";
6171 } else
6172 memcpy(&module, r, sizeof(struct objc_module_t));
6173 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6174 swapStruct(module);
6175
6176 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6177 outs() << " version " << module.version << "\n";
6178 outs() << " size " << module.size << "\n";
6179 outs() << " name ";
6180 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6181 if (name != nullptr)
6182 outs() << format("%.*s", left, name);
6183 else
6184 outs() << format("0x%08" PRIx32, module.name)
6185 << "(not in an __OBJC section)";
6186 outs() << "\n";
6187
6188 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6189 if (module.symtab == 0 || r == nullptr) {
6190 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6191 << " (not in an __OBJC section)\n";
6192 continue;
6193 }
6194 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6195 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6196 defs_left = 0;
6197 defs = nullptr;
6198 if (left < sizeof(struct objc_symtab_t)) {
6199 memcpy(&symtab, r, left);
6200 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6201 } else {
6202 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6203 if (left > sizeof(struct objc_symtab_t)) {
6204 defs_left = left - sizeof(struct objc_symtab_t);
6205 defs = r + sizeof(struct objc_symtab_t);
6206 }
6207 }
6208 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6209 swapStruct(symtab);
6210
6211 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6212 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6213 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6214 if (r == nullptr)
6215 outs() << " (not in an __OBJC section)";
6216 outs() << "\n";
6217 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6218 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6219 if (symtab.cls_def_cnt > 0)
6220 outs() << "\tClass Definitions\n";
6221 for (j = 0; j < symtab.cls_def_cnt; j++) {
6222 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6223 outs() << "\t(remaining class defs entries entends past the end of the "
6224 << "section)\n";
6225 break;
6226 }
6227 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6228 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6229 sys::swapByteOrder(def);
6230
6231 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6232 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6233 if (r != nullptr) {
6234 if (left > sizeof(struct objc_class_t)) {
6235 outs() << "\n";
6236 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6237 } else {
6238 outs() << " (entends past the end of the section)\n";
6239 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6240 memcpy(&objc_class, r, left);
6241 }
6242 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6243 swapStruct(objc_class);
6244 print_objc_class_t(&objc_class, &info);
6245 } else {
6246 outs() << "(not in an __OBJC section)\n";
6247 }
6248
6249 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6250 outs() << "\tMeta Class";
6251 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6252 if (r != nullptr) {
6253 if (left > sizeof(struct objc_class_t)) {
6254 outs() << "\n";
6255 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6256 } else {
6257 outs() << " (entends past the end of the section)\n";
6258 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6259 memcpy(&objc_class, r, left);
6260 }
6261 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6262 swapStruct(objc_class);
6263 print_objc_class_t(&objc_class, &info);
6264 } else {
6265 outs() << "(not in an __OBJC section)\n";
6266 }
6267 }
6268 }
6269 if (symtab.cat_def_cnt > 0)
6270 outs() << "\tCategory Definitions\n";
6271 for (j = 0; j < symtab.cat_def_cnt; j++) {
6272 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6273 outs() << "\t(remaining category defs entries entends past the end of "
6274 << "the section)\n";
6275 break;
6276 }
6277 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6278 sizeof(uint32_t));
6279 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6280 sys::swapByteOrder(def);
6281
6282 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6283 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6284 << format("0x%08" PRIx32, def);
6285 if (r != nullptr) {
6286 if (left > sizeof(struct objc_category_t)) {
6287 outs() << "\n";
6288 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6289 } else {
6290 outs() << " (entends past the end of the section)\n";
6291 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6292 memcpy(&objc_category, r, left);
6293 }
6294 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6295 swapStruct(objc_category);
6296 print_objc_objc_category_t(&objc_category, &info);
6297 } else {
6298 outs() << "(not in an __OBJC section)\n";
6299 }
6300 }
6301 }
6302 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6303 if (II != SectionRef())
6304 print_image_info(II, &info);
6305
6306 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006307}
6308
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006309static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6310 uint32_t size, uint32_t addr) {
6311 SymbolAddressMap AddrMap;
6312 CreateSymbolAddressMap(O, &AddrMap);
6313
6314 std::vector<SectionRef> Sections;
6315 for (const SectionRef &Section : O->sections()) {
6316 StringRef SectName;
6317 Section.getName(SectName);
6318 Sections.push_back(Section);
6319 }
6320
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006321 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006322
6323 const char *p;
6324 struct objc_protocol_t protocol;
6325 uint32_t left, paddr;
6326 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6327 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6328 left = size - (p - sect);
6329 if (left < sizeof(struct objc_protocol_t)) {
6330 outs() << "Protocol extends past end of __protocol section\n";
6331 memcpy(&protocol, p, left);
6332 } else
6333 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6334 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6335 swapStruct(protocol);
6336 paddr = addr + (p - sect);
6337 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6338 if (print_protocol(paddr, 0, &info))
6339 outs() << "(not in an __OBJC section)\n";
6340 }
6341}
6342
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006343#ifdef HAVE_LIBXAR
6344inline void swapStruct(struct xar_header &xar) {
6345 sys::swapByteOrder(xar.magic);
6346 sys::swapByteOrder(xar.size);
6347 sys::swapByteOrder(xar.version);
6348 sys::swapByteOrder(xar.toc_length_compressed);
6349 sys::swapByteOrder(xar.toc_length_uncompressed);
6350 sys::swapByteOrder(xar.cksum_alg);
6351}
6352
6353static void PrintModeVerbose(uint32_t mode) {
6354 switch(mode & S_IFMT){
6355 case S_IFDIR:
6356 outs() << "d";
6357 break;
6358 case S_IFCHR:
6359 outs() << "c";
6360 break;
6361 case S_IFBLK:
6362 outs() << "b";
6363 break;
6364 case S_IFREG:
6365 outs() << "-";
6366 break;
6367 case S_IFLNK:
6368 outs() << "l";
6369 break;
6370 case S_IFSOCK:
6371 outs() << "s";
6372 break;
6373 default:
6374 outs() << "?";
6375 break;
6376 }
6377
6378 /* owner permissions */
6379 if(mode & S_IREAD)
6380 outs() << "r";
6381 else
6382 outs() << "-";
6383 if(mode & S_IWRITE)
6384 outs() << "w";
6385 else
6386 outs() << "-";
6387 if(mode & S_ISUID)
6388 outs() << "s";
6389 else if(mode & S_IEXEC)
6390 outs() << "x";
6391 else
6392 outs() << "-";
6393
6394 /* group permissions */
6395 if(mode & (S_IREAD >> 3))
6396 outs() << "r";
6397 else
6398 outs() << "-";
6399 if(mode & (S_IWRITE >> 3))
6400 outs() << "w";
6401 else
6402 outs() << "-";
6403 if(mode & S_ISGID)
6404 outs() << "s";
6405 else if(mode & (S_IEXEC >> 3))
6406 outs() << "x";
6407 else
6408 outs() << "-";
6409
6410 /* other permissions */
6411 if(mode & (S_IREAD >> 6))
6412 outs() << "r";
6413 else
6414 outs() << "-";
6415 if(mode & (S_IWRITE >> 6))
6416 outs() << "w";
6417 else
6418 outs() << "-";
6419 if(mode & S_ISVTX)
6420 outs() << "t";
6421 else if(mode & (S_IEXEC >> 6))
6422 outs() << "x";
6423 else
6424 outs() << "-";
6425}
6426
6427static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006428 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006429 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6430 char *endp;
6431 uint32_t mode_value;
6432
Francis Ricci6f942972017-10-06 15:33:28 +00006433 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006434 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006435 WithColor::error(errs(), "llvm-objdump")
6436 << "can't obtain an xar iterator for xar archive " << XarFilename
6437 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006438 return;
6439 }
6440
6441 // Go through the xar's files.
6442 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006443 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006444 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006445 WithColor::error(errs(), "llvm-objdump")
6446 << "can't obtain an xar iterator for xar archive " << XarFilename
6447 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006448 return;
6449 }
6450 type = nullptr;
6451 mode = nullptr;
6452 user = nullptr;
6453 group = nullptr;
6454 size = nullptr;
6455 mtime = nullptr;
6456 name = nullptr;
6457 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006458 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006459 xar_prop_get(xf, key, &val);
6460#if 0 // Useful for debugging.
6461 outs() << "key: " << key << " value: " << val << "\n";
6462#endif
6463 if(strcmp(key, "type") == 0)
6464 type = val;
6465 if(strcmp(key, "mode") == 0)
6466 mode = val;
6467 if(strcmp(key, "user") == 0)
6468 user = val;
6469 if(strcmp(key, "group") == 0)
6470 group = val;
6471 if(strcmp(key, "data/size") == 0)
6472 size = val;
6473 if(strcmp(key, "mtime") == 0)
6474 mtime = val;
6475 if(strcmp(key, "name") == 0)
6476 name = val;
6477 }
6478 if(mode != nullptr){
6479 mode_value = strtoul(mode, &endp, 8);
6480 if(*endp != '\0')
6481 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6482 if(strcmp(type, "file") == 0)
6483 mode_value |= S_IFREG;
6484 PrintModeVerbose(mode_value);
6485 outs() << " ";
6486 }
6487 if(user != nullptr)
6488 outs() << format("%10s/", user);
6489 if(group != nullptr)
6490 outs() << format("%-10s ", group);
6491 if(size != nullptr)
6492 outs() << format("%7s ", size);
6493 if(mtime != nullptr){
6494 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6495 outs() << *m;
6496 if(*m == 'T')
6497 m++;
6498 outs() << " ";
6499 for( ; *m != 'Z' && *m != '\0'; m++)
6500 outs() << *m;
6501 outs() << " ";
6502 }
6503 if(name != nullptr)
6504 outs() << name;
6505 outs() << "\n";
6506 }
6507}
6508
6509static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6510 uint32_t size, bool verbose,
6511 bool PrintXarHeader, bool PrintXarFileHeaders,
6512 std::string XarMemberName) {
6513 if(size < sizeof(struct xar_header)) {
6514 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6515 "of struct xar_header)\n";
6516 return;
6517 }
6518 struct xar_header XarHeader;
6519 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6520 if (sys::IsLittleEndianHost)
6521 swapStruct(XarHeader);
6522 if (PrintXarHeader) {
6523 if (!XarMemberName.empty())
6524 outs() << "In xar member " << XarMemberName << ": ";
6525 else
6526 outs() << "For (__LLVM,__bundle) section: ";
6527 outs() << "xar header\n";
6528 if (XarHeader.magic == XAR_HEADER_MAGIC)
6529 outs() << " magic XAR_HEADER_MAGIC\n";
6530 else
6531 outs() << " magic "
6532 << format_hex(XarHeader.magic, 10, true)
6533 << " (not XAR_HEADER_MAGIC)\n";
6534 outs() << " size " << XarHeader.size << "\n";
6535 outs() << " version " << XarHeader.version << "\n";
6536 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6537 << "\n";
6538 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6539 << "\n";
6540 outs() << " cksum_alg ";
6541 switch (XarHeader.cksum_alg) {
6542 case XAR_CKSUM_NONE:
6543 outs() << "XAR_CKSUM_NONE\n";
6544 break;
6545 case XAR_CKSUM_SHA1:
6546 outs() << "XAR_CKSUM_SHA1\n";
6547 break;
6548 case XAR_CKSUM_MD5:
6549 outs() << "XAR_CKSUM_MD5\n";
6550 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006551#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006552 case XAR_CKSUM_SHA256:
6553 outs() << "XAR_CKSUM_SHA256\n";
6554 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006555#endif
6556#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006557 case XAR_CKSUM_SHA512:
6558 outs() << "XAR_CKSUM_SHA512\n";
6559 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006560#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006561 default:
6562 outs() << XarHeader.cksum_alg << "\n";
6563 }
6564 }
6565
6566 SmallString<128> XarFilename;
6567 int FD;
6568 std::error_code XarEC =
6569 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6570 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006571 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006572 return;
6573 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006574 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006575 raw_fd_ostream &XarOut = XarFile.os();
6576 StringRef XarContents(sect, size);
6577 XarOut << XarContents;
6578 XarOut.close();
6579 if (XarOut.has_error())
6580 return;
6581
Francis Ricci6f942972017-10-06 15:33:28 +00006582 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006583 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006584 WithColor::error(errs(), "llvm-objdump")
6585 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006586 return;
6587 }
6588
6589 SmallString<128> TocFilename;
6590 std::error_code TocEC =
6591 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6592 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006593 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006594 return;
6595 }
6596 xar_serialize(xar, TocFilename.c_str());
6597
6598 if (PrintXarFileHeaders) {
6599 if (!XarMemberName.empty())
6600 outs() << "In xar member " << XarMemberName << ": ";
6601 else
6602 outs() << "For (__LLVM,__bundle) section: ";
6603 outs() << "xar archive files:\n";
6604 PrintXarFilesSummary(XarFilename.c_str(), xar);
6605 }
6606
6607 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6608 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6609 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006610 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006611 return;
6612 }
6613 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6614
6615 if (!XarMemberName.empty())
6616 outs() << "In xar member " << XarMemberName << ": ";
6617 else
6618 outs() << "For (__LLVM,__bundle) section: ";
6619 outs() << "xar table of contents:\n";
6620 outs() << Buffer->getBuffer() << "\n";
6621
6622 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006623 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006624 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006625 WithColor::error(errs(), "llvm-objdump")
6626 << "can't obtain an xar iterator for xar archive "
6627 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006628 return;
6629 }
6630 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6631 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006632 const char *member_name, *member_type, *member_size_string;
6633 size_t member_size;
6634
Francis Ricci6f942972017-10-06 15:33:28 +00006635 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006636 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006637 WithColor::error(errs(), "llvm-objdump")
6638 << "can't obtain an xar iterator for xar archive "
6639 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006640 return;
6641 }
6642 member_name = NULL;
6643 member_type = NULL;
6644 member_size_string = NULL;
6645 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006646 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006647 xar_prop_get(xf, key, &val);
6648#if 0 // Useful for debugging.
6649 outs() << "key: " << key << " value: " << val << "\n";
6650#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006651 if (strcmp(key, "name") == 0)
6652 member_name = val;
6653 if (strcmp(key, "type") == 0)
6654 member_type = val;
6655 if (strcmp(key, "data/size") == 0)
6656 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006657 }
6658 /*
6659 * If we find a file with a name, date/size and type properties
6660 * and with the type being "file" see if that is a xar file.
6661 */
6662 if (member_name != NULL && member_type != NULL &&
6663 strcmp(member_type, "file") == 0 &&
6664 member_size_string != NULL){
6665 // Extract the file into a buffer.
6666 char *endptr;
6667 member_size = strtoul(member_size_string, &endptr, 10);
6668 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006669 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006670 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006671#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006672 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006673#endif
6674 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006675 std::string OldXarMemberName;
6676 // If XarMemberName is already set this is nested. So
6677 // save the old name and create the nested name.
6678 if (!XarMemberName.empty()) {
6679 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006680 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006681 (Twine("[") + XarMemberName + "]" + member_name).str();
6682 } else {
6683 OldXarMemberName = "";
6684 XarMemberName = member_name;
6685 }
6686 // See if this is could be a xar file (nested).
6687 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006688#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006689 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006690#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006691 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006692 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006693 swapStruct(XarHeader);
6694 if (XarHeader.magic == XAR_HEADER_MAGIC)
6695 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006696 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006697 XarMemberName);
6698 }
6699 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006700 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006701 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006702 }
6703 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006704 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006705}
6706#endif // defined(HAVE_LIBXAR)
6707
Kevin Enderby0fc11822015-04-01 20:57:01 +00006708static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6709 if (O->is64Bit())
6710 printObjc2_64bit_MetaData(O, verbose);
6711 else {
6712 MachO::mach_header H;
6713 H = O->getHeader();
6714 if (H.cputype == MachO::CPU_TYPE_ARM)
6715 printObjc2_32bit_MetaData(O, verbose);
6716 else {
6717 // This is the 32-bit non-arm cputype case. Which is normally
6718 // the first Objective-C ABI. But it may be the case of a
6719 // binary for the iOS simulator which is the second Objective-C
6720 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6721 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006722 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006723 printObjc2_32bit_MetaData(O, verbose);
6724 }
6725 }
6726}
6727
Kevin Enderbybf246f52014-09-24 23:08:22 +00006728// GuessLiteralPointer returns a string which for the item in the Mach-O file
6729// for the address passed in as ReferenceValue for printing as a comment with
6730// the instruction and also returns the corresponding type of that item
6731// indirectly through ReferenceType.
6732//
6733// If ReferenceValue is an address of literal cstring then a pointer to the
6734// cstring is returned and ReferenceType is set to
6735// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6736//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006737// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6738// Class ref that name is returned and the ReferenceType is set accordingly.
6739//
6740// Lastly, literals which are Symbol address in a literal pool are looked for
6741// and if found the symbol name is returned and ReferenceType is set to
6742// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6743//
6744// If there is no item in the Mach-O file for the address passed in as
6745// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006746static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6747 uint64_t ReferencePC,
6748 uint64_t *ReferenceType,
6749 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006750 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006751 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6752 uint64_t sect_addr = info->S.getAddress();
6753 uint64_t sect_offset = ReferencePC - sect_addr;
6754 bool reloc_found = false;
6755 DataRefImpl Rel;
6756 MachO::any_relocation_info RE;
6757 bool isExtern = false;
6758 SymbolRef Symbol;
6759 for (const RelocationRef &Reloc : info->S.relocations()) {
6760 uint64_t RelocOffset = Reloc.getOffset();
6761 if (RelocOffset == sect_offset) {
6762 Rel = Reloc.getRawDataRefImpl();
6763 RE = info->O->getRelocation(Rel);
6764 if (info->O->isRelocationScattered(RE))
6765 continue;
6766 isExtern = info->O->getPlainRelocationExternal(RE);
6767 if (isExtern) {
6768 symbol_iterator RelocSym = Reloc.getSymbol();
6769 Symbol = *RelocSym;
6770 }
6771 reloc_found = true;
6772 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006773 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006774 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006775 // If there is an external relocation entry for a symbol in a section
6776 // then used that symbol's value for the value of the reference.
6777 if (reloc_found && isExtern) {
6778 if (info->O->getAnyRelocationPCRel(RE)) {
6779 unsigned Type = info->O->getAnyRelocationType(RE);
6780 if (Type == MachO::X86_64_RELOC_SIGNED) {
6781 ReferenceValue = Symbol.getValue();
6782 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006783 }
6784 }
6785 }
6786
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006787 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6788 // Message refs and Class refs.
6789 bool classref, selref, msgref, cfstring;
6790 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6791 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006792 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006793 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6794 // And the pointer_value in that section is typically zero as it will be
6795 // set by dyld as part of the "bind information".
6796 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6797 if (name != nullptr) {
6798 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006799 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006800 if (class_name != nullptr && class_name[1] == '_' &&
6801 class_name[2] != '\0') {
6802 info->class_name = class_name + 2;
6803 return name;
6804 }
6805 }
6806 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006807
David Blaikie33dd45d02015-03-23 18:39:02 +00006808 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006809 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6810 const char *name =
6811 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6812 if (name != nullptr)
6813 info->class_name = name;
6814 else
6815 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006816 return name;
6817 }
6818
David Blaikie33dd45d02015-03-23 18:39:02 +00006819 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006820 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6821 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6822 return name;
6823 }
6824
David Blaikie33dd45d02015-03-23 18:39:02 +00006825 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006826 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6827
6828 if (pointer_value != 0)
6829 ReferenceValue = pointer_value;
6830
6831 const char *name = GuessCstringPointer(ReferenceValue, info);
6832 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006833 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006834 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6835 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006836 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006837 info->class_name = nullptr;
6838 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6839 info->selector_name = name;
6840 } else
6841 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6842 return name;
6843 }
6844
6845 // Lastly look for an indirect symbol with this ReferenceValue which is in
6846 // a literal pool. If found return that symbol name.
6847 name = GuessIndirectSymbol(ReferenceValue, info);
6848 if (name) {
6849 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6850 return name;
6851 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006852
6853 return nullptr;
6854}
6855
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006856// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006857// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006858// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6859// is created and returns the symbol name that matches the ReferenceValue or
6860// nullptr if none. The ReferenceType is passed in for the IN type of
6861// reference the instruction is making from the values in defined in the header
6862// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6863// Out type and the ReferenceName will also be set which is added as a comment
6864// to the disassembled instruction.
6865//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006866// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006867// returned through ReferenceName and ReferenceType is set to
6868// LLVMDisassembler_ReferenceType_DeMangled_Name .
6869//
6870// When this is called to get a symbol name for a branch target then the
6871// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6872// SymbolValue will be looked for in the indirect symbol table to determine if
6873// it is an address for a symbol stub. If so then the symbol name for that
6874// stub is returned indirectly through ReferenceName and then ReferenceType is
6875// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6876//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006877// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006878// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6879// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6880// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006881// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006882static const char *SymbolizerSymbolLookUp(void *DisInfo,
6883 uint64_t ReferenceValue,
6884 uint64_t *ReferenceType,
6885 uint64_t ReferencePC,
6886 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006887 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006888 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006889 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006890 *ReferenceName = nullptr;
6891 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006892 return nullptr;
6893 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006894
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006895 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006896
Kevin Enderby85974882014-09-26 22:20:44 +00006897 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6898 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006899 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006900 method_reference(info, ReferenceType, ReferenceName);
6901 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6902 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006903 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006904 if (info->demangled_name != nullptr)
6905 free(info->demangled_name);
6906 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006907 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006908 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006909 if (info->demangled_name != nullptr) {
6910 *ReferenceName = info->demangled_name;
6911 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6912 } else
6913 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6914 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006915 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6916 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6917 *ReferenceName =
6918 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006919 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006920 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006921 else
6922 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006923 // If this is arm64 and the reference is an adrp instruction save the
6924 // instruction, passed in ReferenceValue and the address of the instruction
6925 // for use later if we see and add immediate instruction.
6926 } else if (info->O->getArch() == Triple::aarch64 &&
6927 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6928 info->adrp_inst = ReferenceValue;
6929 info->adrp_addr = ReferencePC;
6930 SymbolName = nullptr;
6931 *ReferenceName = nullptr;
6932 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6933 // If this is arm64 and reference is an add immediate instruction and we
6934 // have
6935 // seen an adrp instruction just before it and the adrp's Xd register
6936 // matches
6937 // this add's Xn register reconstruct the value being referenced and look to
6938 // see if it is a literal pointer. Note the add immediate instruction is
6939 // passed in ReferenceValue.
6940 } else if (info->O->getArch() == Triple::aarch64 &&
6941 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6942 ReferencePC - 4 == info->adrp_addr &&
6943 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6944 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6945 uint32_t addxri_inst;
6946 uint64_t adrp_imm, addxri_imm;
6947
6948 adrp_imm =
6949 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6950 if (info->adrp_inst & 0x0200000)
6951 adrp_imm |= 0xfffffffffc000000LL;
6952
6953 addxri_inst = ReferenceValue;
6954 addxri_imm = (addxri_inst >> 10) & 0xfff;
6955 if (((addxri_inst >> 22) & 0x3) == 1)
6956 addxri_imm <<= 12;
6957
6958 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6959 (adrp_imm << 12) + addxri_imm;
6960
6961 *ReferenceName =
6962 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6963 if (*ReferenceName == nullptr)
6964 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6965 // If this is arm64 and the reference is a load register instruction and we
6966 // have seen an adrp instruction just before it and the adrp's Xd register
6967 // matches this add's Xn register reconstruct the value being referenced and
6968 // look to see if it is a literal pointer. Note the load register
6969 // instruction is passed in ReferenceValue.
6970 } else if (info->O->getArch() == Triple::aarch64 &&
6971 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6972 ReferencePC - 4 == info->adrp_addr &&
6973 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6974 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6975 uint32_t ldrxui_inst;
6976 uint64_t adrp_imm, ldrxui_imm;
6977
6978 adrp_imm =
6979 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6980 if (info->adrp_inst & 0x0200000)
6981 adrp_imm |= 0xfffffffffc000000LL;
6982
6983 ldrxui_inst = ReferenceValue;
6984 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6985
6986 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6987 (adrp_imm << 12) + (ldrxui_imm << 3);
6988
6989 *ReferenceName =
6990 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6991 if (*ReferenceName == nullptr)
6992 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6993 }
6994 // If this arm64 and is an load register (PC-relative) instruction the
6995 // ReferenceValue is the PC plus the immediate value.
6996 else if (info->O->getArch() == Triple::aarch64 &&
6997 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6998 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6999 *ReferenceName =
7000 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7001 if (*ReferenceName == nullptr)
7002 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00007003 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00007004 if (info->demangled_name != nullptr)
7005 free(info->demangled_name);
7006 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007007 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00007008 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007009 if (info->demangled_name != nullptr) {
7010 *ReferenceName = info->demangled_name;
7011 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7012 }
7013 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007014 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007015 *ReferenceName = nullptr;
7016 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7017 }
7018
7019 return SymbolName;
7020}
7021
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007022/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007023/// Each comment in the CommentStream must end with a newline.
7024static void emitComments(raw_svector_ostream &CommentStream,
7025 SmallString<128> &CommentsToEmit,
7026 formatted_raw_ostream &FormattedOS,
7027 const MCAsmInfo &MAI) {
7028 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007029 StringRef Comments = CommentsToEmit.str();
7030 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00007031 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00007032 unsigned CommentColumn = MAI.getCommentColumn();
7033 bool IsFirst = true;
7034 while (!Comments.empty()) {
7035 if (!IsFirst)
7036 FormattedOS << '\n';
7037 // Emit a line of comments.
7038 FormattedOS.PadToColumn(CommentColumn);
7039 size_t Position = Comments.find('\n');
7040 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7041 // Move after the newline character.
7042 Comments = Comments.substr(Position + 1);
7043 IsFirst = false;
7044 }
7045 FormattedOS.flush();
7046
7047 // Tell the comment stream that the vector changed underneath it.
7048 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007049}
7050
Kevin Enderby95df54c2015-02-04 01:01:38 +00007051static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7052 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007053 const char *McpuDefault = nullptr;
7054 const Target *ThumbTarget = nullptr;
7055 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007056 if (!TheTarget) {
7057 // GetTarget prints out stuff.
7058 return;
7059 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007060 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007061 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007062 MachOMCPU = McpuDefault;
7063 else
7064 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007065
Ahmed Charles56440fd2014-03-06 05:51:42 +00007066 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007067 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007068 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007069 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007070
Kevin Enderbyc9595622014-08-06 23:24:41 +00007071 // Package up features to be passed to target/subtarget
7072 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007073 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007074 SubtargetFeatures Features;
7075 for (unsigned i = 0; i != MAttrs.size(); ++i)
7076 Features.AddFeature(MAttrs[i]);
7077 FeaturesStr = Features.getString();
7078 }
7079
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007080 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007081 std::unique_ptr<const MCRegisterInfo> MRI(
7082 TheTarget->createMCRegInfo(TripleName));
7083 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007084 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007085 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007086 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007087 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007088 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007089 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007090 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007091 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007092 std::unique_ptr<MCRelocationInfo> RelInfo(
7093 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7094 if (RelInfo) {
7095 Symbolizer.reset(TheTarget->createMCSymbolizer(
7096 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007097 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007098 DisAsm->setSymbolizer(std::move(Symbolizer));
7099 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007100 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007101 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007102 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007103 // Set the display preference for hex vs. decimal immediates.
7104 IP->setPrintImmHex(PrintImmHex);
7105 // Comment stream and backing vector.
7106 SmallString<128> CommentsToEmit;
7107 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007108 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7109 // if it is done then arm64 comments for string literals don't get printed
7110 // and some constant get printed instead and not setting it causes intel
7111 // (32-bit and 64-bit) comments printed with different spacing before the
7112 // comment causing different diffs with the 'C' disassembler library API.
7113 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007114
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007115 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007116 WithColor::error(errs(), "llvm-objdump")
7117 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007118 return;
7119 }
7120
Tim Northover09ca33e2016-04-22 23:23:31 +00007121 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007122 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7123 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7124 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007125 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007126 std::unique_ptr<MCInstPrinter> ThumbIP;
7127 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007128 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007129 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007130 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007131 if (ThumbTarget) {
7132 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7133 ThumbAsmInfo.reset(
7134 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7135 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007136 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7137 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007138 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7139 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007140 MCContext *PtrThumbCtx = ThumbCtx.get();
7141 ThumbRelInfo.reset(
7142 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7143 if (ThumbRelInfo) {
7144 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7145 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007146 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007147 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7148 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007149 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7150 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007151 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7152 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007153 // Set the display preference for hex vs. decimal immediates.
7154 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007155 }
7156
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007157 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007158 WithColor::error(errs(), "llvm-objdump")
7159 << "couldn't initialize disassembler for target " << ThumbTripleName
7160 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007161 return;
7162 }
7163
Charles Davis8bdfafd2013-09-01 04:28:48 +00007164 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007165
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007166 // FIXME: Using the -cfg command line option, this code used to be able to
7167 // annotate relocations with the referenced symbol's name, and if this was
7168 // inside a __[cf]string section, the data it points to. This is now replaced
7169 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007170 std::vector<SectionRef> Sections;
7171 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007172 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007173 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007174
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007175 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007176 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007177
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007178 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007179 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007180
Kevin Enderby273ae012013-06-06 17:20:50 +00007181 // Build a data in code table that is sorted on by the address of each entry.
7182 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007183 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007184 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007185 else
7186 BaseAddress = BaseSegmentAddress;
7187 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007188 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007189 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007190 uint32_t Offset;
7191 DI->getOffset(Offset);
7192 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7193 }
7194 array_pod_sort(Dices.begin(), Dices.end());
7195
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007196#ifndef NDEBUG
7197 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7198#else
7199 raw_ostream &DebugOut = nulls();
7200#endif
7201
Ahmed Charles56440fd2014-03-06 05:51:42 +00007202 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007203 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007204 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007205 // Try to find debug info and set up the DIContext for it.
7206 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007207 // A separate DSym file path was specified, parse it as a macho file,
7208 // get the sections and supply it to the section name parsing machinery.
7209 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007210 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007211 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007212 if (std::error_code EC = BufOrErr.getError()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007213 report_error(errorCodeToError(EC), DSYMFile);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007214 return;
7215 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007216
Fangrui Songe7834bd2019-04-07 08:19:55 +00007217 std::unique_ptr<MachOObjectFile> DbgObjCheck = unwrapOrError(
7218 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef()),
7219 DSYMFile.getValue());
7220 DbgObj = DbgObjCheck.release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007221 // We need to keep the file alive, because we're replacing DbgObj with it.
7222 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007223 }
7224
Eric Christopher7370b552012-11-12 21:40:38 +00007225 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007226 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007227 }
7228
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007229 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007230 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007231
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007232 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007233 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007234 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7235 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007236
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007237 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007238
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007239 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007240 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007241 continue;
7242
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007243 StringRef BytesStr;
7244 Sections[SectIdx].getContents(BytesStr);
Fangrui Song6a0746a2019-04-07 03:58:42 +00007245 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
Rafael Espindola80291272014-10-08 15:28:58 +00007246 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007247
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007248 bool symbolTableWorked = false;
7249
Kevin Enderbybf246f52014-09-24 23:08:22 +00007250 // Create a map of symbol addresses to symbol names for use by
7251 // the SymbolizerSymbolLookUp() routine.
7252 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007253 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007254 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007255 SymbolRef::Type ST =
7256 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007257 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7258 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007259 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00007260 StringRef SymName =
7261 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007262 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007263 if (!DisSymName.empty() && DisSymName == SymName)
7264 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007265 }
7266 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007267 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007268 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7269 return;
7270 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007271 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007272 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007273 SymbolizerInfo.O = MachOOF;
7274 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007275 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007276 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007277 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007278 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007279 ThumbSymbolizerInfo.O = MachOOF;
7280 ThumbSymbolizerInfo.S = Sections[SectIdx];
7281 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7282 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007283
Kevin Enderby4b627be2016-04-28 20:14:13 +00007284 unsigned int Arch = MachOOF->getArch();
7285
Tim Northoverf203ab52016-07-14 22:13:32 +00007286 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007287 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007288 return;
7289
Kevin Enderbyc138da32017-02-06 18:43:18 +00007290 // If the section has symbols but no symbol at the start of the section
7291 // these are used to make sure the bytes before the first symbol are
7292 // disassembled.
7293 bool FirstSymbol = true;
7294 bool FirstSymbolAtSectionStart = true;
7295
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007296 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007297 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007298 StringRef SymName =
7299 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7300 SymbolRef::Type ST =
7301 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
Kuba Breckade833222015-11-12 09:40:29 +00007302 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007303 continue;
7304
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007305 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007306 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007307 if (!containsSym) {
7308 if (!DisSymName.empty() && DisSymName == SymName) {
7309 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7310 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007311 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007312 continue;
7313 }
7314 // The __mh_execute_header is special and we need to deal with that fact
7315 // this symbol is before the start of the (__TEXT,__text) section and at the
7316 // address of the start of the __TEXT segment. This is because this symbol
7317 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7318 // start of the section in a standard MH_EXECUTE filetype.
7319 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7320 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7321 return;
7322 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007323 // When this code is trying to disassemble a symbol at a time and in the
7324 // case there is only the __mh_execute_header symbol left as in a stripped
7325 // executable, we need to deal with this by ignoring this symbol so the
7326 // whole section is disassembled and this symbol is then not displayed.
7327 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7328 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7329 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007330 continue;
7331
Kevin Enderby6a221752015-03-17 17:10:57 +00007332 // If we are only disassembling one symbol see if this is that symbol.
7333 if (!DisSymName.empty() && DisSymName != SymName)
7334 continue;
7335
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007336 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007337 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007338 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007339 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007340 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007341
Tim Northoverf203ab52016-07-14 22:13:32 +00007342 if (Start > SectSize) {
7343 outs() << "section data ends, " << SymName
7344 << " lies outside valid range\n";
7345 return;
7346 }
7347
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007348 // Stop disassembling either at the beginning of the next symbol or at
7349 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007350 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007351 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007352 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007353 while (Symbols.size() > NextSymIdx) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007354 SymbolRef::Type NextSymType = unwrapOrError(
7355 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
Owen Andersond9243c42011-10-17 21:37:35 +00007356 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007357 containsNextSym =
7358 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007359 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007360 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007361 break;
7362 }
7363 ++NextSymIdx;
7364 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007365
Tim Northoverf203ab52016-07-14 22:13:32 +00007366 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007367 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007368
7369 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007370
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007371 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007372 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7373
7374 // We only need the dedicated Thumb target if there's a real choice
7375 // (i.e. we're not targeting M-class) and the function is Thumb.
7376 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007377
Kevin Enderbyc138da32017-02-06 18:43:18 +00007378 // If we are not specifying a symbol to start disassembly with and this
7379 // is the first symbol in the section but not at the start of the section
7380 // then move the disassembly index to the start of the section and
7381 // don't print the symbol name just yet. This is so the bytes before the
7382 // first symbol are disassembled.
7383 uint64_t SymbolStart = Start;
7384 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7385 FirstSymbolAtSectionStart = false;
7386 Start = 0;
7387 }
7388 else
7389 outs() << SymName << ":\n";
7390
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007391 DILineInfo lastLine;
7392 for (uint64_t Index = Start; Index < End; Index += Size) {
7393 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007394
Kevin Enderbyc138da32017-02-06 18:43:18 +00007395 // If this is the first symbol in the section and it was not at the
7396 // start of the section, see if we are at its Index now and if so print
7397 // the symbol name.
7398 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7399 outs() << SymName << ":\n";
7400
Kevin Enderbybf246f52014-09-24 23:08:22 +00007401 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007402 if (!NoLeadingAddr) {
7403 if (FullLeadingAddr) {
7404 if (MachOOF->is64Bit())
7405 outs() << format("%016" PRIx64, PC);
7406 else
7407 outs() << format("%08" PRIx64, PC);
7408 } else {
7409 outs() << format("%8" PRIx64 ":", PC);
7410 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007411 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007412 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007413 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007414
7415 // Check the data in code table here to see if this is data not an
7416 // instruction to be disassembled.
7417 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007418 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007419 dice_table_iterator DTI =
7420 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7421 compareDiceTableEntries);
7422 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007423 uint16_t Length;
7424 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007425 uint16_t Kind;
7426 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007427 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007428 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7429 (PC == (DTI->first + Length - 1)) && (Length & 1))
7430 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007431 continue;
7432 }
7433
Kevin Enderbybf246f52014-09-24 23:08:22 +00007434 SmallVector<char, 64> AnnotationsBytes;
7435 raw_svector_ostream Annotations(AnnotationsBytes);
7436
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007437 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007438 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007439 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007440 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007441 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007442 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007443 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007444 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007445 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007446 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007447 }
7448 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007449 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007450 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007451 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007452 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007453 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007454 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007455
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007456 // Print debug info.
7457 if (diContext) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00007458 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007459 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007460 if (dli != lastLine && dli.Line != 0)
7461 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7462 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007463 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007464 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007465 outs() << "\n";
7466 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007467 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007468 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007469 outs() << format("\t.byte 0x%02x #bad opcode\n",
7470 *(Bytes.data() + Index) & 0xff);
7471 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007472 } else if (Arch == Triple::aarch64 ||
7473 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007474 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7475 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7476 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7477 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7478 outs() << format("\t.long\t0x%08x\n", opcode);
7479 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007480 } else if (Arch == Triple::arm) {
7481 assert(IsThumb && "ARM mode should have been dealt with above");
7482 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7483 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7484 outs() << format("\t.short\t0x%04x\n", opcode);
7485 Size = 2;
7486 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007487 WithColor::warning(errs(), "llvm-objdump")
7488 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007489 if (Size == 0)
7490 Size = 1; // skip illegible bytes
7491 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007492 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007493 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007494 // Now that we are done disassembled the first symbol set the bool that
7495 // were doing this to false.
7496 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007497 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007498 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007499 // Reading the symbol table didn't work, disassemble the whole section.
7500 uint64_t SectAddress = Sections[SectIdx].getAddress();
7501 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007502 uint64_t InstSize;
7503 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007504 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007505
Kevin Enderbybf246f52014-09-24 23:08:22 +00007506 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007507 SmallVector<char, 64> AnnotationsBytes;
7508 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007509 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007510 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007511 if (!NoLeadingAddr) {
7512 if (FullLeadingAddr) {
7513 if (MachOOF->is64Bit())
7514 outs() << format("%016" PRIx64, PC);
7515 else
7516 outs() << format("%08" PRIx64, PC);
7517 } else {
7518 outs() << format("%8" PRIx64 ":", PC);
7519 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007520 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007521 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007522 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007523 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007524 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007525 StringRef AnnotationsStr = Annotations.str();
7526 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007527 outs() << "\n";
7528 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007529 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007530 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007531 outs() << format("\t.byte 0x%02x #bad opcode\n",
7532 *(Bytes.data() + Index) & 0xff);
7533 InstSize = 1; // skip exactly one illegible byte and move on.
7534 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007535 WithColor::warning(errs(), "llvm-objdump")
7536 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007537 if (InstSize == 0)
7538 InstSize = 1; // skip illegible bytes
7539 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007540 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007541 }
7542 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007543 // The TripleName's need to be reset if we are called again for a different
7544 // archtecture.
7545 TripleName = "";
7546 ThumbTripleName = "";
7547
Kevin Enderby04bf6932014-10-28 23:39:46 +00007548 if (SymbolizerInfo.demangled_name != nullptr)
7549 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007550 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7551 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007552 }
7553}
Tim Northover4bd286a2014-08-01 13:07:19 +00007554
Tim Northover39c70bb2014-08-12 11:52:59 +00007555//===----------------------------------------------------------------------===//
7556// __compact_unwind section dumping
7557//===----------------------------------------------------------------------===//
7558
Tim Northover4bd286a2014-08-01 13:07:19 +00007559namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007560
Tim Northover3a4e1c72018-01-23 13:51:57 +00007561template <typename T>
7562static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007563 using llvm::support::little;
7564 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007565
Tim Northover3a4e1c72018-01-23 13:51:57 +00007566 if (Offset + sizeof(T) > Contents.size()) {
7567 outs() << "warning: attempt to read past end of buffer\n";
7568 return T();
7569 }
7570
7571 uint64_t Val =
7572 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7573 return Val;
7574}
7575
7576template <typename T>
7577static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7578 T Val = read<T>(Contents, Offset);
7579 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007580 return Val;
7581}
Tim Northover39c70bb2014-08-12 11:52:59 +00007582
Tim Northover4bd286a2014-08-01 13:07:19 +00007583struct CompactUnwindEntry {
7584 uint32_t OffsetInSection;
7585
7586 uint64_t FunctionAddr;
7587 uint32_t Length;
7588 uint32_t CompactEncoding;
7589 uint64_t PersonalityAddr;
7590 uint64_t LSDAAddr;
7591
7592 RelocationRef FunctionReloc;
7593 RelocationRef PersonalityReloc;
7594 RelocationRef LSDAReloc;
7595
7596 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007597 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007598 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007599 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007600 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007601 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007602 }
7603
7604private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007605 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7606 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7607 Length = readNext<uint32_t>(Contents, Offset);
7608 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7609 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7610 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007611 }
7612};
7613}
7614
7615/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7616/// and data being relocated, determine the best base Name and Addend to use for
7617/// display purposes.
7618///
7619/// 1. An Extern relocation will directly reference a symbol (and the data is
7620/// then already an addend), so use that.
7621/// 2. Otherwise the data is an offset in the object file's layout; try to find
7622// a symbol before it in the same section, and use the offset from there.
7623/// 3. Finally, if all that fails, fall back to an offset from the start of the
7624/// referenced section.
7625static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7626 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007627 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007628 StringRef &Name, uint64_t &Addend) {
7629 if (Reloc.getSymbol() != Obj->symbol_end()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007630 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007631 Addend = Addr;
7632 return;
7633 }
7634
7635 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007636 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007637
Rafael Espindola80291272014-10-08 15:28:58 +00007638 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007639
7640 auto Sym = Symbols.upper_bound(Addr);
7641 if (Sym == Symbols.begin()) {
7642 // The first symbol in the object is after this reference, the best we can
7643 // do is section-relative notation.
7644 RelocSection.getName(Name);
7645 Addend = Addr - SectionAddr;
7646 return;
7647 }
7648
7649 // Go back one so that SymbolAddress <= Addr.
7650 --Sym;
7651
Fangrui Songe7834bd2019-04-07 08:19:55 +00007652 section_iterator SymSection =
7653 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007654 if (RelocSection == *SymSection) {
7655 // There's a valid symbol in the same section before this reference.
Fangrui Songe7834bd2019-04-07 08:19:55 +00007656 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007657 Addend = Addr - Sym->first;
7658 return;
7659 }
7660
7661 // There is a symbol before this reference, but it's in a different
7662 // section. Probably not helpful to mention it, so use the section name.
7663 RelocSection.getName(Name);
7664 Addend = Addr - SectionAddr;
7665}
7666
7667static void printUnwindRelocDest(const MachOObjectFile *Obj,
7668 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007669 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007670 StringRef Name;
7671 uint64_t Addend;
7672
Rafael Espindola854038e2015-06-26 14:51:16 +00007673 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007674 return;
7675
Tim Northover4bd286a2014-08-01 13:07:19 +00007676 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7677
7678 outs() << Name;
7679 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007680 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007681}
7682
7683static void
7684printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7685 std::map<uint64_t, SymbolRef> &Symbols,
7686 const SectionRef &CompactUnwind) {
7687
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007688 if (!Obj->isLittleEndian()) {
7689 outs() << "Skipping big-endian __compact_unwind section\n";
7690 return;
7691 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007692
7693 bool Is64 = Obj->is64Bit();
7694 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7695 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7696
7697 StringRef Contents;
7698 CompactUnwind.getContents(Contents);
7699
7700 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7701
7702 // First populate the initial raw offsets, encodings and so on from the entry.
7703 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007704 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007705 CompactUnwinds.push_back(Entry);
7706 }
7707
7708 // Next we need to look at the relocations to find out what objects are
7709 // actually being referred to.
7710 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007711 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007712
7713 uint32_t EntryIdx = RelocAddress / EntrySize;
7714 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7715 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7716
7717 if (OffsetInEntry == 0)
7718 Entry.FunctionReloc = Reloc;
7719 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7720 Entry.PersonalityReloc = Reloc;
7721 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7722 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007723 else {
7724 outs() << "Invalid relocation in __compact_unwind section\n";
7725 return;
7726 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007727 }
7728
7729 // Finally, we're ready to print the data we've gathered.
7730 outs() << "Contents of __compact_unwind section:\n";
7731 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007732 outs() << " Entry at offset "
7733 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007734
7735 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007736 outs() << " start: " << format("0x%" PRIx64,
7737 Entry.FunctionAddr) << ' ';
7738 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007739 outs() << '\n';
7740
7741 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007742 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7743 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007744 // 3. The 32-bit compact encoding.
7745 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007746 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007747
7748 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007749 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007750 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007751 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007752 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7753 Entry.PersonalityAddr);
7754 outs() << '\n';
7755 }
7756
7757 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007758 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007759 outs() << " LSDA: " << format("0x%" PRIx64,
7760 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007761 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7762 outs() << '\n';
7763 }
7764 }
7765}
7766
Tim Northover39c70bb2014-08-12 11:52:59 +00007767//===----------------------------------------------------------------------===//
7768// __unwind_info section dumping
7769//===----------------------------------------------------------------------===//
7770
Tim Northover3a4e1c72018-01-23 13:51:57 +00007771static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7772 ptrdiff_t Pos = 0;
7773 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007774 (void)Kind;
7775 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7776
Tim Northover3a4e1c72018-01-23 13:51:57 +00007777 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7778 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007779
Tim Northover3a4e1c72018-01-23 13:51:57 +00007780 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007781 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007782 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7783 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007784
7785 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007786 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7787 << ", "
7788 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007789 }
7790}
7791
7792static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007793 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007794 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007795 ptrdiff_t Pos = 0;
7796 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007797 (void)Kind;
7798 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7799
Tim Northover3a4e1c72018-01-23 13:51:57 +00007800 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7801 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007802
Tim Northover3a4e1c72018-01-23 13:51:57 +00007803 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7804 readNext<uint16_t>(PageData, Pos);
7805 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007806
Tim Northover3a4e1c72018-01-23 13:51:57 +00007807 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007808 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007809 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007810 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7811 uint32_t EncodingIdx = Entry >> 24;
7812
7813 uint32_t Encoding;
7814 if (EncodingIdx < CommonEncodings.size())
7815 Encoding = CommonEncodings[EncodingIdx];
7816 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007817 Encoding = read<uint32_t>(PageEncodings,
7818 sizeof(uint32_t) *
7819 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007820
7821 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007822 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7823 << ", "
7824 << "encoding[" << EncodingIdx
7825 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007826 }
7827}
7828
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007829static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7830 std::map<uint64_t, SymbolRef> &Symbols,
7831 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007832
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007833 if (!Obj->isLittleEndian()) {
7834 outs() << "Skipping big-endian __unwind_info section\n";
7835 return;
7836 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007837
7838 outs() << "Contents of __unwind_info section:\n";
7839
7840 StringRef Contents;
7841 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007842 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007843
7844 //===----------------------------------
7845 // Section header
7846 //===----------------------------------
7847
Tim Northover3a4e1c72018-01-23 13:51:57 +00007848 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007849 outs() << " Version: "
7850 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007851 if (Version != 1) {
7852 outs() << " Skipping section with unknown version\n";
7853 return;
7854 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007855
Tim Northover3a4e1c72018-01-23 13:51:57 +00007856 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007857 outs() << " Common encodings array section offset: "
7858 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007859 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007860 outs() << " Number of common encodings in array: "
7861 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7862
Tim Northover3a4e1c72018-01-23 13:51:57 +00007863 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007864 outs() << " Personality function array section offset: "
7865 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007866 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007867 outs() << " Number of personality functions in array: "
7868 << format("0x%" PRIx32, NumPersonalities) << '\n';
7869
Tim Northover3a4e1c72018-01-23 13:51:57 +00007870 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007871 outs() << " Index array section offset: "
7872 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007873 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007874 outs() << " Number of indices in array: "
7875 << format("0x%" PRIx32, NumIndices) << '\n';
7876
7877 //===----------------------------------
7878 // A shared list of common encodings
7879 //===----------------------------------
7880
7881 // These occupy indices in the range [0, N] whenever an encoding is referenced
7882 // from a compressed 2nd level index table. In practice the linker only
7883 // creates ~128 of these, so that indices are available to embed encodings in
7884 // the 2nd level index.
7885
7886 SmallVector<uint32_t, 64> CommonEncodings;
7887 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007888 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007889 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007890 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007891 CommonEncodings.push_back(Encoding);
7892
7893 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7894 << '\n';
7895 }
7896
Tim Northover39c70bb2014-08-12 11:52:59 +00007897 //===----------------------------------
7898 // Personality functions used in this executable
7899 //===----------------------------------
7900
7901 // There should be only a handful of these (one per source language,
7902 // roughly). Particularly since they only get 2 bits in the compact encoding.
7903
7904 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007905 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007906 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007907 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007908 outs() << " personality[" << i + 1
7909 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7910 }
7911
7912 //===----------------------------------
7913 // The level 1 index entries
7914 //===----------------------------------
7915
7916 // These specify an approximate place to start searching for the more detailed
7917 // information, sorted by PC.
7918
7919 struct IndexEntry {
7920 uint32_t FunctionOffset;
7921 uint32_t SecondLevelPageStart;
7922 uint32_t LSDAStart;
7923 };
7924
7925 SmallVector<IndexEntry, 4> IndexEntries;
7926
7927 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007928 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007929 for (unsigned i = 0; i < NumIndices; ++i) {
7930 IndexEntry Entry;
7931
Tim Northover3a4e1c72018-01-23 13:51:57 +00007932 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7933 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7934 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007935 IndexEntries.push_back(Entry);
7936
7937 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007938 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7939 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007940 << "2nd level page offset="
7941 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007942 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007943 }
7944
Tim Northover39c70bb2014-08-12 11:52:59 +00007945 //===----------------------------------
7946 // Next come the LSDA tables
7947 //===----------------------------------
7948
7949 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7950 // the first top-level index's LSDAOffset to the last (sentinel).
7951
7952 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007953 Pos = IndexEntries[0].LSDAStart;
7954 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7955 int NumLSDAs =
7956 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7957
Tim Northover39c70bb2014-08-12 11:52:59 +00007958 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007959 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7960 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007961 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007962 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7963 << ", "
7964 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007965 }
7966
7967 //===----------------------------------
7968 // Finally, the 2nd level indices
7969 //===----------------------------------
7970
7971 // Generally these are 4K in size, and have 2 possible forms:
7972 // + Regular stores up to 511 entries with disparate encodings
7973 // + Compressed stores up to 1021 entries if few enough compact encoding
7974 // values are used.
7975 outs() << " Second level indices:\n";
7976 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7977 // The final sentinel top-level index has no associated 2nd level page
7978 if (IndexEntries[i].SecondLevelPageStart == 0)
7979 break;
7980
7981 outs() << " Second level index[" << i << "]: "
7982 << "offset in section="
7983 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7984 << ", "
7985 << "base function offset="
7986 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7987
Tim Northover3a4e1c72018-01-23 13:51:57 +00007988 Pos = IndexEntries[i].SecondLevelPageStart;
7989 if (Pos + sizeof(uint32_t) > Contents.size()) {
7990 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7991 continue;
7992 }
7993
7994 uint32_t Kind =
7995 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007996 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007997 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007998 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007999 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8000 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00008001 CommonEncodings);
8002 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00008003 outs() << " Skipping 2nd level page with unknown kind " << Kind
8004 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008005 }
8006}
8007
Tim Northover4bd286a2014-08-01 13:07:19 +00008008void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8009 std::map<uint64_t, SymbolRef> Symbols;
8010 for (const SymbolRef &SymRef : Obj->symbols()) {
8011 // Discard any undefined or absolute symbols. They're not going to take part
8012 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00008013 auto SectOrErr = SymRef.getSection();
8014 if (!SectOrErr) {
8015 // TODO: Actually report errors helpfully.
8016 consumeError(SectOrErr.takeError());
8017 continue;
8018 }
8019 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00008020 if (Section == Obj->section_end())
8021 continue;
8022
Rafael Espindoladea00162015-07-03 17:44:18 +00008023 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00008024 Symbols.insert(std::make_pair(Addr, SymRef));
8025 }
8026
8027 for (const SectionRef &Section : Obj->sections()) {
8028 StringRef SectName;
8029 Section.getName(SectName);
8030 if (SectName == "__compact_unwind")
8031 printMachOCompactUnwindSection(Obj, Symbols, Section);
8032 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00008033 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00008034 }
8035}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008036
8037static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8038 uint32_t cpusubtype, uint32_t filetype,
8039 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8040 bool verbose) {
8041 outs() << "Mach header\n";
8042 outs() << " magic cputype cpusubtype caps filetype ncmds "
8043 "sizeofcmds flags\n";
8044 if (verbose) {
8045 if (magic == MachO::MH_MAGIC)
8046 outs() << " MH_MAGIC";
8047 else if (magic == MachO::MH_MAGIC_64)
8048 outs() << "MH_MAGIC_64";
8049 else
8050 outs() << format(" 0x%08" PRIx32, magic);
8051 switch (cputype) {
8052 case MachO::CPU_TYPE_I386:
8053 outs() << " I386";
8054 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8055 case MachO::CPU_SUBTYPE_I386_ALL:
8056 outs() << " ALL";
8057 break;
8058 default:
8059 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8060 break;
8061 }
8062 break;
8063 case MachO::CPU_TYPE_X86_64:
8064 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008065 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8066 case MachO::CPU_SUBTYPE_X86_64_ALL:
8067 outs() << " ALL";
8068 break;
8069 case MachO::CPU_SUBTYPE_X86_64_H:
8070 outs() << " Haswell";
8071 break;
8072 default:
8073 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8074 break;
8075 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008076 break;
8077 case MachO::CPU_TYPE_ARM:
8078 outs() << " ARM";
8079 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8080 case MachO::CPU_SUBTYPE_ARM_ALL:
8081 outs() << " ALL";
8082 break;
8083 case MachO::CPU_SUBTYPE_ARM_V4T:
8084 outs() << " V4T";
8085 break;
8086 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8087 outs() << " V5TEJ";
8088 break;
8089 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8090 outs() << " XSCALE";
8091 break;
8092 case MachO::CPU_SUBTYPE_ARM_V6:
8093 outs() << " V6";
8094 break;
8095 case MachO::CPU_SUBTYPE_ARM_V6M:
8096 outs() << " V6M";
8097 break;
8098 case MachO::CPU_SUBTYPE_ARM_V7:
8099 outs() << " V7";
8100 break;
8101 case MachO::CPU_SUBTYPE_ARM_V7EM:
8102 outs() << " V7EM";
8103 break;
8104 case MachO::CPU_SUBTYPE_ARM_V7K:
8105 outs() << " V7K";
8106 break;
8107 case MachO::CPU_SUBTYPE_ARM_V7M:
8108 outs() << " V7M";
8109 break;
8110 case MachO::CPU_SUBTYPE_ARM_V7S:
8111 outs() << " V7S";
8112 break;
8113 default:
8114 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8115 break;
8116 }
8117 break;
8118 case MachO::CPU_TYPE_ARM64:
8119 outs() << " ARM64";
8120 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8121 case MachO::CPU_SUBTYPE_ARM64_ALL:
8122 outs() << " ALL";
8123 break;
Shoaib Meenai867131a2019-04-08 21:37:08 +00008124 case MachO::CPU_SUBTYPE_ARM64E:
8125 outs() << " E";
8126 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008127 default:
8128 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8129 break;
8130 }
8131 break;
8132 case MachO::CPU_TYPE_POWERPC:
8133 outs() << " PPC";
8134 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8135 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8136 outs() << " ALL";
8137 break;
8138 default:
8139 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8140 break;
8141 }
8142 break;
8143 case MachO::CPU_TYPE_POWERPC64:
8144 outs() << " PPC64";
8145 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8146 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8147 outs() << " ALL";
8148 break;
8149 default:
8150 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8151 break;
8152 }
8153 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008154 default:
8155 outs() << format(" %7d", cputype);
8156 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8157 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008158 }
8159 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008160 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008161 } else {
8162 outs() << format(" 0x%02" PRIx32,
8163 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8164 }
8165 switch (filetype) {
8166 case MachO::MH_OBJECT:
8167 outs() << " OBJECT";
8168 break;
8169 case MachO::MH_EXECUTE:
8170 outs() << " EXECUTE";
8171 break;
8172 case MachO::MH_FVMLIB:
8173 outs() << " FVMLIB";
8174 break;
8175 case MachO::MH_CORE:
8176 outs() << " CORE";
8177 break;
8178 case MachO::MH_PRELOAD:
8179 outs() << " PRELOAD";
8180 break;
8181 case MachO::MH_DYLIB:
8182 outs() << " DYLIB";
8183 break;
8184 case MachO::MH_DYLIB_STUB:
8185 outs() << " DYLIB_STUB";
8186 break;
8187 case MachO::MH_DYLINKER:
8188 outs() << " DYLINKER";
8189 break;
8190 case MachO::MH_BUNDLE:
8191 outs() << " BUNDLE";
8192 break;
8193 case MachO::MH_DSYM:
8194 outs() << " DSYM";
8195 break;
8196 case MachO::MH_KEXT_BUNDLE:
8197 outs() << " KEXTBUNDLE";
8198 break;
8199 default:
8200 outs() << format(" %10u", filetype);
8201 break;
8202 }
8203 outs() << format(" %5u", ncmds);
8204 outs() << format(" %10u", sizeofcmds);
8205 uint32_t f = flags;
8206 if (f & MachO::MH_NOUNDEFS) {
8207 outs() << " NOUNDEFS";
8208 f &= ~MachO::MH_NOUNDEFS;
8209 }
8210 if (f & MachO::MH_INCRLINK) {
8211 outs() << " INCRLINK";
8212 f &= ~MachO::MH_INCRLINK;
8213 }
8214 if (f & MachO::MH_DYLDLINK) {
8215 outs() << " DYLDLINK";
8216 f &= ~MachO::MH_DYLDLINK;
8217 }
8218 if (f & MachO::MH_BINDATLOAD) {
8219 outs() << " BINDATLOAD";
8220 f &= ~MachO::MH_BINDATLOAD;
8221 }
8222 if (f & MachO::MH_PREBOUND) {
8223 outs() << " PREBOUND";
8224 f &= ~MachO::MH_PREBOUND;
8225 }
8226 if (f & MachO::MH_SPLIT_SEGS) {
8227 outs() << " SPLIT_SEGS";
8228 f &= ~MachO::MH_SPLIT_SEGS;
8229 }
8230 if (f & MachO::MH_LAZY_INIT) {
8231 outs() << " LAZY_INIT";
8232 f &= ~MachO::MH_LAZY_INIT;
8233 }
8234 if (f & MachO::MH_TWOLEVEL) {
8235 outs() << " TWOLEVEL";
8236 f &= ~MachO::MH_TWOLEVEL;
8237 }
8238 if (f & MachO::MH_FORCE_FLAT) {
8239 outs() << " FORCE_FLAT";
8240 f &= ~MachO::MH_FORCE_FLAT;
8241 }
8242 if (f & MachO::MH_NOMULTIDEFS) {
8243 outs() << " NOMULTIDEFS";
8244 f &= ~MachO::MH_NOMULTIDEFS;
8245 }
8246 if (f & MachO::MH_NOFIXPREBINDING) {
8247 outs() << " NOFIXPREBINDING";
8248 f &= ~MachO::MH_NOFIXPREBINDING;
8249 }
8250 if (f & MachO::MH_PREBINDABLE) {
8251 outs() << " PREBINDABLE";
8252 f &= ~MachO::MH_PREBINDABLE;
8253 }
8254 if (f & MachO::MH_ALLMODSBOUND) {
8255 outs() << " ALLMODSBOUND";
8256 f &= ~MachO::MH_ALLMODSBOUND;
8257 }
8258 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8259 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8260 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8261 }
8262 if (f & MachO::MH_CANONICAL) {
8263 outs() << " CANONICAL";
8264 f &= ~MachO::MH_CANONICAL;
8265 }
8266 if (f & MachO::MH_WEAK_DEFINES) {
8267 outs() << " WEAK_DEFINES";
8268 f &= ~MachO::MH_WEAK_DEFINES;
8269 }
8270 if (f & MachO::MH_BINDS_TO_WEAK) {
8271 outs() << " BINDS_TO_WEAK";
8272 f &= ~MachO::MH_BINDS_TO_WEAK;
8273 }
8274 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8275 outs() << " ALLOW_STACK_EXECUTION";
8276 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8277 }
8278 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8279 outs() << " DEAD_STRIPPABLE_DYLIB";
8280 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8281 }
8282 if (f & MachO::MH_PIE) {
8283 outs() << " PIE";
8284 f &= ~MachO::MH_PIE;
8285 }
8286 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8287 outs() << " NO_REEXPORTED_DYLIBS";
8288 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8289 }
8290 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8291 outs() << " MH_HAS_TLV_DESCRIPTORS";
8292 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8293 }
8294 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8295 outs() << " MH_NO_HEAP_EXECUTION";
8296 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8297 }
8298 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8299 outs() << " APP_EXTENSION_SAFE";
8300 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8301 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008302 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8303 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8304 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8305 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008306 if (f != 0 || flags == 0)
8307 outs() << format(" 0x%08" PRIx32, f);
8308 } else {
8309 outs() << format(" 0x%08" PRIx32, magic);
8310 outs() << format(" %7d", cputype);
8311 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8312 outs() << format(" 0x%02" PRIx32,
8313 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8314 outs() << format(" %10u", filetype);
8315 outs() << format(" %5u", ncmds);
8316 outs() << format(" %10u", sizeofcmds);
8317 outs() << format(" 0x%08" PRIx32, flags);
8318 }
8319 outs() << "\n";
8320}
8321
Kevin Enderby956366c2014-08-29 22:30:52 +00008322static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8323 StringRef SegName, uint64_t vmaddr,
8324 uint64_t vmsize, uint64_t fileoff,
8325 uint64_t filesize, uint32_t maxprot,
8326 uint32_t initprot, uint32_t nsects,
8327 uint32_t flags, uint32_t object_size,
8328 bool verbose) {
8329 uint64_t expected_cmdsize;
8330 if (cmd == MachO::LC_SEGMENT) {
8331 outs() << " cmd LC_SEGMENT\n";
8332 expected_cmdsize = nsects;
8333 expected_cmdsize *= sizeof(struct MachO::section);
8334 expected_cmdsize += sizeof(struct MachO::segment_command);
8335 } else {
8336 outs() << " cmd LC_SEGMENT_64\n";
8337 expected_cmdsize = nsects;
8338 expected_cmdsize *= sizeof(struct MachO::section_64);
8339 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8340 }
8341 outs() << " cmdsize " << cmdsize;
8342 if (cmdsize != expected_cmdsize)
8343 outs() << " Inconsistent size\n";
8344 else
8345 outs() << "\n";
8346 outs() << " segname " << SegName << "\n";
8347 if (cmd == MachO::LC_SEGMENT_64) {
8348 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8349 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8350 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008351 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8352 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008353 }
8354 outs() << " fileoff " << fileoff;
8355 if (fileoff > object_size)
8356 outs() << " (past end of file)\n";
8357 else
8358 outs() << "\n";
8359 outs() << " filesize " << filesize;
8360 if (fileoff + filesize > object_size)
8361 outs() << " (past end of file)\n";
8362 else
8363 outs() << "\n";
8364 if (verbose) {
8365 if ((maxprot &
8366 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8367 MachO::VM_PROT_EXECUTE)) != 0)
8368 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8369 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008370 outs() << " maxprot ";
8371 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8372 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8373 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008374 }
8375 if ((initprot &
8376 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8377 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008378 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008379 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008380 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008381 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8382 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8383 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008384 }
8385 } else {
8386 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8387 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8388 }
8389 outs() << " nsects " << nsects << "\n";
8390 if (verbose) {
8391 outs() << " flags";
8392 if (flags == 0)
8393 outs() << " (none)\n";
8394 else {
8395 if (flags & MachO::SG_HIGHVM) {
8396 outs() << " HIGHVM";
8397 flags &= ~MachO::SG_HIGHVM;
8398 }
8399 if (flags & MachO::SG_FVMLIB) {
8400 outs() << " FVMLIB";
8401 flags &= ~MachO::SG_FVMLIB;
8402 }
8403 if (flags & MachO::SG_NORELOC) {
8404 outs() << " NORELOC";
8405 flags &= ~MachO::SG_NORELOC;
8406 }
8407 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8408 outs() << " PROTECTED_VERSION_1";
8409 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8410 }
8411 if (flags)
8412 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8413 else
8414 outs() << "\n";
8415 }
8416 } else {
8417 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8418 }
8419}
8420
8421static void PrintSection(const char *sectname, const char *segname,
8422 uint64_t addr, uint64_t size, uint32_t offset,
8423 uint32_t align, uint32_t reloff, uint32_t nreloc,
8424 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8425 uint32_t cmd, const char *sg_segname,
8426 uint32_t filetype, uint32_t object_size,
8427 bool verbose) {
8428 outs() << "Section\n";
8429 outs() << " sectname " << format("%.16s\n", sectname);
8430 outs() << " segname " << format("%.16s", segname);
8431 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8432 outs() << " (does not match segment)\n";
8433 else
8434 outs() << "\n";
8435 if (cmd == MachO::LC_SEGMENT_64) {
8436 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8437 outs() << " size " << format("0x%016" PRIx64, size);
8438 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008439 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8440 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008441 }
8442 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8443 outs() << " (past end of file)\n";
8444 else
8445 outs() << "\n";
8446 outs() << " offset " << offset;
8447 if (offset > object_size)
8448 outs() << " (past end of file)\n";
8449 else
8450 outs() << "\n";
8451 uint32_t align_shifted = 1 << align;
8452 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8453 outs() << " reloff " << reloff;
8454 if (reloff > object_size)
8455 outs() << " (past end of file)\n";
8456 else
8457 outs() << "\n";
8458 outs() << " nreloc " << nreloc;
8459 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8460 outs() << " (past end of file)\n";
8461 else
8462 outs() << "\n";
8463 uint32_t section_type = flags & MachO::SECTION_TYPE;
8464 if (verbose) {
8465 outs() << " type";
8466 if (section_type == MachO::S_REGULAR)
8467 outs() << " S_REGULAR\n";
8468 else if (section_type == MachO::S_ZEROFILL)
8469 outs() << " S_ZEROFILL\n";
8470 else if (section_type == MachO::S_CSTRING_LITERALS)
8471 outs() << " S_CSTRING_LITERALS\n";
8472 else if (section_type == MachO::S_4BYTE_LITERALS)
8473 outs() << " S_4BYTE_LITERALS\n";
8474 else if (section_type == MachO::S_8BYTE_LITERALS)
8475 outs() << " S_8BYTE_LITERALS\n";
8476 else if (section_type == MachO::S_16BYTE_LITERALS)
8477 outs() << " S_16BYTE_LITERALS\n";
8478 else if (section_type == MachO::S_LITERAL_POINTERS)
8479 outs() << " S_LITERAL_POINTERS\n";
8480 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8481 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8482 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8483 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8484 else if (section_type == MachO::S_SYMBOL_STUBS)
8485 outs() << " S_SYMBOL_STUBS\n";
8486 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8487 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8488 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8489 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8490 else if (section_type == MachO::S_COALESCED)
8491 outs() << " S_COALESCED\n";
8492 else if (section_type == MachO::S_INTERPOSING)
8493 outs() << " S_INTERPOSING\n";
8494 else if (section_type == MachO::S_DTRACE_DOF)
8495 outs() << " S_DTRACE_DOF\n";
8496 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8497 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8498 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8499 outs() << " S_THREAD_LOCAL_REGULAR\n";
8500 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8501 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8502 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8503 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8504 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8505 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8506 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8507 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8508 else
8509 outs() << format("0x%08" PRIx32, section_type) << "\n";
8510 outs() << "attributes";
8511 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8512 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8513 outs() << " PURE_INSTRUCTIONS";
8514 if (section_attributes & MachO::S_ATTR_NO_TOC)
8515 outs() << " NO_TOC";
8516 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8517 outs() << " STRIP_STATIC_SYMS";
8518 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8519 outs() << " NO_DEAD_STRIP";
8520 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8521 outs() << " LIVE_SUPPORT";
8522 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8523 outs() << " SELF_MODIFYING_CODE";
8524 if (section_attributes & MachO::S_ATTR_DEBUG)
8525 outs() << " DEBUG";
8526 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8527 outs() << " SOME_INSTRUCTIONS";
8528 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8529 outs() << " EXT_RELOC";
8530 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8531 outs() << " LOC_RELOC";
8532 if (section_attributes == 0)
8533 outs() << " (none)";
8534 outs() << "\n";
8535 } else
8536 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8537 outs() << " reserved1 " << reserved1;
8538 if (section_type == MachO::S_SYMBOL_STUBS ||
8539 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8540 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8541 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8542 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8543 outs() << " (index into indirect symbol table)\n";
8544 else
8545 outs() << "\n";
8546 outs() << " reserved2 " << reserved2;
8547 if (section_type == MachO::S_SYMBOL_STUBS)
8548 outs() << " (size of stubs)\n";
8549 else
8550 outs() << "\n";
8551}
8552
David Majnemer73cc6ff2014-11-13 19:48:56 +00008553static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008554 uint32_t object_size) {
8555 outs() << " cmd LC_SYMTAB\n";
8556 outs() << " cmdsize " << st.cmdsize;
8557 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8558 outs() << " Incorrect size\n";
8559 else
8560 outs() << "\n";
8561 outs() << " symoff " << st.symoff;
8562 if (st.symoff > object_size)
8563 outs() << " (past end of file)\n";
8564 else
8565 outs() << "\n";
8566 outs() << " nsyms " << st.nsyms;
8567 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008568 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008569 big_size = st.nsyms;
8570 big_size *= sizeof(struct MachO::nlist_64);
8571 big_size += st.symoff;
8572 if (big_size > object_size)
8573 outs() << " (past end of file)\n";
8574 else
8575 outs() << "\n";
8576 } else {
8577 big_size = st.nsyms;
8578 big_size *= sizeof(struct MachO::nlist);
8579 big_size += st.symoff;
8580 if (big_size > object_size)
8581 outs() << " (past end of file)\n";
8582 else
8583 outs() << "\n";
8584 }
8585 outs() << " stroff " << st.stroff;
8586 if (st.stroff > object_size)
8587 outs() << " (past end of file)\n";
8588 else
8589 outs() << "\n";
8590 outs() << " strsize " << st.strsize;
8591 big_size = st.stroff;
8592 big_size += st.strsize;
8593 if (big_size > object_size)
8594 outs() << " (past end of file)\n";
8595 else
8596 outs() << "\n";
8597}
8598
8599static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8600 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008601 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008602 outs() << " cmd LC_DYSYMTAB\n";
8603 outs() << " cmdsize " << dyst.cmdsize;
8604 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8605 outs() << " Incorrect size\n";
8606 else
8607 outs() << "\n";
8608 outs() << " ilocalsym " << dyst.ilocalsym;
8609 if (dyst.ilocalsym > nsyms)
8610 outs() << " (greater than the number of symbols)\n";
8611 else
8612 outs() << "\n";
8613 outs() << " nlocalsym " << dyst.nlocalsym;
8614 uint64_t big_size;
8615 big_size = dyst.ilocalsym;
8616 big_size += dyst.nlocalsym;
8617 if (big_size > nsyms)
8618 outs() << " (past the end of the symbol table)\n";
8619 else
8620 outs() << "\n";
8621 outs() << " iextdefsym " << dyst.iextdefsym;
8622 if (dyst.iextdefsym > nsyms)
8623 outs() << " (greater than the number of symbols)\n";
8624 else
8625 outs() << "\n";
8626 outs() << " nextdefsym " << dyst.nextdefsym;
8627 big_size = dyst.iextdefsym;
8628 big_size += dyst.nextdefsym;
8629 if (big_size > nsyms)
8630 outs() << " (past the end of the symbol table)\n";
8631 else
8632 outs() << "\n";
8633 outs() << " iundefsym " << dyst.iundefsym;
8634 if (dyst.iundefsym > nsyms)
8635 outs() << " (greater than the number of symbols)\n";
8636 else
8637 outs() << "\n";
8638 outs() << " nundefsym " << dyst.nundefsym;
8639 big_size = dyst.iundefsym;
8640 big_size += dyst.nundefsym;
8641 if (big_size > nsyms)
8642 outs() << " (past the end of the symbol table)\n";
8643 else
8644 outs() << "\n";
8645 outs() << " tocoff " << dyst.tocoff;
8646 if (dyst.tocoff > object_size)
8647 outs() << " (past end of file)\n";
8648 else
8649 outs() << "\n";
8650 outs() << " ntoc " << dyst.ntoc;
8651 big_size = dyst.ntoc;
8652 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8653 big_size += dyst.tocoff;
8654 if (big_size > object_size)
8655 outs() << " (past end of file)\n";
8656 else
8657 outs() << "\n";
8658 outs() << " modtaboff " << dyst.modtaboff;
8659 if (dyst.modtaboff > object_size)
8660 outs() << " (past end of file)\n";
8661 else
8662 outs() << "\n";
8663 outs() << " nmodtab " << dyst.nmodtab;
8664 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008665 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008666 modtabend = dyst.nmodtab;
8667 modtabend *= sizeof(struct MachO::dylib_module_64);
8668 modtabend += dyst.modtaboff;
8669 } else {
8670 modtabend = dyst.nmodtab;
8671 modtabend *= sizeof(struct MachO::dylib_module);
8672 modtabend += dyst.modtaboff;
8673 }
8674 if (modtabend > object_size)
8675 outs() << " (past end of file)\n";
8676 else
8677 outs() << "\n";
8678 outs() << " extrefsymoff " << dyst.extrefsymoff;
8679 if (dyst.extrefsymoff > object_size)
8680 outs() << " (past end of file)\n";
8681 else
8682 outs() << "\n";
8683 outs() << " nextrefsyms " << dyst.nextrefsyms;
8684 big_size = dyst.nextrefsyms;
8685 big_size *= sizeof(struct MachO::dylib_reference);
8686 big_size += dyst.extrefsymoff;
8687 if (big_size > object_size)
8688 outs() << " (past end of file)\n";
8689 else
8690 outs() << "\n";
8691 outs() << " indirectsymoff " << dyst.indirectsymoff;
8692 if (dyst.indirectsymoff > object_size)
8693 outs() << " (past end of file)\n";
8694 else
8695 outs() << "\n";
8696 outs() << " nindirectsyms " << dyst.nindirectsyms;
8697 big_size = dyst.nindirectsyms;
8698 big_size *= sizeof(uint32_t);
8699 big_size += dyst.indirectsymoff;
8700 if (big_size > object_size)
8701 outs() << " (past end of file)\n";
8702 else
8703 outs() << "\n";
8704 outs() << " extreloff " << dyst.extreloff;
8705 if (dyst.extreloff > object_size)
8706 outs() << " (past end of file)\n";
8707 else
8708 outs() << "\n";
8709 outs() << " nextrel " << dyst.nextrel;
8710 big_size = dyst.nextrel;
8711 big_size *= sizeof(struct MachO::relocation_info);
8712 big_size += dyst.extreloff;
8713 if (big_size > object_size)
8714 outs() << " (past end of file)\n";
8715 else
8716 outs() << "\n";
8717 outs() << " locreloff " << dyst.locreloff;
8718 if (dyst.locreloff > object_size)
8719 outs() << " (past end of file)\n";
8720 else
8721 outs() << "\n";
8722 outs() << " nlocrel " << dyst.nlocrel;
8723 big_size = dyst.nlocrel;
8724 big_size *= sizeof(struct MachO::relocation_info);
8725 big_size += dyst.locreloff;
8726 if (big_size > object_size)
8727 outs() << " (past end of file)\n";
8728 else
8729 outs() << "\n";
8730}
8731
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008732static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8733 uint32_t object_size) {
8734 if (dc.cmd == MachO::LC_DYLD_INFO)
8735 outs() << " cmd LC_DYLD_INFO\n";
8736 else
8737 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8738 outs() << " cmdsize " << dc.cmdsize;
8739 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8740 outs() << " Incorrect size\n";
8741 else
8742 outs() << "\n";
8743 outs() << " rebase_off " << dc.rebase_off;
8744 if (dc.rebase_off > object_size)
8745 outs() << " (past end of file)\n";
8746 else
8747 outs() << "\n";
8748 outs() << " rebase_size " << dc.rebase_size;
8749 uint64_t big_size;
8750 big_size = dc.rebase_off;
8751 big_size += dc.rebase_size;
8752 if (big_size > object_size)
8753 outs() << " (past end of file)\n";
8754 else
8755 outs() << "\n";
8756 outs() << " bind_off " << dc.bind_off;
8757 if (dc.bind_off > object_size)
8758 outs() << " (past end of file)\n";
8759 else
8760 outs() << "\n";
8761 outs() << " bind_size " << dc.bind_size;
8762 big_size = dc.bind_off;
8763 big_size += dc.bind_size;
8764 if (big_size > object_size)
8765 outs() << " (past end of file)\n";
8766 else
8767 outs() << "\n";
8768 outs() << " weak_bind_off " << dc.weak_bind_off;
8769 if (dc.weak_bind_off > object_size)
8770 outs() << " (past end of file)\n";
8771 else
8772 outs() << "\n";
8773 outs() << " weak_bind_size " << dc.weak_bind_size;
8774 big_size = dc.weak_bind_off;
8775 big_size += dc.weak_bind_size;
8776 if (big_size > object_size)
8777 outs() << " (past end of file)\n";
8778 else
8779 outs() << "\n";
8780 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8781 if (dc.lazy_bind_off > object_size)
8782 outs() << " (past end of file)\n";
8783 else
8784 outs() << "\n";
8785 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8786 big_size = dc.lazy_bind_off;
8787 big_size += dc.lazy_bind_size;
8788 if (big_size > object_size)
8789 outs() << " (past end of file)\n";
8790 else
8791 outs() << "\n";
8792 outs() << " export_off " << dc.export_off;
8793 if (dc.export_off > object_size)
8794 outs() << " (past end of file)\n";
8795 else
8796 outs() << "\n";
8797 outs() << " export_size " << dc.export_size;
8798 big_size = dc.export_off;
8799 big_size += dc.export_size;
8800 if (big_size > object_size)
8801 outs() << " (past end of file)\n";
8802 else
8803 outs() << "\n";
8804}
8805
8806static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8807 const char *Ptr) {
8808 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8809 outs() << " cmd LC_ID_DYLINKER\n";
8810 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8811 outs() << " cmd LC_LOAD_DYLINKER\n";
8812 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8813 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8814 else
8815 outs() << " cmd ?(" << dyld.cmd << ")\n";
8816 outs() << " cmdsize " << dyld.cmdsize;
8817 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8818 outs() << " Incorrect size\n";
8819 else
8820 outs() << "\n";
8821 if (dyld.name >= dyld.cmdsize)
8822 outs() << " name ?(bad offset " << dyld.name << ")\n";
8823 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008824 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008825 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8826 }
8827}
8828
8829static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8830 outs() << " cmd LC_UUID\n";
8831 outs() << " cmdsize " << uuid.cmdsize;
8832 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8833 outs() << " Incorrect size\n";
8834 else
8835 outs() << "\n";
8836 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008837 for (int i = 0; i < 16; ++i) {
8838 outs() << format("%02" PRIX32, uuid.uuid[i]);
8839 if (i == 3 || i == 5 || i == 7 || i == 9)
8840 outs() << "-";
8841 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008842 outs() << "\n";
8843}
8844
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008845static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008846 outs() << " cmd LC_RPATH\n";
8847 outs() << " cmdsize " << rpath.cmdsize;
8848 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8849 outs() << " Incorrect size\n";
8850 else
8851 outs() << "\n";
8852 if (rpath.path >= rpath.cmdsize)
8853 outs() << " path ?(bad offset " << rpath.path << ")\n";
8854 else {
8855 const char *P = (const char *)(Ptr) + rpath.path;
8856 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8857 }
8858}
8859
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008860static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008861 StringRef LoadCmdName;
8862 switch (vd.cmd) {
8863 case MachO::LC_VERSION_MIN_MACOSX:
8864 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8865 break;
8866 case MachO::LC_VERSION_MIN_IPHONEOS:
8867 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8868 break;
8869 case MachO::LC_VERSION_MIN_TVOS:
8870 LoadCmdName = "LC_VERSION_MIN_TVOS";
8871 break;
8872 case MachO::LC_VERSION_MIN_WATCHOS:
8873 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8874 break;
8875 default:
8876 llvm_unreachable("Unknown version min load command");
8877 }
8878
8879 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008880 outs() << " cmdsize " << vd.cmdsize;
8881 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8882 outs() << " Incorrect size\n";
8883 else
8884 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008885 outs() << " version "
8886 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8887 << MachOObjectFile::getVersionMinMinor(vd, false);
8888 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8889 if (Update != 0)
8890 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008891 outs() << "\n";
8892 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008893 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008894 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008895 outs() << " sdk "
8896 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8897 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008898 }
Davide Italiano56baef32015-08-26 12:26:11 +00008899 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8900 if (Update != 0)
8901 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008902 outs() << "\n";
8903}
8904
Kevin Enderbya4579c42017-01-19 17:36:31 +00008905static void PrintNoteLoadCommand(MachO::note_command Nt) {
8906 outs() << " cmd LC_NOTE\n";
8907 outs() << " cmdsize " << Nt.cmdsize;
8908 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8909 outs() << " Incorrect size\n";
8910 else
8911 outs() << "\n";
8912 const char *d = Nt.data_owner;
8913 outs() << "data_owner " << format("%.16s\n", d);
8914 outs() << " offset " << Nt.offset << "\n";
8915 outs() << " size " << Nt.size << "\n";
8916}
8917
Steven Wu5b54a422017-01-23 20:07:55 +00008918static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8919 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8920 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8921 << "\n";
8922}
8923
8924static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8925 MachO::build_version_command bd) {
8926 outs() << " cmd LC_BUILD_VERSION\n";
8927 outs() << " cmdsize " << bd.cmdsize;
8928 if (bd.cmdsize !=
8929 sizeof(struct MachO::build_version_command) +
8930 bd.ntools * sizeof(struct MachO::build_tool_version))
8931 outs() << " Incorrect size\n";
8932 else
8933 outs() << "\n";
8934 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8935 << "\n";
8936 if (bd.sdk)
8937 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8938 << "\n";
8939 else
8940 outs() << " sdk n/a\n";
8941 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8942 << "\n";
8943 outs() << " ntools " << bd.ntools << "\n";
8944 for (unsigned i = 0; i < bd.ntools; ++i) {
8945 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8946 PrintBuildToolVersion(bv);
8947 }
8948}
8949
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008950static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8951 outs() << " cmd LC_SOURCE_VERSION\n";
8952 outs() << " cmdsize " << sd.cmdsize;
8953 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8954 outs() << " Incorrect size\n";
8955 else
8956 outs() << "\n";
8957 uint64_t a = (sd.version >> 40) & 0xffffff;
8958 uint64_t b = (sd.version >> 30) & 0x3ff;
8959 uint64_t c = (sd.version >> 20) & 0x3ff;
8960 uint64_t d = (sd.version >> 10) & 0x3ff;
8961 uint64_t e = sd.version & 0x3ff;
8962 outs() << " version " << a << "." << b;
8963 if (e != 0)
8964 outs() << "." << c << "." << d << "." << e;
8965 else if (d != 0)
8966 outs() << "." << c << "." << d;
8967 else if (c != 0)
8968 outs() << "." << c;
8969 outs() << "\n";
8970}
8971
8972static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8973 outs() << " cmd LC_MAIN\n";
8974 outs() << " cmdsize " << ep.cmdsize;
8975 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8976 outs() << " Incorrect size\n";
8977 else
8978 outs() << "\n";
8979 outs() << " entryoff " << ep.entryoff << "\n";
8980 outs() << " stacksize " << ep.stacksize << "\n";
8981}
8982
Kevin Enderby0804f4672014-12-16 23:25:52 +00008983static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8984 uint32_t object_size) {
8985 outs() << " cmd LC_ENCRYPTION_INFO\n";
8986 outs() << " cmdsize " << ec.cmdsize;
8987 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8988 outs() << " Incorrect size\n";
8989 else
8990 outs() << "\n";
8991 outs() << " cryptoff " << ec.cryptoff;
8992 if (ec.cryptoff > object_size)
8993 outs() << " (past end of file)\n";
8994 else
8995 outs() << "\n";
8996 outs() << " cryptsize " << ec.cryptsize;
8997 if (ec.cryptsize > object_size)
8998 outs() << " (past end of file)\n";
8999 else
9000 outs() << "\n";
9001 outs() << " cryptid " << ec.cryptid << "\n";
9002}
9003
Kevin Enderby57538292014-12-17 01:01:30 +00009004static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009005 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00009006 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9007 outs() << " cmdsize " << ec.cmdsize;
9008 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9009 outs() << " Incorrect size\n";
9010 else
9011 outs() << "\n";
9012 outs() << " cryptoff " << ec.cryptoff;
9013 if (ec.cryptoff > object_size)
9014 outs() << " (past end of file)\n";
9015 else
9016 outs() << "\n";
9017 outs() << " cryptsize " << ec.cryptsize;
9018 if (ec.cryptsize > object_size)
9019 outs() << " (past end of file)\n";
9020 else
9021 outs() << "\n";
9022 outs() << " cryptid " << ec.cryptid << "\n";
9023 outs() << " pad " << ec.pad << "\n";
9024}
9025
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009026static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9027 const char *Ptr) {
9028 outs() << " cmd LC_LINKER_OPTION\n";
9029 outs() << " cmdsize " << lo.cmdsize;
9030 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9031 outs() << " Incorrect size\n";
9032 else
9033 outs() << "\n";
9034 outs() << " count " << lo.count << "\n";
9035 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9036 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9037 uint32_t i = 0;
9038 while (left > 0) {
9039 while (*string == '\0' && left > 0) {
9040 string++;
9041 left--;
9042 }
9043 if (left > 0) {
9044 i++;
9045 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009046 uint32_t NullPos = StringRef(string, left).find('\0');
9047 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009048 string += len;
9049 left -= len;
9050 }
9051 }
9052 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009053 outs() << " count " << lo.count << " does not match number of strings "
9054 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009055}
9056
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009057static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9058 const char *Ptr) {
9059 outs() << " cmd LC_SUB_FRAMEWORK\n";
9060 outs() << " cmdsize " << sub.cmdsize;
9061 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9062 outs() << " Incorrect size\n";
9063 else
9064 outs() << "\n";
9065 if (sub.umbrella < sub.cmdsize) {
9066 const char *P = Ptr + sub.umbrella;
9067 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9068 } else {
9069 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9070 }
9071}
9072
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009073static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9074 const char *Ptr) {
9075 outs() << " cmd LC_SUB_UMBRELLA\n";
9076 outs() << " cmdsize " << sub.cmdsize;
9077 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9078 outs() << " Incorrect size\n";
9079 else
9080 outs() << "\n";
9081 if (sub.sub_umbrella < sub.cmdsize) {
9082 const char *P = Ptr + sub.sub_umbrella;
9083 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9084 } else {
9085 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9086 }
9087}
9088
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009089static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009090 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009091 outs() << " cmd LC_SUB_LIBRARY\n";
9092 outs() << " cmdsize " << sub.cmdsize;
9093 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9094 outs() << " Incorrect size\n";
9095 else
9096 outs() << "\n";
9097 if (sub.sub_library < sub.cmdsize) {
9098 const char *P = Ptr + sub.sub_library;
9099 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9100 } else {
9101 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9102 }
9103}
9104
Kevin Enderby186eac32014-12-19 21:06:24 +00009105static void PrintSubClientCommand(MachO::sub_client_command sub,
9106 const char *Ptr) {
9107 outs() << " cmd LC_SUB_CLIENT\n";
9108 outs() << " cmdsize " << sub.cmdsize;
9109 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9110 outs() << " Incorrect size\n";
9111 else
9112 outs() << "\n";
9113 if (sub.client < sub.cmdsize) {
9114 const char *P = Ptr + sub.client;
9115 outs() << " client " << P << " (offset " << sub.client << ")\n";
9116 } else {
9117 outs() << " client ?(bad offset " << sub.client << ")\n";
9118 }
9119}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009120
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009121static void PrintRoutinesCommand(MachO::routines_command r) {
9122 outs() << " cmd LC_ROUTINES\n";
9123 outs() << " cmdsize " << r.cmdsize;
9124 if (r.cmdsize != sizeof(struct MachO::routines_command))
9125 outs() << " Incorrect size\n";
9126 else
9127 outs() << "\n";
9128 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9129 outs() << " init_module " << r.init_module << "\n";
9130 outs() << " reserved1 " << r.reserved1 << "\n";
9131 outs() << " reserved2 " << r.reserved2 << "\n";
9132 outs() << " reserved3 " << r.reserved3 << "\n";
9133 outs() << " reserved4 " << r.reserved4 << "\n";
9134 outs() << " reserved5 " << r.reserved5 << "\n";
9135 outs() << " reserved6 " << r.reserved6 << "\n";
9136}
9137
9138static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9139 outs() << " cmd LC_ROUTINES_64\n";
9140 outs() << " cmdsize " << r.cmdsize;
9141 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9142 outs() << " Incorrect size\n";
9143 else
9144 outs() << "\n";
9145 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9146 outs() << " init_module " << r.init_module << "\n";
9147 outs() << " reserved1 " << r.reserved1 << "\n";
9148 outs() << " reserved2 " << r.reserved2 << "\n";
9149 outs() << " reserved3 " << r.reserved3 << "\n";
9150 outs() << " reserved4 " << r.reserved4 << "\n";
9151 outs() << " reserved5 " << r.reserved5 << "\n";
9152 outs() << " reserved6 " << r.reserved6 << "\n";
9153}
9154
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009155static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9156 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9157 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9158 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9159 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9160 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9161 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9162 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9163 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9164 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9165 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9166 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9167 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9168 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9169 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9170 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9171 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9172}
9173
Kevin Enderby48ef5342014-12-23 22:56:39 +00009174static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9175 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9176 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9177 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9178 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9179 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9180 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9181 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9182 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9183 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9184 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9185 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9186 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9187 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9188 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9189 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9190 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9191 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9192 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9193 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9194 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9195 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9196}
9197
Kevin Enderby227df342014-12-23 23:43:59 +00009198static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009199 uint32_t f;
9200 outs() << "\t mmst_reg ";
9201 for (f = 0; f < 10; f++)
9202 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9203 outs() << "\n";
9204 outs() << "\t mmst_rsrv ";
9205 for (f = 0; f < 6; f++)
9206 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9207 outs() << "\n";
9208}
9209
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009210static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009211 uint32_t f;
9212 outs() << "\t xmm_reg ";
9213 for (f = 0; f < 16; f++)
9214 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9215 outs() << "\n";
9216}
9217
9218static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9219 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9220 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9221 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9222 outs() << " denorm " << fpu.fpu_fcw.denorm;
9223 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9224 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9225 outs() << " undfl " << fpu.fpu_fcw.undfl;
9226 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9227 outs() << "\t\t pc ";
9228 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9229 outs() << "FP_PREC_24B ";
9230 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9231 outs() << "FP_PREC_53B ";
9232 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9233 outs() << "FP_PREC_64B ";
9234 else
9235 outs() << fpu.fpu_fcw.pc << " ";
9236 outs() << "rc ";
9237 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9238 outs() << "FP_RND_NEAR ";
9239 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9240 outs() << "FP_RND_DOWN ";
9241 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9242 outs() << "FP_RND_UP ";
9243 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009244 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009245 outs() << "\n";
9246 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9247 outs() << " denorm " << fpu.fpu_fsw.denorm;
9248 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9249 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9250 outs() << " undfl " << fpu.fpu_fsw.undfl;
9251 outs() << " precis " << fpu.fpu_fsw.precis;
9252 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9253 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9254 outs() << " c0 " << fpu.fpu_fsw.c0;
9255 outs() << " c1 " << fpu.fpu_fsw.c1;
9256 outs() << " c2 " << fpu.fpu_fsw.c2;
9257 outs() << " tos " << fpu.fpu_fsw.tos;
9258 outs() << " c3 " << fpu.fpu_fsw.c3;
9259 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9260 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9261 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9262 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9263 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9264 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9265 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9266 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9267 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9268 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9269 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9270 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9271 outs() << "\n";
9272 outs() << "\t fpu_stmm0:\n";
9273 Print_mmst_reg(fpu.fpu_stmm0);
9274 outs() << "\t fpu_stmm1:\n";
9275 Print_mmst_reg(fpu.fpu_stmm1);
9276 outs() << "\t fpu_stmm2:\n";
9277 Print_mmst_reg(fpu.fpu_stmm2);
9278 outs() << "\t fpu_stmm3:\n";
9279 Print_mmst_reg(fpu.fpu_stmm3);
9280 outs() << "\t fpu_stmm4:\n";
9281 Print_mmst_reg(fpu.fpu_stmm4);
9282 outs() << "\t fpu_stmm5:\n";
9283 Print_mmst_reg(fpu.fpu_stmm5);
9284 outs() << "\t fpu_stmm6:\n";
9285 Print_mmst_reg(fpu.fpu_stmm6);
9286 outs() << "\t fpu_stmm7:\n";
9287 Print_mmst_reg(fpu.fpu_stmm7);
9288 outs() << "\t fpu_xmm0:\n";
9289 Print_xmm_reg(fpu.fpu_xmm0);
9290 outs() << "\t fpu_xmm1:\n";
9291 Print_xmm_reg(fpu.fpu_xmm1);
9292 outs() << "\t fpu_xmm2:\n";
9293 Print_xmm_reg(fpu.fpu_xmm2);
9294 outs() << "\t fpu_xmm3:\n";
9295 Print_xmm_reg(fpu.fpu_xmm3);
9296 outs() << "\t fpu_xmm4:\n";
9297 Print_xmm_reg(fpu.fpu_xmm4);
9298 outs() << "\t fpu_xmm5:\n";
9299 Print_xmm_reg(fpu.fpu_xmm5);
9300 outs() << "\t fpu_xmm6:\n";
9301 Print_xmm_reg(fpu.fpu_xmm6);
9302 outs() << "\t fpu_xmm7:\n";
9303 Print_xmm_reg(fpu.fpu_xmm7);
9304 outs() << "\t fpu_xmm8:\n";
9305 Print_xmm_reg(fpu.fpu_xmm8);
9306 outs() << "\t fpu_xmm9:\n";
9307 Print_xmm_reg(fpu.fpu_xmm9);
9308 outs() << "\t fpu_xmm10:\n";
9309 Print_xmm_reg(fpu.fpu_xmm10);
9310 outs() << "\t fpu_xmm11:\n";
9311 Print_xmm_reg(fpu.fpu_xmm11);
9312 outs() << "\t fpu_xmm12:\n";
9313 Print_xmm_reg(fpu.fpu_xmm12);
9314 outs() << "\t fpu_xmm13:\n";
9315 Print_xmm_reg(fpu.fpu_xmm13);
9316 outs() << "\t fpu_xmm14:\n";
9317 Print_xmm_reg(fpu.fpu_xmm14);
9318 outs() << "\t fpu_xmm15:\n";
9319 Print_xmm_reg(fpu.fpu_xmm15);
9320 outs() << "\t fpu_rsrv4:\n";
9321 for (uint32_t f = 0; f < 6; f++) {
9322 outs() << "\t ";
9323 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009324 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009325 outs() << "\n";
9326 }
9327 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9328 outs() << "\n";
9329}
9330
9331static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9332 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9333 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9334 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9335}
9336
Kevin Enderby41c9c002016-10-21 18:22:35 +00009337static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9338 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9339 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9340 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9341 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9342 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9343 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9344 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9345 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9346 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9347 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9348 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9349 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9350 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9351 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9352 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9353 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9354 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9355}
9356
Kevin Enderby7747cb52016-11-03 20:51:28 +00009357static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9358 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9359 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9360 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9361 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9362 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9363 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9364 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9365 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9366 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9367 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9368 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9369 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9370 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9371 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9372 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9373 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9374 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9375 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9376 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9377 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9378 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9379 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9380 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9381 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9382 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9383 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9384 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9385 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9386 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9387 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9388 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9389 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9390 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9391 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9392}
9393
Kevin Enderby48ef5342014-12-23 22:56:39 +00009394static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9395 bool isLittleEndian, uint32_t cputype) {
9396 if (t.cmd == MachO::LC_THREAD)
9397 outs() << " cmd LC_THREAD\n";
9398 else if (t.cmd == MachO::LC_UNIXTHREAD)
9399 outs() << " cmd LC_UNIXTHREAD\n";
9400 else
9401 outs() << " cmd " << t.cmd << " (unknown)\n";
9402 outs() << " cmdsize " << t.cmdsize;
9403 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9404 outs() << " Incorrect size\n";
9405 else
9406 outs() << "\n";
9407
9408 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9409 const char *end = Ptr + t.cmdsize;
9410 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009411 if (cputype == MachO::CPU_TYPE_I386) {
9412 while (begin < end) {
9413 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9414 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9415 begin += sizeof(uint32_t);
9416 } else {
9417 flavor = 0;
9418 begin = end;
9419 }
9420 if (isLittleEndian != sys::IsLittleEndianHost)
9421 sys::swapByteOrder(flavor);
9422 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9423 memcpy((char *)&count, begin, sizeof(uint32_t));
9424 begin += sizeof(uint32_t);
9425 } else {
9426 count = 0;
9427 begin = end;
9428 }
9429 if (isLittleEndian != sys::IsLittleEndianHost)
9430 sys::swapByteOrder(count);
9431 if (flavor == MachO::x86_THREAD_STATE32) {
9432 outs() << " flavor i386_THREAD_STATE\n";
9433 if (count == MachO::x86_THREAD_STATE32_COUNT)
9434 outs() << " count i386_THREAD_STATE_COUNT\n";
9435 else
9436 outs() << " count " << count
9437 << " (not x86_THREAD_STATE32_COUNT)\n";
9438 MachO::x86_thread_state32_t cpu32;
9439 left = end - begin;
9440 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9441 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9442 begin += sizeof(MachO::x86_thread_state32_t);
9443 } else {
9444 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9445 memcpy(&cpu32, begin, left);
9446 begin += left;
9447 }
9448 if (isLittleEndian != sys::IsLittleEndianHost)
9449 swapStruct(cpu32);
9450 Print_x86_thread_state32_t(cpu32);
9451 } else if (flavor == MachO::x86_THREAD_STATE) {
9452 outs() << " flavor x86_THREAD_STATE\n";
9453 if (count == MachO::x86_THREAD_STATE_COUNT)
9454 outs() << " count x86_THREAD_STATE_COUNT\n";
9455 else
9456 outs() << " count " << count
9457 << " (not x86_THREAD_STATE_COUNT)\n";
9458 struct MachO::x86_thread_state_t ts;
9459 left = end - begin;
9460 if (left >= sizeof(MachO::x86_thread_state_t)) {
9461 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9462 begin += sizeof(MachO::x86_thread_state_t);
9463 } else {
9464 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9465 memcpy(&ts, begin, left);
9466 begin += left;
9467 }
9468 if (isLittleEndian != sys::IsLittleEndianHost)
9469 swapStruct(ts);
9470 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9471 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9472 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9473 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9474 else
9475 outs() << "tsh.count " << ts.tsh.count
9476 << " (not x86_THREAD_STATE32_COUNT\n";
9477 Print_x86_thread_state32_t(ts.uts.ts32);
9478 } else {
9479 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9480 << ts.tsh.count << "\n";
9481 }
9482 } else {
9483 outs() << " flavor " << flavor << " (unknown)\n";
9484 outs() << " count " << count << "\n";
9485 outs() << " state (unknown)\n";
9486 begin += count * sizeof(uint32_t);
9487 }
9488 }
9489 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009490 while (begin < end) {
9491 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9492 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9493 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009494 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009495 flavor = 0;
9496 begin = end;
9497 }
9498 if (isLittleEndian != sys::IsLittleEndianHost)
9499 sys::swapByteOrder(flavor);
9500 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9501 memcpy((char *)&count, begin, sizeof(uint32_t));
9502 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009503 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009504 count = 0;
9505 begin = end;
9506 }
9507 if (isLittleEndian != sys::IsLittleEndianHost)
9508 sys::swapByteOrder(count);
9509 if (flavor == MachO::x86_THREAD_STATE64) {
9510 outs() << " flavor x86_THREAD_STATE64\n";
9511 if (count == MachO::x86_THREAD_STATE64_COUNT)
9512 outs() << " count x86_THREAD_STATE64_COUNT\n";
9513 else
9514 outs() << " count " << count
9515 << " (not x86_THREAD_STATE64_COUNT)\n";
9516 MachO::x86_thread_state64_t cpu64;
9517 left = end - begin;
9518 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9519 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9520 begin += sizeof(MachO::x86_thread_state64_t);
9521 } else {
9522 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9523 memcpy(&cpu64, begin, left);
9524 begin += left;
9525 }
9526 if (isLittleEndian != sys::IsLittleEndianHost)
9527 swapStruct(cpu64);
9528 Print_x86_thread_state64_t(cpu64);
9529 } else if (flavor == MachO::x86_THREAD_STATE) {
9530 outs() << " flavor x86_THREAD_STATE\n";
9531 if (count == MachO::x86_THREAD_STATE_COUNT)
9532 outs() << " count x86_THREAD_STATE_COUNT\n";
9533 else
9534 outs() << " count " << count
9535 << " (not x86_THREAD_STATE_COUNT)\n";
9536 struct MachO::x86_thread_state_t ts;
9537 left = end - begin;
9538 if (left >= sizeof(MachO::x86_thread_state_t)) {
9539 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9540 begin += sizeof(MachO::x86_thread_state_t);
9541 } else {
9542 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9543 memcpy(&ts, begin, left);
9544 begin += left;
9545 }
9546 if (isLittleEndian != sys::IsLittleEndianHost)
9547 swapStruct(ts);
9548 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9549 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9550 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9551 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9552 else
9553 outs() << "tsh.count " << ts.tsh.count
9554 << " (not x86_THREAD_STATE64_COUNT\n";
9555 Print_x86_thread_state64_t(ts.uts.ts64);
9556 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009557 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9558 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009559 }
9560 } else if (flavor == MachO::x86_FLOAT_STATE) {
9561 outs() << " flavor x86_FLOAT_STATE\n";
9562 if (count == MachO::x86_FLOAT_STATE_COUNT)
9563 outs() << " count x86_FLOAT_STATE_COUNT\n";
9564 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009565 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009566 struct MachO::x86_float_state_t fs;
9567 left = end - begin;
9568 if (left >= sizeof(MachO::x86_float_state_t)) {
9569 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9570 begin += sizeof(MachO::x86_float_state_t);
9571 } else {
9572 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9573 memcpy(&fs, begin, left);
9574 begin += left;
9575 }
9576 if (isLittleEndian != sys::IsLittleEndianHost)
9577 swapStruct(fs);
9578 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9579 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009580 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009581 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9582 else
9583 outs() << "fsh.count " << fs.fsh.count
9584 << " (not x86_FLOAT_STATE64_COUNT\n";
9585 Print_x86_float_state_t(fs.ufs.fs64);
9586 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009587 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9588 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009589 }
9590 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9591 outs() << " flavor x86_EXCEPTION_STATE\n";
9592 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9593 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9594 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009595 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009596 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9597 struct MachO::x86_exception_state_t es;
9598 left = end - begin;
9599 if (left >= sizeof(MachO::x86_exception_state_t)) {
9600 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9601 begin += sizeof(MachO::x86_exception_state_t);
9602 } else {
9603 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9604 memcpy(&es, begin, left);
9605 begin += left;
9606 }
9607 if (isLittleEndian != sys::IsLittleEndianHost)
9608 swapStruct(es);
9609 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9610 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009611 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009612 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9613 else
9614 outs() << "\t esh.count " << es.esh.count
9615 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9616 Print_x86_exception_state_t(es.ues.es64);
9617 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009618 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9619 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009620 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009621 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9622 outs() << " flavor x86_EXCEPTION_STATE64\n";
9623 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9624 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9625 else
9626 outs() << " count " << count
9627 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9628 struct MachO::x86_exception_state64_t es64;
9629 left = end - begin;
9630 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9631 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9632 begin += sizeof(MachO::x86_exception_state64_t);
9633 } else {
9634 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9635 memcpy(&es64, begin, left);
9636 begin += left;
9637 }
9638 if (isLittleEndian != sys::IsLittleEndianHost)
9639 swapStruct(es64);
9640 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009641 } else {
9642 outs() << " flavor " << flavor << " (unknown)\n";
9643 outs() << " count " << count << "\n";
9644 outs() << " state (unknown)\n";
9645 begin += count * sizeof(uint32_t);
9646 }
9647 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009648 } else if (cputype == MachO::CPU_TYPE_ARM) {
9649 while (begin < end) {
9650 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9651 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9652 begin += sizeof(uint32_t);
9653 } else {
9654 flavor = 0;
9655 begin = end;
9656 }
9657 if (isLittleEndian != sys::IsLittleEndianHost)
9658 sys::swapByteOrder(flavor);
9659 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9660 memcpy((char *)&count, begin, sizeof(uint32_t));
9661 begin += sizeof(uint32_t);
9662 } else {
9663 count = 0;
9664 begin = end;
9665 }
9666 if (isLittleEndian != sys::IsLittleEndianHost)
9667 sys::swapByteOrder(count);
9668 if (flavor == MachO::ARM_THREAD_STATE) {
9669 outs() << " flavor ARM_THREAD_STATE\n";
9670 if (count == MachO::ARM_THREAD_STATE_COUNT)
9671 outs() << " count ARM_THREAD_STATE_COUNT\n";
9672 else
9673 outs() << " count " << count
9674 << " (not ARM_THREAD_STATE_COUNT)\n";
9675 MachO::arm_thread_state32_t cpu32;
9676 left = end - begin;
9677 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9678 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9679 begin += sizeof(MachO::arm_thread_state32_t);
9680 } else {
9681 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9682 memcpy(&cpu32, begin, left);
9683 begin += left;
9684 }
9685 if (isLittleEndian != sys::IsLittleEndianHost)
9686 swapStruct(cpu32);
9687 Print_arm_thread_state32_t(cpu32);
9688 } else {
9689 outs() << " flavor " << flavor << " (unknown)\n";
9690 outs() << " count " << count << "\n";
9691 outs() << " state (unknown)\n";
9692 begin += count * sizeof(uint32_t);
9693 }
9694 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009695 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9696 while (begin < end) {
9697 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9698 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9699 begin += sizeof(uint32_t);
9700 } else {
9701 flavor = 0;
9702 begin = end;
9703 }
9704 if (isLittleEndian != sys::IsLittleEndianHost)
9705 sys::swapByteOrder(flavor);
9706 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9707 memcpy((char *)&count, begin, sizeof(uint32_t));
9708 begin += sizeof(uint32_t);
9709 } else {
9710 count = 0;
9711 begin = end;
9712 }
9713 if (isLittleEndian != sys::IsLittleEndianHost)
9714 sys::swapByteOrder(count);
9715 if (flavor == MachO::ARM_THREAD_STATE64) {
9716 outs() << " flavor ARM_THREAD_STATE64\n";
9717 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9718 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9719 else
9720 outs() << " count " << count
9721 << " (not ARM_THREAD_STATE64_COUNT)\n";
9722 MachO::arm_thread_state64_t cpu64;
9723 left = end - begin;
9724 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9725 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9726 begin += sizeof(MachO::arm_thread_state64_t);
9727 } else {
9728 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9729 memcpy(&cpu64, begin, left);
9730 begin += left;
9731 }
9732 if (isLittleEndian != sys::IsLittleEndianHost)
9733 swapStruct(cpu64);
9734 Print_arm_thread_state64_t(cpu64);
9735 } else {
9736 outs() << " flavor " << flavor << " (unknown)\n";
9737 outs() << " count " << count << "\n";
9738 outs() << " state (unknown)\n";
9739 begin += count * sizeof(uint32_t);
9740 }
9741 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009742 } else {
9743 while (begin < end) {
9744 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9745 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9746 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009747 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009748 flavor = 0;
9749 begin = end;
9750 }
9751 if (isLittleEndian != sys::IsLittleEndianHost)
9752 sys::swapByteOrder(flavor);
9753 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9754 memcpy((char *)&count, begin, sizeof(uint32_t));
9755 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009756 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009757 count = 0;
9758 begin = end;
9759 }
9760 if (isLittleEndian != sys::IsLittleEndianHost)
9761 sys::swapByteOrder(count);
9762 outs() << " flavor " << flavor << "\n";
9763 outs() << " count " << count << "\n";
9764 outs() << " state (Unknown cputype/cpusubtype)\n";
9765 begin += count * sizeof(uint32_t);
9766 }
9767 }
9768}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009769
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009770static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9771 if (dl.cmd == MachO::LC_ID_DYLIB)
9772 outs() << " cmd LC_ID_DYLIB\n";
9773 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9774 outs() << " cmd LC_LOAD_DYLIB\n";
9775 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9776 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9777 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9778 outs() << " cmd LC_REEXPORT_DYLIB\n";
9779 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9780 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9781 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9782 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9783 else
9784 outs() << " cmd " << dl.cmd << " (unknown)\n";
9785 outs() << " cmdsize " << dl.cmdsize;
9786 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9787 outs() << " Incorrect size\n";
9788 else
9789 outs() << "\n";
9790 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009791 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009792 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9793 } else {
9794 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9795 }
9796 outs() << " time stamp " << dl.dylib.timestamp << " ";
9797 time_t t = dl.dylib.timestamp;
9798 outs() << ctime(&t);
9799 outs() << " current version ";
9800 if (dl.dylib.current_version == 0xffffffff)
9801 outs() << "n/a\n";
9802 else
9803 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9804 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9805 << (dl.dylib.current_version & 0xff) << "\n";
9806 outs() << "compatibility version ";
9807 if (dl.dylib.compatibility_version == 0xffffffff)
9808 outs() << "n/a\n";
9809 else
9810 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9811 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9812 << (dl.dylib.compatibility_version & 0xff) << "\n";
9813}
9814
9815static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9816 uint32_t object_size) {
9817 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009818 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009819 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9820 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9821 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9822 outs() << " cmd LC_FUNCTION_STARTS\n";
9823 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9824 outs() << " cmd LC_DATA_IN_CODE\n";
9825 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9826 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9827 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9828 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9829 else
9830 outs() << " cmd " << ld.cmd << " (?)\n";
9831 outs() << " cmdsize " << ld.cmdsize;
9832 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9833 outs() << " Incorrect size\n";
9834 else
9835 outs() << "\n";
9836 outs() << " dataoff " << ld.dataoff;
9837 if (ld.dataoff > object_size)
9838 outs() << " (past end of file)\n";
9839 else
9840 outs() << "\n";
9841 outs() << " datasize " << ld.datasize;
9842 uint64_t big_size = ld.dataoff;
9843 big_size += ld.datasize;
9844 if (big_size > object_size)
9845 outs() << " (past end of file)\n";
9846 else
9847 outs() << "\n";
9848}
9849
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009850static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9851 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009852 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009853 unsigned Index = 0;
9854 for (const auto &Command : Obj->load_commands()) {
9855 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009856 if (Command.C.cmd == MachO::LC_SEGMENT) {
9857 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9858 const char *sg_segname = SLC.segname;
9859 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9860 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9861 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9862 verbose);
9863 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009864 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009865 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9866 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9867 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9868 }
9869 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9870 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9871 const char *sg_segname = SLC_64.segname;
9872 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9873 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9874 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9875 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9876 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9877 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9878 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9879 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9880 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9881 sg_segname, filetype, Buf.size(), verbose);
9882 }
9883 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9884 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009885 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009886 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9887 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9888 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009889 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9890 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009891 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9892 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9893 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9894 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9895 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9896 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9897 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9898 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9899 PrintDyldLoadCommand(Dyld, Command.Ptr);
9900 } else if (Command.C.cmd == MachO::LC_UUID) {
9901 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9902 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009903 } else if (Command.C.cmd == MachO::LC_RPATH) {
9904 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9905 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009906 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009907 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9908 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9909 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009910 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9911 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009912 } else if (Command.C.cmd == MachO::LC_NOTE) {
9913 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9914 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009915 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9916 MachO::build_version_command Bv =
9917 Obj->getBuildVersionLoadCommand(Command);
9918 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009919 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9920 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9921 PrintSourceVersionCommand(Sd);
9922 } else if (Command.C.cmd == MachO::LC_MAIN) {
9923 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9924 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009925 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009926 MachO::encryption_info_command Ei =
9927 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009928 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009929 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009930 MachO::encryption_info_command_64 Ei =
9931 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009932 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009933 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009934 MachO::linker_option_command Lo =
9935 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009936 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009937 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9938 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9939 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009940 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9941 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9942 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009943 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9944 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9945 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009946 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9947 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9948 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009949 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9950 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9951 PrintRoutinesCommand(Rc);
9952 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9953 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9954 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009955 } else if (Command.C.cmd == MachO::LC_THREAD ||
9956 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9957 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9958 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009959 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9960 Command.C.cmd == MachO::LC_ID_DYLIB ||
9961 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9962 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9963 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9964 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009965 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9966 PrintDylibCommand(Dl, Command.Ptr);
9967 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9968 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9969 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9970 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9971 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9972 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9973 MachO::linkedit_data_command Ld =
9974 Obj->getLinkeditDataLoadCommand(Command);
9975 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009976 } else {
9977 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9978 << ")\n";
9979 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9980 // TODO: get and print the raw bytes of the load command.
9981 }
9982 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009983 }
9984}
9985
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009986static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009987 if (Obj->is64Bit()) {
9988 MachO::mach_header_64 H_64;
9989 H_64 = Obj->getHeader64();
9990 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9991 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9992 } else {
9993 MachO::mach_header H;
9994 H = Obj->getHeader();
9995 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9996 H.sizeofcmds, H.flags, verbose);
9997 }
9998}
9999
10000void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
10001 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010002 PrintMachHeader(file, !NonVerbose);
10003}
10004
10005void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
10006 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +000010007 uint32_t filetype = 0;
10008 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010009 if (file->is64Bit()) {
10010 MachO::mach_header_64 H_64;
10011 H_64 = file->getHeader64();
10012 filetype = H_64.filetype;
10013 cputype = H_64.cputype;
10014 } else {
10015 MachO::mach_header H;
10016 H = file->getHeader();
10017 filetype = H.filetype;
10018 cputype = H.cputype;
10019 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010020 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010021}
Nick Kledzikd04bc352014-08-30 00:20:14 +000010022
10023//===----------------------------------------------------------------------===//
10024// export trie dumping
10025//===----------------------------------------------------------------------===//
10026
10027void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010028 uint64_t BaseSegmentAddress = 0;
10029 for (const auto &Command : Obj->load_commands()) {
10030 if (Command.C.cmd == MachO::LC_SEGMENT) {
10031 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10032 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10033 BaseSegmentAddress = Seg.vmaddr;
10034 break;
10035 }
10036 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10037 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10038 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10039 BaseSegmentAddress = Seg.vmaddr;
10040 break;
10041 }
10042 }
10043 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010044 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +000010045 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010046 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010047 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10048 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10049 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10050 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10051 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10052 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10053 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10054 if (ReExport)
10055 outs() << "[re-export] ";
10056 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010057 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010058 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010059 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010060 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010061 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010062 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010063 if (WeakDef) {
10064 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010065 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010066 }
10067 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010068 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010069 outs() << ", ";
10070 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010071 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010072 }
10073 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010074 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010075 outs() << ", ";
10076 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010077 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010078 }
10079 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010080 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010081 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010082 outs() << format("resolver=0x%08llX", Entry.other());
10083 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010084 }
10085 outs() << "]";
10086 }
10087 if (ReExport) {
10088 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010089 int Ordinal = Entry.other() - 1;
10090 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10091 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010092 outs() << " (from " << DylibName << ")";
10093 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010094 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010095 }
10096 outs() << "\n";
10097 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010098 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010099 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikd04bc352014-08-30 00:20:14 +000010100}
Nick Kledzikac431442014-09-12 21:34:15 +000010101
Nick Kledzikac431442014-09-12 21:34:15 +000010102//===----------------------------------------------------------------------===//
10103// rebase table dumping
10104//===----------------------------------------------------------------------===//
10105
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010106void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010107 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010108 Error Err = Error::success();
10109 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10110 StringRef SegmentName = Entry.segmentName();
10111 StringRef SectionName = Entry.sectionName();
10112 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010113
10114 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010115 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10116 SegmentName.str().c_str(), SectionName.str().c_str(),
10117 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010118 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010119 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010120 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikac431442014-09-12 21:34:15 +000010121}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010122
10123static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10124 StringRef DylibName;
10125 switch (Ordinal) {
10126 case MachO::BIND_SPECIAL_DYLIB_SELF:
10127 return "this-image";
10128 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10129 return "main-executable";
10130 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10131 return "flat-namespace";
10132 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010133 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010134 std::error_code EC =
10135 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010136 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010137 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010138 return DylibName;
10139 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010140 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010141 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010142}
10143
10144//===----------------------------------------------------------------------===//
10145// bind table dumping
10146//===----------------------------------------------------------------------===//
10147
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010148void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010149 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010150 outs() << "segment section address type "
10151 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010152 Error Err = Error::success();
10153 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010154 StringRef SegmentName = Entry.segmentName();
10155 StringRef SectionName = Entry.sectionName();
10156 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010157
10158 // Table lines look like:
10159 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010160 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010161 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010162 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010163 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010164 << left_justify(SectionName, 18) << " "
10165 << format_hex(Address, 10, true) << " "
10166 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010167 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010168 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010169 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010170 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010171 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010172 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010173}
10174
10175//===----------------------------------------------------------------------===//
10176// lazy bind table dumping
10177//===----------------------------------------------------------------------===//
10178
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010179void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010180 outs() << "segment section address "
10181 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010182 Error Err = Error::success();
10183 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010184 StringRef SegmentName = Entry.segmentName();
10185 StringRef SectionName = Entry.sectionName();
10186 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010187
10188 // Table lines look like:
10189 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010190 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010191 << left_justify(SectionName, 18) << " "
10192 << format_hex(Address, 10, true) << " "
10193 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010194 << Entry.symbolName() << "\n";
10195 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010196 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010197 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010198}
10199
Nick Kledzik56ebef42014-09-16 01:41:51 +000010200//===----------------------------------------------------------------------===//
10201// weak bind table dumping
10202//===----------------------------------------------------------------------===//
10203
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010204void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010205 outs() << "segment section address "
10206 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010207 Error Err = Error::success();
10208 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010209 // Strong symbols don't have a location to update.
10210 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010211 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010212 << Entry.symbolName() << "\n";
10213 continue;
10214 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010215 StringRef SegmentName = Entry.segmentName();
10216 StringRef SectionName = Entry.sectionName();
10217 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010218
10219 // Table lines look like:
10220 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010221 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010222 << left_justify(SectionName, 18) << " "
10223 << format_hex(Address, 10, true) << " "
10224 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010225 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10226 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010227 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010228 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010229 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010230}
10231
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010232// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10233// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10234// information for that address. If the address is found its binding symbol
10235// name is returned. If not nullptr is returned.
10236static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10237 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010238 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010239 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010240 Error Err = Error::success();
10241 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010242 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010243 StringRef name = Entry.symbolName();
10244 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010245 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010246 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010247 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010248 report_error(std::move(Err), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010249 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010250 auto name = info->bindtable->lookup(ReferenceValue);
10251 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010252}
Michael Trent1854ecc2017-12-05 07:50:00 +000010253
Fangrui Song9d812f42019-04-15 15:00:10 +000010254void llvm::printLazyBindTable(ObjectFile *o) {
10255 outs() << "Lazy bind table:\n";
10256 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10257 printMachOLazyBindTable(MachO);
10258 else
10259 WithColor::error()
10260 << "This operation is only currently supported "
10261 "for Mach-O executable files.\n";
10262}
10263
10264void llvm::printWeakBindTable(ObjectFile *o) {
10265 outs() << "Weak bind table:\n";
10266 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10267 printMachOWeakBindTable(MachO);
10268 else
10269 WithColor::error()
10270 << "This operation is only currently supported "
10271 "for Mach-O executable files.\n";
10272}
10273
10274void llvm::printExportsTrie(const ObjectFile *o) {
10275 outs() << "Exports trie:\n";
10276 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10277 printMachOExportsTrie(MachO);
10278 else
10279 WithColor::error()
10280 << "This operation is only currently supported "
10281 "for Mach-O executable files.\n";
10282}
10283
10284void llvm::printRebaseTable(ObjectFile *o) {
10285 outs() << "Rebase table:\n";
10286 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10287 printMachORebaseTable(MachO);
10288 else
10289 WithColor::error()
10290 << "This operation is only currently supported "
10291 "for Mach-O executable files.\n";
10292}
10293
10294void llvm::printBindTable(ObjectFile *o) {
10295 outs() << "Bind table:\n";
10296 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10297 printMachOBindTable(MachO);
10298 else
10299 WithColor::error()
10300 << "This operation is only currently supported "
10301 "for Mach-O executable files.\n";
10302}