blob: c5aba86b20e100a04d8403a05477213565a0be6e [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000034#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000035#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000038#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000042#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.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
61static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000079 llvm::ArchiveHeaders("archive-headers",
80 cl::desc("Print archive headers for Mach-O archives "
81 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000082
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000083cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000084 ArchiveMemberOffsets("archive-member-offsets",
85 cl::desc("Print the offset to each archive member for "
86 "Mach-O archives (requires -macho and "
87 "-archive-headers)"));
88
89cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000090 llvm::IndirectSymbols("indirect-symbols",
91 cl::desc("Print indirect symbol table for Mach-O "
92 "objects (requires -macho)"));
93
Kevin Enderby69fe98d2015-01-23 18:52:17 +000094cl::opt<bool>
95 llvm::DataInCode("data-in-code",
96 cl::desc("Print the data in code table for Mach-O objects "
97 "(requires -macho)"));
98
Kevin Enderby9a509442015-01-27 21:28:24 +000099cl::opt<bool>
100 llvm::LinkOptHints("link-opt-hints",
101 cl::desc("Print the linker optimization hints for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbycd66be52015-03-11 22:06:32 +0000104cl::opt<bool>
105 llvm::InfoPlist("info-plist",
106 cl::desc("Print the info plist section as strings for "
107 "Mach-O objects (requires -macho)"));
108
Kevin Enderbyf0640752015-03-13 17:56:32 +0000109cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000110 llvm::DylibsUsed("dylibs-used",
111 cl::desc("Print the shared libraries used for linked "
112 "Mach-O files (requires -macho)"));
113
114cl::opt<bool>
115 llvm::DylibId("dylib-id",
116 cl::desc("Print the shared library's id for the dylib Mach-O "
117 "file (requires -macho)"));
118
119cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000120 llvm::NonVerbose("non-verbose",
121 cl::desc("Print the info for Mach-O objects in "
122 "non-verbose or numeric form (requires -macho)"));
123
Kevin Enderby0fc11822015-04-01 20:57:01 +0000124cl::opt<bool>
125 llvm::ObjcMetaData("objc-meta-data",
126 cl::desc("Print the Objective-C runtime meta data for "
127 "Mach-O files (requires -macho)"));
128
Kevin Enderby6a221752015-03-17 17:10:57 +0000129cl::opt<std::string> llvm::DisSymName(
130 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000131 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000132
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000133static cl::opt<bool> NoSymbolicOperands(
134 "no-symbolic-operands",
135 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137static cl::list<std::string>
138 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
139 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000140
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000141bool ArchAll = false;
142
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000143static std::string ThumbTripleName;
144
145static const Target *GetTarget(const MachOObjectFile *MachOObj,
146 const char **McpuDefault,
147 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000148 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000151 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000152 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000153 }
154
155 if (TT.getArch() == Triple::arm) {
156 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
157 // that support ARM are also capable of Thumb mode.
158 llvm::Triple ThumbTriple = TT;
159 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
160 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000161 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 }
163
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 // Get the target specific parser.
165 std::string Error;
166 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000167 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000168 return TheTarget;
169
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
171 if (*ThumbTarget)
172 return TheTarget;
173
174 errs() << "llvm-objdump: error: unable to get target for '";
175 if (!TheTarget)
176 errs() << TripleName;
177 else
178 errs() << ThumbTripleName;
179 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000180 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000181}
182
Owen Andersond9243c42011-10-17 21:37:35 +0000183struct SymbolSorter {
184 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000185 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000186 if (!ATypeOrErr)
187 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000189 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000190 if (!BTypeOrErr)
191 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000192 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000193 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
194 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000195 return AAddr < BAddr;
196 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000197};
198
Kevin Enderby273ae012013-06-06 17:20:50 +0000199// Types for the storted data in code table that is built before disassembly
200// and the predicate function to sort them.
201typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
202typedef std::vector<DiceTableEntry> DiceTable;
203typedef DiceTable::iterator dice_table_iterator;
204
Francis Ricci195a66f2017-10-06 15:54:20 +0000205#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000206namespace {
207struct ScopedXarFile {
208 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000209 ScopedXarFile(const char *filename, int32_t flags)
210 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000211 ~ScopedXarFile() {
212 if (xar)
213 xar_close(xar);
214 }
215 ScopedXarFile(const ScopedXarFile &) = delete;
216 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
217 operator xar_t() { return xar; }
218};
219
220struct ScopedXarIter {
221 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000222 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000223 ~ScopedXarIter() {
224 if (iter)
225 xar_iter_free(iter);
226 }
227 ScopedXarIter(const ScopedXarIter &) = delete;
228 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
229 operator xar_iter_t() { return iter; }
230};
231} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000232#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000233
Kevin Enderby930fdc72014-11-06 19:00:13 +0000234// This is used to search for a data in code table entry for the PC being
235// disassembled. The j parameter has the PC in j.first. A single data in code
236// table entry can cover many bytes for each of its Kind's. So if the offset,
237// aka the i.first value, of the data in code table entry plus its Length
238// covers the PC being searched for this will return true. If not it will
239// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000240static bool compareDiceTableEntries(const DiceTableEntry &i,
241 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000242 uint16_t Length;
243 i.second.getLength(Length);
244
245 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246}
247
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000248static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000249 unsigned short Kind) {
250 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000251
252 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000253 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000254 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 if (Length >= 4) {
256 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000257 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000258 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000259 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000260 Size = 4;
261 } else if (Length >= 2) {
262 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000263 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000264 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000266 Size = 2;
267 } else {
268 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000269 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000270 Value = bytes[0];
271 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000272 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 if (Kind == MachO::DICE_KIND_DATA)
275 outs() << "\t@ KIND_DATA\n";
276 else
277 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000278 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000279 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000280 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000281 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000282 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
284 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000285 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000286 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000287 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000288 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000289 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 outs() << "\t.short " << format("%5u", Value & 0xffff)
291 << "\t@ KIND_JUMP_TABLE16\n";
292 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000293 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000294 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000295 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
296 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000297 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000298 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000299 outs() << "\t.long " << Value;
300 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
301 outs() << "\t@ KIND_JUMP_TABLE32\n";
302 else
303 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
304 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000305 break;
306 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000307 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000308}
309
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000310static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000311 std::vector<SectionRef> &Sections,
312 std::vector<SymbolRef> &Symbols,
313 SmallVectorImpl<uint64_t> &FoundFns,
314 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000315 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000316 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000317 if (!SymName)
318 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000319 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000320 Symbols.push_back(Symbol);
321 }
Owen Andersond9243c42011-10-17 21:37:35 +0000322
Alexey Samsonov48803e52014-03-13 14:37:36 +0000323 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000324 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000325 Section.getName(SectName);
326 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000327 }
328
Kevin Enderby273ae012013-06-06 17:20:50 +0000329 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000330 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000332 // We found a function starts segment, parse the addresses for later
333 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000334 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000335 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000336
Charles Davis8bdfafd2013-09-01 04:28:48 +0000337 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000338 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
339 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000340 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000341 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000342 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000343 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000344 }
345 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000346 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000347}
348
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000349static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
350 uint32_t n, uint32_t count,
351 uint32_t stride, uint64_t addr) {
352 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
353 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
354 if (n > nindirectsyms)
355 outs() << " (entries start past the end of the indirect symbol "
356 "table) (reserved1 field greater than the table size)";
357 else if (n + count > nindirectsyms)
358 outs() << " (entries extends past the end of the indirect symbol "
359 "table)";
360 outs() << "\n";
361 uint32_t cputype = O->getHeader().cputype;
362 if (cputype & MachO::CPU_ARCH_ABI64)
363 outs() << "address index";
364 else
365 outs() << "address index";
366 if (verbose)
367 outs() << " name\n";
368 else
369 outs() << "\n";
370 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
371 if (cputype & MachO::CPU_ARCH_ABI64)
372 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
373 else
Tim Northover43978372016-04-26 18:29:16 +0000374 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000375 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
376 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
377 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
378 outs() << "LOCAL\n";
379 continue;
380 }
381 if (indirect_symbol ==
382 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
383 outs() << "LOCAL ABSOLUTE\n";
384 continue;
385 }
386 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
387 outs() << "ABSOLUTE\n";
388 continue;
389 }
390 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000391 if (verbose) {
392 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
393 if (indirect_symbol < Symtab.nsyms) {
394 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
395 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000396 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000397 if (!SymName)
398 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000399 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000400 } else {
401 outs() << "?";
402 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000403 }
404 outs() << "\n";
405 }
406}
407
408static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000409 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000410 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
411 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
412 for (unsigned J = 0; J < Seg.nsects; ++J) {
413 MachO::section_64 Sec = O->getSection64(Load, J);
414 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
415 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
416 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
417 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
418 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
419 section_type == MachO::S_SYMBOL_STUBS) {
420 uint32_t stride;
421 if (section_type == MachO::S_SYMBOL_STUBS)
422 stride = Sec.reserved2;
423 else
424 stride = 8;
425 if (stride == 0) {
426 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
427 << Sec.sectname << ") "
428 << "(size of stubs in reserved2 field is zero)\n";
429 continue;
430 }
431 uint32_t count = Sec.size / stride;
432 outs() << "Indirect symbols for (" << Sec.segname << ","
433 << Sec.sectname << ") " << count << " entries";
434 uint32_t n = Sec.reserved1;
435 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
436 }
437 }
438 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
439 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
440 for (unsigned J = 0; J < Seg.nsects; ++J) {
441 MachO::section Sec = O->getSection(Load, J);
442 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
443 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
444 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
445 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
446 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
447 section_type == MachO::S_SYMBOL_STUBS) {
448 uint32_t stride;
449 if (section_type == MachO::S_SYMBOL_STUBS)
450 stride = Sec.reserved2;
451 else
452 stride = 4;
453 if (stride == 0) {
454 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
455 << Sec.sectname << ") "
456 << "(size of stubs in reserved2 field is zero)\n";
457 continue;
458 }
459 uint32_t count = Sec.size / stride;
460 outs() << "Indirect symbols for (" << Sec.segname << ","
461 << Sec.sectname << ") " << count << " entries";
462 uint32_t n = Sec.reserved1;
463 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
464 }
465 }
466 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000467 }
468}
469
Michael Trenta1703b12017-12-15 17:57:40 +0000470static void PrintRType(const uint64_t cputype, const unsigned r_type) {
471 static char const *generic_r_types[] = {
472 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
473 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
474 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
475 };
476 static char const *x86_64_r_types[] = {
477 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
478 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
479 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
480 };
481 static char const *arm_r_types[] = {
482 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
483 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
484 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
485 };
486 static char const *arm64_r_types[] = {
487 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
488 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
489 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
490 };
491
492 if (r_type > 0xf){
493 outs() << format("%-7u", r_type) << " ";
494 return;
495 }
496 switch (cputype) {
497 case MachO::CPU_TYPE_I386:
498 outs() << generic_r_types[r_type];
499 break;
500 case MachO::CPU_TYPE_X86_64:
501 outs() << x86_64_r_types[r_type];
502 break;
503 case MachO::CPU_TYPE_ARM:
504 outs() << arm_r_types[r_type];
505 break;
506 case MachO::CPU_TYPE_ARM64:
507 outs() << arm64_r_types[r_type];
508 break;
509 default:
510 outs() << format("%-7u ", r_type);
511 }
512}
513
514static void PrintRLength(const uint64_t cputype, const unsigned r_type,
515 const unsigned r_length, const bool previous_arm_half){
516 if (cputype == MachO::CPU_TYPE_ARM &&
517 (r_type == llvm::MachO::ARM_RELOC_HALF ||
518 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
519 previous_arm_half == true)) {
520 if ((r_length & 0x1) == 0)
521 outs() << "lo/";
522 else
523 outs() << "hi/";
524 if ((r_length & 0x1) == 0)
525 outs() << "arm ";
526 else
527 outs() << "thm ";
528 } else {
529 switch (r_length) {
530 case 0:
531 outs() << "byte ";
532 break;
533 case 1:
534 outs() << "word ";
535 break;
536 case 2:
537 outs() << "long ";
538 break;
539 case 3:
540 if (cputype == MachO::CPU_TYPE_X86_64)
541 outs() << "quad ";
542 else
543 outs() << format("?(%2d) ", r_length);
544 break;
545 default:
546 outs() << format("?(%2d) ", r_length);
547 }
548 }
549}
550
551static void PrintRelocationEntries(const MachOObjectFile *O,
552 const relocation_iterator Begin,
553 const relocation_iterator End,
554 const uint64_t cputype,
555 const bool verbose) {
556 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
557 bool previous_arm_half = false;
558 bool previous_sectdiff = false;
559 uint32_t sectdiff_r_type = 0;
560
561 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
562 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
563 const MachO::any_relocation_info RE = O->getRelocation(Rel);
564 const unsigned r_type = O->getAnyRelocationType(RE);
565 const bool r_scattered = O->isRelocationScattered(RE);
566 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
567 const unsigned r_length = O->getAnyRelocationLength(RE);
568 const unsigned r_address = O->getAnyRelocationAddress(RE);
569 const bool r_extern = (r_scattered ? false :
570 O->getPlainRelocationExternal(RE));
571 const uint32_t r_value = (r_scattered ?
572 O->getScatteredRelocationValue(RE) : 0);
573 const unsigned r_symbolnum = (r_scattered ? 0 :
574 O->getPlainRelocationSymbolNum(RE));
575
576 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
577 if (verbose) {
578 // scattered: address
579 if ((cputype == MachO::CPU_TYPE_I386 &&
580 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
581 (cputype == MachO::CPU_TYPE_ARM &&
582 r_type == llvm::MachO::ARM_RELOC_PAIR))
583 outs() << " ";
584 else
585 outs() << format("%08x ", (unsigned int)r_address);
586
587 // scattered: pcrel
588 if (r_pcrel)
589 outs() << "True ";
590 else
591 outs() << "False ";
592
593 // scattered: length
594 PrintRLength(cputype, r_type, r_length, previous_arm_half);
595
596 // scattered: extern & type
597 outs() << "n/a ";
598 PrintRType(cputype, r_type);
599
600 // scattered: scattered & value
601 outs() << format("True 0x%08x", (unsigned int)r_value);
602 if (previous_sectdiff == false) {
603 if ((cputype == MachO::CPU_TYPE_ARM &&
604 r_type == llvm::MachO::ARM_RELOC_PAIR))
605 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
606 }
607 else if (cputype == MachO::CPU_TYPE_ARM &&
608 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
609 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
610 if ((cputype == MachO::CPU_TYPE_I386 &&
611 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
612 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
613 (cputype == MachO::CPU_TYPE_ARM &&
614 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
615 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
616 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
617 previous_sectdiff = true;
618 sectdiff_r_type = r_type;
619 }
620 else {
621 previous_sectdiff = false;
622 sectdiff_r_type = 0;
623 }
624 if (cputype == MachO::CPU_TYPE_ARM &&
625 (r_type == llvm::MachO::ARM_RELOC_HALF ||
626 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
627 previous_arm_half = true;
628 else
629 previous_arm_half = false;
630 outs() << "\n";
631 }
632 else {
633 // scattered: address pcrel length extern type scattered value
634 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
635 (unsigned int)r_address, r_pcrel, r_length, r_type,
636 (unsigned int)r_value);
637 }
638 }
639 else {
640 if (verbose) {
641 // plain: address
642 if (cputype == MachO::CPU_TYPE_ARM &&
643 r_type == llvm::MachO::ARM_RELOC_PAIR)
644 outs() << " ";
645 else
646 outs() << format("%08x ", (unsigned int)r_address);
647
648 // plain: pcrel
649 if (r_pcrel)
650 outs() << "True ";
651 else
652 outs() << "False ";
653
654 // plain: length
655 PrintRLength(cputype, r_type, r_length, previous_arm_half);
656
657 if (r_extern) {
658 // plain: extern & type & scattered
659 outs() << "True ";
660 PrintRType(cputype, r_type);
661 outs() << "False ";
662
663 // plain: symbolnum/value
664 if (r_symbolnum > Symtab.nsyms)
665 outs() << format("?(%d)\n", r_symbolnum);
666 else {
667 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
668 Expected<StringRef> SymNameNext = Symbol.getName();
669 const char *name = NULL;
670 if (SymNameNext)
671 name = SymNameNext->data();
672 if (name == NULL)
673 outs() << format("?(%d)\n", r_symbolnum);
674 else
675 outs() << name << "\n";
676 }
677 }
678 else {
679 // plain: extern & type & scattered
680 outs() << "False ";
681 PrintRType(cputype, r_type);
682 outs() << "False ";
683
684 // plain: symbolnum/value
685 if (cputype == MachO::CPU_TYPE_ARM &&
686 r_type == llvm::MachO::ARM_RELOC_PAIR)
687 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
688 else if (cputype == MachO::CPU_TYPE_ARM64 &&
689 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
690 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
691 else {
692 outs() << format("%d ", r_symbolnum);
693 if (r_symbolnum == llvm::MachO::R_ABS)
694 outs() << "R_ABS\n";
695 else {
696 // in this case, r_symbolnum is actually a 1-based section number
697 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
698 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
699 llvm::object::DataRefImpl DRI;
700 DRI.d.a = r_symbolnum-1;
701 StringRef SegName = O->getSectionFinalSegmentName(DRI);
702 StringRef SectName;
703 if (O->getSectionName(DRI, SectName))
704 outs() << "(?,?)\n";
705 else
706 outs() << "(" << SegName << "," << SectName << ")\n";
707 }
708 else {
709 outs() << "(?,?)\n";
710 }
711 }
712 }
713 }
714 if (cputype == MachO::CPU_TYPE_ARM &&
715 (r_type == llvm::MachO::ARM_RELOC_HALF ||
716 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
717 previous_arm_half = true;
718 else
719 previous_arm_half = false;
720 }
721 else {
722 // plain: address pcrel length extern type scattered symbolnum/section
723 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
724 (unsigned int)r_address, r_pcrel, r_length, r_extern,
725 r_type, r_symbolnum);
726 }
727 }
728 }
729}
730
731static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
732 const uint64_t cputype = O->getHeader().cputype;
733 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
734 if (Dysymtab.nextrel != 0) {
735 outs() << "External relocation information " << Dysymtab.nextrel
736 << " entries";
737 outs() << "\naddress pcrel length extern type scattered "
738 "symbolnum/value\n";
739 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
740 verbose);
741 }
742 if (Dysymtab.nlocrel != 0) {
743 outs() << format("Local relocation information %u entries",
744 Dysymtab.nlocrel);
745 outs() << "\naddress pcrel length extern type scattered "
746 "symbolnum/value\n";
747 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
748 verbose);
749 }
750 for (const auto &Load : O->load_commands()) {
751 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
752 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
753 for (unsigned J = 0; J < Seg.nsects; ++J) {
754 const MachO::section_64 Sec = O->getSection64(Load, J);
755 if (Sec.nreloc != 0) {
756 DataRefImpl DRI;
757 DRI.d.a = J;
758 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
759 StringRef SectName;
760 if (O->getSectionName(DRI, SectName))
761 outs() << "Relocation information (" << SegName << ",?) "
762 << format("%u entries", Sec.nreloc);
763 else
764 outs() << "Relocation information (" << SegName << ","
765 << SectName << format(") %u entries", Sec.nreloc);
766 outs() << "\naddress pcrel length extern type scattered "
767 "symbolnum/value\n";
768 PrintRelocationEntries(O, O->section_rel_begin(DRI),
769 O->section_rel_end(DRI), cputype, verbose);
770 }
771 }
772 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
773 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
774 for (unsigned J = 0; J < Seg.nsects; ++J) {
775 const MachO::section Sec = O->getSection(Load, J);
776 if (Sec.nreloc != 0) {
777 DataRefImpl DRI;
778 DRI.d.a = J;
779 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
780 StringRef SectName;
781 if (O->getSectionName(DRI, SectName))
782 outs() << "Relocation information (" << SegName << ",?) "
783 << format("%u entries", Sec.nreloc);
784 else
785 outs() << "Relocation information (" << SegName << ","
786 << SectName << format(") %u entries", Sec.nreloc);
787 outs() << "\naddress pcrel length extern type scattered "
788 "symbolnum/value\n";
789 PrintRelocationEntries(O, O->section_rel_begin(DRI),
790 O->section_rel_end(DRI), cputype, verbose);
791 }
792 }
793 }
794 }
795}
796
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000797static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
798 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
799 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
800 outs() << "Data in code table (" << nentries << " entries)\n";
801 outs() << "offset length kind\n";
802 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
803 ++DI) {
804 uint32_t Offset;
805 DI->getOffset(Offset);
806 outs() << format("0x%08" PRIx32, Offset) << " ";
807 uint16_t Length;
808 DI->getLength(Length);
809 outs() << format("%6u", Length) << " ";
810 uint16_t Kind;
811 DI->getKind(Kind);
812 if (verbose) {
813 switch (Kind) {
814 case MachO::DICE_KIND_DATA:
815 outs() << "DATA";
816 break;
817 case MachO::DICE_KIND_JUMP_TABLE8:
818 outs() << "JUMP_TABLE8";
819 break;
820 case MachO::DICE_KIND_JUMP_TABLE16:
821 outs() << "JUMP_TABLE16";
822 break;
823 case MachO::DICE_KIND_JUMP_TABLE32:
824 outs() << "JUMP_TABLE32";
825 break;
826 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
827 outs() << "ABS_JUMP_TABLE32";
828 break;
829 default:
830 outs() << format("0x%04" PRIx32, Kind);
831 break;
832 }
833 } else
834 outs() << format("0x%04" PRIx32, Kind);
835 outs() << "\n";
836 }
837}
838
Kevin Enderby9a509442015-01-27 21:28:24 +0000839static void PrintLinkOptHints(MachOObjectFile *O) {
840 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
841 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
842 uint32_t nloh = LohLC.datasize;
843 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
844 for (uint32_t i = 0; i < nloh;) {
845 unsigned n;
846 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
847 i += n;
848 outs() << " identifier " << identifier << " ";
849 if (i >= nloh)
850 return;
851 switch (identifier) {
852 case 1:
853 outs() << "AdrpAdrp\n";
854 break;
855 case 2:
856 outs() << "AdrpLdr\n";
857 break;
858 case 3:
859 outs() << "AdrpAddLdr\n";
860 break;
861 case 4:
862 outs() << "AdrpLdrGotLdr\n";
863 break;
864 case 5:
865 outs() << "AdrpAddStr\n";
866 break;
867 case 6:
868 outs() << "AdrpLdrGotStr\n";
869 break;
870 case 7:
871 outs() << "AdrpAdd\n";
872 break;
873 case 8:
874 outs() << "AdrpLdrGot\n";
875 break;
876 default:
877 outs() << "Unknown identifier value\n";
878 break;
879 }
880 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
881 i += n;
882 outs() << " narguments " << narguments << "\n";
883 if (i >= nloh)
884 return;
885
886 for (uint32_t j = 0; j < narguments; j++) {
887 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
888 i += n;
889 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
890 if (i >= nloh)
891 return;
892 }
893 }
894}
895
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000896static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000897 unsigned Index = 0;
898 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000899 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
900 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
901 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
902 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
903 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
904 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
905 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
906 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
907 if (dl.dylib.name < dl.cmdsize) {
908 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
909 if (JustId)
910 outs() << p << "\n";
911 else {
912 outs() << "\t" << p;
913 outs() << " (compatibility version "
914 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
915 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
916 << (dl.dylib.compatibility_version & 0xff) << ",";
917 outs() << " current version "
918 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
919 << ((dl.dylib.current_version >> 8) & 0xff) << "."
920 << (dl.dylib.current_version & 0xff) << ")\n";
921 }
922 } else {
923 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
924 if (Load.C.cmd == MachO::LC_ID_DYLIB)
925 outs() << "LC_ID_DYLIB ";
926 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
927 outs() << "LC_LOAD_DYLIB ";
928 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
929 outs() << "LC_LOAD_WEAK_DYLIB ";
930 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
931 outs() << "LC_LAZY_LOAD_DYLIB ";
932 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
933 outs() << "LC_REEXPORT_DYLIB ";
934 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
935 outs() << "LC_LOAD_UPWARD_DYLIB ";
936 else
937 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000938 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000939 }
940 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000941 }
942}
943
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000944typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
945
946static void CreateSymbolAddressMap(MachOObjectFile *O,
947 SymbolAddressMap *AddrMap) {
948 // Create a map of symbol addresses to symbol names.
949 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000950 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000951 if (!STOrErr)
952 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000953 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000954 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
955 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000956 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000957 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000958 if (!SymNameOrErr)
959 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000960 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000961 if (!SymName.startswith(".objc"))
962 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000963 }
964 }
965}
966
967// GuessSymbolName is passed the address of what might be a symbol and a
968// pointer to the SymbolAddressMap. It returns the name of a symbol
969// with that address or nullptr if no symbol is found with that address.
970static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
971 const char *SymbolName = nullptr;
972 // A DenseMap can't lookup up some values.
973 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
974 StringRef name = AddrMap->lookup(value);
975 if (!name.empty())
976 SymbolName = name.data();
977 }
978 return SymbolName;
979}
980
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000981static void DumpCstringChar(const char c) {
982 char p[2];
983 p[0] = c;
984 p[1] = '\0';
985 outs().write_escaped(p);
986}
987
Kevin Enderby10ba0412015-02-04 21:38:42 +0000988static void DumpCstringSection(MachOObjectFile *O, const char *sect,
989 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000990 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000991 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000992 if (print_addresses) {
993 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000994 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000995 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000996 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000997 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000998 for (; i < sect_size && sect[i] != '\0'; i++)
999 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001000 if (i < sect_size && sect[i] == '\0')
1001 outs() << "\n";
1002 }
1003}
1004
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001005static void DumpLiteral4(uint32_t l, float f) {
1006 outs() << format("0x%08" PRIx32, l);
1007 if ((l & 0x7f800000) != 0x7f800000)
1008 outs() << format(" (%.16e)\n", f);
1009 else {
1010 if (l == 0x7f800000)
1011 outs() << " (+Infinity)\n";
1012 else if (l == 0xff800000)
1013 outs() << " (-Infinity)\n";
1014 else if ((l & 0x00400000) == 0x00400000)
1015 outs() << " (non-signaling Not-a-Number)\n";
1016 else
1017 outs() << " (signaling Not-a-Number)\n";
1018 }
1019}
1020
1021static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1022 uint32_t sect_size, uint64_t sect_addr,
1023 bool print_addresses) {
1024 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1025 if (print_addresses) {
1026 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001027 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001028 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001029 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001030 }
1031 float f;
1032 memcpy(&f, sect + i, sizeof(float));
1033 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1034 sys::swapByteOrder(f);
1035 uint32_t l;
1036 memcpy(&l, sect + i, sizeof(uint32_t));
1037 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1038 sys::swapByteOrder(l);
1039 DumpLiteral4(l, f);
1040 }
1041}
1042
1043static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1044 double d) {
1045 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1046 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001047 Hi = (O->isLittleEndian()) ? l1 : l0;
1048 Lo = (O->isLittleEndian()) ? l0 : l1;
1049
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001050 // Hi is the high word, so this is equivalent to if(isfinite(d))
1051 if ((Hi & 0x7ff00000) != 0x7ff00000)
1052 outs() << format(" (%.16e)\n", d);
1053 else {
1054 if (Hi == 0x7ff00000 && Lo == 0)
1055 outs() << " (+Infinity)\n";
1056 else if (Hi == 0xfff00000 && Lo == 0)
1057 outs() << " (-Infinity)\n";
1058 else if ((Hi & 0x00080000) == 0x00080000)
1059 outs() << " (non-signaling Not-a-Number)\n";
1060 else
1061 outs() << " (signaling Not-a-Number)\n";
1062 }
1063}
1064
1065static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1066 uint32_t sect_size, uint64_t sect_addr,
1067 bool print_addresses) {
1068 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1069 if (print_addresses) {
1070 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001071 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001072 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001073 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001074 }
1075 double d;
1076 memcpy(&d, sect + i, sizeof(double));
1077 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1078 sys::swapByteOrder(d);
1079 uint32_t l0, l1;
1080 memcpy(&l0, sect + i, sizeof(uint32_t));
1081 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1082 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1083 sys::swapByteOrder(l0);
1084 sys::swapByteOrder(l1);
1085 }
1086 DumpLiteral8(O, l0, l1, d);
1087 }
1088}
1089
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001090static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1091 outs() << format("0x%08" PRIx32, l0) << " ";
1092 outs() << format("0x%08" PRIx32, l1) << " ";
1093 outs() << format("0x%08" PRIx32, l2) << " ";
1094 outs() << format("0x%08" PRIx32, l3) << "\n";
1095}
1096
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001097static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1098 uint32_t sect_size, uint64_t sect_addr,
1099 bool print_addresses) {
1100 for (uint32_t i = 0; i < sect_size; i += 16) {
1101 if (print_addresses) {
1102 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001103 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001104 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001105 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001106 }
1107 uint32_t l0, l1, l2, l3;
1108 memcpy(&l0, sect + i, sizeof(uint32_t));
1109 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1110 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1111 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1112 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1113 sys::swapByteOrder(l0);
1114 sys::swapByteOrder(l1);
1115 sys::swapByteOrder(l2);
1116 sys::swapByteOrder(l3);
1117 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001118 DumpLiteral16(l0, l1, l2, l3);
1119 }
1120}
1121
1122static void DumpLiteralPointerSection(MachOObjectFile *O,
1123 const SectionRef &Section,
1124 const char *sect, uint32_t sect_size,
1125 uint64_t sect_addr,
1126 bool print_addresses) {
1127 // Collect the literal sections in this Mach-O file.
1128 std::vector<SectionRef> LiteralSections;
1129 for (const SectionRef &Section : O->sections()) {
1130 DataRefImpl Ref = Section.getRawDataRefImpl();
1131 uint32_t section_type;
1132 if (O->is64Bit()) {
1133 const MachO::section_64 Sec = O->getSection64(Ref);
1134 section_type = Sec.flags & MachO::SECTION_TYPE;
1135 } else {
1136 const MachO::section Sec = O->getSection(Ref);
1137 section_type = Sec.flags & MachO::SECTION_TYPE;
1138 }
1139 if (section_type == MachO::S_CSTRING_LITERALS ||
1140 section_type == MachO::S_4BYTE_LITERALS ||
1141 section_type == MachO::S_8BYTE_LITERALS ||
1142 section_type == MachO::S_16BYTE_LITERALS)
1143 LiteralSections.push_back(Section);
1144 }
1145
1146 // Set the size of the literal pointer.
1147 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1148
Eric Christopher572e03a2015-06-19 01:53:21 +00001149 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001150 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1151 for (const RelocationRef &Reloc : Section.relocations()) {
1152 DataRefImpl Rel;
1153 MachO::any_relocation_info RE;
1154 bool isExtern = false;
1155 Rel = Reloc.getRawDataRefImpl();
1156 RE = O->getRelocation(Rel);
1157 isExtern = O->getPlainRelocationExternal(RE);
1158 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001159 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001160 symbol_iterator RelocSym = Reloc.getSymbol();
1161 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1162 }
1163 }
1164 array_pod_sort(Relocs.begin(), Relocs.end());
1165
1166 // Dump each literal pointer.
1167 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1168 if (print_addresses) {
1169 if (O->is64Bit())
1170 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1171 else
1172 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1173 }
1174 uint64_t lp;
1175 if (O->is64Bit()) {
1176 memcpy(&lp, sect + i, sizeof(uint64_t));
1177 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1178 sys::swapByteOrder(lp);
1179 } else {
1180 uint32_t li;
1181 memcpy(&li, sect + i, sizeof(uint32_t));
1182 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1183 sys::swapByteOrder(li);
1184 lp = li;
1185 }
1186
1187 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001188 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1189 return P.first == i;
1190 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001191 if (Reloc != Relocs.end()) {
1192 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001193 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001194 if (!SymName)
1195 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001196 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001197 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001198 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001199
1200 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001201 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1202 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1203 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001204 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001205 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001206 continue;
1207 }
1208
1209 uint64_t SectAddress = Sect->getAddress();
1210 uint64_t SectSize = Sect->getSize();
1211
1212 StringRef SectName;
1213 Sect->getName(SectName);
1214 DataRefImpl Ref = Sect->getRawDataRefImpl();
1215 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1216 outs() << SegmentName << ":" << SectName << ":";
1217
1218 uint32_t section_type;
1219 if (O->is64Bit()) {
1220 const MachO::section_64 Sec = O->getSection64(Ref);
1221 section_type = Sec.flags & MachO::SECTION_TYPE;
1222 } else {
1223 const MachO::section Sec = O->getSection(Ref);
1224 section_type = Sec.flags & MachO::SECTION_TYPE;
1225 }
1226
1227 StringRef BytesStr;
1228 Sect->getContents(BytesStr);
1229 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1230
1231 switch (section_type) {
1232 case MachO::S_CSTRING_LITERALS:
1233 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1234 i++) {
1235 DumpCstringChar(Contents[i]);
1236 }
1237 outs() << "\n";
1238 break;
1239 case MachO::S_4BYTE_LITERALS:
1240 float f;
1241 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1242 uint32_t l;
1243 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1244 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1245 sys::swapByteOrder(f);
1246 sys::swapByteOrder(l);
1247 }
1248 DumpLiteral4(l, f);
1249 break;
1250 case MachO::S_8BYTE_LITERALS: {
1251 double d;
1252 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1253 uint32_t l0, l1;
1254 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1255 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1256 sizeof(uint32_t));
1257 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1258 sys::swapByteOrder(f);
1259 sys::swapByteOrder(l0);
1260 sys::swapByteOrder(l1);
1261 }
1262 DumpLiteral8(O, l0, l1, d);
1263 break;
1264 }
1265 case MachO::S_16BYTE_LITERALS: {
1266 uint32_t l0, l1, l2, l3;
1267 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1268 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1269 sizeof(uint32_t));
1270 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1271 sizeof(uint32_t));
1272 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1273 sizeof(uint32_t));
1274 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1275 sys::swapByteOrder(l0);
1276 sys::swapByteOrder(l1);
1277 sys::swapByteOrder(l2);
1278 sys::swapByteOrder(l3);
1279 }
1280 DumpLiteral16(l0, l1, l2, l3);
1281 break;
1282 }
1283 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001284 }
1285}
1286
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001287static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
1288 uint32_t sect_size, uint64_t sect_addr,
1289 SymbolAddressMap *AddrMap,
1290 bool verbose) {
1291 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001292 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001293 for (uint32_t i = 0; i < sect_size; i += stride) {
1294 const char *SymbolName = nullptr;
1295 if (O->is64Bit()) {
1296 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1297 uint64_t pointer_value;
1298 memcpy(&pointer_value, sect + i, stride);
1299 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1300 sys::swapByteOrder(pointer_value);
1301 outs() << format("0x%016" PRIx64, pointer_value);
1302 if (verbose)
1303 SymbolName = GuessSymbolName(pointer_value, AddrMap);
1304 } else {
1305 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1306 uint32_t pointer_value;
1307 memcpy(&pointer_value, sect + i, stride);
1308 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1309 sys::swapByteOrder(pointer_value);
1310 outs() << format("0x%08" PRIx32, pointer_value);
1311 if (verbose)
1312 SymbolName = GuessSymbolName(pointer_value, AddrMap);
1313 }
1314 if (SymbolName)
1315 outs() << " " << SymbolName;
1316 outs() << "\n";
1317 }
1318}
1319
1320static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1321 uint32_t size, uint64_t addr) {
1322 uint32_t cputype = O->getHeader().cputype;
1323 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1324 uint32_t j;
1325 for (uint32_t i = 0; i < size; i += j, addr += j) {
1326 if (O->is64Bit())
1327 outs() << format("%016" PRIx64, addr) << "\t";
1328 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001329 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001330 for (j = 0; j < 16 && i + j < size; j++) {
1331 uint8_t byte_word = *(sect + i + j);
1332 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1333 }
1334 outs() << "\n";
1335 }
1336 } else {
1337 uint32_t j;
1338 for (uint32_t i = 0; i < size; i += j, addr += j) {
1339 if (O->is64Bit())
1340 outs() << format("%016" PRIx64, addr) << "\t";
1341 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001342 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001343 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1344 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001345 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001346 uint32_t long_word;
1347 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1348 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1349 sys::swapByteOrder(long_word);
1350 outs() << format("%08" PRIx32, long_word) << " ";
1351 } else {
1352 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001353 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001354 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1355 }
1356 }
1357 }
1358 outs() << "\n";
1359 }
1360 }
1361}
1362
Kevin Enderby95df54c2015-02-04 01:01:38 +00001363static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1364 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001365static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1366 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001367#ifdef HAVE_LIBXAR
1368static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1369 uint32_t size, bool verbose,
1370 bool PrintXarHeader, bool PrintXarFileHeaders,
1371 std::string XarMemberName);
1372#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001373
1374static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1375 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001376 SymbolAddressMap AddrMap;
1377 if (verbose)
1378 CreateSymbolAddressMap(O, &AddrMap);
1379
Colin LeMahieufcc32762015-07-29 19:08:10 +00001380 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1381 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001382 std::pair<StringRef, StringRef> DumpSegSectName;
1383 DumpSegSectName = DumpSection.split(',');
1384 StringRef DumpSegName, DumpSectName;
1385 if (DumpSegSectName.second.size()) {
1386 DumpSegName = DumpSegSectName.first;
1387 DumpSectName = DumpSegSectName.second;
1388 } else {
1389 DumpSegName = "";
1390 DumpSectName = DumpSegSectName.first;
1391 }
1392 for (const SectionRef &Section : O->sections()) {
1393 StringRef SectName;
1394 Section.getName(SectName);
1395 DataRefImpl Ref = Section.getRawDataRefImpl();
1396 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1397 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1398 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001399
Kevin Enderby95df54c2015-02-04 01:01:38 +00001400 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001401 if (O->is64Bit()) {
1402 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001403 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001404
1405 } else {
1406 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001407 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001408 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001409 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001410
1411 StringRef BytesStr;
1412 Section.getContents(BytesStr);
1413 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1414 uint32_t sect_size = BytesStr.size();
1415 uint64_t sect_addr = Section.getAddress();
1416
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001417 outs() << "Contents of (" << SegName << "," << SectName
1418 << ") section\n";
1419
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001420 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001421 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1422 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1423 DisassembleMachO(Filename, O, SegName, SectName);
1424 continue;
1425 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001426 if (SegName == "__TEXT" && SectName == "__info_plist") {
1427 outs() << sect;
1428 continue;
1429 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001430 if (SegName == "__OBJC" && SectName == "__protocol") {
1431 DumpProtocolSection(O, sect, sect_size, sect_addr);
1432 continue;
1433 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001434#ifdef HAVE_LIBXAR
1435 if (SegName == "__LLVM" && SectName == "__bundle") {
1436 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1437 ArchiveHeaders, "");
1438 continue;
1439 }
1440#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001441 switch (section_type) {
1442 case MachO::S_REGULAR:
1443 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1444 break;
1445 case MachO::S_ZEROFILL:
1446 outs() << "zerofill section and has no contents in the file\n";
1447 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001448 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001449 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001450 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001451 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001452 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001453 break;
1454 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001455 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001456 break;
1457 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001458 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1459 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001460 case MachO::S_LITERAL_POINTERS:
1461 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001462 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001463 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001464 case MachO::S_MOD_INIT_FUNC_POINTERS:
1465 case MachO::S_MOD_TERM_FUNC_POINTERS:
1466 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1467 verbose);
1468 break;
1469 default:
1470 outs() << "Unknown section type ("
1471 << format("0x%08" PRIx32, section_type) << ")\n";
1472 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1473 break;
1474 }
1475 } else {
1476 if (section_type == MachO::S_ZEROFILL)
1477 outs() << "zerofill section and has no contents in the file\n";
1478 else
1479 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1480 }
1481 }
1482 }
1483 }
1484}
1485
Kevin Enderbycd66be52015-03-11 22:06:32 +00001486static void DumpInfoPlistSectionContents(StringRef Filename,
1487 MachOObjectFile *O) {
1488 for (const SectionRef &Section : O->sections()) {
1489 StringRef SectName;
1490 Section.getName(SectName);
1491 DataRefImpl Ref = Section.getRawDataRefImpl();
1492 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1493 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001494 if (!NoLeadingHeaders)
1495 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001496 StringRef BytesStr;
1497 Section.getContents(BytesStr);
1498 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001499 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001500 return;
1501 }
1502 }
1503}
1504
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001505// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1506// and if it is and there is a list of architecture flags is specified then
1507// check to make sure this Mach-O file is one of those architectures or all
1508// architectures were specified. If not then an error is generated and this
1509// routine returns false. Else it returns true.
1510static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001511 auto *MachO = dyn_cast<MachOObjectFile>(O);
1512
1513 if (!MachO || ArchAll || ArchFlags.empty())
1514 return true;
1515
1516 MachO::mach_header H;
1517 MachO::mach_header_64 H_64;
1518 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001519 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001520 if (MachO->is64Bit()) {
1521 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001522 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1523 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001524 } else {
1525 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001526 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1527 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001528 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001529 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001530 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001531 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001532 })) {
1533 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1534 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001535 }
1536 return true;
1537}
1538
Kevin Enderby0fc11822015-04-01 20:57:01 +00001539static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1540
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001541// ProcessMachO() is passed a single opened Mach-O file, which may be an
1542// archive member and or in a slice of a universal file. It prints the
1543// the file name and header info and then processes it according to the
1544// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001545static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001546 StringRef ArchiveMemberName = StringRef(),
1547 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001548 // If we are doing some processing here on the Mach-O file print the header
1549 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001550 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001551 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1552 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1553 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1554 (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001555 if (!NoLeadingHeaders) {
1556 outs() << Name;
1557 if (!ArchiveMemberName.empty())
1558 outs() << '(' << ArchiveMemberName << ')';
1559 if (!ArchitectureName.empty())
1560 outs() << " (architecture " << ArchitectureName << ")";
1561 outs() << ":\n";
1562 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001563 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001564 // To use the report_error() form with an ArchiveName and FileName set
1565 // these up based on what is passed for Name and ArchiveMemberName.
1566 StringRef ArchiveName;
1567 StringRef FileName;
1568 if (!ArchiveMemberName.empty()) {
1569 ArchiveName = Name;
1570 FileName = ArchiveMemberName;
1571 } else {
1572 ArchiveName = StringRef();
1573 FileName = Name;
1574 }
1575
1576 // If we need the symbol table to do the operation then check it here to
1577 // produce a good error message as to where the Mach-O file comes from in
1578 // the error message.
1579 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1580 UnwindInfo)
1581 if (Error Err = MachOOF->checkSymbolTable())
1582 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001583
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001584 if (Disassemble) {
1585 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001586 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001587 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1588 else
1589 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1590 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001591 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001592 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001593 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001594 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001595 if (LinkOptHints)
1596 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001597 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001598 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001599 if (SectionHeaders)
1600 PrintSectionHeaders(MachOOF);
1601 if (SectionContents)
1602 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001603 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001604 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001605 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001606 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001607 if (DylibsUsed)
1608 PrintDylibs(MachOOF, false);
1609 if (DylibId)
1610 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001611 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001612 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001613 if (UnwindInfo)
1614 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001615 if (PrivateHeaders) {
1616 printMachOFileHeader(MachOOF);
1617 printMachOLoadCommands(MachOOF);
1618 }
1619 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001620 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001621 if (ObjcMetaData)
1622 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001623 if (ExportsTrie)
1624 printExportsTrie(MachOOF);
1625 if (Rebase)
1626 printRebaseTable(MachOOF);
1627 if (Bind)
1628 printBindTable(MachOOF);
1629 if (LazyBind)
1630 printLazyBindTable(MachOOF);
1631 if (WeakBind)
1632 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001633
1634 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001635 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001636 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001637 DIDumpOptions DumpOpts;
1638 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001639 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001640 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001641}
1642
Kevin Enderby131d1772015-01-09 19:22:37 +00001643// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1644static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1645 outs() << " cputype (" << cputype << ")\n";
1646 outs() << " cpusubtype (" << cpusubtype << ")\n";
1647}
1648
1649// printCPUType() helps print_fat_headers by printing the cputype and
1650// pusubtype (symbolically for the one's it knows about).
1651static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1652 switch (cputype) {
1653 case MachO::CPU_TYPE_I386:
1654 switch (cpusubtype) {
1655 case MachO::CPU_SUBTYPE_I386_ALL:
1656 outs() << " cputype CPU_TYPE_I386\n";
1657 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1658 break;
1659 default:
1660 printUnknownCPUType(cputype, cpusubtype);
1661 break;
1662 }
1663 break;
1664 case MachO::CPU_TYPE_X86_64:
1665 switch (cpusubtype) {
1666 case MachO::CPU_SUBTYPE_X86_64_ALL:
1667 outs() << " cputype CPU_TYPE_X86_64\n";
1668 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1669 break;
1670 case MachO::CPU_SUBTYPE_X86_64_H:
1671 outs() << " cputype CPU_TYPE_X86_64\n";
1672 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1673 break;
1674 default:
1675 printUnknownCPUType(cputype, cpusubtype);
1676 break;
1677 }
1678 break;
1679 case MachO::CPU_TYPE_ARM:
1680 switch (cpusubtype) {
1681 case MachO::CPU_SUBTYPE_ARM_ALL:
1682 outs() << " cputype CPU_TYPE_ARM\n";
1683 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1684 break;
1685 case MachO::CPU_SUBTYPE_ARM_V4T:
1686 outs() << " cputype CPU_TYPE_ARM\n";
1687 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1688 break;
1689 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1690 outs() << " cputype CPU_TYPE_ARM\n";
1691 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1692 break;
1693 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1694 outs() << " cputype CPU_TYPE_ARM\n";
1695 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1696 break;
1697 case MachO::CPU_SUBTYPE_ARM_V6:
1698 outs() << " cputype CPU_TYPE_ARM\n";
1699 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1700 break;
1701 case MachO::CPU_SUBTYPE_ARM_V6M:
1702 outs() << " cputype CPU_TYPE_ARM\n";
1703 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1704 break;
1705 case MachO::CPU_SUBTYPE_ARM_V7:
1706 outs() << " cputype CPU_TYPE_ARM\n";
1707 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1708 break;
1709 case MachO::CPU_SUBTYPE_ARM_V7EM:
1710 outs() << " cputype CPU_TYPE_ARM\n";
1711 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1712 break;
1713 case MachO::CPU_SUBTYPE_ARM_V7K:
1714 outs() << " cputype CPU_TYPE_ARM\n";
1715 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1716 break;
1717 case MachO::CPU_SUBTYPE_ARM_V7M:
1718 outs() << " cputype CPU_TYPE_ARM\n";
1719 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1720 break;
1721 case MachO::CPU_SUBTYPE_ARM_V7S:
1722 outs() << " cputype CPU_TYPE_ARM\n";
1723 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1724 break;
1725 default:
1726 printUnknownCPUType(cputype, cpusubtype);
1727 break;
1728 }
1729 break;
1730 case MachO::CPU_TYPE_ARM64:
1731 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1732 case MachO::CPU_SUBTYPE_ARM64_ALL:
1733 outs() << " cputype CPU_TYPE_ARM64\n";
1734 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1735 break;
1736 default:
1737 printUnknownCPUType(cputype, cpusubtype);
1738 break;
1739 }
1740 break;
1741 default:
1742 printUnknownCPUType(cputype, cpusubtype);
1743 break;
1744 }
1745}
1746
1747static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1748 bool verbose) {
1749 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001750 if (verbose) {
1751 if (UB->getMagic() == MachO::FAT_MAGIC)
1752 outs() << "fat_magic FAT_MAGIC\n";
1753 else // UB->getMagic() == MachO::FAT_MAGIC_64
1754 outs() << "fat_magic FAT_MAGIC_64\n";
1755 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001756 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1757
1758 uint32_t nfat_arch = UB->getNumberOfObjects();
1759 StringRef Buf = UB->getData();
1760 uint64_t size = Buf.size();
1761 uint64_t big_size = sizeof(struct MachO::fat_header) +
1762 nfat_arch * sizeof(struct MachO::fat_arch);
1763 outs() << "nfat_arch " << UB->getNumberOfObjects();
1764 if (nfat_arch == 0)
1765 outs() << " (malformed, contains zero architecture types)\n";
1766 else if (big_size > size)
1767 outs() << " (malformed, architectures past end of file)\n";
1768 else
1769 outs() << "\n";
1770
1771 for (uint32_t i = 0; i < nfat_arch; ++i) {
1772 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1773 uint32_t cputype = OFA.getCPUType();
1774 uint32_t cpusubtype = OFA.getCPUSubType();
1775 outs() << "architecture ";
1776 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1777 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1778 uint32_t other_cputype = other_OFA.getCPUType();
1779 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001780 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001781 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001782 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001783 outs() << "(illegal duplicate architecture) ";
1784 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001785 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001786 }
1787 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001788 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001789 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1790 } else {
1791 outs() << i << "\n";
1792 outs() << " cputype " << cputype << "\n";
1793 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1794 << "\n";
1795 }
1796 if (verbose &&
1797 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1798 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1799 else
1800 outs() << " capabilities "
1801 << format("0x%" PRIx32,
1802 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1803 outs() << " offset " << OFA.getOffset();
1804 if (OFA.getOffset() > size)
1805 outs() << " (past end of file)";
1806 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1807 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1808 outs() << "\n";
1809 outs() << " size " << OFA.getSize();
1810 big_size = OFA.getOffset() + OFA.getSize();
1811 if (big_size > size)
1812 outs() << " (past end of file)";
1813 outs() << "\n";
1814 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1815 << ")\n";
1816 }
1817}
1818
Kevin Enderby6524bd82016-07-19 20:47:07 +00001819static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1820 bool verbose, bool print_offset,
1821 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001822 if (print_offset)
1823 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001824 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1825 if (!ModeOrErr)
1826 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1827 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001828 if (verbose) {
1829 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1830 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1831 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001832 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1833 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1834 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1835 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1836 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1837 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1838 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1839 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1840 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001841 } else {
1842 outs() << format("0%o ", Mode);
1843 }
1844
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001845 Expected<unsigned> UIDOrErr = C.getUID();
1846 if (!UIDOrErr)
1847 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1848 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001849 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001850 Expected<unsigned> GIDOrErr = C.getGID();
1851 if (!GIDOrErr)
1852 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1853 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001854 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001855 Expected<uint64_t> Size = C.getRawSize();
1856 if (!Size)
1857 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001858 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001859
1860 StringRef RawLastModified = C.getRawLastModified();
1861 if (verbose) {
1862 unsigned Seconds;
1863 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001864 outs() << "(date: \"" << RawLastModified
1865 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001866 else {
1867 // Since cime(3) returns a 26 character string of the form:
1868 // "Sun Sep 16 01:03:52 1973\n\0"
1869 // just print 24 characters.
1870 time_t t = Seconds;
1871 outs() << format("%.24s ", ctime(&t));
1872 }
1873 } else {
1874 outs() << RawLastModified << " ";
1875 }
1876
1877 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001878 Expected<StringRef> NameOrErr = C.getName();
1879 if (!NameOrErr) {
1880 consumeError(NameOrErr.takeError());
1881 Expected<StringRef> NameOrErr = C.getRawName();
1882 if (!NameOrErr)
1883 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1884 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001885 outs() << RawName << "\n";
1886 } else {
1887 StringRef Name = NameOrErr.get();
1888 outs() << Name << "\n";
1889 }
1890 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001891 Expected<StringRef> NameOrErr = C.getRawName();
1892 if (!NameOrErr)
1893 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1894 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001895 outs() << RawName << "\n";
1896 }
1897}
1898
Kevin Enderby6524bd82016-07-19 20:47:07 +00001899static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1900 bool print_offset,
1901 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001902 Error Err = Error::success();
1903 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001904 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001905 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1906
Lang Hamesfc209622016-07-14 02:24:01 +00001907 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001908 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001909}
1910
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001911// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1912// -arch flags selecting just those slices as specified by them and also parses
1913// archive files. Then for each individual Mach-O file ProcessMachO() is
1914// called to process the file based on the command line options.
1915void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001916 // Check for -arch all and verifiy the -arch flags are valid.
1917 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1918 if (ArchFlags[i] == "all") {
1919 ArchAll = true;
1920 } else {
1921 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1922 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1923 "'for the -arch option\n";
1924 return;
1925 }
1926 }
1927 }
1928
1929 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001930 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001931 if (!BinaryOrErr) {
1932 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1933 report_error(Filename, std::move(E));
1934 else
1935 outs() << Filename << ": is not an object file\n";
1936 return;
1937 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001938 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001939
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001940 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1941 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001942 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001943 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1944
Mehdi Amini41af4302016-11-11 04:28:40 +00001945 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001946 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001947 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1948 if (!ChildOrErr) {
1949 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1950 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001951 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001952 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001953 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1954 if (!checkMachOAndArchFlags(O, Filename))
1955 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001956 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001957 }
1958 }
Lang Hamesfc209622016-07-14 02:24:01 +00001959 if (Err)
1960 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001961 return;
1962 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001963 if (UniversalHeaders) {
1964 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001965 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001966 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001967 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1968 // If we have a list of architecture flags specified dump only those.
1969 if (!ArchAll && ArchFlags.size() != 0) {
1970 // Look for a slice in the universal binary that matches each ArchFlag.
1971 bool ArchFound;
1972 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1973 ArchFound = false;
1974 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1975 E = UB->end_objects();
1976 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001977 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001978 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001979 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001980 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001981 std::string ArchitectureName = "";
1982 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001983 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001984 if (ObjOrErr) {
1985 ObjectFile &O = *ObjOrErr.get();
1986 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001987 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001988 } else if (auto E = isNotObjectErrorInvalidFileType(
1989 ObjOrErr.takeError())) {
1990 report_error(Filename, StringRef(), std::move(E),
1991 ArchitectureName);
1992 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001993 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001994 I->getAsArchive()) {
1995 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001996 outs() << "Archive : " << Filename;
1997 if (!ArchitectureName.empty())
1998 outs() << " (architecture " << ArchitectureName << ")";
1999 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002000 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002001 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2002 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00002003 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002004 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002005 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2006 if (!ChildOrErr) {
2007 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00002008 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002009 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002010 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002011 if (MachOObjectFile *O =
2012 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002013 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002014 }
Lang Hamesfc209622016-07-14 02:24:01 +00002015 if (Err)
2016 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002017 } else {
2018 consumeError(AOrErr.takeError());
2019 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002020 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002021 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002022 }
2023 }
2024 }
2025 if (!ArchFound) {
2026 errs() << "llvm-objdump: file: " + Filename + " does not contain "
2027 << "architecture: " + ArchFlags[i] + "\n";
2028 return;
2029 }
2030 }
2031 return;
2032 }
2033 // No architecture flags were specified so if this contains a slice that
2034 // matches the host architecture dump only that.
2035 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002036 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2037 E = UB->end_objects();
2038 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00002039 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00002040 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00002041 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002042 std::string ArchiveName;
2043 ArchiveName.clear();
2044 if (ObjOrErr) {
2045 ObjectFile &O = *ObjOrErr.get();
2046 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002047 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00002048 } else if (auto E = isNotObjectErrorInvalidFileType(
2049 ObjOrErr.takeError())) {
2050 report_error(Filename, std::move(E));
2051 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00002052 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00002053 I->getAsArchive()) {
2054 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002055 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002056 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002057 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2058 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00002059 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002060 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002061 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2062 if (!ChildOrErr) {
2063 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2064 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002065 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002066 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002067 if (MachOObjectFile *O =
2068 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002069 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002070 }
Lang Hamesfc209622016-07-14 02:24:01 +00002071 if (Err)
2072 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002073 } else {
2074 consumeError(AOrErr.takeError());
2075 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002076 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002077 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002078 }
2079 return;
2080 }
2081 }
2082 }
2083 // Either all architectures have been specified or none have been specified
2084 // and this does not contain the host architecture so dump all the slices.
2085 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2086 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2087 E = UB->end_objects();
2088 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00002089 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002090 std::string ArchitectureName = "";
2091 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00002092 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002093 if (ObjOrErr) {
2094 ObjectFile &Obj = *ObjOrErr.get();
2095 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002096 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00002097 } else if (auto E = isNotObjectErrorInvalidFileType(
2098 ObjOrErr.takeError())) {
2099 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
2100 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00002101 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2102 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00002103 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002104 outs() << "Archive : " << Filename;
2105 if (!ArchitectureName.empty())
2106 outs() << " (architecture " << ArchitectureName << ")";
2107 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002108 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002109 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2110 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00002111 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002112 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002113 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2114 if (!ChildOrErr) {
2115 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00002116 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002117 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002118 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002119 if (MachOObjectFile *O =
2120 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2121 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002122 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2123 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002124 }
2125 }
Lang Hamesfc209622016-07-14 02:24:01 +00002126 if (Err)
2127 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002128 } else {
2129 consumeError(AOrErr.takeError());
2130 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002131 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002132 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002133 }
2134 }
2135 return;
2136 }
2137 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2138 if (!checkMachOAndArchFlags(O, Filename))
2139 return;
2140 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002141 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002142 } else
2143 errs() << "llvm-objdump: '" << Filename << "': "
2144 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002145 return;
2146 }
2147 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002148}
2149
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002150// The block of info used by the Symbolizer call backs.
2151struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002152 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2153 std::vector<SectionRef> *Sections, bool verbose)
2154 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002155 bool verbose;
2156 MachOObjectFile *O;
2157 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002158 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002159 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002160 const char *class_name = nullptr;
2161 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002162 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002163 char *demangled_name = nullptr;
2164 uint64_t adrp_addr = 0;
2165 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002166 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002167 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002168};
2169
2170// SymbolizerGetOpInfo() is the operand information call back function.
2171// This is called to get the symbolic information for operand(s) of an
2172// instruction when it is being done. This routine does this from
2173// the relocation information, symbol table, etc. That block of information
2174// is a pointer to the struct DisassembleInfo that was passed when the
2175// disassembler context was created and passed to back to here when
2176// called back by the disassembler for instruction operands that could have
2177// relocation information. The address of the instruction containing operand is
2178// at the Pc parameter. The immediate value the operand has is passed in
2179// op_info->Value and is at Offset past the start of the instruction and has a
2180// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2181// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2182// names and addends of the symbolic expression to add for the operand. The
2183// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2184// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002185static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2186 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002187 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2188 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002189 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002190
2191 // Make sure all fields returned are zero if we don't set them.
2192 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2193 op_info->Value = value;
2194
2195 // If the TagType is not the value 1 which it code knows about or if no
2196 // verbose symbolic information is wanted then just return 0, indicating no
2197 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002198 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002199 return 0;
2200
2201 unsigned int Arch = info->O->getArch();
2202 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002203 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2204 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002205 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2206 // TODO:
2207 // Search the external relocation entries of a fully linked image
2208 // (if any) for an entry that matches this segment offset.
2209 // uint32_t seg_offset = (Pc + Offset);
2210 return 0;
2211 }
2212 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2213 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002214 uint32_t sect_addr = info->S.getAddress();
2215 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2216 bool reloc_found = false;
2217 DataRefImpl Rel;
2218 MachO::any_relocation_info RE;
2219 bool isExtern = false;
2220 SymbolRef Symbol;
2221 bool r_scattered = false;
2222 uint32_t r_value, pair_r_value, r_type;
2223 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002224 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002225 if (RelocOffset == sect_offset) {
2226 Rel = Reloc.getRawDataRefImpl();
2227 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002228 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002229 r_scattered = info->O->isRelocationScattered(RE);
2230 if (r_scattered) {
2231 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002232 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2233 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2234 DataRefImpl RelNext = Rel;
2235 info->O->moveRelocationNext(RelNext);
2236 MachO::any_relocation_info RENext;
2237 RENext = info->O->getRelocation(RelNext);
2238 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002239 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002240 else
2241 return 0;
2242 }
2243 } else {
2244 isExtern = info->O->getPlainRelocationExternal(RE);
2245 if (isExtern) {
2246 symbol_iterator RelocSym = Reloc.getSymbol();
2247 Symbol = *RelocSym;
2248 }
2249 }
2250 reloc_found = true;
2251 break;
2252 }
2253 }
2254 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002255 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002256 if (!SymName)
2257 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002258 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002259 op_info->AddSymbol.Present = 1;
2260 op_info->AddSymbol.Name = name;
2261 // For i386 extern relocation entries the value in the instruction is
2262 // the offset from the symbol, and value is already set in op_info->Value.
2263 return 1;
2264 }
2265 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2266 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002267 const char *add = GuessSymbolName(r_value, info->AddrMap);
2268 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002269 uint32_t offset = value - (r_value - pair_r_value);
2270 op_info->AddSymbol.Present = 1;
2271 if (add != nullptr)
2272 op_info->AddSymbol.Name = add;
2273 else
2274 op_info->AddSymbol.Value = r_value;
2275 op_info->SubtractSymbol.Present = 1;
2276 if (sub != nullptr)
2277 op_info->SubtractSymbol.Name = sub;
2278 else
2279 op_info->SubtractSymbol.Value = pair_r_value;
2280 op_info->Value = offset;
2281 return 1;
2282 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002283 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002284 }
2285 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002286 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2287 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002288 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2289 // relocation entries of a linked image (if any) for an entry that matches
2290 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002291 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002292 uint64_t seg_offset = Pc + Offset;
2293 bool reloc_found = false;
2294 DataRefImpl Rel;
2295 MachO::any_relocation_info RE;
2296 bool isExtern = false;
2297 SymbolRef Symbol;
2298 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2299 uint64_t RelocOffset = Reloc.getOffset();
2300 if (RelocOffset == seg_offset) {
2301 Rel = Reloc.getRawDataRefImpl();
2302 RE = info->O->getRelocation(Rel);
2303 // external relocation entries should always be external.
2304 isExtern = info->O->getPlainRelocationExternal(RE);
2305 if (isExtern) {
2306 symbol_iterator RelocSym = Reloc.getSymbol();
2307 Symbol = *RelocSym;
2308 }
2309 reloc_found = true;
2310 break;
2311 }
2312 }
2313 if (reloc_found && isExtern) {
2314 // The Value passed in will be adjusted by the Pc if the instruction
2315 // adds the Pc. But for x86_64 external relocation entries the Value
2316 // is the offset from the external symbol.
2317 if (info->O->getAnyRelocationPCRel(RE))
2318 op_info->Value -= Pc + Offset + Size;
2319 Expected<StringRef> SymName = Symbol.getName();
2320 if (!SymName)
2321 report_error(info->O->getFileName(), SymName.takeError());
2322 const char *name = SymName->data();
2323 op_info->AddSymbol.Present = 1;
2324 op_info->AddSymbol.Name = name;
2325 return 1;
2326 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002327 return 0;
2328 }
2329 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2330 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002331 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002332 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2333 bool reloc_found = false;
2334 DataRefImpl Rel;
2335 MachO::any_relocation_info RE;
2336 bool isExtern = false;
2337 SymbolRef Symbol;
2338 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002339 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002340 if (RelocOffset == sect_offset) {
2341 Rel = Reloc.getRawDataRefImpl();
2342 RE = info->O->getRelocation(Rel);
2343 // NOTE: Scattered relocations don't exist on x86_64.
2344 isExtern = info->O->getPlainRelocationExternal(RE);
2345 if (isExtern) {
2346 symbol_iterator RelocSym = Reloc.getSymbol();
2347 Symbol = *RelocSym;
2348 }
2349 reloc_found = true;
2350 break;
2351 }
2352 }
2353 if (reloc_found && isExtern) {
2354 // The Value passed in will be adjusted by the Pc if the instruction
2355 // adds the Pc. But for x86_64 external relocation entries the Value
2356 // is the offset from the external symbol.
2357 if (info->O->getAnyRelocationPCRel(RE))
2358 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002359 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002360 if (!SymName)
2361 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002362 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002363 unsigned Type = info->O->getAnyRelocationType(RE);
2364 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2365 DataRefImpl RelNext = Rel;
2366 info->O->moveRelocationNext(RelNext);
2367 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2368 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2369 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2370 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2371 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2372 op_info->SubtractSymbol.Present = 1;
2373 op_info->SubtractSymbol.Name = name;
2374 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2375 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002376 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002377 if (!SymNameNext)
2378 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002379 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002380 }
2381 }
2382 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2383 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2384 op_info->AddSymbol.Present = 1;
2385 op_info->AddSymbol.Name = name;
2386 return 1;
2387 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002388 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002389 }
2390 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002391 if (Offset != 0 || (Size != 4 && Size != 2))
2392 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002393 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2394 // TODO:
2395 // Search the external relocation entries of a fully linked image
2396 // (if any) for an entry that matches this segment offset.
2397 // uint32_t seg_offset = (Pc + Offset);
2398 return 0;
2399 }
2400 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2401 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002402 uint32_t sect_addr = info->S.getAddress();
2403 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002404 DataRefImpl Rel;
2405 MachO::any_relocation_info RE;
2406 bool isExtern = false;
2407 SymbolRef Symbol;
2408 bool r_scattered = false;
2409 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002410 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002411 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2412 uint64_t RelocOffset = Reloc.getOffset();
2413 return RelocOffset == sect_offset;
2414 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002415
2416 if (Reloc == info->S.relocations().end())
2417 return 0;
2418
2419 Rel = Reloc->getRawDataRefImpl();
2420 RE = info->O->getRelocation(Rel);
2421 r_length = info->O->getAnyRelocationLength(RE);
2422 r_scattered = info->O->isRelocationScattered(RE);
2423 if (r_scattered) {
2424 r_value = info->O->getScatteredRelocationValue(RE);
2425 r_type = info->O->getScatteredRelocationType(RE);
2426 } else {
2427 r_type = info->O->getAnyRelocationType(RE);
2428 isExtern = info->O->getPlainRelocationExternal(RE);
2429 if (isExtern) {
2430 symbol_iterator RelocSym = Reloc->getSymbol();
2431 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002432 }
2433 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002434 if (r_type == MachO::ARM_RELOC_HALF ||
2435 r_type == MachO::ARM_RELOC_SECTDIFF ||
2436 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2437 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2438 DataRefImpl RelNext = Rel;
2439 info->O->moveRelocationNext(RelNext);
2440 MachO::any_relocation_info RENext;
2441 RENext = info->O->getRelocation(RelNext);
2442 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2443 if (info->O->isRelocationScattered(RENext))
2444 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2445 }
2446
2447 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002448 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002449 if (!SymName)
2450 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002451 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002452 op_info->AddSymbol.Present = 1;
2453 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002454 switch (r_type) {
2455 case MachO::ARM_RELOC_HALF:
2456 if ((r_length & 0x1) == 1) {
2457 op_info->Value = value << 16 | other_half;
2458 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2459 } else {
2460 op_info->Value = other_half << 16 | value;
2461 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002462 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002463 break;
2464 default:
2465 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002466 }
2467 return 1;
2468 }
2469 // If we have a branch that is not an external relocation entry then
2470 // return 0 so the code in tryAddingSymbolicOperand() can use the
2471 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002472 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002473 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2474 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002475 return 0;
2476
2477 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002478 if (r_type == MachO::ARM_RELOC_HALF ||
2479 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2480 if ((r_length & 0x1) == 1)
2481 value = value << 16 | other_half;
2482 else
2483 value = other_half << 16 | value;
2484 }
2485 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2486 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2487 offset = value - r_value;
2488 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002489 }
2490
David Blaikie33dd45d02015-03-23 18:39:02 +00002491 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002492 if ((r_length & 0x1) == 1)
2493 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2494 else
2495 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002496 const char *add = GuessSymbolName(r_value, info->AddrMap);
2497 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002498 int32_t offset = value - (r_value - pair_r_value);
2499 op_info->AddSymbol.Present = 1;
2500 if (add != nullptr)
2501 op_info->AddSymbol.Name = add;
2502 else
2503 op_info->AddSymbol.Value = r_value;
2504 op_info->SubtractSymbol.Present = 1;
2505 if (sub != nullptr)
2506 op_info->SubtractSymbol.Name = sub;
2507 else
2508 op_info->SubtractSymbol.Value = pair_r_value;
2509 op_info->Value = offset;
2510 return 1;
2511 }
2512
Kevin Enderby930fdc72014-11-06 19:00:13 +00002513 op_info->AddSymbol.Present = 1;
2514 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002515 if (r_type == MachO::ARM_RELOC_HALF) {
2516 if ((r_length & 0x1) == 1)
2517 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2518 else
2519 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002520 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002521 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002522 if (add != nullptr) {
2523 op_info->AddSymbol.Name = add;
2524 return 1;
2525 }
2526 op_info->AddSymbol.Value = value;
2527 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002528 }
2529 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002530 if (Offset != 0 || Size != 4)
2531 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002532 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2533 // TODO:
2534 // Search the external relocation entries of a fully linked image
2535 // (if any) for an entry that matches this segment offset.
2536 // uint64_t seg_offset = (Pc + Offset);
2537 return 0;
2538 }
2539 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2540 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002541 uint64_t sect_addr = info->S.getAddress();
2542 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002543 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002544 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2545 uint64_t RelocOffset = Reloc.getOffset();
2546 return RelocOffset == sect_offset;
2547 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002548
David Blaikie33dd45d02015-03-23 18:39:02 +00002549 if (Reloc == info->S.relocations().end())
2550 return 0;
2551
2552 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2553 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2554 uint32_t r_type = info->O->getAnyRelocationType(RE);
2555 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2556 DataRefImpl RelNext = Rel;
2557 info->O->moveRelocationNext(RelNext);
2558 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2559 if (value == 0) {
2560 value = info->O->getPlainRelocationSymbolNum(RENext);
2561 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002562 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002563 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002564 // NOTE: Scattered relocations don't exist on arm64.
2565 if (!info->O->getPlainRelocationExternal(RE))
2566 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002567 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002568 if (!SymName)
2569 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002570 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002571 op_info->AddSymbol.Present = 1;
2572 op_info->AddSymbol.Name = name;
2573
2574 switch (r_type) {
2575 case MachO::ARM64_RELOC_PAGE21:
2576 /* @page */
2577 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2578 break;
2579 case MachO::ARM64_RELOC_PAGEOFF12:
2580 /* @pageoff */
2581 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2582 break;
2583 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2584 /* @gotpage */
2585 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2586 break;
2587 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2588 /* @gotpageoff */
2589 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2590 break;
2591 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2592 /* @tvlppage is not implemented in llvm-mc */
2593 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2594 break;
2595 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2596 /* @tvlppageoff is not implemented in llvm-mc */
2597 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2598 break;
2599 default:
2600 case MachO::ARM64_RELOC_BRANCH26:
2601 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2602 break;
2603 }
2604 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002605 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002606 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002607}
2608
Kevin Enderbybf246f52014-09-24 23:08:22 +00002609// GuessCstringPointer is passed the address of what might be a pointer to a
2610// literal string in a cstring section. If that address is in a cstring section
2611// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002612static const char *GuessCstringPointer(uint64_t ReferenceValue,
2613 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002614 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002615 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2616 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2617 for (unsigned J = 0; J < Seg.nsects; ++J) {
2618 MachO::section_64 Sec = info->O->getSection64(Load, J);
2619 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2620 if (section_type == MachO::S_CSTRING_LITERALS &&
2621 ReferenceValue >= Sec.addr &&
2622 ReferenceValue < Sec.addr + Sec.size) {
2623 uint64_t sect_offset = ReferenceValue - Sec.addr;
2624 uint64_t object_offset = Sec.offset + sect_offset;
2625 StringRef MachOContents = info->O->getData();
2626 uint64_t object_size = MachOContents.size();
2627 const char *object_addr = (const char *)MachOContents.data();
2628 if (object_offset < object_size) {
2629 const char *name = object_addr + object_offset;
2630 return name;
2631 } else {
2632 return nullptr;
2633 }
2634 }
2635 }
2636 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2637 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2638 for (unsigned J = 0; J < Seg.nsects; ++J) {
2639 MachO::section Sec = info->O->getSection(Load, J);
2640 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2641 if (section_type == MachO::S_CSTRING_LITERALS &&
2642 ReferenceValue >= Sec.addr &&
2643 ReferenceValue < Sec.addr + Sec.size) {
2644 uint64_t sect_offset = ReferenceValue - Sec.addr;
2645 uint64_t object_offset = Sec.offset + sect_offset;
2646 StringRef MachOContents = info->O->getData();
2647 uint64_t object_size = MachOContents.size();
2648 const char *object_addr = (const char *)MachOContents.data();
2649 if (object_offset < object_size) {
2650 const char *name = object_addr + object_offset;
2651 return name;
2652 } else {
2653 return nullptr;
2654 }
2655 }
2656 }
2657 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002658 }
2659 return nullptr;
2660}
2661
Kevin Enderby85974882014-09-26 22:20:44 +00002662// GuessIndirectSymbol returns the name of the indirect symbol for the
2663// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2664// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2665// symbol name being referenced by the stub or pointer.
2666static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2667 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002668 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2669 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002670 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002671 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2672 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2673 for (unsigned J = 0; J < Seg.nsects; ++J) {
2674 MachO::section_64 Sec = info->O->getSection64(Load, J);
2675 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2676 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2677 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2678 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2679 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2680 section_type == MachO::S_SYMBOL_STUBS) &&
2681 ReferenceValue >= Sec.addr &&
2682 ReferenceValue < Sec.addr + Sec.size) {
2683 uint32_t stride;
2684 if (section_type == MachO::S_SYMBOL_STUBS)
2685 stride = Sec.reserved2;
2686 else
2687 stride = 8;
2688 if (stride == 0)
2689 return nullptr;
2690 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2691 if (index < Dysymtab.nindirectsyms) {
2692 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002693 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002694 if (indirect_symbol < Symtab.nsyms) {
2695 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2696 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002697 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002698 if (!SymName)
2699 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002700 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002701 return name;
2702 }
2703 }
2704 }
2705 }
2706 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2707 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2708 for (unsigned J = 0; J < Seg.nsects; ++J) {
2709 MachO::section Sec = info->O->getSection(Load, J);
2710 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2711 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2712 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2713 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2714 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2715 section_type == MachO::S_SYMBOL_STUBS) &&
2716 ReferenceValue >= Sec.addr &&
2717 ReferenceValue < Sec.addr + Sec.size) {
2718 uint32_t stride;
2719 if (section_type == MachO::S_SYMBOL_STUBS)
2720 stride = Sec.reserved2;
2721 else
2722 stride = 4;
2723 if (stride == 0)
2724 return nullptr;
2725 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2726 if (index < Dysymtab.nindirectsyms) {
2727 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002728 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002729 if (indirect_symbol < Symtab.nsyms) {
2730 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2731 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002732 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002733 if (!SymName)
2734 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002735 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002736 return name;
2737 }
2738 }
2739 }
2740 }
2741 }
Kevin Enderby85974882014-09-26 22:20:44 +00002742 }
2743 return nullptr;
2744}
2745
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002746// method_reference() is called passing it the ReferenceName that might be
2747// a reference it to an Objective-C method call. If so then it allocates and
2748// assembles a method call string with the values last seen and saved in
2749// the DisassembleInfo's class_name and selector_name fields. This is saved
2750// into the method field of the info and any previous string is free'ed.
2751// Then the class_name field in the info is set to nullptr. The method call
2752// string is set into ReferenceName and ReferenceType is set to
2753// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2754// then both ReferenceType and ReferenceName are left unchanged.
2755static void method_reference(struct DisassembleInfo *info,
2756 uint64_t *ReferenceType,
2757 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002758 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002759 if (*ReferenceName != nullptr) {
2760 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002761 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002762 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002763 info->method = llvm::make_unique<char[]>(
2764 5 + strlen(info->class_name) + strlen(info->selector_name));
2765 char *method = info->method.get();
2766 if (method != nullptr) {
2767 strcpy(method, "+[");
2768 strcat(method, info->class_name);
2769 strcat(method, " ");
2770 strcat(method, info->selector_name);
2771 strcat(method, "]");
2772 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002773 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2774 }
2775 } else {
David Blaikie0e550682018-02-20 18:48:51 +00002776 info->method =
2777 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
2778 char *method = info->method.get();
2779 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002780 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002781 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002782 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002783 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002784 else
David Blaikie0e550682018-02-20 18:48:51 +00002785 strcpy(method, "-[r? ");
2786 strcat(method, info->selector_name);
2787 strcat(method, "]");
2788 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002789 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2790 }
2791 }
2792 info->class_name = nullptr;
2793 }
2794 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002795 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002796 info->method =
2797 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
2798 char *method = info->method.get();
2799 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002800 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002801 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002802 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002803 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002804 else
David Blaikie0e550682018-02-20 18:48:51 +00002805 strcpy(method, "-[[r? super] ");
2806 strcat(method, info->selector_name);
2807 strcat(method, "]");
2808 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002809 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2810 }
2811 info->class_name = nullptr;
2812 }
2813 }
2814 }
2815}
2816
2817// GuessPointerPointer() is passed the address of what might be a pointer to
2818// a reference to an Objective-C class, selector, message ref or cfstring.
2819// If so the value of the pointer is returned and one of the booleans are set
2820// to true. If not zero is returned and all the booleans are set to false.
2821static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2822 struct DisassembleInfo *info,
2823 bool &classref, bool &selref, bool &msgref,
2824 bool &cfstring) {
2825 classref = false;
2826 selref = false;
2827 msgref = false;
2828 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002829 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002830 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2831 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2832 for (unsigned J = 0; J < Seg.nsects; ++J) {
2833 MachO::section_64 Sec = info->O->getSection64(Load, J);
2834 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2835 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2836 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2837 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2838 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2839 ReferenceValue >= Sec.addr &&
2840 ReferenceValue < Sec.addr + Sec.size) {
2841 uint64_t sect_offset = ReferenceValue - Sec.addr;
2842 uint64_t object_offset = Sec.offset + sect_offset;
2843 StringRef MachOContents = info->O->getData();
2844 uint64_t object_size = MachOContents.size();
2845 const char *object_addr = (const char *)MachOContents.data();
2846 if (object_offset < object_size) {
2847 uint64_t pointer_value;
2848 memcpy(&pointer_value, object_addr + object_offset,
2849 sizeof(uint64_t));
2850 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2851 sys::swapByteOrder(pointer_value);
2852 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2853 selref = true;
2854 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2855 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2856 classref = true;
2857 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2858 ReferenceValue + 8 < Sec.addr + Sec.size) {
2859 msgref = true;
2860 memcpy(&pointer_value, object_addr + object_offset + 8,
2861 sizeof(uint64_t));
2862 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2863 sys::swapByteOrder(pointer_value);
2864 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2865 cfstring = true;
2866 return pointer_value;
2867 } else {
2868 return 0;
2869 }
2870 }
2871 }
2872 }
2873 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002874 }
2875 return 0;
2876}
2877
2878// get_pointer_64 returns a pointer to the bytes in the object file at the
2879// Address from a section in the Mach-O file. And indirectly returns the
2880// offset into the section, number of bytes left in the section past the offset
2881// and which section is was being referenced. If the Address is not in a
2882// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002883static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2884 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002885 DisassembleInfo *info,
2886 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002887 offset = 0;
2888 left = 0;
2889 S = SectionRef();
2890 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2891 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2892 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002893 if (SectSize == 0)
2894 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002895 if (objc_only) {
2896 StringRef SectName;
2897 ((*(info->Sections))[SectIdx]).getName(SectName);
2898 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2899 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2900 if (SegName != "__OBJC" && SectName != "__cstring")
2901 continue;
2902 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002903 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2904 S = (*(info->Sections))[SectIdx];
2905 offset = Address - SectAddress;
2906 left = SectSize - offset;
2907 StringRef SectContents;
2908 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2909 return SectContents.data() + offset;
2910 }
2911 }
2912 return nullptr;
2913}
2914
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002915static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2916 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002917 DisassembleInfo *info,
2918 bool objc_only = false) {
2919 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002920}
2921
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002922// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2923// the symbol indirectly through n_value. Based on the relocation information
2924// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002925// If no relocation information is found and a non-zero ReferenceValue for the
2926// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002927static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2928 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002929 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002930 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002931 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002932 return nullptr;
2933
2934 // See if there is an external relocation entry at the sect_offset.
2935 bool reloc_found = false;
2936 DataRefImpl Rel;
2937 MachO::any_relocation_info RE;
2938 bool isExtern = false;
2939 SymbolRef Symbol;
2940 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002941 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002942 if (RelocOffset == sect_offset) {
2943 Rel = Reloc.getRawDataRefImpl();
2944 RE = info->O->getRelocation(Rel);
2945 if (info->O->isRelocationScattered(RE))
2946 continue;
2947 isExtern = info->O->getPlainRelocationExternal(RE);
2948 if (isExtern) {
2949 symbol_iterator RelocSym = Reloc.getSymbol();
2950 Symbol = *RelocSym;
2951 }
2952 reloc_found = true;
2953 break;
2954 }
2955 }
2956 // If there is an external relocation entry for a symbol in this section
2957 // at this section_offset then use that symbol's value for the n_value
2958 // and return its name.
2959 const char *SymbolName = nullptr;
2960 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002961 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002962 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002963 if (!NameOrError)
2964 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002965 StringRef Name = *NameOrError;
2966 if (!Name.empty()) {
2967 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002968 return SymbolName;
2969 }
2970 }
2971
2972 // TODO: For fully linked images, look through the external relocation
2973 // entries off the dynamic symtab command. For these the r_offset is from the
2974 // start of the first writeable segment in the Mach-O file. So the offset
2975 // to this section from that segment is passed to this routine by the caller,
2976 // as the database_offset. Which is the difference of the section's starting
2977 // address and the first writable segment.
2978 //
2979 // NOTE: need add passing the database_offset to this routine.
2980
Kevin Enderby0fc11822015-04-01 20:57:01 +00002981 // We did not find an external relocation entry so look up the ReferenceValue
2982 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002983 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002984
2985 return SymbolName;
2986}
2987
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002988static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2989 DisassembleInfo *info,
2990 uint32_t ReferenceValue) {
2991 uint64_t n_value64;
2992 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2993}
2994
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002995// These are structs in the Objective-C meta data and read to produce the
2996// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00002997// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
2998// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002999
3000// The cfstring object in a 64-bit Mach-O file.
3001struct cfstring64_t {
3002 uint64_t isa; // class64_t * (64-bit pointer)
3003 uint64_t flags; // flag bits
3004 uint64_t characters; // char * (64-bit pointer)
3005 uint64_t length; // number of non-NULL characters in above
3006};
3007
3008// The class object in a 64-bit Mach-O file.
3009struct class64_t {
3010 uint64_t isa; // class64_t * (64-bit pointer)
3011 uint64_t superclass; // class64_t * (64-bit pointer)
3012 uint64_t cache; // Cache (64-bit pointer)
3013 uint64_t vtable; // IMP * (64-bit pointer)
3014 uint64_t data; // class_ro64_t * (64-bit pointer)
3015};
3016
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003017struct class32_t {
3018 uint32_t isa; /* class32_t * (32-bit pointer) */
3019 uint32_t superclass; /* class32_t * (32-bit pointer) */
3020 uint32_t cache; /* Cache (32-bit pointer) */
3021 uint32_t vtable; /* IMP * (32-bit pointer) */
3022 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3023};
3024
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003025struct class_ro64_t {
3026 uint32_t flags;
3027 uint32_t instanceStart;
3028 uint32_t instanceSize;
3029 uint32_t reserved;
3030 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3031 uint64_t name; // const char * (64-bit pointer)
3032 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3033 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3034 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3035 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3036 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3037};
3038
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003039struct class_ro32_t {
3040 uint32_t flags;
3041 uint32_t instanceStart;
3042 uint32_t instanceSize;
3043 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3044 uint32_t name; /* const char * (32-bit pointer) */
3045 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3046 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3047 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3048 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3049 uint32_t baseProperties; /* const struct objc_property_list *
3050 (32-bit pointer) */
3051};
3052
3053/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003054#define RO_META (1 << 0)
3055#define RO_ROOT (1 << 1)
3056#define RO_HAS_CXX_STRUCTORS (1 << 2)
3057
3058struct method_list64_t {
3059 uint32_t entsize;
3060 uint32_t count;
3061 /* struct method64_t first; These structures follow inline */
3062};
3063
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003064struct method_list32_t {
3065 uint32_t entsize;
3066 uint32_t count;
3067 /* struct method32_t first; These structures follow inline */
3068};
3069
Kevin Enderby0fc11822015-04-01 20:57:01 +00003070struct method64_t {
3071 uint64_t name; /* SEL (64-bit pointer) */
3072 uint64_t types; /* const char * (64-bit pointer) */
3073 uint64_t imp; /* IMP (64-bit pointer) */
3074};
3075
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003076struct method32_t {
3077 uint32_t name; /* SEL (32-bit pointer) */
3078 uint32_t types; /* const char * (32-bit pointer) */
3079 uint32_t imp; /* IMP (32-bit pointer) */
3080};
3081
Kevin Enderby0fc11822015-04-01 20:57:01 +00003082struct protocol_list64_t {
3083 uint64_t count; /* uintptr_t (a 64-bit value) */
3084 /* struct protocol64_t * list[0]; These pointers follow inline */
3085};
3086
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003087struct protocol_list32_t {
3088 uint32_t count; /* uintptr_t (a 32-bit value) */
3089 /* struct protocol32_t * list[0]; These pointers follow inline */
3090};
3091
Kevin Enderby0fc11822015-04-01 20:57:01 +00003092struct protocol64_t {
3093 uint64_t isa; /* id * (64-bit pointer) */
3094 uint64_t name; /* const char * (64-bit pointer) */
3095 uint64_t protocols; /* struct protocol_list64_t *
3096 (64-bit pointer) */
3097 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3098 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3099 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3100 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3101 uint64_t instanceProperties; /* struct objc_property_list *
3102 (64-bit pointer) */
3103};
3104
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003105struct protocol32_t {
3106 uint32_t isa; /* id * (32-bit pointer) */
3107 uint32_t name; /* const char * (32-bit pointer) */
3108 uint32_t protocols; /* struct protocol_list_t *
3109 (32-bit pointer) */
3110 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3111 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3112 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3113 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3114 uint32_t instanceProperties; /* struct objc_property_list *
3115 (32-bit pointer) */
3116};
3117
Kevin Enderby0fc11822015-04-01 20:57:01 +00003118struct ivar_list64_t {
3119 uint32_t entsize;
3120 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003121 /* struct ivar64_t first; These structures follow inline */
3122};
3123
3124struct ivar_list32_t {
3125 uint32_t entsize;
3126 uint32_t count;
3127 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003128};
3129
3130struct ivar64_t {
3131 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3132 uint64_t name; /* const char * (64-bit pointer) */
3133 uint64_t type; /* const char * (64-bit pointer) */
3134 uint32_t alignment;
3135 uint32_t size;
3136};
3137
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003138struct ivar32_t {
3139 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3140 uint32_t name; /* const char * (32-bit pointer) */
3141 uint32_t type; /* const char * (32-bit pointer) */
3142 uint32_t alignment;
3143 uint32_t size;
3144};
3145
Kevin Enderby0fc11822015-04-01 20:57:01 +00003146struct objc_property_list64 {
3147 uint32_t entsize;
3148 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003149 /* struct objc_property64 first; These structures follow inline */
3150};
3151
3152struct objc_property_list32 {
3153 uint32_t entsize;
3154 uint32_t count;
3155 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003156};
3157
3158struct objc_property64 {
3159 uint64_t name; /* const char * (64-bit pointer) */
3160 uint64_t attributes; /* const char * (64-bit pointer) */
3161};
3162
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003163struct objc_property32 {
3164 uint32_t name; /* const char * (32-bit pointer) */
3165 uint32_t attributes; /* const char * (32-bit pointer) */
3166};
3167
Kevin Enderby0fc11822015-04-01 20:57:01 +00003168struct category64_t {
3169 uint64_t name; /* const char * (64-bit pointer) */
3170 uint64_t cls; /* struct class_t * (64-bit pointer) */
3171 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3172 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3173 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3174 uint64_t instanceProperties; /* struct objc_property_list *
3175 (64-bit pointer) */
3176};
3177
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003178struct category32_t {
3179 uint32_t name; /* const char * (32-bit pointer) */
3180 uint32_t cls; /* struct class_t * (32-bit pointer) */
3181 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3182 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3183 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3184 uint32_t instanceProperties; /* struct objc_property_list *
3185 (32-bit pointer) */
3186};
3187
Kevin Enderby0fc11822015-04-01 20:57:01 +00003188struct objc_image_info64 {
3189 uint32_t version;
3190 uint32_t flags;
3191};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003192struct objc_image_info32 {
3193 uint32_t version;
3194 uint32_t flags;
3195};
Kevin Enderby846c0002015-04-16 17:19:59 +00003196struct imageInfo_t {
3197 uint32_t version;
3198 uint32_t flags;
3199};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003200/* masks for objc_image_info.flags */
3201#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3202#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3203
3204struct message_ref64 {
3205 uint64_t imp; /* IMP (64-bit pointer) */
3206 uint64_t sel; /* SEL (64-bit pointer) */
3207};
3208
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003209struct message_ref32 {
3210 uint32_t imp; /* IMP (32-bit pointer) */
3211 uint32_t sel; /* SEL (32-bit pointer) */
3212};
3213
Kevin Enderby846c0002015-04-16 17:19:59 +00003214// Objective-C 1 (32-bit only) meta data structs.
3215
3216struct objc_module_t {
3217 uint32_t version;
3218 uint32_t size;
3219 uint32_t name; /* char * (32-bit pointer) */
3220 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3221};
3222
3223struct objc_symtab_t {
3224 uint32_t sel_ref_cnt;
3225 uint32_t refs; /* SEL * (32-bit pointer) */
3226 uint16_t cls_def_cnt;
3227 uint16_t cat_def_cnt;
3228 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3229};
3230
3231struct objc_class_t {
3232 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3233 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3234 uint32_t name; /* const char * (32-bit pointer) */
3235 int32_t version;
3236 int32_t info;
3237 int32_t instance_size;
3238 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3239 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3240 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3241 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3242};
3243
3244#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3245// class is not a metaclass
3246#define CLS_CLASS 0x1
3247// class is a metaclass
3248#define CLS_META 0x2
3249
3250struct objc_category_t {
3251 uint32_t category_name; /* char * (32-bit pointer) */
3252 uint32_t class_name; /* char * (32-bit pointer) */
3253 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3254 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3255 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3256};
3257
3258struct objc_ivar_t {
3259 uint32_t ivar_name; /* char * (32-bit pointer) */
3260 uint32_t ivar_type; /* char * (32-bit pointer) */
3261 int32_t ivar_offset;
3262};
3263
3264struct objc_ivar_list_t {
3265 int32_t ivar_count;
3266 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3267};
3268
3269struct objc_method_list_t {
3270 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3271 int32_t method_count;
3272 // struct objc_method_t method_list[1]; /* variable length structure */
3273};
3274
3275struct objc_method_t {
3276 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3277 uint32_t method_types; /* char * (32-bit pointer) */
3278 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3279 (32-bit pointer) */
3280};
3281
3282struct objc_protocol_list_t {
3283 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3284 int32_t count;
3285 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3286 // (32-bit pointer) */
3287};
3288
3289struct objc_protocol_t {
3290 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3291 uint32_t protocol_name; /* char * (32-bit pointer) */
3292 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3293 uint32_t instance_methods; /* struct objc_method_description_list *
3294 (32-bit pointer) */
3295 uint32_t class_methods; /* struct objc_method_description_list *
3296 (32-bit pointer) */
3297};
3298
3299struct objc_method_description_list_t {
3300 int32_t count;
3301 // struct objc_method_description_t list[1];
3302};
3303
3304struct objc_method_description_t {
3305 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3306 uint32_t types; /* char * (32-bit pointer) */
3307};
3308
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003309inline void swapStruct(struct cfstring64_t &cfs) {
3310 sys::swapByteOrder(cfs.isa);
3311 sys::swapByteOrder(cfs.flags);
3312 sys::swapByteOrder(cfs.characters);
3313 sys::swapByteOrder(cfs.length);
3314}
3315
3316inline void swapStruct(struct class64_t &c) {
3317 sys::swapByteOrder(c.isa);
3318 sys::swapByteOrder(c.superclass);
3319 sys::swapByteOrder(c.cache);
3320 sys::swapByteOrder(c.vtable);
3321 sys::swapByteOrder(c.data);
3322}
3323
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003324inline void swapStruct(struct class32_t &c) {
3325 sys::swapByteOrder(c.isa);
3326 sys::swapByteOrder(c.superclass);
3327 sys::swapByteOrder(c.cache);
3328 sys::swapByteOrder(c.vtable);
3329 sys::swapByteOrder(c.data);
3330}
3331
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003332inline void swapStruct(struct class_ro64_t &cro) {
3333 sys::swapByteOrder(cro.flags);
3334 sys::swapByteOrder(cro.instanceStart);
3335 sys::swapByteOrder(cro.instanceSize);
3336 sys::swapByteOrder(cro.reserved);
3337 sys::swapByteOrder(cro.ivarLayout);
3338 sys::swapByteOrder(cro.name);
3339 sys::swapByteOrder(cro.baseMethods);
3340 sys::swapByteOrder(cro.baseProtocols);
3341 sys::swapByteOrder(cro.ivars);
3342 sys::swapByteOrder(cro.weakIvarLayout);
3343 sys::swapByteOrder(cro.baseProperties);
3344}
3345
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003346inline void swapStruct(struct class_ro32_t &cro) {
3347 sys::swapByteOrder(cro.flags);
3348 sys::swapByteOrder(cro.instanceStart);
3349 sys::swapByteOrder(cro.instanceSize);
3350 sys::swapByteOrder(cro.ivarLayout);
3351 sys::swapByteOrder(cro.name);
3352 sys::swapByteOrder(cro.baseMethods);
3353 sys::swapByteOrder(cro.baseProtocols);
3354 sys::swapByteOrder(cro.ivars);
3355 sys::swapByteOrder(cro.weakIvarLayout);
3356 sys::swapByteOrder(cro.baseProperties);
3357}
3358
Kevin Enderby0fc11822015-04-01 20:57:01 +00003359inline void swapStruct(struct method_list64_t &ml) {
3360 sys::swapByteOrder(ml.entsize);
3361 sys::swapByteOrder(ml.count);
3362}
3363
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003364inline void swapStruct(struct method_list32_t &ml) {
3365 sys::swapByteOrder(ml.entsize);
3366 sys::swapByteOrder(ml.count);
3367}
3368
Kevin Enderby0fc11822015-04-01 20:57:01 +00003369inline void swapStruct(struct method64_t &m) {
3370 sys::swapByteOrder(m.name);
3371 sys::swapByteOrder(m.types);
3372 sys::swapByteOrder(m.imp);
3373}
3374
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003375inline void swapStruct(struct method32_t &m) {
3376 sys::swapByteOrder(m.name);
3377 sys::swapByteOrder(m.types);
3378 sys::swapByteOrder(m.imp);
3379}
3380
Kevin Enderby0fc11822015-04-01 20:57:01 +00003381inline void swapStruct(struct protocol_list64_t &pl) {
3382 sys::swapByteOrder(pl.count);
3383}
3384
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003385inline void swapStruct(struct protocol_list32_t &pl) {
3386 sys::swapByteOrder(pl.count);
3387}
3388
Kevin Enderby0fc11822015-04-01 20:57:01 +00003389inline void swapStruct(struct protocol64_t &p) {
3390 sys::swapByteOrder(p.isa);
3391 sys::swapByteOrder(p.name);
3392 sys::swapByteOrder(p.protocols);
3393 sys::swapByteOrder(p.instanceMethods);
3394 sys::swapByteOrder(p.classMethods);
3395 sys::swapByteOrder(p.optionalInstanceMethods);
3396 sys::swapByteOrder(p.optionalClassMethods);
3397 sys::swapByteOrder(p.instanceProperties);
3398}
3399
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003400inline void swapStruct(struct protocol32_t &p) {
3401 sys::swapByteOrder(p.isa);
3402 sys::swapByteOrder(p.name);
3403 sys::swapByteOrder(p.protocols);
3404 sys::swapByteOrder(p.instanceMethods);
3405 sys::swapByteOrder(p.classMethods);
3406 sys::swapByteOrder(p.optionalInstanceMethods);
3407 sys::swapByteOrder(p.optionalClassMethods);
3408 sys::swapByteOrder(p.instanceProperties);
3409}
3410
Kevin Enderby0fc11822015-04-01 20:57:01 +00003411inline void swapStruct(struct ivar_list64_t &il) {
3412 sys::swapByteOrder(il.entsize);
3413 sys::swapByteOrder(il.count);
3414}
3415
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003416inline void swapStruct(struct ivar_list32_t &il) {
3417 sys::swapByteOrder(il.entsize);
3418 sys::swapByteOrder(il.count);
3419}
3420
Kevin Enderby0fc11822015-04-01 20:57:01 +00003421inline void swapStruct(struct ivar64_t &i) {
3422 sys::swapByteOrder(i.offset);
3423 sys::swapByteOrder(i.name);
3424 sys::swapByteOrder(i.type);
3425 sys::swapByteOrder(i.alignment);
3426 sys::swapByteOrder(i.size);
3427}
3428
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003429inline void swapStruct(struct ivar32_t &i) {
3430 sys::swapByteOrder(i.offset);
3431 sys::swapByteOrder(i.name);
3432 sys::swapByteOrder(i.type);
3433 sys::swapByteOrder(i.alignment);
3434 sys::swapByteOrder(i.size);
3435}
3436
Kevin Enderby0fc11822015-04-01 20:57:01 +00003437inline void swapStruct(struct objc_property_list64 &pl) {
3438 sys::swapByteOrder(pl.entsize);
3439 sys::swapByteOrder(pl.count);
3440}
3441
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003442inline void swapStruct(struct objc_property_list32 &pl) {
3443 sys::swapByteOrder(pl.entsize);
3444 sys::swapByteOrder(pl.count);
3445}
3446
Kevin Enderby0fc11822015-04-01 20:57:01 +00003447inline void swapStruct(struct objc_property64 &op) {
3448 sys::swapByteOrder(op.name);
3449 sys::swapByteOrder(op.attributes);
3450}
3451
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003452inline void swapStruct(struct objc_property32 &op) {
3453 sys::swapByteOrder(op.name);
3454 sys::swapByteOrder(op.attributes);
3455}
3456
Kevin Enderby0fc11822015-04-01 20:57:01 +00003457inline void swapStruct(struct category64_t &c) {
3458 sys::swapByteOrder(c.name);
3459 sys::swapByteOrder(c.cls);
3460 sys::swapByteOrder(c.instanceMethods);
3461 sys::swapByteOrder(c.classMethods);
3462 sys::swapByteOrder(c.protocols);
3463 sys::swapByteOrder(c.instanceProperties);
3464}
3465
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003466inline void swapStruct(struct category32_t &c) {
3467 sys::swapByteOrder(c.name);
3468 sys::swapByteOrder(c.cls);
3469 sys::swapByteOrder(c.instanceMethods);
3470 sys::swapByteOrder(c.classMethods);
3471 sys::swapByteOrder(c.protocols);
3472 sys::swapByteOrder(c.instanceProperties);
3473}
3474
Kevin Enderby0fc11822015-04-01 20:57:01 +00003475inline void swapStruct(struct objc_image_info64 &o) {
3476 sys::swapByteOrder(o.version);
3477 sys::swapByteOrder(o.flags);
3478}
3479
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003480inline void swapStruct(struct objc_image_info32 &o) {
3481 sys::swapByteOrder(o.version);
3482 sys::swapByteOrder(o.flags);
3483}
3484
Kevin Enderby846c0002015-04-16 17:19:59 +00003485inline void swapStruct(struct imageInfo_t &o) {
3486 sys::swapByteOrder(o.version);
3487 sys::swapByteOrder(o.flags);
3488}
3489
Kevin Enderby0fc11822015-04-01 20:57:01 +00003490inline void swapStruct(struct message_ref64 &mr) {
3491 sys::swapByteOrder(mr.imp);
3492 sys::swapByteOrder(mr.sel);
3493}
3494
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003495inline void swapStruct(struct message_ref32 &mr) {
3496 sys::swapByteOrder(mr.imp);
3497 sys::swapByteOrder(mr.sel);
3498}
3499
Kevin Enderby846c0002015-04-16 17:19:59 +00003500inline void swapStruct(struct objc_module_t &module) {
3501 sys::swapByteOrder(module.version);
3502 sys::swapByteOrder(module.size);
3503 sys::swapByteOrder(module.name);
3504 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003505}
Kevin Enderby846c0002015-04-16 17:19:59 +00003506
3507inline void swapStruct(struct objc_symtab_t &symtab) {
3508 sys::swapByteOrder(symtab.sel_ref_cnt);
3509 sys::swapByteOrder(symtab.refs);
3510 sys::swapByteOrder(symtab.cls_def_cnt);
3511 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003512}
Kevin Enderby846c0002015-04-16 17:19:59 +00003513
3514inline void swapStruct(struct objc_class_t &objc_class) {
3515 sys::swapByteOrder(objc_class.isa);
3516 sys::swapByteOrder(objc_class.super_class);
3517 sys::swapByteOrder(objc_class.name);
3518 sys::swapByteOrder(objc_class.version);
3519 sys::swapByteOrder(objc_class.info);
3520 sys::swapByteOrder(objc_class.instance_size);
3521 sys::swapByteOrder(objc_class.ivars);
3522 sys::swapByteOrder(objc_class.methodLists);
3523 sys::swapByteOrder(objc_class.cache);
3524 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003525}
Kevin Enderby846c0002015-04-16 17:19:59 +00003526
3527inline void swapStruct(struct objc_category_t &objc_category) {
3528 sys::swapByteOrder(objc_category.category_name);
3529 sys::swapByteOrder(objc_category.class_name);
3530 sys::swapByteOrder(objc_category.instance_methods);
3531 sys::swapByteOrder(objc_category.class_methods);
3532 sys::swapByteOrder(objc_category.protocols);
3533}
3534
3535inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3536 sys::swapByteOrder(objc_ivar_list.ivar_count);
3537}
3538
3539inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3540 sys::swapByteOrder(objc_ivar.ivar_name);
3541 sys::swapByteOrder(objc_ivar.ivar_type);
3542 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003543}
Kevin Enderby846c0002015-04-16 17:19:59 +00003544
3545inline void swapStruct(struct objc_method_list_t &method_list) {
3546 sys::swapByteOrder(method_list.obsolete);
3547 sys::swapByteOrder(method_list.method_count);
3548}
3549
3550inline void swapStruct(struct objc_method_t &method) {
3551 sys::swapByteOrder(method.method_name);
3552 sys::swapByteOrder(method.method_types);
3553 sys::swapByteOrder(method.method_imp);
3554}
3555
3556inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3557 sys::swapByteOrder(protocol_list.next);
3558 sys::swapByteOrder(protocol_list.count);
3559}
3560
3561inline void swapStruct(struct objc_protocol_t &protocol) {
3562 sys::swapByteOrder(protocol.isa);
3563 sys::swapByteOrder(protocol.protocol_name);
3564 sys::swapByteOrder(protocol.protocol_list);
3565 sys::swapByteOrder(protocol.instance_methods);
3566 sys::swapByteOrder(protocol.class_methods);
3567}
3568
3569inline void swapStruct(struct objc_method_description_list_t &mdl) {
3570 sys::swapByteOrder(mdl.count);
3571}
3572
3573inline void swapStruct(struct objc_method_description_t &md) {
3574 sys::swapByteOrder(md.name);
3575 sys::swapByteOrder(md.types);
3576}
3577
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003578static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3579 struct DisassembleInfo *info);
3580
3581// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3582// to an Objective-C class and returns the class name. It is also passed the
3583// address of the pointer, so when the pointer is zero as it can be in an .o
3584// file, that is used to look for an external relocation entry with a symbol
3585// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003586static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3587 uint64_t ReferenceValue,
3588 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003589 const char *r;
3590 uint32_t offset, left;
3591 SectionRef S;
3592
3593 // The pointer_value can be 0 in an object file and have a relocation
3594 // entry for the class symbol at the ReferenceValue (the address of the
3595 // pointer).
3596 if (pointer_value == 0) {
3597 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3598 if (r == nullptr || left < sizeof(uint64_t))
3599 return nullptr;
3600 uint64_t n_value;
3601 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3602 if (symbol_name == nullptr)
3603 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003604 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003605 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3606 return class_name + 2;
3607 else
3608 return nullptr;
3609 }
3610
3611 // The case were the pointer_value is non-zero and points to a class defined
3612 // in this Mach-O file.
3613 r = get_pointer_64(pointer_value, offset, left, S, info);
3614 if (r == nullptr || left < sizeof(struct class64_t))
3615 return nullptr;
3616 struct class64_t c;
3617 memcpy(&c, r, sizeof(struct class64_t));
3618 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3619 swapStruct(c);
3620 if (c.data == 0)
3621 return nullptr;
3622 r = get_pointer_64(c.data, offset, left, S, info);
3623 if (r == nullptr || left < sizeof(struct class_ro64_t))
3624 return nullptr;
3625 struct class_ro64_t cro;
3626 memcpy(&cro, r, sizeof(struct class_ro64_t));
3627 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3628 swapStruct(cro);
3629 if (cro.name == 0)
3630 return nullptr;
3631 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3632 return name;
3633}
3634
3635// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3636// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003637static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3638 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003639 const char *r, *name;
3640 uint32_t offset, left;
3641 SectionRef S;
3642 struct cfstring64_t cfs;
3643 uint64_t cfs_characters;
3644
3645 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3646 if (r == nullptr || left < sizeof(struct cfstring64_t))
3647 return nullptr;
3648 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3649 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3650 swapStruct(cfs);
3651 if (cfs.characters == 0) {
3652 uint64_t n_value;
3653 const char *symbol_name = get_symbol_64(
3654 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3655 if (symbol_name == nullptr)
3656 return nullptr;
3657 cfs_characters = n_value;
3658 } else
3659 cfs_characters = cfs.characters;
3660 name = get_pointer_64(cfs_characters, offset, left, S, info);
3661
3662 return name;
3663}
3664
3665// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3666// of a pointer to an Objective-C selector reference when the pointer value is
3667// zero as in a .o file and is likely to have a external relocation entry with
3668// who's symbol's n_value is the real pointer to the selector name. If that is
3669// the case the real pointer to the selector name is returned else 0 is
3670// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003671static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3672 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003673 uint32_t offset, left;
3674 SectionRef S;
3675
3676 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3677 if (r == nullptr || left < sizeof(uint64_t))
3678 return 0;
3679 uint64_t n_value;
3680 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3681 if (symbol_name == nullptr)
3682 return 0;
3683 return n_value;
3684}
3685
Kevin Enderby0fc11822015-04-01 20:57:01 +00003686static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3687 const char *sectname) {
3688 for (const SectionRef &Section : O->sections()) {
3689 StringRef SectName;
3690 Section.getName(SectName);
3691 DataRefImpl Ref = Section.getRawDataRefImpl();
3692 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3693 if (SegName == segname && SectName == sectname)
3694 return Section;
3695 }
3696 return SectionRef();
3697}
3698
3699static void
3700walk_pointer_list_64(const char *listname, const SectionRef S,
3701 MachOObjectFile *O, struct DisassembleInfo *info,
3702 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3703 if (S == SectionRef())
3704 return;
3705
3706 StringRef SectName;
3707 S.getName(SectName);
3708 DataRefImpl Ref = S.getRawDataRefImpl();
3709 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3710 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3711
3712 StringRef BytesStr;
3713 S.getContents(BytesStr);
3714 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3715
3716 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3717 uint32_t left = S.getSize() - i;
3718 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3719 uint64_t p = 0;
3720 memcpy(&p, Contents + i, size);
3721 if (i + sizeof(uint64_t) > S.getSize())
3722 outs() << listname << " list pointer extends past end of (" << SegName
3723 << "," << SectName << ") section\n";
3724 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3725
3726 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3727 sys::swapByteOrder(p);
3728
3729 uint64_t n_value = 0;
3730 const char *name = get_symbol_64(i, S, info, n_value, p);
3731 if (name == nullptr)
3732 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3733
3734 if (n_value != 0) {
3735 outs() << format("0x%" PRIx64, n_value);
3736 if (p != 0)
3737 outs() << " + " << format("0x%" PRIx64, p);
3738 } else
3739 outs() << format("0x%" PRIx64, p);
3740 if (name != nullptr)
3741 outs() << " " << name;
3742 outs() << "\n";
3743
3744 p += n_value;
3745 if (func)
3746 func(p, info);
3747 }
3748}
3749
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003750static void
3751walk_pointer_list_32(const char *listname, const SectionRef S,
3752 MachOObjectFile *O, struct DisassembleInfo *info,
3753 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3754 if (S == SectionRef())
3755 return;
3756
3757 StringRef SectName;
3758 S.getName(SectName);
3759 DataRefImpl Ref = S.getRawDataRefImpl();
3760 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3761 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3762
3763 StringRef BytesStr;
3764 S.getContents(BytesStr);
3765 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3766
3767 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3768 uint32_t left = S.getSize() - i;
3769 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3770 uint32_t p = 0;
3771 memcpy(&p, Contents + i, size);
3772 if (i + sizeof(uint32_t) > S.getSize())
3773 outs() << listname << " list pointer extends past end of (" << SegName
3774 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003775 uint32_t Address = S.getAddress() + i;
3776 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003777
3778 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3779 sys::swapByteOrder(p);
3780 outs() << format("0x%" PRIx32, p);
3781
3782 const char *name = get_symbol_32(i, S, info, p);
3783 if (name != nullptr)
3784 outs() << " " << name;
3785 outs() << "\n";
3786
3787 if (func)
3788 func(p, info);
3789 }
3790}
3791
3792static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003793 if (layout_map == nullptr)
3794 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003795 outs() << " layout map: ";
3796 do {
3797 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3798 left--;
3799 layout_map++;
3800 } while (*layout_map != '\0' && left != 0);
3801 outs() << "\n";
3802}
3803
Kevin Enderby0fc11822015-04-01 20:57:01 +00003804static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3805 uint32_t offset, left;
3806 SectionRef S;
3807 const char *layout_map;
3808
3809 if (p == 0)
3810 return;
3811 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003812 print_layout_map(layout_map, left);
3813}
3814
3815static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3816 uint32_t offset, left;
3817 SectionRef S;
3818 const char *layout_map;
3819
3820 if (p == 0)
3821 return;
3822 layout_map = get_pointer_32(p, offset, left, S, info);
3823 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003824}
3825
3826static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3827 const char *indent) {
3828 struct method_list64_t ml;
3829 struct method64_t m;
3830 const char *r;
3831 uint32_t offset, xoffset, left, i;
3832 SectionRef S, xS;
3833 const char *name, *sym_name;
3834 uint64_t n_value;
3835
3836 r = get_pointer_64(p, offset, left, S, info);
3837 if (r == nullptr)
3838 return;
3839 memset(&ml, '\0', sizeof(struct method_list64_t));
3840 if (left < sizeof(struct method_list64_t)) {
3841 memcpy(&ml, r, left);
3842 outs() << " (method_list_t entends past the end of the section)\n";
3843 } else
3844 memcpy(&ml, r, sizeof(struct method_list64_t));
3845 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3846 swapStruct(ml);
3847 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3848 outs() << indent << "\t\t count " << ml.count << "\n";
3849
3850 p += sizeof(struct method_list64_t);
3851 offset += sizeof(struct method_list64_t);
3852 for (i = 0; i < ml.count; i++) {
3853 r = get_pointer_64(p, offset, left, S, info);
3854 if (r == nullptr)
3855 return;
3856 memset(&m, '\0', sizeof(struct method64_t));
3857 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003858 memcpy(&m, r, left);
3859 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003860 } else
3861 memcpy(&m, r, sizeof(struct method64_t));
3862 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3863 swapStruct(m);
3864
3865 outs() << indent << "\t\t name ";
3866 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3867 info, n_value, m.name);
3868 if (n_value != 0) {
3869 if (info->verbose && sym_name != nullptr)
3870 outs() << sym_name;
3871 else
3872 outs() << format("0x%" PRIx64, n_value);
3873 if (m.name != 0)
3874 outs() << " + " << format("0x%" PRIx64, m.name);
3875 } else
3876 outs() << format("0x%" PRIx64, m.name);
3877 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3878 if (name != nullptr)
3879 outs() << format(" %.*s", left, name);
3880 outs() << "\n";
3881
3882 outs() << indent << "\t\t types ";
3883 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3884 info, n_value, m.types);
3885 if (n_value != 0) {
3886 if (info->verbose && sym_name != nullptr)
3887 outs() << sym_name;
3888 else
3889 outs() << format("0x%" PRIx64, n_value);
3890 if (m.types != 0)
3891 outs() << " + " << format("0x%" PRIx64, m.types);
3892 } else
3893 outs() << format("0x%" PRIx64, m.types);
3894 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3895 if (name != nullptr)
3896 outs() << format(" %.*s", left, name);
3897 outs() << "\n";
3898
3899 outs() << indent << "\t\t imp ";
3900 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3901 n_value, m.imp);
3902 if (info->verbose && name == nullptr) {
3903 if (n_value != 0) {
3904 outs() << format("0x%" PRIx64, n_value) << " ";
3905 if (m.imp != 0)
3906 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3907 } else
3908 outs() << format("0x%" PRIx64, m.imp) << " ";
3909 }
3910 if (name != nullptr)
3911 outs() << name;
3912 outs() << "\n";
3913
3914 p += sizeof(struct method64_t);
3915 offset += sizeof(struct method64_t);
3916 }
3917}
3918
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003919static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3920 const char *indent) {
3921 struct method_list32_t ml;
3922 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003923 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003924 uint32_t offset, xoffset, left, i;
3925 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003926
3927 r = get_pointer_32(p, offset, left, S, info);
3928 if (r == nullptr)
3929 return;
3930 memset(&ml, '\0', sizeof(struct method_list32_t));
3931 if (left < sizeof(struct method_list32_t)) {
3932 memcpy(&ml, r, left);
3933 outs() << " (method_list_t entends past the end of the section)\n";
3934 } else
3935 memcpy(&ml, r, sizeof(struct method_list32_t));
3936 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3937 swapStruct(ml);
3938 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3939 outs() << indent << "\t\t count " << ml.count << "\n";
3940
3941 p += sizeof(struct method_list32_t);
3942 offset += sizeof(struct method_list32_t);
3943 for (i = 0; i < ml.count; i++) {
3944 r = get_pointer_32(p, offset, left, S, info);
3945 if (r == nullptr)
3946 return;
3947 memset(&m, '\0', sizeof(struct method32_t));
3948 if (left < sizeof(struct method32_t)) {
3949 memcpy(&ml, r, left);
3950 outs() << indent << " (method_t entends past the end of the section)\n";
3951 } else
3952 memcpy(&m, r, sizeof(struct method32_t));
3953 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3954 swapStruct(m);
3955
3956 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3957 name = get_pointer_32(m.name, xoffset, left, xS, info);
3958 if (name != nullptr)
3959 outs() << format(" %.*s", left, name);
3960 outs() << "\n";
3961
3962 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3963 name = get_pointer_32(m.types, xoffset, left, xS, info);
3964 if (name != nullptr)
3965 outs() << format(" %.*s", left, name);
3966 outs() << "\n";
3967
3968 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3969 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3970 m.imp);
3971 if (name != nullptr)
3972 outs() << " " << name;
3973 outs() << "\n";
3974
3975 p += sizeof(struct method32_t);
3976 offset += sizeof(struct method32_t);
3977 }
3978}
3979
Kevin Enderby846c0002015-04-16 17:19:59 +00003980static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3981 uint32_t offset, left, xleft;
3982 SectionRef S;
3983 struct objc_method_list_t method_list;
3984 struct objc_method_t method;
3985 const char *r, *methods, *name, *SymbolName;
3986 int32_t i;
3987
3988 r = get_pointer_32(p, offset, left, S, info, true);
3989 if (r == nullptr)
3990 return true;
3991
3992 outs() << "\n";
3993 if (left > sizeof(struct objc_method_list_t)) {
3994 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3995 } else {
3996 outs() << "\t\t objc_method_list extends past end of the section\n";
3997 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3998 memcpy(&method_list, r, left);
3999 }
4000 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4001 swapStruct(method_list);
4002
4003 outs() << "\t\t obsolete "
4004 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4005 outs() << "\t\t method_count " << method_list.method_count << "\n";
4006
4007 methods = r + sizeof(struct objc_method_list_t);
4008 for (i = 0; i < method_list.method_count; i++) {
4009 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4010 outs() << "\t\t remaining method's extend past the of the section\n";
4011 break;
4012 }
4013 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4014 sizeof(struct objc_method_t));
4015 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4016 swapStruct(method);
4017
4018 outs() << "\t\t method_name "
4019 << format("0x%08" PRIx32, method.method_name);
4020 if (info->verbose) {
4021 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4022 if (name != nullptr)
4023 outs() << format(" %.*s", xleft, name);
4024 else
4025 outs() << " (not in an __OBJC section)";
4026 }
4027 outs() << "\n";
4028
4029 outs() << "\t\t method_types "
4030 << format("0x%08" PRIx32, method.method_types);
4031 if (info->verbose) {
4032 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4033 if (name != nullptr)
4034 outs() << format(" %.*s", xleft, name);
4035 else
4036 outs() << " (not in an __OBJC section)";
4037 }
4038 outs() << "\n";
4039
4040 outs() << "\t\t method_imp "
4041 << format("0x%08" PRIx32, method.method_imp) << " ";
4042 if (info->verbose) {
4043 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4044 if (SymbolName != nullptr)
4045 outs() << SymbolName;
4046 }
4047 outs() << "\n";
4048 }
4049 return false;
4050}
4051
Kevin Enderby0fc11822015-04-01 20:57:01 +00004052static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4053 struct protocol_list64_t pl;
4054 uint64_t q, n_value;
4055 struct protocol64_t pc;
4056 const char *r;
4057 uint32_t offset, xoffset, left, i;
4058 SectionRef S, xS;
4059 const char *name, *sym_name;
4060
4061 r = get_pointer_64(p, offset, left, S, info);
4062 if (r == nullptr)
4063 return;
4064 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4065 if (left < sizeof(struct protocol_list64_t)) {
4066 memcpy(&pl, r, left);
4067 outs() << " (protocol_list_t entends past the end of the section)\n";
4068 } else
4069 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4070 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4071 swapStruct(pl);
4072 outs() << " count " << pl.count << "\n";
4073
4074 p += sizeof(struct protocol_list64_t);
4075 offset += sizeof(struct protocol_list64_t);
4076 for (i = 0; i < pl.count; i++) {
4077 r = get_pointer_64(p, offset, left, S, info);
4078 if (r == nullptr)
4079 return;
4080 q = 0;
4081 if (left < sizeof(uint64_t)) {
4082 memcpy(&q, r, left);
4083 outs() << " (protocol_t * entends past the end of the section)\n";
4084 } else
4085 memcpy(&q, r, sizeof(uint64_t));
4086 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4087 sys::swapByteOrder(q);
4088
4089 outs() << "\t\t list[" << i << "] ";
4090 sym_name = get_symbol_64(offset, S, info, n_value, q);
4091 if (n_value != 0) {
4092 if (info->verbose && sym_name != nullptr)
4093 outs() << sym_name;
4094 else
4095 outs() << format("0x%" PRIx64, n_value);
4096 if (q != 0)
4097 outs() << " + " << format("0x%" PRIx64, q);
4098 } else
4099 outs() << format("0x%" PRIx64, q);
4100 outs() << " (struct protocol_t *)\n";
4101
4102 r = get_pointer_64(q + n_value, offset, left, S, info);
4103 if (r == nullptr)
4104 return;
4105 memset(&pc, '\0', sizeof(struct protocol64_t));
4106 if (left < sizeof(struct protocol64_t)) {
4107 memcpy(&pc, r, left);
4108 outs() << " (protocol_t entends past the end of the section)\n";
4109 } else
4110 memcpy(&pc, r, sizeof(struct protocol64_t));
4111 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4112 swapStruct(pc);
4113
4114 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4115
4116 outs() << "\t\t\t name ";
4117 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4118 info, n_value, pc.name);
4119 if (n_value != 0) {
4120 if (info->verbose && sym_name != nullptr)
4121 outs() << sym_name;
4122 else
4123 outs() << format("0x%" PRIx64, n_value);
4124 if (pc.name != 0)
4125 outs() << " + " << format("0x%" PRIx64, pc.name);
4126 } else
4127 outs() << format("0x%" PRIx64, pc.name);
4128 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4129 if (name != nullptr)
4130 outs() << format(" %.*s", left, name);
4131 outs() << "\n";
4132
4133 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4134
4135 outs() << "\t\t instanceMethods ";
4136 sym_name =
4137 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4138 S, info, n_value, pc.instanceMethods);
4139 if (n_value != 0) {
4140 if (info->verbose && sym_name != nullptr)
4141 outs() << sym_name;
4142 else
4143 outs() << format("0x%" PRIx64, n_value);
4144 if (pc.instanceMethods != 0)
4145 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4146 } else
4147 outs() << format("0x%" PRIx64, pc.instanceMethods);
4148 outs() << " (struct method_list_t *)\n";
4149 if (pc.instanceMethods + n_value != 0)
4150 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4151
4152 outs() << "\t\t classMethods ";
4153 sym_name =
4154 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4155 info, n_value, pc.classMethods);
4156 if (n_value != 0) {
4157 if (info->verbose && sym_name != nullptr)
4158 outs() << sym_name;
4159 else
4160 outs() << format("0x%" PRIx64, n_value);
4161 if (pc.classMethods != 0)
4162 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4163 } else
4164 outs() << format("0x%" PRIx64, pc.classMethods);
4165 outs() << " (struct method_list_t *)\n";
4166 if (pc.classMethods + n_value != 0)
4167 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4168
4169 outs() << "\t optionalInstanceMethods "
4170 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4171 outs() << "\t optionalClassMethods "
4172 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4173 outs() << "\t instanceProperties "
4174 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4175
4176 p += sizeof(uint64_t);
4177 offset += sizeof(uint64_t);
4178 }
4179}
4180
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004181static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4182 struct protocol_list32_t pl;
4183 uint32_t q;
4184 struct protocol32_t pc;
4185 const char *r;
4186 uint32_t offset, xoffset, left, i;
4187 SectionRef S, xS;
4188 const char *name;
4189
4190 r = get_pointer_32(p, offset, left, S, info);
4191 if (r == nullptr)
4192 return;
4193 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4194 if (left < sizeof(struct protocol_list32_t)) {
4195 memcpy(&pl, r, left);
4196 outs() << " (protocol_list_t entends past the end of the section)\n";
4197 } else
4198 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4199 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4200 swapStruct(pl);
4201 outs() << " count " << pl.count << "\n";
4202
4203 p += sizeof(struct protocol_list32_t);
4204 offset += sizeof(struct protocol_list32_t);
4205 for (i = 0; i < pl.count; i++) {
4206 r = get_pointer_32(p, offset, left, S, info);
4207 if (r == nullptr)
4208 return;
4209 q = 0;
4210 if (left < sizeof(uint32_t)) {
4211 memcpy(&q, r, left);
4212 outs() << " (protocol_t * entends past the end of the section)\n";
4213 } else
4214 memcpy(&q, r, sizeof(uint32_t));
4215 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4216 sys::swapByteOrder(q);
4217 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4218 << " (struct protocol_t *)\n";
4219 r = get_pointer_32(q, offset, left, S, info);
4220 if (r == nullptr)
4221 return;
4222 memset(&pc, '\0', sizeof(struct protocol32_t));
4223 if (left < sizeof(struct protocol32_t)) {
4224 memcpy(&pc, r, left);
4225 outs() << " (protocol_t entends past the end of the section)\n";
4226 } else
4227 memcpy(&pc, r, sizeof(struct protocol32_t));
4228 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4229 swapStruct(pc);
4230 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4231 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4232 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4233 if (name != nullptr)
4234 outs() << format(" %.*s", left, name);
4235 outs() << "\n";
4236 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4237 outs() << "\t\t instanceMethods "
4238 << format("0x%" PRIx32, pc.instanceMethods)
4239 << " (struct method_list_t *)\n";
4240 if (pc.instanceMethods != 0)
4241 print_method_list32_t(pc.instanceMethods, info, "\t");
4242 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4243 << " (struct method_list_t *)\n";
4244 if (pc.classMethods != 0)
4245 print_method_list32_t(pc.classMethods, info, "\t");
4246 outs() << "\t optionalInstanceMethods "
4247 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4248 outs() << "\t optionalClassMethods "
4249 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4250 outs() << "\t instanceProperties "
4251 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4252 p += sizeof(uint32_t);
4253 offset += sizeof(uint32_t);
4254 }
4255}
4256
Kevin Enderby846c0002015-04-16 17:19:59 +00004257static void print_indent(uint32_t indent) {
4258 for (uint32_t i = 0; i < indent;) {
4259 if (indent - i >= 8) {
4260 outs() << "\t";
4261 i += 8;
4262 } else {
4263 for (uint32_t j = i; j < indent; j++)
4264 outs() << " ";
4265 return;
4266 }
4267 }
4268}
4269
4270static bool print_method_description_list(uint32_t p, uint32_t indent,
4271 struct DisassembleInfo *info) {
4272 uint32_t offset, left, xleft;
4273 SectionRef S;
4274 struct objc_method_description_list_t mdl;
4275 struct objc_method_description_t md;
4276 const char *r, *list, *name;
4277 int32_t i;
4278
4279 r = get_pointer_32(p, offset, left, S, info, true);
4280 if (r == nullptr)
4281 return true;
4282
4283 outs() << "\n";
4284 if (left > sizeof(struct objc_method_description_list_t)) {
4285 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4286 } else {
4287 print_indent(indent);
4288 outs() << " objc_method_description_list extends past end of the section\n";
4289 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4290 memcpy(&mdl, r, left);
4291 }
4292 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4293 swapStruct(mdl);
4294
4295 print_indent(indent);
4296 outs() << " count " << mdl.count << "\n";
4297
4298 list = r + sizeof(struct objc_method_description_list_t);
4299 for (i = 0; i < mdl.count; i++) {
4300 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4301 print_indent(indent);
4302 outs() << " remaining list entries extend past the of the section\n";
4303 break;
4304 }
4305 print_indent(indent);
4306 outs() << " list[" << i << "]\n";
4307 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4308 sizeof(struct objc_method_description_t));
4309 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4310 swapStruct(md);
4311
4312 print_indent(indent);
4313 outs() << " name " << format("0x%08" PRIx32, md.name);
4314 if (info->verbose) {
4315 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4316 if (name != nullptr)
4317 outs() << format(" %.*s", xleft, name);
4318 else
4319 outs() << " (not in an __OBJC section)";
4320 }
4321 outs() << "\n";
4322
4323 print_indent(indent);
4324 outs() << " types " << format("0x%08" PRIx32, md.types);
4325 if (info->verbose) {
4326 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4327 if (name != nullptr)
4328 outs() << format(" %.*s", xleft, name);
4329 else
4330 outs() << " (not in an __OBJC section)";
4331 }
4332 outs() << "\n";
4333 }
4334 return false;
4335}
4336
4337static bool print_protocol_list(uint32_t p, uint32_t indent,
4338 struct DisassembleInfo *info);
4339
4340static bool print_protocol(uint32_t p, uint32_t indent,
4341 struct DisassembleInfo *info) {
4342 uint32_t offset, left;
4343 SectionRef S;
4344 struct objc_protocol_t protocol;
4345 const char *r, *name;
4346
4347 r = get_pointer_32(p, offset, left, S, info, true);
4348 if (r == nullptr)
4349 return true;
4350
4351 outs() << "\n";
4352 if (left >= sizeof(struct objc_protocol_t)) {
4353 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4354 } else {
4355 print_indent(indent);
4356 outs() << " Protocol extends past end of the section\n";
4357 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4358 memcpy(&protocol, r, left);
4359 }
4360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4361 swapStruct(protocol);
4362
4363 print_indent(indent);
4364 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4365 << "\n";
4366
4367 print_indent(indent);
4368 outs() << " protocol_name "
4369 << format("0x%08" PRIx32, protocol.protocol_name);
4370 if (info->verbose) {
4371 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4372 if (name != nullptr)
4373 outs() << format(" %.*s", left, name);
4374 else
4375 outs() << " (not in an __OBJC section)";
4376 }
4377 outs() << "\n";
4378
4379 print_indent(indent);
4380 outs() << " protocol_list "
4381 << format("0x%08" PRIx32, protocol.protocol_list);
4382 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4383 outs() << " (not in an __OBJC section)\n";
4384
4385 print_indent(indent);
4386 outs() << " instance_methods "
4387 << format("0x%08" PRIx32, protocol.instance_methods);
4388 if (print_method_description_list(protocol.instance_methods, indent, info))
4389 outs() << " (not in an __OBJC section)\n";
4390
4391 print_indent(indent);
4392 outs() << " class_methods "
4393 << format("0x%08" PRIx32, protocol.class_methods);
4394 if (print_method_description_list(protocol.class_methods, indent, info))
4395 outs() << " (not in an __OBJC section)\n";
4396
4397 return false;
4398}
4399
4400static bool print_protocol_list(uint32_t p, uint32_t indent,
4401 struct DisassembleInfo *info) {
4402 uint32_t offset, left, l;
4403 SectionRef S;
4404 struct objc_protocol_list_t protocol_list;
4405 const char *r, *list;
4406 int32_t i;
4407
4408 r = get_pointer_32(p, offset, left, S, info, true);
4409 if (r == nullptr)
4410 return true;
4411
4412 outs() << "\n";
4413 if (left > sizeof(struct objc_protocol_list_t)) {
4414 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4415 } else {
4416 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4417 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4418 memcpy(&protocol_list, r, left);
4419 }
4420 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4421 swapStruct(protocol_list);
4422
4423 print_indent(indent);
4424 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4425 << "\n";
4426 print_indent(indent);
4427 outs() << " count " << protocol_list.count << "\n";
4428
4429 list = r + sizeof(struct objc_protocol_list_t);
4430 for (i = 0; i < protocol_list.count; i++) {
4431 if ((i + 1) * sizeof(uint32_t) > left) {
4432 outs() << "\t\t remaining list entries extend past the of the section\n";
4433 break;
4434 }
4435 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4436 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4437 sys::swapByteOrder(l);
4438
4439 print_indent(indent);
4440 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4441 if (print_protocol(l, indent, info))
4442 outs() << "(not in an __OBJC section)\n";
4443 }
4444 return false;
4445}
4446
Kevin Enderby0fc11822015-04-01 20:57:01 +00004447static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4448 struct ivar_list64_t il;
4449 struct ivar64_t i;
4450 const char *r;
4451 uint32_t offset, xoffset, left, j;
4452 SectionRef S, xS;
4453 const char *name, *sym_name, *ivar_offset_p;
4454 uint64_t ivar_offset, n_value;
4455
4456 r = get_pointer_64(p, offset, left, S, info);
4457 if (r == nullptr)
4458 return;
4459 memset(&il, '\0', sizeof(struct ivar_list64_t));
4460 if (left < sizeof(struct ivar_list64_t)) {
4461 memcpy(&il, r, left);
4462 outs() << " (ivar_list_t entends past the end of the section)\n";
4463 } else
4464 memcpy(&il, r, sizeof(struct ivar_list64_t));
4465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4466 swapStruct(il);
4467 outs() << " entsize " << il.entsize << "\n";
4468 outs() << " count " << il.count << "\n";
4469
4470 p += sizeof(struct ivar_list64_t);
4471 offset += sizeof(struct ivar_list64_t);
4472 for (j = 0; j < il.count; j++) {
4473 r = get_pointer_64(p, offset, left, S, info);
4474 if (r == nullptr)
4475 return;
4476 memset(&i, '\0', sizeof(struct ivar64_t));
4477 if (left < sizeof(struct ivar64_t)) {
4478 memcpy(&i, r, left);
4479 outs() << " (ivar_t entends past the end of the section)\n";
4480 } else
4481 memcpy(&i, r, sizeof(struct ivar64_t));
4482 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4483 swapStruct(i);
4484
4485 outs() << "\t\t\t offset ";
4486 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4487 info, n_value, i.offset);
4488 if (n_value != 0) {
4489 if (info->verbose && sym_name != nullptr)
4490 outs() << sym_name;
4491 else
4492 outs() << format("0x%" PRIx64, n_value);
4493 if (i.offset != 0)
4494 outs() << " + " << format("0x%" PRIx64, i.offset);
4495 } else
4496 outs() << format("0x%" PRIx64, i.offset);
4497 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4498 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4499 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4500 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4501 sys::swapByteOrder(ivar_offset);
4502 outs() << " " << ivar_offset << "\n";
4503 } else
4504 outs() << "\n";
4505
4506 outs() << "\t\t\t name ";
4507 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4508 n_value, i.name);
4509 if (n_value != 0) {
4510 if (info->verbose && sym_name != nullptr)
4511 outs() << sym_name;
4512 else
4513 outs() << format("0x%" PRIx64, n_value);
4514 if (i.name != 0)
4515 outs() << " + " << format("0x%" PRIx64, i.name);
4516 } else
4517 outs() << format("0x%" PRIx64, i.name);
4518 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4519 if (name != nullptr)
4520 outs() << format(" %.*s", left, name);
4521 outs() << "\n";
4522
4523 outs() << "\t\t\t type ";
4524 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4525 n_value, i.name);
4526 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4527 if (n_value != 0) {
4528 if (info->verbose && sym_name != nullptr)
4529 outs() << sym_name;
4530 else
4531 outs() << format("0x%" PRIx64, n_value);
4532 if (i.type != 0)
4533 outs() << " + " << format("0x%" PRIx64, i.type);
4534 } else
4535 outs() << format("0x%" PRIx64, i.type);
4536 if (name != nullptr)
4537 outs() << format(" %.*s", left, name);
4538 outs() << "\n";
4539
4540 outs() << "\t\t\talignment " << i.alignment << "\n";
4541 outs() << "\t\t\t size " << i.size << "\n";
4542
4543 p += sizeof(struct ivar64_t);
4544 offset += sizeof(struct ivar64_t);
4545 }
4546}
4547
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004548static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4549 struct ivar_list32_t il;
4550 struct ivar32_t i;
4551 const char *r;
4552 uint32_t offset, xoffset, left, j;
4553 SectionRef S, xS;
4554 const char *name, *ivar_offset_p;
4555 uint32_t ivar_offset;
4556
4557 r = get_pointer_32(p, offset, left, S, info);
4558 if (r == nullptr)
4559 return;
4560 memset(&il, '\0', sizeof(struct ivar_list32_t));
4561 if (left < sizeof(struct ivar_list32_t)) {
4562 memcpy(&il, r, left);
4563 outs() << " (ivar_list_t entends past the end of the section)\n";
4564 } else
4565 memcpy(&il, r, sizeof(struct ivar_list32_t));
4566 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4567 swapStruct(il);
4568 outs() << " entsize " << il.entsize << "\n";
4569 outs() << " count " << il.count << "\n";
4570
4571 p += sizeof(struct ivar_list32_t);
4572 offset += sizeof(struct ivar_list32_t);
4573 for (j = 0; j < il.count; j++) {
4574 r = get_pointer_32(p, offset, left, S, info);
4575 if (r == nullptr)
4576 return;
4577 memset(&i, '\0', sizeof(struct ivar32_t));
4578 if (left < sizeof(struct ivar32_t)) {
4579 memcpy(&i, r, left);
4580 outs() << " (ivar_t entends past the end of the section)\n";
4581 } else
4582 memcpy(&i, r, sizeof(struct ivar32_t));
4583 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4584 swapStruct(i);
4585
4586 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4587 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4588 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4589 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4590 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4591 sys::swapByteOrder(ivar_offset);
4592 outs() << " " << ivar_offset << "\n";
4593 } else
4594 outs() << "\n";
4595
4596 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4597 name = get_pointer_32(i.name, xoffset, left, xS, info);
4598 if (name != nullptr)
4599 outs() << format(" %.*s", left, name);
4600 outs() << "\n";
4601
4602 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4603 name = get_pointer_32(i.type, xoffset, left, xS, info);
4604 if (name != nullptr)
4605 outs() << format(" %.*s", left, name);
4606 outs() << "\n";
4607
4608 outs() << "\t\t\talignment " << i.alignment << "\n";
4609 outs() << "\t\t\t size " << i.size << "\n";
4610
4611 p += sizeof(struct ivar32_t);
4612 offset += sizeof(struct ivar32_t);
4613 }
4614}
4615
Kevin Enderby0fc11822015-04-01 20:57:01 +00004616static void print_objc_property_list64(uint64_t p,
4617 struct DisassembleInfo *info) {
4618 struct objc_property_list64 opl;
4619 struct objc_property64 op;
4620 const char *r;
4621 uint32_t offset, xoffset, left, j;
4622 SectionRef S, xS;
4623 const char *name, *sym_name;
4624 uint64_t n_value;
4625
4626 r = get_pointer_64(p, offset, left, S, info);
4627 if (r == nullptr)
4628 return;
4629 memset(&opl, '\0', sizeof(struct objc_property_list64));
4630 if (left < sizeof(struct objc_property_list64)) {
4631 memcpy(&opl, r, left);
4632 outs() << " (objc_property_list entends past the end of the section)\n";
4633 } else
4634 memcpy(&opl, r, sizeof(struct objc_property_list64));
4635 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4636 swapStruct(opl);
4637 outs() << " entsize " << opl.entsize << "\n";
4638 outs() << " count " << opl.count << "\n";
4639
4640 p += sizeof(struct objc_property_list64);
4641 offset += sizeof(struct objc_property_list64);
4642 for (j = 0; j < opl.count; j++) {
4643 r = get_pointer_64(p, offset, left, S, info);
4644 if (r == nullptr)
4645 return;
4646 memset(&op, '\0', sizeof(struct objc_property64));
4647 if (left < sizeof(struct objc_property64)) {
4648 memcpy(&op, r, left);
4649 outs() << " (objc_property entends past the end of the section)\n";
4650 } else
4651 memcpy(&op, r, sizeof(struct objc_property64));
4652 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4653 swapStruct(op);
4654
4655 outs() << "\t\t\t name ";
4656 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4657 info, n_value, op.name);
4658 if (n_value != 0) {
4659 if (info->verbose && sym_name != nullptr)
4660 outs() << sym_name;
4661 else
4662 outs() << format("0x%" PRIx64, n_value);
4663 if (op.name != 0)
4664 outs() << " + " << format("0x%" PRIx64, op.name);
4665 } else
4666 outs() << format("0x%" PRIx64, op.name);
4667 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4668 if (name != nullptr)
4669 outs() << format(" %.*s", left, name);
4670 outs() << "\n";
4671
4672 outs() << "\t\t\tattributes ";
4673 sym_name =
4674 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4675 info, n_value, op.attributes);
4676 if (n_value != 0) {
4677 if (info->verbose && sym_name != nullptr)
4678 outs() << sym_name;
4679 else
4680 outs() << format("0x%" PRIx64, n_value);
4681 if (op.attributes != 0)
4682 outs() << " + " << format("0x%" PRIx64, op.attributes);
4683 } else
4684 outs() << format("0x%" PRIx64, op.attributes);
4685 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4686 if (name != nullptr)
4687 outs() << format(" %.*s", left, name);
4688 outs() << "\n";
4689
4690 p += sizeof(struct objc_property64);
4691 offset += sizeof(struct objc_property64);
4692 }
4693}
4694
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004695static void print_objc_property_list32(uint32_t p,
4696 struct DisassembleInfo *info) {
4697 struct objc_property_list32 opl;
4698 struct objc_property32 op;
4699 const char *r;
4700 uint32_t offset, xoffset, left, j;
4701 SectionRef S, xS;
4702 const char *name;
4703
4704 r = get_pointer_32(p, offset, left, S, info);
4705 if (r == nullptr)
4706 return;
4707 memset(&opl, '\0', sizeof(struct objc_property_list32));
4708 if (left < sizeof(struct objc_property_list32)) {
4709 memcpy(&opl, r, left);
4710 outs() << " (objc_property_list entends past the end of the section)\n";
4711 } else
4712 memcpy(&opl, r, sizeof(struct objc_property_list32));
4713 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4714 swapStruct(opl);
4715 outs() << " entsize " << opl.entsize << "\n";
4716 outs() << " count " << opl.count << "\n";
4717
4718 p += sizeof(struct objc_property_list32);
4719 offset += sizeof(struct objc_property_list32);
4720 for (j = 0; j < opl.count; j++) {
4721 r = get_pointer_32(p, offset, left, S, info);
4722 if (r == nullptr)
4723 return;
4724 memset(&op, '\0', sizeof(struct objc_property32));
4725 if (left < sizeof(struct objc_property32)) {
4726 memcpy(&op, r, left);
4727 outs() << " (objc_property entends past the end of the section)\n";
4728 } else
4729 memcpy(&op, r, sizeof(struct objc_property32));
4730 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4731 swapStruct(op);
4732
4733 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4734 name = get_pointer_32(op.name, xoffset, left, xS, info);
4735 if (name != nullptr)
4736 outs() << format(" %.*s", left, name);
4737 outs() << "\n";
4738
4739 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4740 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4741 if (name != nullptr)
4742 outs() << format(" %.*s", left, name);
4743 outs() << "\n";
4744
4745 p += sizeof(struct objc_property32);
4746 offset += sizeof(struct objc_property32);
4747 }
4748}
4749
Richard Smith81ff44d2015-10-09 22:09:56 +00004750static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004751 bool &is_meta_class) {
4752 struct class_ro64_t cro;
4753 const char *r;
4754 uint32_t offset, xoffset, left;
4755 SectionRef S, xS;
4756 const char *name, *sym_name;
4757 uint64_t n_value;
4758
4759 r = get_pointer_64(p, offset, left, S, info);
4760 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004761 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004762 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004763 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4764 swapStruct(cro);
4765 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4766 if (cro.flags & RO_META)
4767 outs() << " RO_META";
4768 if (cro.flags & RO_ROOT)
4769 outs() << " RO_ROOT";
4770 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4771 outs() << " RO_HAS_CXX_STRUCTORS";
4772 outs() << "\n";
4773 outs() << " instanceStart " << cro.instanceStart << "\n";
4774 outs() << " instanceSize " << cro.instanceSize << "\n";
4775 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4776 << "\n";
4777 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4778 << "\n";
4779 print_layout_map64(cro.ivarLayout, info);
4780
4781 outs() << " name ";
4782 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4783 info, n_value, cro.name);
4784 if (n_value != 0) {
4785 if (info->verbose && sym_name != nullptr)
4786 outs() << sym_name;
4787 else
4788 outs() << format("0x%" PRIx64, n_value);
4789 if (cro.name != 0)
4790 outs() << " + " << format("0x%" PRIx64, cro.name);
4791 } else
4792 outs() << format("0x%" PRIx64, cro.name);
4793 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4794 if (name != nullptr)
4795 outs() << format(" %.*s", left, name);
4796 outs() << "\n";
4797
4798 outs() << " baseMethods ";
4799 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4800 S, info, n_value, cro.baseMethods);
4801 if (n_value != 0) {
4802 if (info->verbose && sym_name != nullptr)
4803 outs() << sym_name;
4804 else
4805 outs() << format("0x%" PRIx64, n_value);
4806 if (cro.baseMethods != 0)
4807 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4808 } else
4809 outs() << format("0x%" PRIx64, cro.baseMethods);
4810 outs() << " (struct method_list_t *)\n";
4811 if (cro.baseMethods + n_value != 0)
4812 print_method_list64_t(cro.baseMethods + n_value, info, "");
4813
4814 outs() << " baseProtocols ";
4815 sym_name =
4816 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4817 info, n_value, cro.baseProtocols);
4818 if (n_value != 0) {
4819 if (info->verbose && sym_name != nullptr)
4820 outs() << sym_name;
4821 else
4822 outs() << format("0x%" PRIx64, n_value);
4823 if (cro.baseProtocols != 0)
4824 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4825 } else
4826 outs() << format("0x%" PRIx64, cro.baseProtocols);
4827 outs() << "\n";
4828 if (cro.baseProtocols + n_value != 0)
4829 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4830
4831 outs() << " ivars ";
4832 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004833 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004834 if (n_value != 0) {
4835 if (info->verbose && sym_name != nullptr)
4836 outs() << sym_name;
4837 else
4838 outs() << format("0x%" PRIx64, n_value);
4839 if (cro.ivars != 0)
4840 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4841 } else
4842 outs() << format("0x%" PRIx64, cro.ivars);
4843 outs() << "\n";
4844 if (cro.ivars + n_value != 0)
4845 print_ivar_list64_t(cro.ivars + n_value, info);
4846
4847 outs() << " weakIvarLayout ";
4848 sym_name =
4849 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4850 info, n_value, cro.weakIvarLayout);
4851 if (n_value != 0) {
4852 if (info->verbose && sym_name != nullptr)
4853 outs() << sym_name;
4854 else
4855 outs() << format("0x%" PRIx64, n_value);
4856 if (cro.weakIvarLayout != 0)
4857 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4858 } else
4859 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4860 outs() << "\n";
4861 print_layout_map64(cro.weakIvarLayout + n_value, info);
4862
4863 outs() << " baseProperties ";
4864 sym_name =
4865 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4866 info, n_value, cro.baseProperties);
4867 if (n_value != 0) {
4868 if (info->verbose && sym_name != nullptr)
4869 outs() << sym_name;
4870 else
4871 outs() << format("0x%" PRIx64, n_value);
4872 if (cro.baseProperties != 0)
4873 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4874 } else
4875 outs() << format("0x%" PRIx64, cro.baseProperties);
4876 outs() << "\n";
4877 if (cro.baseProperties + n_value != 0)
4878 print_objc_property_list64(cro.baseProperties + n_value, info);
4879
Rafael Espindolab9091322015-10-24 23:19:10 +00004880 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004881 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004882}
4883
Richard Smith81ff44d2015-10-09 22:09:56 +00004884static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004885 bool &is_meta_class) {
4886 struct class_ro32_t cro;
4887 const char *r;
4888 uint32_t offset, xoffset, left;
4889 SectionRef S, xS;
4890 const char *name;
4891
4892 r = get_pointer_32(p, offset, left, S, info);
4893 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004894 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004895 memset(&cro, '\0', sizeof(struct class_ro32_t));
4896 if (left < sizeof(struct class_ro32_t)) {
4897 memcpy(&cro, r, left);
4898 outs() << " (class_ro_t entends past the end of the section)\n";
4899 } else
4900 memcpy(&cro, r, sizeof(struct class_ro32_t));
4901 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4902 swapStruct(cro);
4903 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4904 if (cro.flags & RO_META)
4905 outs() << " RO_META";
4906 if (cro.flags & RO_ROOT)
4907 outs() << " RO_ROOT";
4908 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4909 outs() << " RO_HAS_CXX_STRUCTORS";
4910 outs() << "\n";
4911 outs() << " instanceStart " << cro.instanceStart << "\n";
4912 outs() << " instanceSize " << cro.instanceSize << "\n";
4913 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4914 << "\n";
4915 print_layout_map32(cro.ivarLayout, info);
4916
4917 outs() << " name " << format("0x%" PRIx32, cro.name);
4918 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4919 if (name != nullptr)
4920 outs() << format(" %.*s", left, name);
4921 outs() << "\n";
4922
4923 outs() << " baseMethods "
4924 << format("0x%" PRIx32, cro.baseMethods)
4925 << " (struct method_list_t *)\n";
4926 if (cro.baseMethods != 0)
4927 print_method_list32_t(cro.baseMethods, info, "");
4928
4929 outs() << " baseProtocols "
4930 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4931 if (cro.baseProtocols != 0)
4932 print_protocol_list32_t(cro.baseProtocols, info);
4933 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4934 << "\n";
4935 if (cro.ivars != 0)
4936 print_ivar_list32_t(cro.ivars, info);
4937 outs() << " weakIvarLayout "
4938 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4939 print_layout_map32(cro.weakIvarLayout, info);
4940 outs() << " baseProperties "
4941 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4942 if (cro.baseProperties != 0)
4943 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004944 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004945 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004946}
4947
Kevin Enderby0fc11822015-04-01 20:57:01 +00004948static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4949 struct class64_t c;
4950 const char *r;
4951 uint32_t offset, left;
4952 SectionRef S;
4953 const char *name;
4954 uint64_t isa_n_value, n_value;
4955
4956 r = get_pointer_64(p, offset, left, S, info);
4957 if (r == nullptr || left < sizeof(struct class64_t))
4958 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004959 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004960 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4961 swapStruct(c);
4962
4963 outs() << " isa " << format("0x%" PRIx64, c.isa);
4964 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4965 isa_n_value, c.isa);
4966 if (name != nullptr)
4967 outs() << " " << name;
4968 outs() << "\n";
4969
4970 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4971 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4972 n_value, c.superclass);
4973 if (name != nullptr)
4974 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00004975 else {
4976 name = get_dyld_bind_info_symbolname(S.getAddress() +
4977 offset + offsetof(struct class64_t, superclass), info);
4978 if (name != nullptr)
4979 outs() << " " << name;
4980 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00004981 outs() << "\n";
4982
4983 outs() << " cache " << format("0x%" PRIx64, c.cache);
4984 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4985 n_value, c.cache);
4986 if (name != nullptr)
4987 outs() << " " << name;
4988 outs() << "\n";
4989
4990 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4991 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4992 n_value, c.vtable);
4993 if (name != nullptr)
4994 outs() << " " << name;
4995 outs() << "\n";
4996
4997 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4998 n_value, c.data);
4999 outs() << " data ";
5000 if (n_value != 0) {
5001 if (info->verbose && name != nullptr)
5002 outs() << name;
5003 else
5004 outs() << format("0x%" PRIx64, n_value);
5005 if (c.data != 0)
5006 outs() << " + " << format("0x%" PRIx64, c.data);
5007 } else
5008 outs() << format("0x%" PRIx64, c.data);
5009 outs() << " (struct class_ro_t *)";
5010
5011 // This is a Swift class if some of the low bits of the pointer are set.
5012 if ((c.data + n_value) & 0x7)
5013 outs() << " Swift class";
5014 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005015 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005016 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5017 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005018
Kevin Enderbyaac75382015-10-08 16:56:35 +00005019 if (!is_meta_class &&
5020 c.isa + isa_n_value != p &&
5021 c.isa + isa_n_value != 0 &&
5022 info->depth < 100) {
5023 info->depth++;
5024 outs() << "Meta Class\n";
5025 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005026 }
5027}
5028
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005029static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5030 struct class32_t c;
5031 const char *r;
5032 uint32_t offset, left;
5033 SectionRef S;
5034 const char *name;
5035
5036 r = get_pointer_32(p, offset, left, S, info);
5037 if (r == nullptr)
5038 return;
5039 memset(&c, '\0', sizeof(struct class32_t));
5040 if (left < sizeof(struct class32_t)) {
5041 memcpy(&c, r, left);
5042 outs() << " (class_t entends past the end of the section)\n";
5043 } else
5044 memcpy(&c, r, sizeof(struct class32_t));
5045 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5046 swapStruct(c);
5047
5048 outs() << " isa " << format("0x%" PRIx32, c.isa);
5049 name =
5050 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5051 if (name != nullptr)
5052 outs() << " " << name;
5053 outs() << "\n";
5054
5055 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5056 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5057 c.superclass);
5058 if (name != nullptr)
5059 outs() << " " << name;
5060 outs() << "\n";
5061
5062 outs() << " cache " << format("0x%" PRIx32, c.cache);
5063 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5064 c.cache);
5065 if (name != nullptr)
5066 outs() << " " << name;
5067 outs() << "\n";
5068
5069 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5070 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5071 c.vtable);
5072 if (name != nullptr)
5073 outs() << " " << name;
5074 outs() << "\n";
5075
5076 name =
5077 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5078 outs() << " data " << format("0x%" PRIx32, c.data)
5079 << " (struct class_ro_t *)";
5080
5081 // This is a Swift class if some of the low bits of the pointer are set.
5082 if (c.data & 0x3)
5083 outs() << " Swift class";
5084 outs() << "\n";
5085 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005086 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5087 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005088
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005089 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005090 outs() << "Meta Class\n";
5091 print_class32_t(c.isa, info);
5092 }
5093}
5094
Kevin Enderby846c0002015-04-16 17:19:59 +00005095static void print_objc_class_t(struct objc_class_t *objc_class,
5096 struct DisassembleInfo *info) {
5097 uint32_t offset, left, xleft;
5098 const char *name, *p, *ivar_list;
5099 SectionRef S;
5100 int32_t i;
5101 struct objc_ivar_list_t objc_ivar_list;
5102 struct objc_ivar_t ivar;
5103
5104 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5105 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5106 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5107 if (name != nullptr)
5108 outs() << format(" %.*s", left, name);
5109 else
5110 outs() << " (not in an __OBJC section)";
5111 }
5112 outs() << "\n";
5113
5114 outs() << "\t super_class "
5115 << format("0x%08" PRIx32, objc_class->super_class);
5116 if (info->verbose) {
5117 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5118 if (name != nullptr)
5119 outs() << format(" %.*s", left, name);
5120 else
5121 outs() << " (not in an __OBJC section)";
5122 }
5123 outs() << "\n";
5124
5125 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5126 if (info->verbose) {
5127 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5128 if (name != nullptr)
5129 outs() << format(" %.*s", left, name);
5130 else
5131 outs() << " (not in an __OBJC section)";
5132 }
5133 outs() << "\n";
5134
5135 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5136 << "\n";
5137
5138 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5139 if (info->verbose) {
5140 if (CLS_GETINFO(objc_class, CLS_CLASS))
5141 outs() << " CLS_CLASS";
5142 else if (CLS_GETINFO(objc_class, CLS_META))
5143 outs() << " CLS_META";
5144 }
5145 outs() << "\n";
5146
5147 outs() << "\t instance_size "
5148 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5149
5150 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5151 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5152 if (p != nullptr) {
5153 if (left > sizeof(struct objc_ivar_list_t)) {
5154 outs() << "\n";
5155 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5156 } else {
5157 outs() << " (entends past the end of the section)\n";
5158 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5159 memcpy(&objc_ivar_list, p, left);
5160 }
5161 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5162 swapStruct(objc_ivar_list);
5163 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5164 ivar_list = p + sizeof(struct objc_ivar_list_t);
5165 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5166 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5167 outs() << "\t\t remaining ivar's extend past the of the section\n";
5168 break;
5169 }
5170 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5171 sizeof(struct objc_ivar_t));
5172 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5173 swapStruct(ivar);
5174
5175 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5176 if (info->verbose) {
5177 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5178 if (name != nullptr)
5179 outs() << format(" %.*s", xleft, name);
5180 else
5181 outs() << " (not in an __OBJC section)";
5182 }
5183 outs() << "\n";
5184
5185 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5186 if (info->verbose) {
5187 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5188 if (name != nullptr)
5189 outs() << format(" %.*s", xleft, name);
5190 else
5191 outs() << " (not in an __OBJC section)";
5192 }
5193 outs() << "\n";
5194
5195 outs() << "\t\t ivar_offset "
5196 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5197 }
5198 } else {
5199 outs() << " (not in an __OBJC section)\n";
5200 }
5201
5202 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5203 if (print_method_list(objc_class->methodLists, info))
5204 outs() << " (not in an __OBJC section)\n";
5205
5206 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5207 << "\n";
5208
5209 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5210 if (print_protocol_list(objc_class->protocols, 16, info))
5211 outs() << " (not in an __OBJC section)\n";
5212}
5213
5214static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5215 struct DisassembleInfo *info) {
5216 uint32_t offset, left;
5217 const char *name;
5218 SectionRef S;
5219
5220 outs() << "\t category name "
5221 << format("0x%08" PRIx32, objc_category->category_name);
5222 if (info->verbose) {
5223 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5224 true);
5225 if (name != nullptr)
5226 outs() << format(" %.*s", left, name);
5227 else
5228 outs() << " (not in an __OBJC section)";
5229 }
5230 outs() << "\n";
5231
5232 outs() << "\t\t class name "
5233 << format("0x%08" PRIx32, objc_category->class_name);
5234 if (info->verbose) {
5235 name =
5236 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5237 if (name != nullptr)
5238 outs() << format(" %.*s", left, name);
5239 else
5240 outs() << " (not in an __OBJC section)";
5241 }
5242 outs() << "\n";
5243
5244 outs() << "\t instance methods "
5245 << format("0x%08" PRIx32, objc_category->instance_methods);
5246 if (print_method_list(objc_category->instance_methods, info))
5247 outs() << " (not in an __OBJC section)\n";
5248
5249 outs() << "\t class methods "
5250 << format("0x%08" PRIx32, objc_category->class_methods);
5251 if (print_method_list(objc_category->class_methods, info))
5252 outs() << " (not in an __OBJC section)\n";
5253}
5254
Kevin Enderby0fc11822015-04-01 20:57:01 +00005255static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5256 struct category64_t c;
5257 const char *r;
5258 uint32_t offset, xoffset, left;
5259 SectionRef S, xS;
5260 const char *name, *sym_name;
5261 uint64_t n_value;
5262
5263 r = get_pointer_64(p, offset, left, S, info);
5264 if (r == nullptr)
5265 return;
5266 memset(&c, '\0', sizeof(struct category64_t));
5267 if (left < sizeof(struct category64_t)) {
5268 memcpy(&c, r, left);
5269 outs() << " (category_t entends past the end of the section)\n";
5270 } else
5271 memcpy(&c, r, sizeof(struct category64_t));
5272 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5273 swapStruct(c);
5274
5275 outs() << " name ";
5276 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5277 info, n_value, c.name);
5278 if (n_value != 0) {
5279 if (info->verbose && sym_name != nullptr)
5280 outs() << sym_name;
5281 else
5282 outs() << format("0x%" PRIx64, n_value);
5283 if (c.name != 0)
5284 outs() << " + " << format("0x%" PRIx64, c.name);
5285 } else
5286 outs() << format("0x%" PRIx64, c.name);
5287 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5288 if (name != nullptr)
5289 outs() << format(" %.*s", left, name);
5290 outs() << "\n";
5291
5292 outs() << " cls ";
5293 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5294 n_value, c.cls);
5295 if (n_value != 0) {
5296 if (info->verbose && sym_name != nullptr)
5297 outs() << sym_name;
5298 else
5299 outs() << format("0x%" PRIx64, n_value);
5300 if (c.cls != 0)
5301 outs() << " + " << format("0x%" PRIx64, c.cls);
5302 } else
5303 outs() << format("0x%" PRIx64, c.cls);
5304 outs() << "\n";
5305 if (c.cls + n_value != 0)
5306 print_class64_t(c.cls + n_value, info);
5307
5308 outs() << " instanceMethods ";
5309 sym_name =
5310 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5311 info, n_value, c.instanceMethods);
5312 if (n_value != 0) {
5313 if (info->verbose && sym_name != nullptr)
5314 outs() << sym_name;
5315 else
5316 outs() << format("0x%" PRIx64, n_value);
5317 if (c.instanceMethods != 0)
5318 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5319 } else
5320 outs() << format("0x%" PRIx64, c.instanceMethods);
5321 outs() << "\n";
5322 if (c.instanceMethods + n_value != 0)
5323 print_method_list64_t(c.instanceMethods + n_value, info, "");
5324
5325 outs() << " classMethods ";
5326 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5327 S, info, n_value, c.classMethods);
5328 if (n_value != 0) {
5329 if (info->verbose && sym_name != nullptr)
5330 outs() << sym_name;
5331 else
5332 outs() << format("0x%" PRIx64, n_value);
5333 if (c.classMethods != 0)
5334 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5335 } else
5336 outs() << format("0x%" PRIx64, c.classMethods);
5337 outs() << "\n";
5338 if (c.classMethods + n_value != 0)
5339 print_method_list64_t(c.classMethods + n_value, info, "");
5340
5341 outs() << " protocols ";
5342 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5343 info, n_value, c.protocols);
5344 if (n_value != 0) {
5345 if (info->verbose && sym_name != nullptr)
5346 outs() << sym_name;
5347 else
5348 outs() << format("0x%" PRIx64, n_value);
5349 if (c.protocols != 0)
5350 outs() << " + " << format("0x%" PRIx64, c.protocols);
5351 } else
5352 outs() << format("0x%" PRIx64, c.protocols);
5353 outs() << "\n";
5354 if (c.protocols + n_value != 0)
5355 print_protocol_list64_t(c.protocols + n_value, info);
5356
5357 outs() << "instanceProperties ";
5358 sym_name =
5359 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5360 S, info, n_value, c.instanceProperties);
5361 if (n_value != 0) {
5362 if (info->verbose && sym_name != nullptr)
5363 outs() << sym_name;
5364 else
5365 outs() << format("0x%" PRIx64, n_value);
5366 if (c.instanceProperties != 0)
5367 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5368 } else
5369 outs() << format("0x%" PRIx64, c.instanceProperties);
5370 outs() << "\n";
5371 if (c.instanceProperties + n_value != 0)
5372 print_objc_property_list64(c.instanceProperties + n_value, info);
5373}
5374
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005375static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5376 struct category32_t c;
5377 const char *r;
5378 uint32_t offset, left;
5379 SectionRef S, xS;
5380 const char *name;
5381
5382 r = get_pointer_32(p, offset, left, S, info);
5383 if (r == nullptr)
5384 return;
5385 memset(&c, '\0', sizeof(struct category32_t));
5386 if (left < sizeof(struct category32_t)) {
5387 memcpy(&c, r, left);
5388 outs() << " (category_t entends past the end of the section)\n";
5389 } else
5390 memcpy(&c, r, sizeof(struct category32_t));
5391 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5392 swapStruct(c);
5393
5394 outs() << " name " << format("0x%" PRIx32, c.name);
5395 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5396 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005397 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005398 outs() << " " << name;
5399 outs() << "\n";
5400
5401 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5402 if (c.cls != 0)
5403 print_class32_t(c.cls, info);
5404 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5405 << "\n";
5406 if (c.instanceMethods != 0)
5407 print_method_list32_t(c.instanceMethods, info, "");
5408 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5409 << "\n";
5410 if (c.classMethods != 0)
5411 print_method_list32_t(c.classMethods, info, "");
5412 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5413 if (c.protocols != 0)
5414 print_protocol_list32_t(c.protocols, info);
5415 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5416 << "\n";
5417 if (c.instanceProperties != 0)
5418 print_objc_property_list32(c.instanceProperties, info);
5419}
5420
Kevin Enderby0fc11822015-04-01 20:57:01 +00005421static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5422 uint32_t i, left, offset, xoffset;
5423 uint64_t p, n_value;
5424 struct message_ref64 mr;
5425 const char *name, *sym_name;
5426 const char *r;
5427 SectionRef xS;
5428
5429 if (S == SectionRef())
5430 return;
5431
5432 StringRef SectName;
5433 S.getName(SectName);
5434 DataRefImpl Ref = S.getRawDataRefImpl();
5435 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5436 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5437 offset = 0;
5438 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5439 p = S.getAddress() + i;
5440 r = get_pointer_64(p, offset, left, S, info);
5441 if (r == nullptr)
5442 return;
5443 memset(&mr, '\0', sizeof(struct message_ref64));
5444 if (left < sizeof(struct message_ref64)) {
5445 memcpy(&mr, r, left);
5446 outs() << " (message_ref entends past the end of the section)\n";
5447 } else
5448 memcpy(&mr, r, sizeof(struct message_ref64));
5449 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5450 swapStruct(mr);
5451
5452 outs() << " imp ";
5453 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5454 n_value, mr.imp);
5455 if (n_value != 0) {
5456 outs() << format("0x%" PRIx64, n_value) << " ";
5457 if (mr.imp != 0)
5458 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5459 } else
5460 outs() << format("0x%" PRIx64, mr.imp) << " ";
5461 if (name != nullptr)
5462 outs() << " " << name;
5463 outs() << "\n";
5464
5465 outs() << " sel ";
5466 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5467 info, n_value, mr.sel);
5468 if (n_value != 0) {
5469 if (info->verbose && sym_name != nullptr)
5470 outs() << sym_name;
5471 else
5472 outs() << format("0x%" PRIx64, n_value);
5473 if (mr.sel != 0)
5474 outs() << " + " << format("0x%" PRIx64, mr.sel);
5475 } else
5476 outs() << format("0x%" PRIx64, mr.sel);
5477 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5478 if (name != nullptr)
5479 outs() << format(" %.*s", left, name);
5480 outs() << "\n";
5481
5482 offset += sizeof(struct message_ref64);
5483 }
5484}
5485
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005486static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5487 uint32_t i, left, offset, xoffset, p;
5488 struct message_ref32 mr;
5489 const char *name, *r;
5490 SectionRef xS;
5491
5492 if (S == SectionRef())
5493 return;
5494
5495 StringRef SectName;
5496 S.getName(SectName);
5497 DataRefImpl Ref = S.getRawDataRefImpl();
5498 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5499 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5500 offset = 0;
5501 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5502 p = S.getAddress() + i;
5503 r = get_pointer_32(p, offset, left, S, info);
5504 if (r == nullptr)
5505 return;
5506 memset(&mr, '\0', sizeof(struct message_ref32));
5507 if (left < sizeof(struct message_ref32)) {
5508 memcpy(&mr, r, left);
5509 outs() << " (message_ref entends past the end of the section)\n";
5510 } else
5511 memcpy(&mr, r, sizeof(struct message_ref32));
5512 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5513 swapStruct(mr);
5514
5515 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5516 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5517 mr.imp);
5518 if (name != nullptr)
5519 outs() << " " << name;
5520 outs() << "\n";
5521
5522 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5523 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5524 if (name != nullptr)
5525 outs() << " " << name;
5526 outs() << "\n";
5527
5528 offset += sizeof(struct message_ref32);
5529 }
5530}
5531
Kevin Enderby0fc11822015-04-01 20:57:01 +00005532static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5533 uint32_t left, offset, swift_version;
5534 uint64_t p;
5535 struct objc_image_info64 o;
5536 const char *r;
5537
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005538 if (S == SectionRef())
5539 return;
5540
Kevin Enderby0fc11822015-04-01 20:57:01 +00005541 StringRef SectName;
5542 S.getName(SectName);
5543 DataRefImpl Ref = S.getRawDataRefImpl();
5544 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5545 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5546 p = S.getAddress();
5547 r = get_pointer_64(p, offset, left, S, info);
5548 if (r == nullptr)
5549 return;
5550 memset(&o, '\0', sizeof(struct objc_image_info64));
5551 if (left < sizeof(struct objc_image_info64)) {
5552 memcpy(&o, r, left);
5553 outs() << " (objc_image_info entends past the end of the section)\n";
5554 } else
5555 memcpy(&o, r, sizeof(struct objc_image_info64));
5556 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5557 swapStruct(o);
5558 outs() << " version " << o.version << "\n";
5559 outs() << " flags " << format("0x%" PRIx32, o.flags);
5560 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5561 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5562 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5563 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5564 swift_version = (o.flags >> 8) & 0xff;
5565 if (swift_version != 0) {
5566 if (swift_version == 1)
5567 outs() << " Swift 1.0";
5568 else if (swift_version == 2)
5569 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005570 else if(swift_version == 3)
5571 outs() << " Swift 2.0";
5572 else if(swift_version == 4)
5573 outs() << " Swift 3.0";
5574 else if(swift_version == 5)
5575 outs() << " Swift 4.0";
5576 else if(swift_version == 6)
5577 outs() << " Swift 4.1";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005578 else
5579 outs() << " unknown future Swift version (" << swift_version << ")";
5580 }
5581 outs() << "\n";
5582}
5583
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005584static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5585 uint32_t left, offset, swift_version, p;
5586 struct objc_image_info32 o;
5587 const char *r;
5588
Kevin Enderby19be2512016-04-21 19:49:29 +00005589 if (S == SectionRef())
5590 return;
5591
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005592 StringRef SectName;
5593 S.getName(SectName);
5594 DataRefImpl Ref = S.getRawDataRefImpl();
5595 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5596 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5597 p = S.getAddress();
5598 r = get_pointer_32(p, offset, left, S, info);
5599 if (r == nullptr)
5600 return;
5601 memset(&o, '\0', sizeof(struct objc_image_info32));
5602 if (left < sizeof(struct objc_image_info32)) {
5603 memcpy(&o, r, left);
5604 outs() << " (objc_image_info entends past the end of the section)\n";
5605 } else
5606 memcpy(&o, r, sizeof(struct objc_image_info32));
5607 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5608 swapStruct(o);
5609 outs() << " version " << o.version << "\n";
5610 outs() << " flags " << format("0x%" PRIx32, o.flags);
5611 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5612 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5613 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5614 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5615 swift_version = (o.flags >> 8) & 0xff;
5616 if (swift_version != 0) {
5617 if (swift_version == 1)
5618 outs() << " Swift 1.0";
5619 else if (swift_version == 2)
5620 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005621 else if(swift_version == 3)
5622 outs() << " Swift 2.0";
5623 else if(swift_version == 4)
5624 outs() << " Swift 3.0";
5625 else if(swift_version == 5)
5626 outs() << " Swift 4.0";
5627 else if(swift_version == 6)
5628 outs() << " Swift 4.1";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005629 else
5630 outs() << " unknown future Swift version (" << swift_version << ")";
5631 }
5632 outs() << "\n";
5633}
5634
Kevin Enderby846c0002015-04-16 17:19:59 +00005635static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5636 uint32_t left, offset, p;
5637 struct imageInfo_t o;
5638 const char *r;
5639
5640 StringRef SectName;
5641 S.getName(SectName);
5642 DataRefImpl Ref = S.getRawDataRefImpl();
5643 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5644 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5645 p = S.getAddress();
5646 r = get_pointer_32(p, offset, left, S, info);
5647 if (r == nullptr)
5648 return;
5649 memset(&o, '\0', sizeof(struct imageInfo_t));
5650 if (left < sizeof(struct imageInfo_t)) {
5651 memcpy(&o, r, left);
5652 outs() << " (imageInfo entends past the end of the section)\n";
5653 } else
5654 memcpy(&o, r, sizeof(struct imageInfo_t));
5655 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5656 swapStruct(o);
5657 outs() << " version " << o.version << "\n";
5658 outs() << " flags " << format("0x%" PRIx32, o.flags);
5659 if (o.flags & 0x1)
5660 outs() << " F&C";
5661 if (o.flags & 0x2)
5662 outs() << " GC";
5663 if (o.flags & 0x4)
5664 outs() << " GC-only";
5665 else
5666 outs() << " RR";
5667 outs() << "\n";
5668}
5669
Kevin Enderby0fc11822015-04-01 20:57:01 +00005670static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5671 SymbolAddressMap AddrMap;
5672 if (verbose)
5673 CreateSymbolAddressMap(O, &AddrMap);
5674
5675 std::vector<SectionRef> Sections;
5676 for (const SectionRef &Section : O->sections()) {
5677 StringRef SectName;
5678 Section.getName(SectName);
5679 Sections.push_back(Section);
5680 }
5681
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005682 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005683
Davide Italiano62507042015-12-11 22:27:59 +00005684 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5685 if (CL == SectionRef())
5686 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005687 if (CL == SectionRef())
5688 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5689 if (CL == SectionRef())
5690 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005691 info.S = CL;
5692 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005693
Davide Italiano62507042015-12-11 22:27:59 +00005694 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5695 if (CR == SectionRef())
5696 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005697 if (CR == SectionRef())
5698 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5699 if (CR == SectionRef())
5700 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005701 info.S = CR;
5702 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005703
Davide Italiano62507042015-12-11 22:27:59 +00005704 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5705 if (SR == SectionRef())
5706 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005707 if (SR == SectionRef())
5708 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5709 if (SR == SectionRef())
5710 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005711 info.S = SR;
5712 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005713
Davide Italiano62507042015-12-11 22:27:59 +00005714 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5715 if (CA == SectionRef())
5716 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005717 if (CA == SectionRef())
5718 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5719 if (CA == SectionRef())
5720 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005721 info.S = CA;
5722 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005723
Davide Italiano62507042015-12-11 22:27:59 +00005724 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5725 if (PL == SectionRef())
5726 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005727 if (PL == SectionRef())
5728 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5729 if (PL == SectionRef())
5730 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005731 info.S = PL;
5732 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005733
Davide Italiano62507042015-12-11 22:27:59 +00005734 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5735 if (MR == SectionRef())
5736 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005737 if (MR == SectionRef())
5738 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5739 if (MR == SectionRef())
5740 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005741 info.S = MR;
5742 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005743
Davide Italiano62507042015-12-11 22:27:59 +00005744 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5745 if (II == SectionRef())
5746 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005747 if (II == SectionRef())
5748 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5749 if (II == SectionRef())
5750 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005751 info.S = II;
5752 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005753}
5754
5755static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005756 SymbolAddressMap AddrMap;
5757 if (verbose)
5758 CreateSymbolAddressMap(O, &AddrMap);
5759
5760 std::vector<SectionRef> Sections;
5761 for (const SectionRef &Section : O->sections()) {
5762 StringRef SectName;
5763 Section.getName(SectName);
5764 Sections.push_back(Section);
5765 }
5766
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005767 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005768
Kevin Enderby5879a482017-02-09 17:56:26 +00005769 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5770 if (CL == SectionRef())
5771 CL = get_section(O, "__DATA", "__objc_classlist");
5772 if (CL == SectionRef())
5773 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5774 if (CL == SectionRef())
5775 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5776 info.S = CL;
5777 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005778
Kevin Enderby5879a482017-02-09 17:56:26 +00005779 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5780 if (CR == SectionRef())
5781 CR = get_section(O, "__DATA", "__objc_classrefs");
5782 if (CR == SectionRef())
5783 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5784 if (CR == SectionRef())
5785 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5786 info.S = CR;
5787 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005788
Kevin Enderby5879a482017-02-09 17:56:26 +00005789 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5790 if (SR == SectionRef())
5791 SR = get_section(O, "__DATA", "__objc_superrefs");
5792 if (SR == SectionRef())
5793 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5794 if (SR == SectionRef())
5795 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5796 info.S = SR;
5797 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005798
Kevin Enderby5879a482017-02-09 17:56:26 +00005799 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5800 if (CA == SectionRef())
5801 CA = get_section(O, "__DATA", "__objc_catlist");
5802 if (CA == SectionRef())
5803 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5804 if (CA == SectionRef())
5805 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5806 info.S = CA;
5807 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005808
Kevin Enderby5879a482017-02-09 17:56:26 +00005809 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5810 if (PL == SectionRef())
5811 PL = get_section(O, "__DATA", "__objc_protolist");
5812 if (PL == SectionRef())
5813 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5814 if (PL == SectionRef())
5815 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5816 info.S = PL;
5817 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005818
Kevin Enderby5879a482017-02-09 17:56:26 +00005819 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5820 if (MR == SectionRef())
5821 MR = get_section(O, "__DATA", "__objc_msgrefs");
5822 if (MR == SectionRef())
5823 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5824 if (MR == SectionRef())
5825 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5826 info.S = MR;
5827 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005828
Kevin Enderby5879a482017-02-09 17:56:26 +00005829 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5830 if (II == SectionRef())
5831 II = get_section(O, "__DATA", "__objc_imageinfo");
5832 if (II == SectionRef())
5833 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5834 if (II == SectionRef())
5835 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5836 info.S = II;
5837 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005838}
5839
5840static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005841 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5842 const char *r, *name, *defs;
5843 struct objc_module_t module;
5844 SectionRef S, xS;
5845 struct objc_symtab_t symtab;
5846 struct objc_class_t objc_class;
5847 struct objc_category_t objc_category;
5848
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005849 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005850 S = get_section(O, "__OBJC", "__module_info");
5851 if (S == SectionRef())
5852 return false;
5853
5854 SymbolAddressMap AddrMap;
5855 if (verbose)
5856 CreateSymbolAddressMap(O, &AddrMap);
5857
5858 std::vector<SectionRef> Sections;
5859 for (const SectionRef &Section : O->sections()) {
5860 StringRef SectName;
5861 Section.getName(SectName);
5862 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005863 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005864
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005865 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00005866
5867 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5868 p = S.getAddress() + i;
5869 r = get_pointer_32(p, offset, left, S, &info, true);
5870 if (r == nullptr)
5871 return true;
5872 memset(&module, '\0', sizeof(struct objc_module_t));
5873 if (left < sizeof(struct objc_module_t)) {
5874 memcpy(&module, r, left);
5875 outs() << " (module extends past end of __module_info section)\n";
5876 } else
5877 memcpy(&module, r, sizeof(struct objc_module_t));
5878 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5879 swapStruct(module);
5880
5881 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5882 outs() << " version " << module.version << "\n";
5883 outs() << " size " << module.size << "\n";
5884 outs() << " name ";
5885 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5886 if (name != nullptr)
5887 outs() << format("%.*s", left, name);
5888 else
5889 outs() << format("0x%08" PRIx32, module.name)
5890 << "(not in an __OBJC section)";
5891 outs() << "\n";
5892
5893 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5894 if (module.symtab == 0 || r == nullptr) {
5895 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5896 << " (not in an __OBJC section)\n";
5897 continue;
5898 }
5899 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5900 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5901 defs_left = 0;
5902 defs = nullptr;
5903 if (left < sizeof(struct objc_symtab_t)) {
5904 memcpy(&symtab, r, left);
5905 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5906 } else {
5907 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5908 if (left > sizeof(struct objc_symtab_t)) {
5909 defs_left = left - sizeof(struct objc_symtab_t);
5910 defs = r + sizeof(struct objc_symtab_t);
5911 }
5912 }
5913 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5914 swapStruct(symtab);
5915
5916 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5917 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5918 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5919 if (r == nullptr)
5920 outs() << " (not in an __OBJC section)";
5921 outs() << "\n";
5922 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5923 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5924 if (symtab.cls_def_cnt > 0)
5925 outs() << "\tClass Definitions\n";
5926 for (j = 0; j < symtab.cls_def_cnt; j++) {
5927 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5928 outs() << "\t(remaining class defs entries entends past the end of the "
5929 << "section)\n";
5930 break;
5931 }
5932 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5933 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5934 sys::swapByteOrder(def);
5935
5936 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5937 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5938 if (r != nullptr) {
5939 if (left > sizeof(struct objc_class_t)) {
5940 outs() << "\n";
5941 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5942 } else {
5943 outs() << " (entends past the end of the section)\n";
5944 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5945 memcpy(&objc_class, r, left);
5946 }
5947 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5948 swapStruct(objc_class);
5949 print_objc_class_t(&objc_class, &info);
5950 } else {
5951 outs() << "(not in an __OBJC section)\n";
5952 }
5953
5954 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5955 outs() << "\tMeta Class";
5956 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5957 if (r != nullptr) {
5958 if (left > sizeof(struct objc_class_t)) {
5959 outs() << "\n";
5960 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5961 } else {
5962 outs() << " (entends past the end of the section)\n";
5963 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5964 memcpy(&objc_class, r, left);
5965 }
5966 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5967 swapStruct(objc_class);
5968 print_objc_class_t(&objc_class, &info);
5969 } else {
5970 outs() << "(not in an __OBJC section)\n";
5971 }
5972 }
5973 }
5974 if (symtab.cat_def_cnt > 0)
5975 outs() << "\tCategory Definitions\n";
5976 for (j = 0; j < symtab.cat_def_cnt; j++) {
5977 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5978 outs() << "\t(remaining category defs entries entends past the end of "
5979 << "the section)\n";
5980 break;
5981 }
5982 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5983 sizeof(uint32_t));
5984 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5985 sys::swapByteOrder(def);
5986
5987 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5988 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5989 << format("0x%08" PRIx32, def);
5990 if (r != nullptr) {
5991 if (left > sizeof(struct objc_category_t)) {
5992 outs() << "\n";
5993 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5994 } else {
5995 outs() << " (entends past the end of the section)\n";
5996 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5997 memcpy(&objc_category, r, left);
5998 }
5999 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6000 swapStruct(objc_category);
6001 print_objc_objc_category_t(&objc_category, &info);
6002 } else {
6003 outs() << "(not in an __OBJC section)\n";
6004 }
6005 }
6006 }
6007 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6008 if (II != SectionRef())
6009 print_image_info(II, &info);
6010
6011 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006012}
6013
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006014static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6015 uint32_t size, uint32_t addr) {
6016 SymbolAddressMap AddrMap;
6017 CreateSymbolAddressMap(O, &AddrMap);
6018
6019 std::vector<SectionRef> Sections;
6020 for (const SectionRef &Section : O->sections()) {
6021 StringRef SectName;
6022 Section.getName(SectName);
6023 Sections.push_back(Section);
6024 }
6025
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006026 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006027
6028 const char *p;
6029 struct objc_protocol_t protocol;
6030 uint32_t left, paddr;
6031 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6032 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6033 left = size - (p - sect);
6034 if (left < sizeof(struct objc_protocol_t)) {
6035 outs() << "Protocol extends past end of __protocol section\n";
6036 memcpy(&protocol, p, left);
6037 } else
6038 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6039 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6040 swapStruct(protocol);
6041 paddr = addr + (p - sect);
6042 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6043 if (print_protocol(paddr, 0, &info))
6044 outs() << "(not in an __OBJC section)\n";
6045 }
6046}
6047
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006048#ifdef HAVE_LIBXAR
6049inline void swapStruct(struct xar_header &xar) {
6050 sys::swapByteOrder(xar.magic);
6051 sys::swapByteOrder(xar.size);
6052 sys::swapByteOrder(xar.version);
6053 sys::swapByteOrder(xar.toc_length_compressed);
6054 sys::swapByteOrder(xar.toc_length_uncompressed);
6055 sys::swapByteOrder(xar.cksum_alg);
6056}
6057
6058static void PrintModeVerbose(uint32_t mode) {
6059 switch(mode & S_IFMT){
6060 case S_IFDIR:
6061 outs() << "d";
6062 break;
6063 case S_IFCHR:
6064 outs() << "c";
6065 break;
6066 case S_IFBLK:
6067 outs() << "b";
6068 break;
6069 case S_IFREG:
6070 outs() << "-";
6071 break;
6072 case S_IFLNK:
6073 outs() << "l";
6074 break;
6075 case S_IFSOCK:
6076 outs() << "s";
6077 break;
6078 default:
6079 outs() << "?";
6080 break;
6081 }
6082
6083 /* owner permissions */
6084 if(mode & S_IREAD)
6085 outs() << "r";
6086 else
6087 outs() << "-";
6088 if(mode & S_IWRITE)
6089 outs() << "w";
6090 else
6091 outs() << "-";
6092 if(mode & S_ISUID)
6093 outs() << "s";
6094 else if(mode & S_IEXEC)
6095 outs() << "x";
6096 else
6097 outs() << "-";
6098
6099 /* group permissions */
6100 if(mode & (S_IREAD >> 3))
6101 outs() << "r";
6102 else
6103 outs() << "-";
6104 if(mode & (S_IWRITE >> 3))
6105 outs() << "w";
6106 else
6107 outs() << "-";
6108 if(mode & S_ISGID)
6109 outs() << "s";
6110 else if(mode & (S_IEXEC >> 3))
6111 outs() << "x";
6112 else
6113 outs() << "-";
6114
6115 /* other permissions */
6116 if(mode & (S_IREAD >> 6))
6117 outs() << "r";
6118 else
6119 outs() << "-";
6120 if(mode & (S_IWRITE >> 6))
6121 outs() << "w";
6122 else
6123 outs() << "-";
6124 if(mode & S_ISVTX)
6125 outs() << "t";
6126 else if(mode & (S_IEXEC >> 6))
6127 outs() << "x";
6128 else
6129 outs() << "-";
6130}
6131
6132static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006133 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006134 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6135 char *endp;
6136 uint32_t mode_value;
6137
Francis Ricci6f942972017-10-06 15:33:28 +00006138 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006139 if (!xi) {
6140 errs() << "Can't obtain an xar iterator for xar archive "
6141 << XarFilename << "\n";
6142 return;
6143 }
6144
6145 // Go through the xar's files.
6146 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006147 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006148 if(!xp){
6149 errs() << "Can't obtain an xar iterator for xar archive "
6150 << XarFilename << "\n";
6151 return;
6152 }
6153 type = nullptr;
6154 mode = nullptr;
6155 user = nullptr;
6156 group = nullptr;
6157 size = nullptr;
6158 mtime = nullptr;
6159 name = nullptr;
6160 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006161 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006162 xar_prop_get(xf, key, &val);
6163#if 0 // Useful for debugging.
6164 outs() << "key: " << key << " value: " << val << "\n";
6165#endif
6166 if(strcmp(key, "type") == 0)
6167 type = val;
6168 if(strcmp(key, "mode") == 0)
6169 mode = val;
6170 if(strcmp(key, "user") == 0)
6171 user = val;
6172 if(strcmp(key, "group") == 0)
6173 group = val;
6174 if(strcmp(key, "data/size") == 0)
6175 size = val;
6176 if(strcmp(key, "mtime") == 0)
6177 mtime = val;
6178 if(strcmp(key, "name") == 0)
6179 name = val;
6180 }
6181 if(mode != nullptr){
6182 mode_value = strtoul(mode, &endp, 8);
6183 if(*endp != '\0')
6184 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6185 if(strcmp(type, "file") == 0)
6186 mode_value |= S_IFREG;
6187 PrintModeVerbose(mode_value);
6188 outs() << " ";
6189 }
6190 if(user != nullptr)
6191 outs() << format("%10s/", user);
6192 if(group != nullptr)
6193 outs() << format("%-10s ", group);
6194 if(size != nullptr)
6195 outs() << format("%7s ", size);
6196 if(mtime != nullptr){
6197 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6198 outs() << *m;
6199 if(*m == 'T')
6200 m++;
6201 outs() << " ";
6202 for( ; *m != 'Z' && *m != '\0'; m++)
6203 outs() << *m;
6204 outs() << " ";
6205 }
6206 if(name != nullptr)
6207 outs() << name;
6208 outs() << "\n";
6209 }
6210}
6211
6212static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6213 uint32_t size, bool verbose,
6214 bool PrintXarHeader, bool PrintXarFileHeaders,
6215 std::string XarMemberName) {
6216 if(size < sizeof(struct xar_header)) {
6217 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6218 "of struct xar_header)\n";
6219 return;
6220 }
6221 struct xar_header XarHeader;
6222 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6223 if (sys::IsLittleEndianHost)
6224 swapStruct(XarHeader);
6225 if (PrintXarHeader) {
6226 if (!XarMemberName.empty())
6227 outs() << "In xar member " << XarMemberName << ": ";
6228 else
6229 outs() << "For (__LLVM,__bundle) section: ";
6230 outs() << "xar header\n";
6231 if (XarHeader.magic == XAR_HEADER_MAGIC)
6232 outs() << " magic XAR_HEADER_MAGIC\n";
6233 else
6234 outs() << " magic "
6235 << format_hex(XarHeader.magic, 10, true)
6236 << " (not XAR_HEADER_MAGIC)\n";
6237 outs() << " size " << XarHeader.size << "\n";
6238 outs() << " version " << XarHeader.version << "\n";
6239 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6240 << "\n";
6241 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6242 << "\n";
6243 outs() << " cksum_alg ";
6244 switch (XarHeader.cksum_alg) {
6245 case XAR_CKSUM_NONE:
6246 outs() << "XAR_CKSUM_NONE\n";
6247 break;
6248 case XAR_CKSUM_SHA1:
6249 outs() << "XAR_CKSUM_SHA1\n";
6250 break;
6251 case XAR_CKSUM_MD5:
6252 outs() << "XAR_CKSUM_MD5\n";
6253 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006254#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006255 case XAR_CKSUM_SHA256:
6256 outs() << "XAR_CKSUM_SHA256\n";
6257 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006258#endif
6259#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006260 case XAR_CKSUM_SHA512:
6261 outs() << "XAR_CKSUM_SHA512\n";
6262 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006263#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006264 default:
6265 outs() << XarHeader.cksum_alg << "\n";
6266 }
6267 }
6268
6269 SmallString<128> XarFilename;
6270 int FD;
6271 std::error_code XarEC =
6272 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6273 if (XarEC) {
6274 errs() << XarEC.message() << "\n";
6275 return;
6276 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006277 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006278 raw_fd_ostream &XarOut = XarFile.os();
6279 StringRef XarContents(sect, size);
6280 XarOut << XarContents;
6281 XarOut.close();
6282 if (XarOut.has_error())
6283 return;
6284
Francis Ricci6f942972017-10-06 15:33:28 +00006285 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006286 if (!xar) {
6287 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
6288 return;
6289 }
6290
6291 SmallString<128> TocFilename;
6292 std::error_code TocEC =
6293 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6294 if (TocEC) {
6295 errs() << TocEC.message() << "\n";
6296 return;
6297 }
6298 xar_serialize(xar, TocFilename.c_str());
6299
6300 if (PrintXarFileHeaders) {
6301 if (!XarMemberName.empty())
6302 outs() << "In xar member " << XarMemberName << ": ";
6303 else
6304 outs() << "For (__LLVM,__bundle) section: ";
6305 outs() << "xar archive files:\n";
6306 PrintXarFilesSummary(XarFilename.c_str(), xar);
6307 }
6308
6309 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6310 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6311 if (std::error_code EC = FileOrErr.getError()) {
6312 errs() << EC.message() << "\n";
6313 return;
6314 }
6315 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6316
6317 if (!XarMemberName.empty())
6318 outs() << "In xar member " << XarMemberName << ": ";
6319 else
6320 outs() << "For (__LLVM,__bundle) section: ";
6321 outs() << "xar table of contents:\n";
6322 outs() << Buffer->getBuffer() << "\n";
6323
6324 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006325 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006326 if(!xi){
6327 errs() << "Can't obtain an xar iterator for xar archive "
6328 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006329 return;
6330 }
6331 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6332 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006333 const char *member_name, *member_type, *member_size_string;
6334 size_t member_size;
6335
Francis Ricci6f942972017-10-06 15:33:28 +00006336 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006337 if(!xp){
6338 errs() << "Can't obtain an xar iterator for xar archive "
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006339 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006340 return;
6341 }
6342 member_name = NULL;
6343 member_type = NULL;
6344 member_size_string = NULL;
6345 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006346 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006347 xar_prop_get(xf, key, &val);
6348#if 0 // Useful for debugging.
6349 outs() << "key: " << key << " value: " << val << "\n";
6350#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006351 if (strcmp(key, "name") == 0)
6352 member_name = val;
6353 if (strcmp(key, "type") == 0)
6354 member_type = val;
6355 if (strcmp(key, "data/size") == 0)
6356 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006357 }
6358 /*
6359 * If we find a file with a name, date/size and type properties
6360 * and with the type being "file" see if that is a xar file.
6361 */
6362 if (member_name != NULL && member_type != NULL &&
6363 strcmp(member_type, "file") == 0 &&
6364 member_size_string != NULL){
6365 // Extract the file into a buffer.
6366 char *endptr;
6367 member_size = strtoul(member_size_string, &endptr, 10);
6368 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006369 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006370 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006371#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006372 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006373#endif
6374 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006375 std::string OldXarMemberName;
6376 // If XarMemberName is already set this is nested. So
6377 // save the old name and create the nested name.
6378 if (!XarMemberName.empty()) {
6379 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006380 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006381 (Twine("[") + XarMemberName + "]" + member_name).str();
6382 } else {
6383 OldXarMemberName = "";
6384 XarMemberName = member_name;
6385 }
6386 // See if this is could be a xar file (nested).
6387 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006388#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006389 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006390#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006391 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006392 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006393 swapStruct(XarHeader);
6394 if (XarHeader.magic == XAR_HEADER_MAGIC)
6395 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006396 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006397 XarMemberName);
6398 }
6399 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006400 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006401 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006402 }
6403 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006404 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006405}
6406#endif // defined(HAVE_LIBXAR)
6407
Kevin Enderby0fc11822015-04-01 20:57:01 +00006408static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6409 if (O->is64Bit())
6410 printObjc2_64bit_MetaData(O, verbose);
6411 else {
6412 MachO::mach_header H;
6413 H = O->getHeader();
6414 if (H.cputype == MachO::CPU_TYPE_ARM)
6415 printObjc2_32bit_MetaData(O, verbose);
6416 else {
6417 // This is the 32-bit non-arm cputype case. Which is normally
6418 // the first Objective-C ABI. But it may be the case of a
6419 // binary for the iOS simulator which is the second Objective-C
6420 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6421 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006422 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006423 printObjc2_32bit_MetaData(O, verbose);
6424 }
6425 }
6426}
6427
Kevin Enderbybf246f52014-09-24 23:08:22 +00006428// GuessLiteralPointer returns a string which for the item in the Mach-O file
6429// for the address passed in as ReferenceValue for printing as a comment with
6430// the instruction and also returns the corresponding type of that item
6431// indirectly through ReferenceType.
6432//
6433// If ReferenceValue is an address of literal cstring then a pointer to the
6434// cstring is returned and ReferenceType is set to
6435// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6436//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006437// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6438// Class ref that name is returned and the ReferenceType is set accordingly.
6439//
6440// Lastly, literals which are Symbol address in a literal pool are looked for
6441// and if found the symbol name is returned and ReferenceType is set to
6442// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6443//
6444// If there is no item in the Mach-O file for the address passed in as
6445// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006446static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6447 uint64_t ReferencePC,
6448 uint64_t *ReferenceType,
6449 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006450 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006451 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6452 uint64_t sect_addr = info->S.getAddress();
6453 uint64_t sect_offset = ReferencePC - sect_addr;
6454 bool reloc_found = false;
6455 DataRefImpl Rel;
6456 MachO::any_relocation_info RE;
6457 bool isExtern = false;
6458 SymbolRef Symbol;
6459 for (const RelocationRef &Reloc : info->S.relocations()) {
6460 uint64_t RelocOffset = Reloc.getOffset();
6461 if (RelocOffset == sect_offset) {
6462 Rel = Reloc.getRawDataRefImpl();
6463 RE = info->O->getRelocation(Rel);
6464 if (info->O->isRelocationScattered(RE))
6465 continue;
6466 isExtern = info->O->getPlainRelocationExternal(RE);
6467 if (isExtern) {
6468 symbol_iterator RelocSym = Reloc.getSymbol();
6469 Symbol = *RelocSym;
6470 }
6471 reloc_found = true;
6472 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006473 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006474 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006475 // If there is an external relocation entry for a symbol in a section
6476 // then used that symbol's value for the value of the reference.
6477 if (reloc_found && isExtern) {
6478 if (info->O->getAnyRelocationPCRel(RE)) {
6479 unsigned Type = info->O->getAnyRelocationType(RE);
6480 if (Type == MachO::X86_64_RELOC_SIGNED) {
6481 ReferenceValue = Symbol.getValue();
6482 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006483 }
6484 }
6485 }
6486
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006487 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6488 // Message refs and Class refs.
6489 bool classref, selref, msgref, cfstring;
6490 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6491 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006492 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006493 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6494 // And the pointer_value in that section is typically zero as it will be
6495 // set by dyld as part of the "bind information".
6496 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6497 if (name != nullptr) {
6498 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006499 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006500 if (class_name != nullptr && class_name[1] == '_' &&
6501 class_name[2] != '\0') {
6502 info->class_name = class_name + 2;
6503 return name;
6504 }
6505 }
6506 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006507
David Blaikie33dd45d02015-03-23 18:39:02 +00006508 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006509 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6510 const char *name =
6511 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6512 if (name != nullptr)
6513 info->class_name = name;
6514 else
6515 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006516 return name;
6517 }
6518
David Blaikie33dd45d02015-03-23 18:39:02 +00006519 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006520 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6521 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6522 return name;
6523 }
6524
David Blaikie33dd45d02015-03-23 18:39:02 +00006525 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006526 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6527
6528 if (pointer_value != 0)
6529 ReferenceValue = pointer_value;
6530
6531 const char *name = GuessCstringPointer(ReferenceValue, info);
6532 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006533 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006534 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6535 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006536 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006537 info->class_name = nullptr;
6538 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6539 info->selector_name = name;
6540 } else
6541 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6542 return name;
6543 }
6544
6545 // Lastly look for an indirect symbol with this ReferenceValue which is in
6546 // a literal pool. If found return that symbol name.
6547 name = GuessIndirectSymbol(ReferenceValue, info);
6548 if (name) {
6549 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6550 return name;
6551 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006552
6553 return nullptr;
6554}
6555
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006556// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006557// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006558// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6559// is created and returns the symbol name that matches the ReferenceValue or
6560// nullptr if none. The ReferenceType is passed in for the IN type of
6561// reference the instruction is making from the values in defined in the header
6562// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6563// Out type and the ReferenceName will also be set which is added as a comment
6564// to the disassembled instruction.
6565//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006566// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006567// returned through ReferenceName and ReferenceType is set to
6568// LLVMDisassembler_ReferenceType_DeMangled_Name .
6569//
6570// When this is called to get a symbol name for a branch target then the
6571// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6572// SymbolValue will be looked for in the indirect symbol table to determine if
6573// it is an address for a symbol stub. If so then the symbol name for that
6574// stub is returned indirectly through ReferenceName and then ReferenceType is
6575// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6576//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006577// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006578// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6579// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6580// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006581// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006582static const char *SymbolizerSymbolLookUp(void *DisInfo,
6583 uint64_t ReferenceValue,
6584 uint64_t *ReferenceType,
6585 uint64_t ReferencePC,
6586 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006587 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006588 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006589 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006590 *ReferenceName = nullptr;
6591 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006592 return nullptr;
6593 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006594
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006595 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006596
Kevin Enderby85974882014-09-26 22:20:44 +00006597 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6598 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006599 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006600 method_reference(info, ReferenceType, ReferenceName);
6601 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6602 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006603 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006604 if (info->demangled_name != nullptr)
6605 free(info->demangled_name);
6606 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006607 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006608 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006609 if (info->demangled_name != nullptr) {
6610 *ReferenceName = info->demangled_name;
6611 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6612 } else
6613 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6614 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006615 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6616 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6617 *ReferenceName =
6618 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006619 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006620 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006621 else
6622 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006623 // If this is arm64 and the reference is an adrp instruction save the
6624 // instruction, passed in ReferenceValue and the address of the instruction
6625 // for use later if we see and add immediate instruction.
6626 } else if (info->O->getArch() == Triple::aarch64 &&
6627 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6628 info->adrp_inst = ReferenceValue;
6629 info->adrp_addr = ReferencePC;
6630 SymbolName = nullptr;
6631 *ReferenceName = nullptr;
6632 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6633 // If this is arm64 and reference is an add immediate instruction and we
6634 // have
6635 // seen an adrp instruction just before it and the adrp's Xd register
6636 // matches
6637 // this add's Xn register reconstruct the value being referenced and look to
6638 // see if it is a literal pointer. Note the add immediate instruction is
6639 // passed in ReferenceValue.
6640 } else if (info->O->getArch() == Triple::aarch64 &&
6641 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6642 ReferencePC - 4 == info->adrp_addr &&
6643 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6644 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6645 uint32_t addxri_inst;
6646 uint64_t adrp_imm, addxri_imm;
6647
6648 adrp_imm =
6649 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6650 if (info->adrp_inst & 0x0200000)
6651 adrp_imm |= 0xfffffffffc000000LL;
6652
6653 addxri_inst = ReferenceValue;
6654 addxri_imm = (addxri_inst >> 10) & 0xfff;
6655 if (((addxri_inst >> 22) & 0x3) == 1)
6656 addxri_imm <<= 12;
6657
6658 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6659 (adrp_imm << 12) + addxri_imm;
6660
6661 *ReferenceName =
6662 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6663 if (*ReferenceName == nullptr)
6664 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6665 // If this is arm64 and the reference is a load register instruction and we
6666 // have seen an adrp instruction just before it and the adrp's Xd register
6667 // matches this add's Xn register reconstruct the value being referenced and
6668 // look to see if it is a literal pointer. Note the load register
6669 // instruction is passed in ReferenceValue.
6670 } else if (info->O->getArch() == Triple::aarch64 &&
6671 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6672 ReferencePC - 4 == info->adrp_addr &&
6673 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6674 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6675 uint32_t ldrxui_inst;
6676 uint64_t adrp_imm, ldrxui_imm;
6677
6678 adrp_imm =
6679 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6680 if (info->adrp_inst & 0x0200000)
6681 adrp_imm |= 0xfffffffffc000000LL;
6682
6683 ldrxui_inst = ReferenceValue;
6684 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6685
6686 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6687 (adrp_imm << 12) + (ldrxui_imm << 3);
6688
6689 *ReferenceName =
6690 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6691 if (*ReferenceName == nullptr)
6692 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6693 }
6694 // If this arm64 and is an load register (PC-relative) instruction the
6695 // ReferenceValue is the PC plus the immediate value.
6696 else if (info->O->getArch() == Triple::aarch64 &&
6697 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6698 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6699 *ReferenceName =
6700 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6701 if (*ReferenceName == nullptr)
6702 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006703 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006704 if (info->demangled_name != nullptr)
6705 free(info->demangled_name);
6706 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006707 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006708 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006709 if (info->demangled_name != nullptr) {
6710 *ReferenceName = info->demangled_name;
6711 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6712 }
6713 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006714 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006715 *ReferenceName = nullptr;
6716 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6717 }
6718
6719 return SymbolName;
6720}
6721
Kevin Enderbybf246f52014-09-24 23:08:22 +00006722/// \brief Emits the comments that are stored in the CommentStream.
6723/// Each comment in the CommentStream must end with a newline.
6724static void emitComments(raw_svector_ostream &CommentStream,
6725 SmallString<128> &CommentsToEmit,
6726 formatted_raw_ostream &FormattedOS,
6727 const MCAsmInfo &MAI) {
6728 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006729 StringRef Comments = CommentsToEmit.str();
6730 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006731 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006732 unsigned CommentColumn = MAI.getCommentColumn();
6733 bool IsFirst = true;
6734 while (!Comments.empty()) {
6735 if (!IsFirst)
6736 FormattedOS << '\n';
6737 // Emit a line of comments.
6738 FormattedOS.PadToColumn(CommentColumn);
6739 size_t Position = Comments.find('\n');
6740 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6741 // Move after the newline character.
6742 Comments = Comments.substr(Position + 1);
6743 IsFirst = false;
6744 }
6745 FormattedOS.flush();
6746
6747 // Tell the comment stream that the vector changed underneath it.
6748 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006749}
6750
Kevin Enderby95df54c2015-02-04 01:01:38 +00006751static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6752 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006753 const char *McpuDefault = nullptr;
6754 const Target *ThumbTarget = nullptr;
6755 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006756 if (!TheTarget) {
6757 // GetTarget prints out stuff.
6758 return;
6759 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006760 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006761 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006762 MachOMCPU = McpuDefault;
6763 else
6764 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006765
Ahmed Charles56440fd2014-03-06 05:51:42 +00006766 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006767 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006768 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006769 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006770
Kevin Enderbyc9595622014-08-06 23:24:41 +00006771 // Package up features to be passed to target/subtarget
6772 std::string FeaturesStr;
6773 if (MAttrs.size()) {
6774 SubtargetFeatures Features;
6775 for (unsigned i = 0; i != MAttrs.size(); ++i)
6776 Features.AddFeature(MAttrs[i]);
6777 FeaturesStr = Features.getString();
6778 }
6779
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006780 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006781 std::unique_ptr<const MCRegisterInfo> MRI(
6782 TheTarget->createMCRegInfo(TripleName));
6783 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006784 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006785 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006786 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006787 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006788 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006789 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006790 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006791 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006792 std::unique_ptr<MCRelocationInfo> RelInfo(
6793 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6794 if (RelInfo) {
6795 Symbolizer.reset(TheTarget->createMCSymbolizer(
6796 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006797 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006798 DisAsm->setSymbolizer(std::move(Symbolizer));
6799 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006800 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006801 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006802 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006803 // Set the display preference for hex vs. decimal immediates.
6804 IP->setPrintImmHex(PrintImmHex);
6805 // Comment stream and backing vector.
6806 SmallString<128> CommentsToEmit;
6807 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006808 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6809 // if it is done then arm64 comments for string literals don't get printed
6810 // and some constant get printed instead and not setting it causes intel
6811 // (32-bit and 64-bit) comments printed with different spacing before the
6812 // comment causing different diffs with the 'C' disassembler library API.
6813 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006814
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006815 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006816 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006817 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006818 return;
6819 }
6820
Tim Northover09ca33e2016-04-22 23:23:31 +00006821 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006822 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6823 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6824 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006825 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006826 std::unique_ptr<MCInstPrinter> ThumbIP;
6827 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006828 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006829 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006830 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006831 if (ThumbTarget) {
6832 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6833 ThumbAsmInfo.reset(
6834 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6835 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006836 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6837 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006838 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6839 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006840 MCContext *PtrThumbCtx = ThumbCtx.get();
6841 ThumbRelInfo.reset(
6842 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6843 if (ThumbRelInfo) {
6844 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6845 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006846 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006847 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6848 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006849 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6850 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006851 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6852 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006853 // Set the display preference for hex vs. decimal immediates.
6854 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006855 }
6856
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006857 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006858 errs() << "error: couldn't initialize disassembler for target "
6859 << ThumbTripleName << '\n';
6860 return;
6861 }
6862
Charles Davis8bdfafd2013-09-01 04:28:48 +00006863 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006864
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006865 // FIXME: Using the -cfg command line option, this code used to be able to
6866 // annotate relocations with the referenced symbol's name, and if this was
6867 // inside a __[cf]string section, the data it points to. This is now replaced
6868 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006869 std::vector<SectionRef> Sections;
6870 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006871 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006872 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006873
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006874 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006875 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006876
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006877 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006878 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006879
Kevin Enderby273ae012013-06-06 17:20:50 +00006880 // Build a data in code table that is sorted on by the address of each entry.
6881 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006882 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006883 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006884 else
6885 BaseAddress = BaseSegmentAddress;
6886 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006887 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006888 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006889 uint32_t Offset;
6890 DI->getOffset(Offset);
6891 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6892 }
6893 array_pod_sort(Dices.begin(), Dices.end());
6894
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006895#ifndef NDEBUG
6896 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6897#else
6898 raw_ostream &DebugOut = nulls();
6899#endif
6900
Ahmed Charles56440fd2014-03-06 05:51:42 +00006901 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006902 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006903 // Try to find debug info and set up the DIContext for it.
6904 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006905 // A separate DSym file path was specified, parse it as a macho file,
6906 // get the sections and supply it to the section name parsing machinery.
6907 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006908 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006909 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006910 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006911 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006912 return;
6913 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006914 DbgObj =
6915 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6916 .get()
6917 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006918 }
6919
Eric Christopher7370b552012-11-12 21:40:38 +00006920 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006921 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006922 }
6923
Colin LeMahieufcc32762015-07-29 19:08:10 +00006924 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006925 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006926
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006927 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006928 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006929 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6930 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006931
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006932 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006933
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006934 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006935 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006936 continue;
6937
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006938 StringRef BytesStr;
6939 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006940 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6941 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006942 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006943
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006944 bool symbolTableWorked = false;
6945
Kevin Enderbybf246f52014-09-24 23:08:22 +00006946 // Create a map of symbol addresses to symbol names for use by
6947 // the SymbolizerSymbolLookUp() routine.
6948 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006949 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006950 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006951 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006952 if (!STOrErr)
6953 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006954 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006955 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6956 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006957 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006958 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006959 if (!SymNameOrErr)
6960 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006961 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006962 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006963 if (!DisSymName.empty() && DisSymName == SymName)
6964 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006965 }
6966 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006967 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006968 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6969 return;
6970 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006971 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006972 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006973 SymbolizerInfo.O = MachOOF;
6974 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006975 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006976 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006977 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006978 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006979 ThumbSymbolizerInfo.O = MachOOF;
6980 ThumbSymbolizerInfo.S = Sections[SectIdx];
6981 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6982 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006983
Kevin Enderby4b627be2016-04-28 20:14:13 +00006984 unsigned int Arch = MachOOF->getArch();
6985
Tim Northoverf203ab52016-07-14 22:13:32 +00006986 // Skip all symbols if this is a stubs file.
6987 if (Bytes.size() == 0)
6988 return;
6989
Kevin Enderbyc138da32017-02-06 18:43:18 +00006990 // If the section has symbols but no symbol at the start of the section
6991 // these are used to make sure the bytes before the first symbol are
6992 // disassembled.
6993 bool FirstSymbol = true;
6994 bool FirstSymbolAtSectionStart = true;
6995
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006996 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006997 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006998 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006999 if (!SymNameOrErr)
7000 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007001 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007002
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007003 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007004 if (!STOrErr)
7005 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007006 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007007 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007008 continue;
7009
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007010 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007011 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007012 if (!containsSym) {
7013 if (!DisSymName.empty() && DisSymName == SymName) {
7014 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7015 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007016 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007017 continue;
7018 }
7019 // The __mh_execute_header is special and we need to deal with that fact
7020 // this symbol is before the start of the (__TEXT,__text) section and at the
7021 // address of the start of the __TEXT segment. This is because this symbol
7022 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7023 // start of the section in a standard MH_EXECUTE filetype.
7024 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7025 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7026 return;
7027 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007028 // When this code is trying to disassemble a symbol at a time and in the
7029 // case there is only the __mh_execute_header symbol left as in a stripped
7030 // executable, we need to deal with this by ignoring this symbol so the
7031 // whole section is disassembled and this symbol is then not displayed.
7032 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7033 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7034 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007035 continue;
7036
Kevin Enderby6a221752015-03-17 17:10:57 +00007037 // If we are only disassembling one symbol see if this is that symbol.
7038 if (!DisSymName.empty() && DisSymName != SymName)
7039 continue;
7040
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007041 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007042 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007043 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007044 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007045 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007046
Tim Northoverf203ab52016-07-14 22:13:32 +00007047 if (Start > SectSize) {
7048 outs() << "section data ends, " << SymName
7049 << " lies outside valid range\n";
7050 return;
7051 }
7052
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007053 // Stop disassembling either at the beginning of the next symbol or at
7054 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007055 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007056 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007057 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007058 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007059 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007060 if (!STOrErr)
7061 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007062 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007063 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007064 containsNextSym =
7065 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007066 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007067 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007068 break;
7069 }
7070 ++NextSymIdx;
7071 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007072
Tim Northoverf203ab52016-07-14 22:13:32 +00007073 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007074 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007075
7076 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007077
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007078 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007079 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7080
7081 // We only need the dedicated Thumb target if there's a real choice
7082 // (i.e. we're not targeting M-class) and the function is Thumb.
7083 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007084
Kevin Enderbyc138da32017-02-06 18:43:18 +00007085 // If we are not specifying a symbol to start disassembly with and this
7086 // is the first symbol in the section but not at the start of the section
7087 // then move the disassembly index to the start of the section and
7088 // don't print the symbol name just yet. This is so the bytes before the
7089 // first symbol are disassembled.
7090 uint64_t SymbolStart = Start;
7091 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7092 FirstSymbolAtSectionStart = false;
7093 Start = 0;
7094 }
7095 else
7096 outs() << SymName << ":\n";
7097
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007098 DILineInfo lastLine;
7099 for (uint64_t Index = Start; Index < End; Index += Size) {
7100 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007101
Kevin Enderbyc138da32017-02-06 18:43:18 +00007102 // If this is the first symbol in the section and it was not at the
7103 // start of the section, see if we are at its Index now and if so print
7104 // the symbol name.
7105 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7106 outs() << SymName << ":\n";
7107
Kevin Enderbybf246f52014-09-24 23:08:22 +00007108 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007109 if (!NoLeadingAddr) {
7110 if (FullLeadingAddr) {
7111 if (MachOOF->is64Bit())
7112 outs() << format("%016" PRIx64, PC);
7113 else
7114 outs() << format("%08" PRIx64, PC);
7115 } else {
7116 outs() << format("%8" PRIx64 ":", PC);
7117 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007118 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007119 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007120 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007121
7122 // Check the data in code table here to see if this is data not an
7123 // instruction to be disassembled.
7124 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007125 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007126 dice_table_iterator DTI =
7127 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7128 compareDiceTableEntries);
7129 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007130 uint16_t Length;
7131 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007132 uint16_t Kind;
7133 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007134 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007135 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7136 (PC == (DTI->first + Length - 1)) && (Length & 1))
7137 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007138 continue;
7139 }
7140
Kevin Enderbybf246f52014-09-24 23:08:22 +00007141 SmallVector<char, 64> AnnotationsBytes;
7142 raw_svector_ostream Annotations(AnnotationsBytes);
7143
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007144 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007145 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007146 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007147 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007148 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007149 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007150 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007151 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007152 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007153 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007154 }
7155 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007156 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007157 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007158 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007159 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007160 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007161 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007162
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007163 // Print debug info.
7164 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007165 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007166 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007167 if (dli != lastLine && dli.Line != 0)
7168 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7169 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007170 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007171 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007172 outs() << "\n";
7173 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007174 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007175 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007176 outs() << format("\t.byte 0x%02x #bad opcode\n",
7177 *(Bytes.data() + Index) & 0xff);
7178 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007179 } else if (Arch == Triple::aarch64 ||
7180 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007181 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7182 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7183 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7184 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7185 outs() << format("\t.long\t0x%08x\n", opcode);
7186 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007187 } else if (Arch == Triple::arm) {
7188 assert(IsThumb && "ARM mode should have been dealt with above");
7189 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7190 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7191 outs() << format("\t.short\t0x%04x\n", opcode);
7192 Size = 2;
7193 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007194 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7195 if (Size == 0)
7196 Size = 1; // skip illegible bytes
7197 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007198 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007199 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007200 // Now that we are done disassembled the first symbol set the bool that
7201 // were doing this to false.
7202 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007203 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007204 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007205 // Reading the symbol table didn't work, disassemble the whole section.
7206 uint64_t SectAddress = Sections[SectIdx].getAddress();
7207 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007208 uint64_t InstSize;
7209 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007210 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007211
Kevin Enderbybf246f52014-09-24 23:08:22 +00007212 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007213 SmallVector<char, 64> AnnotationsBytes;
7214 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007215 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007216 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007217 if (!NoLeadingAddr) {
7218 if (FullLeadingAddr) {
7219 if (MachOOF->is64Bit())
7220 outs() << format("%016" PRIx64, PC);
7221 else
7222 outs() << format("%08" PRIx64, PC);
7223 } else {
7224 outs() << format("%8" PRIx64 ":", PC);
7225 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007226 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007227 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007228 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007229 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007230 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007231 StringRef AnnotationsStr = Annotations.str();
7232 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007233 outs() << "\n";
7234 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007235 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007236 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007237 outs() << format("\t.byte 0x%02x #bad opcode\n",
7238 *(Bytes.data() + Index) & 0xff);
7239 InstSize = 1; // skip exactly one illegible byte and move on.
7240 } else {
7241 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7242 if (InstSize == 0)
7243 InstSize = 1; // skip illegible bytes
7244 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007245 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007246 }
7247 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007248 // The TripleName's need to be reset if we are called again for a different
7249 // archtecture.
7250 TripleName = "";
7251 ThumbTripleName = "";
7252
Kevin Enderby04bf6932014-10-28 23:39:46 +00007253 if (SymbolizerInfo.demangled_name != nullptr)
7254 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007255 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7256 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007257 }
7258}
Tim Northover4bd286a2014-08-01 13:07:19 +00007259
Tim Northover39c70bb2014-08-12 11:52:59 +00007260//===----------------------------------------------------------------------===//
7261// __compact_unwind section dumping
7262//===----------------------------------------------------------------------===//
7263
Tim Northover4bd286a2014-08-01 13:07:19 +00007264namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007265
Tim Northover3a4e1c72018-01-23 13:51:57 +00007266template <typename T>
7267static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007268 using llvm::support::little;
7269 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007270
Tim Northover3a4e1c72018-01-23 13:51:57 +00007271 if (Offset + sizeof(T) > Contents.size()) {
7272 outs() << "warning: attempt to read past end of buffer\n";
7273 return T();
7274 }
7275
7276 uint64_t Val =
7277 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7278 return Val;
7279}
7280
7281template <typename T>
7282static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7283 T Val = read<T>(Contents, Offset);
7284 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007285 return Val;
7286}
Tim Northover39c70bb2014-08-12 11:52:59 +00007287
Tim Northover4bd286a2014-08-01 13:07:19 +00007288struct CompactUnwindEntry {
7289 uint32_t OffsetInSection;
7290
7291 uint64_t FunctionAddr;
7292 uint32_t Length;
7293 uint32_t CompactEncoding;
7294 uint64_t PersonalityAddr;
7295 uint64_t LSDAAddr;
7296
7297 RelocationRef FunctionReloc;
7298 RelocationRef PersonalityReloc;
7299 RelocationRef LSDAReloc;
7300
7301 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007302 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007303 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007304 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007305 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007306 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007307 }
7308
7309private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007310 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7311 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7312 Length = readNext<uint32_t>(Contents, Offset);
7313 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7314 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7315 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007316 }
7317};
7318}
7319
7320/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7321/// and data being relocated, determine the best base Name and Addend to use for
7322/// display purposes.
7323///
7324/// 1. An Extern relocation will directly reference a symbol (and the data is
7325/// then already an addend), so use that.
7326/// 2. Otherwise the data is an offset in the object file's layout; try to find
7327// a symbol before it in the same section, and use the offset from there.
7328/// 3. Finally, if all that fails, fall back to an offset from the start of the
7329/// referenced section.
7330static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7331 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007332 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007333 StringRef &Name, uint64_t &Addend) {
7334 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007335 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007336 if (!NameOrErr)
7337 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007338 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007339 Addend = Addr;
7340 return;
7341 }
7342
7343 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007344 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007345
Rafael Espindola80291272014-10-08 15:28:58 +00007346 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007347
7348 auto Sym = Symbols.upper_bound(Addr);
7349 if (Sym == Symbols.begin()) {
7350 // The first symbol in the object is after this reference, the best we can
7351 // do is section-relative notation.
7352 RelocSection.getName(Name);
7353 Addend = Addr - SectionAddr;
7354 return;
7355 }
7356
7357 // Go back one so that SymbolAddress <= Addr.
7358 --Sym;
7359
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007360 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007361 if (!SectOrErr)
7362 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007363 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007364 if (RelocSection == *SymSection) {
7365 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007366 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007367 if (!NameOrErr)
7368 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007369 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007370 Addend = Addr - Sym->first;
7371 return;
7372 }
7373
7374 // There is a symbol before this reference, but it's in a different
7375 // section. Probably not helpful to mention it, so use the section name.
7376 RelocSection.getName(Name);
7377 Addend = Addr - SectionAddr;
7378}
7379
7380static void printUnwindRelocDest(const MachOObjectFile *Obj,
7381 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007382 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007383 StringRef Name;
7384 uint64_t Addend;
7385
Rafael Espindola854038e2015-06-26 14:51:16 +00007386 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007387 return;
7388
Tim Northover4bd286a2014-08-01 13:07:19 +00007389 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7390
7391 outs() << Name;
7392 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007393 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007394}
7395
7396static void
7397printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7398 std::map<uint64_t, SymbolRef> &Symbols,
7399 const SectionRef &CompactUnwind) {
7400
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007401 if (!Obj->isLittleEndian()) {
7402 outs() << "Skipping big-endian __compact_unwind section\n";
7403 return;
7404 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007405
7406 bool Is64 = Obj->is64Bit();
7407 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7408 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7409
7410 StringRef Contents;
7411 CompactUnwind.getContents(Contents);
7412
7413 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7414
7415 // First populate the initial raw offsets, encodings and so on from the entry.
7416 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007417 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007418 CompactUnwinds.push_back(Entry);
7419 }
7420
7421 // Next we need to look at the relocations to find out what objects are
7422 // actually being referred to.
7423 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007424 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007425
7426 uint32_t EntryIdx = RelocAddress / EntrySize;
7427 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7428 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7429
7430 if (OffsetInEntry == 0)
7431 Entry.FunctionReloc = Reloc;
7432 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7433 Entry.PersonalityReloc = Reloc;
7434 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7435 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007436 else {
7437 outs() << "Invalid relocation in __compact_unwind section\n";
7438 return;
7439 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007440 }
7441
7442 // Finally, we're ready to print the data we've gathered.
7443 outs() << "Contents of __compact_unwind section:\n";
7444 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007445 outs() << " Entry at offset "
7446 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007447
7448 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007449 outs() << " start: " << format("0x%" PRIx64,
7450 Entry.FunctionAddr) << ' ';
7451 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007452 outs() << '\n';
7453
7454 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007455 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7456 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007457 // 3. The 32-bit compact encoding.
7458 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007459 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007460
7461 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007462 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007463 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007464 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007465 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7466 Entry.PersonalityAddr);
7467 outs() << '\n';
7468 }
7469
7470 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007471 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007472 outs() << " LSDA: " << format("0x%" PRIx64,
7473 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007474 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7475 outs() << '\n';
7476 }
7477 }
7478}
7479
Tim Northover39c70bb2014-08-12 11:52:59 +00007480//===----------------------------------------------------------------------===//
7481// __unwind_info section dumping
7482//===----------------------------------------------------------------------===//
7483
Tim Northover3a4e1c72018-01-23 13:51:57 +00007484static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7485 ptrdiff_t Pos = 0;
7486 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007487 (void)Kind;
7488 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7489
Tim Northover3a4e1c72018-01-23 13:51:57 +00007490 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7491 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007492
Tim Northover3a4e1c72018-01-23 13:51:57 +00007493 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007494 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007495 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7496 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007497
7498 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007499 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7500 << ", "
7501 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007502 }
7503}
7504
7505static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007506 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007507 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007508 ptrdiff_t Pos = 0;
7509 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007510 (void)Kind;
7511 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7512
Tim Northover3a4e1c72018-01-23 13:51:57 +00007513 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7514 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007515
Tim Northover3a4e1c72018-01-23 13:51:57 +00007516 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7517 readNext<uint16_t>(PageData, Pos);
7518 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007519
Tim Northover3a4e1c72018-01-23 13:51:57 +00007520 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007521 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007522 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007523 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7524 uint32_t EncodingIdx = Entry >> 24;
7525
7526 uint32_t Encoding;
7527 if (EncodingIdx < CommonEncodings.size())
7528 Encoding = CommonEncodings[EncodingIdx];
7529 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007530 Encoding = read<uint32_t>(PageEncodings,
7531 sizeof(uint32_t) *
7532 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007533
7534 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007535 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7536 << ", "
7537 << "encoding[" << EncodingIdx
7538 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007539 }
7540}
7541
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007542static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7543 std::map<uint64_t, SymbolRef> &Symbols,
7544 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007545
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007546 if (!Obj->isLittleEndian()) {
7547 outs() << "Skipping big-endian __unwind_info section\n";
7548 return;
7549 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007550
7551 outs() << "Contents of __unwind_info section:\n";
7552
7553 StringRef Contents;
7554 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007555 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007556
7557 //===----------------------------------
7558 // Section header
7559 //===----------------------------------
7560
Tim Northover3a4e1c72018-01-23 13:51:57 +00007561 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007562 outs() << " Version: "
7563 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007564 if (Version != 1) {
7565 outs() << " Skipping section with unknown version\n";
7566 return;
7567 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007568
Tim Northover3a4e1c72018-01-23 13:51:57 +00007569 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007570 outs() << " Common encodings array section offset: "
7571 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007572 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007573 outs() << " Number of common encodings in array: "
7574 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7575
Tim Northover3a4e1c72018-01-23 13:51:57 +00007576 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007577 outs() << " Personality function array section offset: "
7578 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007579 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007580 outs() << " Number of personality functions in array: "
7581 << format("0x%" PRIx32, NumPersonalities) << '\n';
7582
Tim Northover3a4e1c72018-01-23 13:51:57 +00007583 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007584 outs() << " Index array section offset: "
7585 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007586 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007587 outs() << " Number of indices in array: "
7588 << format("0x%" PRIx32, NumIndices) << '\n';
7589
7590 //===----------------------------------
7591 // A shared list of common encodings
7592 //===----------------------------------
7593
7594 // These occupy indices in the range [0, N] whenever an encoding is referenced
7595 // from a compressed 2nd level index table. In practice the linker only
7596 // creates ~128 of these, so that indices are available to embed encodings in
7597 // the 2nd level index.
7598
7599 SmallVector<uint32_t, 64> CommonEncodings;
7600 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007601 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007602 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007603 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007604 CommonEncodings.push_back(Encoding);
7605
7606 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7607 << '\n';
7608 }
7609
Tim Northover39c70bb2014-08-12 11:52:59 +00007610 //===----------------------------------
7611 // Personality functions used in this executable
7612 //===----------------------------------
7613
7614 // There should be only a handful of these (one per source language,
7615 // roughly). Particularly since they only get 2 bits in the compact encoding.
7616
7617 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007618 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007619 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007620 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007621 outs() << " personality[" << i + 1
7622 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7623 }
7624
7625 //===----------------------------------
7626 // The level 1 index entries
7627 //===----------------------------------
7628
7629 // These specify an approximate place to start searching for the more detailed
7630 // information, sorted by PC.
7631
7632 struct IndexEntry {
7633 uint32_t FunctionOffset;
7634 uint32_t SecondLevelPageStart;
7635 uint32_t LSDAStart;
7636 };
7637
7638 SmallVector<IndexEntry, 4> IndexEntries;
7639
7640 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007641 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007642 for (unsigned i = 0; i < NumIndices; ++i) {
7643 IndexEntry Entry;
7644
Tim Northover3a4e1c72018-01-23 13:51:57 +00007645 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7646 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7647 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007648 IndexEntries.push_back(Entry);
7649
7650 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007651 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7652 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007653 << "2nd level page offset="
7654 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007655 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007656 }
7657
Tim Northover39c70bb2014-08-12 11:52:59 +00007658 //===----------------------------------
7659 // Next come the LSDA tables
7660 //===----------------------------------
7661
7662 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7663 // the first top-level index's LSDAOffset to the last (sentinel).
7664
7665 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007666 Pos = IndexEntries[0].LSDAStart;
7667 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7668 int NumLSDAs =
7669 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7670
Tim Northover39c70bb2014-08-12 11:52:59 +00007671 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007672 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7673 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007674 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007675 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7676 << ", "
7677 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007678 }
7679
7680 //===----------------------------------
7681 // Finally, the 2nd level indices
7682 //===----------------------------------
7683
7684 // Generally these are 4K in size, and have 2 possible forms:
7685 // + Regular stores up to 511 entries with disparate encodings
7686 // + Compressed stores up to 1021 entries if few enough compact encoding
7687 // values are used.
7688 outs() << " Second level indices:\n";
7689 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7690 // The final sentinel top-level index has no associated 2nd level page
7691 if (IndexEntries[i].SecondLevelPageStart == 0)
7692 break;
7693
7694 outs() << " Second level index[" << i << "]: "
7695 << "offset in section="
7696 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7697 << ", "
7698 << "base function offset="
7699 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7700
Tim Northover3a4e1c72018-01-23 13:51:57 +00007701 Pos = IndexEntries[i].SecondLevelPageStart;
7702 if (Pos + sizeof(uint32_t) > Contents.size()) {
7703 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7704 continue;
7705 }
7706
7707 uint32_t Kind =
7708 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007709 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007710 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007711 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007712 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7713 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007714 CommonEncodings);
7715 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007716 outs() << " Skipping 2nd level page with unknown kind " << Kind
7717 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007718 }
7719}
7720
Tim Northover4bd286a2014-08-01 13:07:19 +00007721void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7722 std::map<uint64_t, SymbolRef> Symbols;
7723 for (const SymbolRef &SymRef : Obj->symbols()) {
7724 // Discard any undefined or absolute symbols. They're not going to take part
7725 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007726 auto SectOrErr = SymRef.getSection();
7727 if (!SectOrErr) {
7728 // TODO: Actually report errors helpfully.
7729 consumeError(SectOrErr.takeError());
7730 continue;
7731 }
7732 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007733 if (Section == Obj->section_end())
7734 continue;
7735
Rafael Espindoladea00162015-07-03 17:44:18 +00007736 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007737 Symbols.insert(std::make_pair(Addr, SymRef));
7738 }
7739
7740 for (const SectionRef &Section : Obj->sections()) {
7741 StringRef SectName;
7742 Section.getName(SectName);
7743 if (SectName == "__compact_unwind")
7744 printMachOCompactUnwindSection(Obj, Symbols, Section);
7745 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007746 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007747 }
7748}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007749
7750static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7751 uint32_t cpusubtype, uint32_t filetype,
7752 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7753 bool verbose) {
7754 outs() << "Mach header\n";
7755 outs() << " magic cputype cpusubtype caps filetype ncmds "
7756 "sizeofcmds flags\n";
7757 if (verbose) {
7758 if (magic == MachO::MH_MAGIC)
7759 outs() << " MH_MAGIC";
7760 else if (magic == MachO::MH_MAGIC_64)
7761 outs() << "MH_MAGIC_64";
7762 else
7763 outs() << format(" 0x%08" PRIx32, magic);
7764 switch (cputype) {
7765 case MachO::CPU_TYPE_I386:
7766 outs() << " I386";
7767 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7768 case MachO::CPU_SUBTYPE_I386_ALL:
7769 outs() << " ALL";
7770 break;
7771 default:
7772 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7773 break;
7774 }
7775 break;
7776 case MachO::CPU_TYPE_X86_64:
7777 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007778 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7779 case MachO::CPU_SUBTYPE_X86_64_ALL:
7780 outs() << " ALL";
7781 break;
7782 case MachO::CPU_SUBTYPE_X86_64_H:
7783 outs() << " Haswell";
7784 break;
7785 default:
7786 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7787 break;
7788 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007789 break;
7790 case MachO::CPU_TYPE_ARM:
7791 outs() << " ARM";
7792 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7793 case MachO::CPU_SUBTYPE_ARM_ALL:
7794 outs() << " ALL";
7795 break;
7796 case MachO::CPU_SUBTYPE_ARM_V4T:
7797 outs() << " V4T";
7798 break;
7799 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7800 outs() << " V5TEJ";
7801 break;
7802 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7803 outs() << " XSCALE";
7804 break;
7805 case MachO::CPU_SUBTYPE_ARM_V6:
7806 outs() << " V6";
7807 break;
7808 case MachO::CPU_SUBTYPE_ARM_V6M:
7809 outs() << " V6M";
7810 break;
7811 case MachO::CPU_SUBTYPE_ARM_V7:
7812 outs() << " V7";
7813 break;
7814 case MachO::CPU_SUBTYPE_ARM_V7EM:
7815 outs() << " V7EM";
7816 break;
7817 case MachO::CPU_SUBTYPE_ARM_V7K:
7818 outs() << " V7K";
7819 break;
7820 case MachO::CPU_SUBTYPE_ARM_V7M:
7821 outs() << " V7M";
7822 break;
7823 case MachO::CPU_SUBTYPE_ARM_V7S:
7824 outs() << " V7S";
7825 break;
7826 default:
7827 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7828 break;
7829 }
7830 break;
7831 case MachO::CPU_TYPE_ARM64:
7832 outs() << " ARM64";
7833 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7834 case MachO::CPU_SUBTYPE_ARM64_ALL:
7835 outs() << " ALL";
7836 break;
7837 default:
7838 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7839 break;
7840 }
7841 break;
7842 case MachO::CPU_TYPE_POWERPC:
7843 outs() << " PPC";
7844 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7845 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7846 outs() << " ALL";
7847 break;
7848 default:
7849 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7850 break;
7851 }
7852 break;
7853 case MachO::CPU_TYPE_POWERPC64:
7854 outs() << " PPC64";
7855 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7856 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7857 outs() << " ALL";
7858 break;
7859 default:
7860 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7861 break;
7862 }
7863 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007864 default:
7865 outs() << format(" %7d", cputype);
7866 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7867 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007868 }
7869 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007870 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007871 } else {
7872 outs() << format(" 0x%02" PRIx32,
7873 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7874 }
7875 switch (filetype) {
7876 case MachO::MH_OBJECT:
7877 outs() << " OBJECT";
7878 break;
7879 case MachO::MH_EXECUTE:
7880 outs() << " EXECUTE";
7881 break;
7882 case MachO::MH_FVMLIB:
7883 outs() << " FVMLIB";
7884 break;
7885 case MachO::MH_CORE:
7886 outs() << " CORE";
7887 break;
7888 case MachO::MH_PRELOAD:
7889 outs() << " PRELOAD";
7890 break;
7891 case MachO::MH_DYLIB:
7892 outs() << " DYLIB";
7893 break;
7894 case MachO::MH_DYLIB_STUB:
7895 outs() << " DYLIB_STUB";
7896 break;
7897 case MachO::MH_DYLINKER:
7898 outs() << " DYLINKER";
7899 break;
7900 case MachO::MH_BUNDLE:
7901 outs() << " BUNDLE";
7902 break;
7903 case MachO::MH_DSYM:
7904 outs() << " DSYM";
7905 break;
7906 case MachO::MH_KEXT_BUNDLE:
7907 outs() << " KEXTBUNDLE";
7908 break;
7909 default:
7910 outs() << format(" %10u", filetype);
7911 break;
7912 }
7913 outs() << format(" %5u", ncmds);
7914 outs() << format(" %10u", sizeofcmds);
7915 uint32_t f = flags;
7916 if (f & MachO::MH_NOUNDEFS) {
7917 outs() << " NOUNDEFS";
7918 f &= ~MachO::MH_NOUNDEFS;
7919 }
7920 if (f & MachO::MH_INCRLINK) {
7921 outs() << " INCRLINK";
7922 f &= ~MachO::MH_INCRLINK;
7923 }
7924 if (f & MachO::MH_DYLDLINK) {
7925 outs() << " DYLDLINK";
7926 f &= ~MachO::MH_DYLDLINK;
7927 }
7928 if (f & MachO::MH_BINDATLOAD) {
7929 outs() << " BINDATLOAD";
7930 f &= ~MachO::MH_BINDATLOAD;
7931 }
7932 if (f & MachO::MH_PREBOUND) {
7933 outs() << " PREBOUND";
7934 f &= ~MachO::MH_PREBOUND;
7935 }
7936 if (f & MachO::MH_SPLIT_SEGS) {
7937 outs() << " SPLIT_SEGS";
7938 f &= ~MachO::MH_SPLIT_SEGS;
7939 }
7940 if (f & MachO::MH_LAZY_INIT) {
7941 outs() << " LAZY_INIT";
7942 f &= ~MachO::MH_LAZY_INIT;
7943 }
7944 if (f & MachO::MH_TWOLEVEL) {
7945 outs() << " TWOLEVEL";
7946 f &= ~MachO::MH_TWOLEVEL;
7947 }
7948 if (f & MachO::MH_FORCE_FLAT) {
7949 outs() << " FORCE_FLAT";
7950 f &= ~MachO::MH_FORCE_FLAT;
7951 }
7952 if (f & MachO::MH_NOMULTIDEFS) {
7953 outs() << " NOMULTIDEFS";
7954 f &= ~MachO::MH_NOMULTIDEFS;
7955 }
7956 if (f & MachO::MH_NOFIXPREBINDING) {
7957 outs() << " NOFIXPREBINDING";
7958 f &= ~MachO::MH_NOFIXPREBINDING;
7959 }
7960 if (f & MachO::MH_PREBINDABLE) {
7961 outs() << " PREBINDABLE";
7962 f &= ~MachO::MH_PREBINDABLE;
7963 }
7964 if (f & MachO::MH_ALLMODSBOUND) {
7965 outs() << " ALLMODSBOUND";
7966 f &= ~MachO::MH_ALLMODSBOUND;
7967 }
7968 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7969 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7970 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7971 }
7972 if (f & MachO::MH_CANONICAL) {
7973 outs() << " CANONICAL";
7974 f &= ~MachO::MH_CANONICAL;
7975 }
7976 if (f & MachO::MH_WEAK_DEFINES) {
7977 outs() << " WEAK_DEFINES";
7978 f &= ~MachO::MH_WEAK_DEFINES;
7979 }
7980 if (f & MachO::MH_BINDS_TO_WEAK) {
7981 outs() << " BINDS_TO_WEAK";
7982 f &= ~MachO::MH_BINDS_TO_WEAK;
7983 }
7984 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7985 outs() << " ALLOW_STACK_EXECUTION";
7986 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7987 }
7988 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7989 outs() << " DEAD_STRIPPABLE_DYLIB";
7990 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7991 }
7992 if (f & MachO::MH_PIE) {
7993 outs() << " PIE";
7994 f &= ~MachO::MH_PIE;
7995 }
7996 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7997 outs() << " NO_REEXPORTED_DYLIBS";
7998 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7999 }
8000 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8001 outs() << " MH_HAS_TLV_DESCRIPTORS";
8002 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8003 }
8004 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8005 outs() << " MH_NO_HEAP_EXECUTION";
8006 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8007 }
8008 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8009 outs() << " APP_EXTENSION_SAFE";
8010 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8011 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008012 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8013 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8014 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8015 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008016 if (f != 0 || flags == 0)
8017 outs() << format(" 0x%08" PRIx32, f);
8018 } else {
8019 outs() << format(" 0x%08" PRIx32, magic);
8020 outs() << format(" %7d", cputype);
8021 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8022 outs() << format(" 0x%02" PRIx32,
8023 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8024 outs() << format(" %10u", filetype);
8025 outs() << format(" %5u", ncmds);
8026 outs() << format(" %10u", sizeofcmds);
8027 outs() << format(" 0x%08" PRIx32, flags);
8028 }
8029 outs() << "\n";
8030}
8031
Kevin Enderby956366c2014-08-29 22:30:52 +00008032static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8033 StringRef SegName, uint64_t vmaddr,
8034 uint64_t vmsize, uint64_t fileoff,
8035 uint64_t filesize, uint32_t maxprot,
8036 uint32_t initprot, uint32_t nsects,
8037 uint32_t flags, uint32_t object_size,
8038 bool verbose) {
8039 uint64_t expected_cmdsize;
8040 if (cmd == MachO::LC_SEGMENT) {
8041 outs() << " cmd LC_SEGMENT\n";
8042 expected_cmdsize = nsects;
8043 expected_cmdsize *= sizeof(struct MachO::section);
8044 expected_cmdsize += sizeof(struct MachO::segment_command);
8045 } else {
8046 outs() << " cmd LC_SEGMENT_64\n";
8047 expected_cmdsize = nsects;
8048 expected_cmdsize *= sizeof(struct MachO::section_64);
8049 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8050 }
8051 outs() << " cmdsize " << cmdsize;
8052 if (cmdsize != expected_cmdsize)
8053 outs() << " Inconsistent size\n";
8054 else
8055 outs() << "\n";
8056 outs() << " segname " << SegName << "\n";
8057 if (cmd == MachO::LC_SEGMENT_64) {
8058 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8059 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8060 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008061 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8062 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008063 }
8064 outs() << " fileoff " << fileoff;
8065 if (fileoff > object_size)
8066 outs() << " (past end of file)\n";
8067 else
8068 outs() << "\n";
8069 outs() << " filesize " << filesize;
8070 if (fileoff + filesize > object_size)
8071 outs() << " (past end of file)\n";
8072 else
8073 outs() << "\n";
8074 if (verbose) {
8075 if ((maxprot &
8076 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8077 MachO::VM_PROT_EXECUTE)) != 0)
8078 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8079 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008080 outs() << " maxprot ";
8081 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8082 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8083 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008084 }
8085 if ((initprot &
8086 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8087 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008088 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008089 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008090 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008091 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8092 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8093 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008094 }
8095 } else {
8096 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8097 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8098 }
8099 outs() << " nsects " << nsects << "\n";
8100 if (verbose) {
8101 outs() << " flags";
8102 if (flags == 0)
8103 outs() << " (none)\n";
8104 else {
8105 if (flags & MachO::SG_HIGHVM) {
8106 outs() << " HIGHVM";
8107 flags &= ~MachO::SG_HIGHVM;
8108 }
8109 if (flags & MachO::SG_FVMLIB) {
8110 outs() << " FVMLIB";
8111 flags &= ~MachO::SG_FVMLIB;
8112 }
8113 if (flags & MachO::SG_NORELOC) {
8114 outs() << " NORELOC";
8115 flags &= ~MachO::SG_NORELOC;
8116 }
8117 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8118 outs() << " PROTECTED_VERSION_1";
8119 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8120 }
8121 if (flags)
8122 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8123 else
8124 outs() << "\n";
8125 }
8126 } else {
8127 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8128 }
8129}
8130
8131static void PrintSection(const char *sectname, const char *segname,
8132 uint64_t addr, uint64_t size, uint32_t offset,
8133 uint32_t align, uint32_t reloff, uint32_t nreloc,
8134 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8135 uint32_t cmd, const char *sg_segname,
8136 uint32_t filetype, uint32_t object_size,
8137 bool verbose) {
8138 outs() << "Section\n";
8139 outs() << " sectname " << format("%.16s\n", sectname);
8140 outs() << " segname " << format("%.16s", segname);
8141 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8142 outs() << " (does not match segment)\n";
8143 else
8144 outs() << "\n";
8145 if (cmd == MachO::LC_SEGMENT_64) {
8146 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8147 outs() << " size " << format("0x%016" PRIx64, size);
8148 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008149 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8150 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008151 }
8152 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8153 outs() << " (past end of file)\n";
8154 else
8155 outs() << "\n";
8156 outs() << " offset " << offset;
8157 if (offset > object_size)
8158 outs() << " (past end of file)\n";
8159 else
8160 outs() << "\n";
8161 uint32_t align_shifted = 1 << align;
8162 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8163 outs() << " reloff " << reloff;
8164 if (reloff > object_size)
8165 outs() << " (past end of file)\n";
8166 else
8167 outs() << "\n";
8168 outs() << " nreloc " << nreloc;
8169 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8170 outs() << " (past end of file)\n";
8171 else
8172 outs() << "\n";
8173 uint32_t section_type = flags & MachO::SECTION_TYPE;
8174 if (verbose) {
8175 outs() << " type";
8176 if (section_type == MachO::S_REGULAR)
8177 outs() << " S_REGULAR\n";
8178 else if (section_type == MachO::S_ZEROFILL)
8179 outs() << " S_ZEROFILL\n";
8180 else if (section_type == MachO::S_CSTRING_LITERALS)
8181 outs() << " S_CSTRING_LITERALS\n";
8182 else if (section_type == MachO::S_4BYTE_LITERALS)
8183 outs() << " S_4BYTE_LITERALS\n";
8184 else if (section_type == MachO::S_8BYTE_LITERALS)
8185 outs() << " S_8BYTE_LITERALS\n";
8186 else if (section_type == MachO::S_16BYTE_LITERALS)
8187 outs() << " S_16BYTE_LITERALS\n";
8188 else if (section_type == MachO::S_LITERAL_POINTERS)
8189 outs() << " S_LITERAL_POINTERS\n";
8190 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8191 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8192 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8193 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8194 else if (section_type == MachO::S_SYMBOL_STUBS)
8195 outs() << " S_SYMBOL_STUBS\n";
8196 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8197 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8198 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8199 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8200 else if (section_type == MachO::S_COALESCED)
8201 outs() << " S_COALESCED\n";
8202 else if (section_type == MachO::S_INTERPOSING)
8203 outs() << " S_INTERPOSING\n";
8204 else if (section_type == MachO::S_DTRACE_DOF)
8205 outs() << " S_DTRACE_DOF\n";
8206 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8207 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8208 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8209 outs() << " S_THREAD_LOCAL_REGULAR\n";
8210 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8211 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8212 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8213 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8214 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8215 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8216 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8217 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8218 else
8219 outs() << format("0x%08" PRIx32, section_type) << "\n";
8220 outs() << "attributes";
8221 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8222 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8223 outs() << " PURE_INSTRUCTIONS";
8224 if (section_attributes & MachO::S_ATTR_NO_TOC)
8225 outs() << " NO_TOC";
8226 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8227 outs() << " STRIP_STATIC_SYMS";
8228 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8229 outs() << " NO_DEAD_STRIP";
8230 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8231 outs() << " LIVE_SUPPORT";
8232 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8233 outs() << " SELF_MODIFYING_CODE";
8234 if (section_attributes & MachO::S_ATTR_DEBUG)
8235 outs() << " DEBUG";
8236 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8237 outs() << " SOME_INSTRUCTIONS";
8238 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8239 outs() << " EXT_RELOC";
8240 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8241 outs() << " LOC_RELOC";
8242 if (section_attributes == 0)
8243 outs() << " (none)";
8244 outs() << "\n";
8245 } else
8246 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8247 outs() << " reserved1 " << reserved1;
8248 if (section_type == MachO::S_SYMBOL_STUBS ||
8249 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8250 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8251 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8252 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8253 outs() << " (index into indirect symbol table)\n";
8254 else
8255 outs() << "\n";
8256 outs() << " reserved2 " << reserved2;
8257 if (section_type == MachO::S_SYMBOL_STUBS)
8258 outs() << " (size of stubs)\n";
8259 else
8260 outs() << "\n";
8261}
8262
David Majnemer73cc6ff2014-11-13 19:48:56 +00008263static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008264 uint32_t object_size) {
8265 outs() << " cmd LC_SYMTAB\n";
8266 outs() << " cmdsize " << st.cmdsize;
8267 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8268 outs() << " Incorrect size\n";
8269 else
8270 outs() << "\n";
8271 outs() << " symoff " << st.symoff;
8272 if (st.symoff > object_size)
8273 outs() << " (past end of file)\n";
8274 else
8275 outs() << "\n";
8276 outs() << " nsyms " << st.nsyms;
8277 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008278 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008279 big_size = st.nsyms;
8280 big_size *= sizeof(struct MachO::nlist_64);
8281 big_size += st.symoff;
8282 if (big_size > object_size)
8283 outs() << " (past end of file)\n";
8284 else
8285 outs() << "\n";
8286 } else {
8287 big_size = st.nsyms;
8288 big_size *= sizeof(struct MachO::nlist);
8289 big_size += st.symoff;
8290 if (big_size > object_size)
8291 outs() << " (past end of file)\n";
8292 else
8293 outs() << "\n";
8294 }
8295 outs() << " stroff " << st.stroff;
8296 if (st.stroff > object_size)
8297 outs() << " (past end of file)\n";
8298 else
8299 outs() << "\n";
8300 outs() << " strsize " << st.strsize;
8301 big_size = st.stroff;
8302 big_size += st.strsize;
8303 if (big_size > object_size)
8304 outs() << " (past end of file)\n";
8305 else
8306 outs() << "\n";
8307}
8308
8309static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8310 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008311 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008312 outs() << " cmd LC_DYSYMTAB\n";
8313 outs() << " cmdsize " << dyst.cmdsize;
8314 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8315 outs() << " Incorrect size\n";
8316 else
8317 outs() << "\n";
8318 outs() << " ilocalsym " << dyst.ilocalsym;
8319 if (dyst.ilocalsym > nsyms)
8320 outs() << " (greater than the number of symbols)\n";
8321 else
8322 outs() << "\n";
8323 outs() << " nlocalsym " << dyst.nlocalsym;
8324 uint64_t big_size;
8325 big_size = dyst.ilocalsym;
8326 big_size += dyst.nlocalsym;
8327 if (big_size > nsyms)
8328 outs() << " (past the end of the symbol table)\n";
8329 else
8330 outs() << "\n";
8331 outs() << " iextdefsym " << dyst.iextdefsym;
8332 if (dyst.iextdefsym > nsyms)
8333 outs() << " (greater than the number of symbols)\n";
8334 else
8335 outs() << "\n";
8336 outs() << " nextdefsym " << dyst.nextdefsym;
8337 big_size = dyst.iextdefsym;
8338 big_size += dyst.nextdefsym;
8339 if (big_size > nsyms)
8340 outs() << " (past the end of the symbol table)\n";
8341 else
8342 outs() << "\n";
8343 outs() << " iundefsym " << dyst.iundefsym;
8344 if (dyst.iundefsym > nsyms)
8345 outs() << " (greater than the number of symbols)\n";
8346 else
8347 outs() << "\n";
8348 outs() << " nundefsym " << dyst.nundefsym;
8349 big_size = dyst.iundefsym;
8350 big_size += dyst.nundefsym;
8351 if (big_size > nsyms)
8352 outs() << " (past the end of the symbol table)\n";
8353 else
8354 outs() << "\n";
8355 outs() << " tocoff " << dyst.tocoff;
8356 if (dyst.tocoff > object_size)
8357 outs() << " (past end of file)\n";
8358 else
8359 outs() << "\n";
8360 outs() << " ntoc " << dyst.ntoc;
8361 big_size = dyst.ntoc;
8362 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8363 big_size += dyst.tocoff;
8364 if (big_size > object_size)
8365 outs() << " (past end of file)\n";
8366 else
8367 outs() << "\n";
8368 outs() << " modtaboff " << dyst.modtaboff;
8369 if (dyst.modtaboff > object_size)
8370 outs() << " (past end of file)\n";
8371 else
8372 outs() << "\n";
8373 outs() << " nmodtab " << dyst.nmodtab;
8374 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008375 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008376 modtabend = dyst.nmodtab;
8377 modtabend *= sizeof(struct MachO::dylib_module_64);
8378 modtabend += dyst.modtaboff;
8379 } else {
8380 modtabend = dyst.nmodtab;
8381 modtabend *= sizeof(struct MachO::dylib_module);
8382 modtabend += dyst.modtaboff;
8383 }
8384 if (modtabend > object_size)
8385 outs() << " (past end of file)\n";
8386 else
8387 outs() << "\n";
8388 outs() << " extrefsymoff " << dyst.extrefsymoff;
8389 if (dyst.extrefsymoff > object_size)
8390 outs() << " (past end of file)\n";
8391 else
8392 outs() << "\n";
8393 outs() << " nextrefsyms " << dyst.nextrefsyms;
8394 big_size = dyst.nextrefsyms;
8395 big_size *= sizeof(struct MachO::dylib_reference);
8396 big_size += dyst.extrefsymoff;
8397 if (big_size > object_size)
8398 outs() << " (past end of file)\n";
8399 else
8400 outs() << "\n";
8401 outs() << " indirectsymoff " << dyst.indirectsymoff;
8402 if (dyst.indirectsymoff > object_size)
8403 outs() << " (past end of file)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " nindirectsyms " << dyst.nindirectsyms;
8407 big_size = dyst.nindirectsyms;
8408 big_size *= sizeof(uint32_t);
8409 big_size += dyst.indirectsymoff;
8410 if (big_size > object_size)
8411 outs() << " (past end of file)\n";
8412 else
8413 outs() << "\n";
8414 outs() << " extreloff " << dyst.extreloff;
8415 if (dyst.extreloff > object_size)
8416 outs() << " (past end of file)\n";
8417 else
8418 outs() << "\n";
8419 outs() << " nextrel " << dyst.nextrel;
8420 big_size = dyst.nextrel;
8421 big_size *= sizeof(struct MachO::relocation_info);
8422 big_size += dyst.extreloff;
8423 if (big_size > object_size)
8424 outs() << " (past end of file)\n";
8425 else
8426 outs() << "\n";
8427 outs() << " locreloff " << dyst.locreloff;
8428 if (dyst.locreloff > object_size)
8429 outs() << " (past end of file)\n";
8430 else
8431 outs() << "\n";
8432 outs() << " nlocrel " << dyst.nlocrel;
8433 big_size = dyst.nlocrel;
8434 big_size *= sizeof(struct MachO::relocation_info);
8435 big_size += dyst.locreloff;
8436 if (big_size > object_size)
8437 outs() << " (past end of file)\n";
8438 else
8439 outs() << "\n";
8440}
8441
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008442static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8443 uint32_t object_size) {
8444 if (dc.cmd == MachO::LC_DYLD_INFO)
8445 outs() << " cmd LC_DYLD_INFO\n";
8446 else
8447 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8448 outs() << " cmdsize " << dc.cmdsize;
8449 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8450 outs() << " Incorrect size\n";
8451 else
8452 outs() << "\n";
8453 outs() << " rebase_off " << dc.rebase_off;
8454 if (dc.rebase_off > object_size)
8455 outs() << " (past end of file)\n";
8456 else
8457 outs() << "\n";
8458 outs() << " rebase_size " << dc.rebase_size;
8459 uint64_t big_size;
8460 big_size = dc.rebase_off;
8461 big_size += dc.rebase_size;
8462 if (big_size > object_size)
8463 outs() << " (past end of file)\n";
8464 else
8465 outs() << "\n";
8466 outs() << " bind_off " << dc.bind_off;
8467 if (dc.bind_off > object_size)
8468 outs() << " (past end of file)\n";
8469 else
8470 outs() << "\n";
8471 outs() << " bind_size " << dc.bind_size;
8472 big_size = dc.bind_off;
8473 big_size += dc.bind_size;
8474 if (big_size > object_size)
8475 outs() << " (past end of file)\n";
8476 else
8477 outs() << "\n";
8478 outs() << " weak_bind_off " << dc.weak_bind_off;
8479 if (dc.weak_bind_off > object_size)
8480 outs() << " (past end of file)\n";
8481 else
8482 outs() << "\n";
8483 outs() << " weak_bind_size " << dc.weak_bind_size;
8484 big_size = dc.weak_bind_off;
8485 big_size += dc.weak_bind_size;
8486 if (big_size > object_size)
8487 outs() << " (past end of file)\n";
8488 else
8489 outs() << "\n";
8490 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8491 if (dc.lazy_bind_off > object_size)
8492 outs() << " (past end of file)\n";
8493 else
8494 outs() << "\n";
8495 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8496 big_size = dc.lazy_bind_off;
8497 big_size += dc.lazy_bind_size;
8498 if (big_size > object_size)
8499 outs() << " (past end of file)\n";
8500 else
8501 outs() << "\n";
8502 outs() << " export_off " << dc.export_off;
8503 if (dc.export_off > object_size)
8504 outs() << " (past end of file)\n";
8505 else
8506 outs() << "\n";
8507 outs() << " export_size " << dc.export_size;
8508 big_size = dc.export_off;
8509 big_size += dc.export_size;
8510 if (big_size > object_size)
8511 outs() << " (past end of file)\n";
8512 else
8513 outs() << "\n";
8514}
8515
8516static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8517 const char *Ptr) {
8518 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8519 outs() << " cmd LC_ID_DYLINKER\n";
8520 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8521 outs() << " cmd LC_LOAD_DYLINKER\n";
8522 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8523 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8524 else
8525 outs() << " cmd ?(" << dyld.cmd << ")\n";
8526 outs() << " cmdsize " << dyld.cmdsize;
8527 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8528 outs() << " Incorrect size\n";
8529 else
8530 outs() << "\n";
8531 if (dyld.name >= dyld.cmdsize)
8532 outs() << " name ?(bad offset " << dyld.name << ")\n";
8533 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008534 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008535 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8536 }
8537}
8538
8539static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8540 outs() << " cmd LC_UUID\n";
8541 outs() << " cmdsize " << uuid.cmdsize;
8542 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8543 outs() << " Incorrect size\n";
8544 else
8545 outs() << "\n";
8546 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008547 for (int i = 0; i < 16; ++i) {
8548 outs() << format("%02" PRIX32, uuid.uuid[i]);
8549 if (i == 3 || i == 5 || i == 7 || i == 9)
8550 outs() << "-";
8551 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008552 outs() << "\n";
8553}
8554
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008555static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008556 outs() << " cmd LC_RPATH\n";
8557 outs() << " cmdsize " << rpath.cmdsize;
8558 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8559 outs() << " Incorrect size\n";
8560 else
8561 outs() << "\n";
8562 if (rpath.path >= rpath.cmdsize)
8563 outs() << " path ?(bad offset " << rpath.path << ")\n";
8564 else {
8565 const char *P = (const char *)(Ptr) + rpath.path;
8566 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8567 }
8568}
8569
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008570static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008571 StringRef LoadCmdName;
8572 switch (vd.cmd) {
8573 case MachO::LC_VERSION_MIN_MACOSX:
8574 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8575 break;
8576 case MachO::LC_VERSION_MIN_IPHONEOS:
8577 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8578 break;
8579 case MachO::LC_VERSION_MIN_TVOS:
8580 LoadCmdName = "LC_VERSION_MIN_TVOS";
8581 break;
8582 case MachO::LC_VERSION_MIN_WATCHOS:
8583 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8584 break;
8585 default:
8586 llvm_unreachable("Unknown version min load command");
8587 }
8588
8589 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008590 outs() << " cmdsize " << vd.cmdsize;
8591 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8592 outs() << " Incorrect size\n";
8593 else
8594 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008595 outs() << " version "
8596 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8597 << MachOObjectFile::getVersionMinMinor(vd, false);
8598 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8599 if (Update != 0)
8600 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008601 outs() << "\n";
8602 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008603 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008604 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008605 outs() << " sdk "
8606 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8607 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008608 }
Davide Italiano56baef32015-08-26 12:26:11 +00008609 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8610 if (Update != 0)
8611 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008612 outs() << "\n";
8613}
8614
Kevin Enderbya4579c42017-01-19 17:36:31 +00008615static void PrintNoteLoadCommand(MachO::note_command Nt) {
8616 outs() << " cmd LC_NOTE\n";
8617 outs() << " cmdsize " << Nt.cmdsize;
8618 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8619 outs() << " Incorrect size\n";
8620 else
8621 outs() << "\n";
8622 const char *d = Nt.data_owner;
8623 outs() << "data_owner " << format("%.16s\n", d);
8624 outs() << " offset " << Nt.offset << "\n";
8625 outs() << " size " << Nt.size << "\n";
8626}
8627
Steven Wu5b54a422017-01-23 20:07:55 +00008628static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8629 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8630 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8631 << "\n";
8632}
8633
8634static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8635 MachO::build_version_command bd) {
8636 outs() << " cmd LC_BUILD_VERSION\n";
8637 outs() << " cmdsize " << bd.cmdsize;
8638 if (bd.cmdsize !=
8639 sizeof(struct MachO::build_version_command) +
8640 bd.ntools * sizeof(struct MachO::build_tool_version))
8641 outs() << " Incorrect size\n";
8642 else
8643 outs() << "\n";
8644 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8645 << "\n";
8646 if (bd.sdk)
8647 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8648 << "\n";
8649 else
8650 outs() << " sdk n/a\n";
8651 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8652 << "\n";
8653 outs() << " ntools " << bd.ntools << "\n";
8654 for (unsigned i = 0; i < bd.ntools; ++i) {
8655 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8656 PrintBuildToolVersion(bv);
8657 }
8658}
8659
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008660static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8661 outs() << " cmd LC_SOURCE_VERSION\n";
8662 outs() << " cmdsize " << sd.cmdsize;
8663 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8664 outs() << " Incorrect size\n";
8665 else
8666 outs() << "\n";
8667 uint64_t a = (sd.version >> 40) & 0xffffff;
8668 uint64_t b = (sd.version >> 30) & 0x3ff;
8669 uint64_t c = (sd.version >> 20) & 0x3ff;
8670 uint64_t d = (sd.version >> 10) & 0x3ff;
8671 uint64_t e = sd.version & 0x3ff;
8672 outs() << " version " << a << "." << b;
8673 if (e != 0)
8674 outs() << "." << c << "." << d << "." << e;
8675 else if (d != 0)
8676 outs() << "." << c << "." << d;
8677 else if (c != 0)
8678 outs() << "." << c;
8679 outs() << "\n";
8680}
8681
8682static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8683 outs() << " cmd LC_MAIN\n";
8684 outs() << " cmdsize " << ep.cmdsize;
8685 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8686 outs() << " Incorrect size\n";
8687 else
8688 outs() << "\n";
8689 outs() << " entryoff " << ep.entryoff << "\n";
8690 outs() << " stacksize " << ep.stacksize << "\n";
8691}
8692
Kevin Enderby0804f4672014-12-16 23:25:52 +00008693static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8694 uint32_t object_size) {
8695 outs() << " cmd LC_ENCRYPTION_INFO\n";
8696 outs() << " cmdsize " << ec.cmdsize;
8697 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8698 outs() << " Incorrect size\n";
8699 else
8700 outs() << "\n";
8701 outs() << " cryptoff " << ec.cryptoff;
8702 if (ec.cryptoff > object_size)
8703 outs() << " (past end of file)\n";
8704 else
8705 outs() << "\n";
8706 outs() << " cryptsize " << ec.cryptsize;
8707 if (ec.cryptsize > object_size)
8708 outs() << " (past end of file)\n";
8709 else
8710 outs() << "\n";
8711 outs() << " cryptid " << ec.cryptid << "\n";
8712}
8713
Kevin Enderby57538292014-12-17 01:01:30 +00008714static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008715 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008716 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8717 outs() << " cmdsize " << ec.cmdsize;
8718 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8719 outs() << " Incorrect size\n";
8720 else
8721 outs() << "\n";
8722 outs() << " cryptoff " << ec.cryptoff;
8723 if (ec.cryptoff > object_size)
8724 outs() << " (past end of file)\n";
8725 else
8726 outs() << "\n";
8727 outs() << " cryptsize " << ec.cryptsize;
8728 if (ec.cryptsize > object_size)
8729 outs() << " (past end of file)\n";
8730 else
8731 outs() << "\n";
8732 outs() << " cryptid " << ec.cryptid << "\n";
8733 outs() << " pad " << ec.pad << "\n";
8734}
8735
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008736static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8737 const char *Ptr) {
8738 outs() << " cmd LC_LINKER_OPTION\n";
8739 outs() << " cmdsize " << lo.cmdsize;
8740 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8741 outs() << " Incorrect size\n";
8742 else
8743 outs() << "\n";
8744 outs() << " count " << lo.count << "\n";
8745 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8746 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8747 uint32_t i = 0;
8748 while (left > 0) {
8749 while (*string == '\0' && left > 0) {
8750 string++;
8751 left--;
8752 }
8753 if (left > 0) {
8754 i++;
8755 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008756 uint32_t NullPos = StringRef(string, left).find('\0');
8757 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008758 string += len;
8759 left -= len;
8760 }
8761 }
8762 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008763 outs() << " count " << lo.count << " does not match number of strings "
8764 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008765}
8766
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008767static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8768 const char *Ptr) {
8769 outs() << " cmd LC_SUB_FRAMEWORK\n";
8770 outs() << " cmdsize " << sub.cmdsize;
8771 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8772 outs() << " Incorrect size\n";
8773 else
8774 outs() << "\n";
8775 if (sub.umbrella < sub.cmdsize) {
8776 const char *P = Ptr + sub.umbrella;
8777 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8778 } else {
8779 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8780 }
8781}
8782
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008783static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8784 const char *Ptr) {
8785 outs() << " cmd LC_SUB_UMBRELLA\n";
8786 outs() << " cmdsize " << sub.cmdsize;
8787 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8788 outs() << " Incorrect size\n";
8789 else
8790 outs() << "\n";
8791 if (sub.sub_umbrella < sub.cmdsize) {
8792 const char *P = Ptr + sub.sub_umbrella;
8793 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8794 } else {
8795 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8796 }
8797}
8798
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008799static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008800 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008801 outs() << " cmd LC_SUB_LIBRARY\n";
8802 outs() << " cmdsize " << sub.cmdsize;
8803 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8804 outs() << " Incorrect size\n";
8805 else
8806 outs() << "\n";
8807 if (sub.sub_library < sub.cmdsize) {
8808 const char *P = Ptr + sub.sub_library;
8809 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8810 } else {
8811 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8812 }
8813}
8814
Kevin Enderby186eac32014-12-19 21:06:24 +00008815static void PrintSubClientCommand(MachO::sub_client_command sub,
8816 const char *Ptr) {
8817 outs() << " cmd LC_SUB_CLIENT\n";
8818 outs() << " cmdsize " << sub.cmdsize;
8819 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8820 outs() << " Incorrect size\n";
8821 else
8822 outs() << "\n";
8823 if (sub.client < sub.cmdsize) {
8824 const char *P = Ptr + sub.client;
8825 outs() << " client " << P << " (offset " << sub.client << ")\n";
8826 } else {
8827 outs() << " client ?(bad offset " << sub.client << ")\n";
8828 }
8829}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008830
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008831static void PrintRoutinesCommand(MachO::routines_command r) {
8832 outs() << " cmd LC_ROUTINES\n";
8833 outs() << " cmdsize " << r.cmdsize;
8834 if (r.cmdsize != sizeof(struct MachO::routines_command))
8835 outs() << " Incorrect size\n";
8836 else
8837 outs() << "\n";
8838 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8839 outs() << " init_module " << r.init_module << "\n";
8840 outs() << " reserved1 " << r.reserved1 << "\n";
8841 outs() << " reserved2 " << r.reserved2 << "\n";
8842 outs() << " reserved3 " << r.reserved3 << "\n";
8843 outs() << " reserved4 " << r.reserved4 << "\n";
8844 outs() << " reserved5 " << r.reserved5 << "\n";
8845 outs() << " reserved6 " << r.reserved6 << "\n";
8846}
8847
8848static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8849 outs() << " cmd LC_ROUTINES_64\n";
8850 outs() << " cmdsize " << r.cmdsize;
8851 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8852 outs() << " Incorrect size\n";
8853 else
8854 outs() << "\n";
8855 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8856 outs() << " init_module " << r.init_module << "\n";
8857 outs() << " reserved1 " << r.reserved1 << "\n";
8858 outs() << " reserved2 " << r.reserved2 << "\n";
8859 outs() << " reserved3 " << r.reserved3 << "\n";
8860 outs() << " reserved4 " << r.reserved4 << "\n";
8861 outs() << " reserved5 " << r.reserved5 << "\n";
8862 outs() << " reserved6 " << r.reserved6 << "\n";
8863}
8864
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008865static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8866 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8867 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8868 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8869 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8870 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8871 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8872 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8873 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8874 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8875 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8876 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8877 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8878 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8879 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8880 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8881 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8882}
8883
Kevin Enderby48ef5342014-12-23 22:56:39 +00008884static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8885 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8886 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8887 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8888 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8889 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8890 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8891 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8892 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8893 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8894 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8895 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8896 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8897 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8898 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8899 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8900 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8901 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8902 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8903 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8904 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8905 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8906}
8907
Kevin Enderby227df342014-12-23 23:43:59 +00008908static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008909 uint32_t f;
8910 outs() << "\t mmst_reg ";
8911 for (f = 0; f < 10; f++)
8912 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8913 outs() << "\n";
8914 outs() << "\t mmst_rsrv ";
8915 for (f = 0; f < 6; f++)
8916 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8917 outs() << "\n";
8918}
8919
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008920static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008921 uint32_t f;
8922 outs() << "\t xmm_reg ";
8923 for (f = 0; f < 16; f++)
8924 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8925 outs() << "\n";
8926}
8927
8928static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8929 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8930 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8931 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8932 outs() << " denorm " << fpu.fpu_fcw.denorm;
8933 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8934 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8935 outs() << " undfl " << fpu.fpu_fcw.undfl;
8936 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8937 outs() << "\t\t pc ";
8938 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8939 outs() << "FP_PREC_24B ";
8940 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8941 outs() << "FP_PREC_53B ";
8942 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8943 outs() << "FP_PREC_64B ";
8944 else
8945 outs() << fpu.fpu_fcw.pc << " ";
8946 outs() << "rc ";
8947 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8948 outs() << "FP_RND_NEAR ";
8949 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8950 outs() << "FP_RND_DOWN ";
8951 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8952 outs() << "FP_RND_UP ";
8953 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008954 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008955 outs() << "\n";
8956 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8957 outs() << " denorm " << fpu.fpu_fsw.denorm;
8958 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8959 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8960 outs() << " undfl " << fpu.fpu_fsw.undfl;
8961 outs() << " precis " << fpu.fpu_fsw.precis;
8962 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8963 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8964 outs() << " c0 " << fpu.fpu_fsw.c0;
8965 outs() << " c1 " << fpu.fpu_fsw.c1;
8966 outs() << " c2 " << fpu.fpu_fsw.c2;
8967 outs() << " tos " << fpu.fpu_fsw.tos;
8968 outs() << " c3 " << fpu.fpu_fsw.c3;
8969 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8970 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8971 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8972 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8973 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8974 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8975 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8976 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8977 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8978 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8979 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8980 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8981 outs() << "\n";
8982 outs() << "\t fpu_stmm0:\n";
8983 Print_mmst_reg(fpu.fpu_stmm0);
8984 outs() << "\t fpu_stmm1:\n";
8985 Print_mmst_reg(fpu.fpu_stmm1);
8986 outs() << "\t fpu_stmm2:\n";
8987 Print_mmst_reg(fpu.fpu_stmm2);
8988 outs() << "\t fpu_stmm3:\n";
8989 Print_mmst_reg(fpu.fpu_stmm3);
8990 outs() << "\t fpu_stmm4:\n";
8991 Print_mmst_reg(fpu.fpu_stmm4);
8992 outs() << "\t fpu_stmm5:\n";
8993 Print_mmst_reg(fpu.fpu_stmm5);
8994 outs() << "\t fpu_stmm6:\n";
8995 Print_mmst_reg(fpu.fpu_stmm6);
8996 outs() << "\t fpu_stmm7:\n";
8997 Print_mmst_reg(fpu.fpu_stmm7);
8998 outs() << "\t fpu_xmm0:\n";
8999 Print_xmm_reg(fpu.fpu_xmm0);
9000 outs() << "\t fpu_xmm1:\n";
9001 Print_xmm_reg(fpu.fpu_xmm1);
9002 outs() << "\t fpu_xmm2:\n";
9003 Print_xmm_reg(fpu.fpu_xmm2);
9004 outs() << "\t fpu_xmm3:\n";
9005 Print_xmm_reg(fpu.fpu_xmm3);
9006 outs() << "\t fpu_xmm4:\n";
9007 Print_xmm_reg(fpu.fpu_xmm4);
9008 outs() << "\t fpu_xmm5:\n";
9009 Print_xmm_reg(fpu.fpu_xmm5);
9010 outs() << "\t fpu_xmm6:\n";
9011 Print_xmm_reg(fpu.fpu_xmm6);
9012 outs() << "\t fpu_xmm7:\n";
9013 Print_xmm_reg(fpu.fpu_xmm7);
9014 outs() << "\t fpu_xmm8:\n";
9015 Print_xmm_reg(fpu.fpu_xmm8);
9016 outs() << "\t fpu_xmm9:\n";
9017 Print_xmm_reg(fpu.fpu_xmm9);
9018 outs() << "\t fpu_xmm10:\n";
9019 Print_xmm_reg(fpu.fpu_xmm10);
9020 outs() << "\t fpu_xmm11:\n";
9021 Print_xmm_reg(fpu.fpu_xmm11);
9022 outs() << "\t fpu_xmm12:\n";
9023 Print_xmm_reg(fpu.fpu_xmm12);
9024 outs() << "\t fpu_xmm13:\n";
9025 Print_xmm_reg(fpu.fpu_xmm13);
9026 outs() << "\t fpu_xmm14:\n";
9027 Print_xmm_reg(fpu.fpu_xmm14);
9028 outs() << "\t fpu_xmm15:\n";
9029 Print_xmm_reg(fpu.fpu_xmm15);
9030 outs() << "\t fpu_rsrv4:\n";
9031 for (uint32_t f = 0; f < 6; f++) {
9032 outs() << "\t ";
9033 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009034 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009035 outs() << "\n";
9036 }
9037 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9038 outs() << "\n";
9039}
9040
9041static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9042 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9043 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9044 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9045}
9046
Kevin Enderby41c9c002016-10-21 18:22:35 +00009047static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9048 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9049 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9050 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9051 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9052 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9053 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9054 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9055 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9056 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9057 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9058 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9059 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9060 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9061 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9062 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9063 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9064 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9065}
9066
Kevin Enderby7747cb52016-11-03 20:51:28 +00009067static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9068 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9069 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9070 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9071 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9072 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9073 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9074 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9075 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9076 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9077 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9078 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9079 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9080 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9081 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9082 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9083 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9084 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9085 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9086 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9087 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9088 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9089 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9090 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9091 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9092 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9093 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9094 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9095 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9096 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9097 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9098 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9099 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9100 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9101 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9102}
9103
Kevin Enderby48ef5342014-12-23 22:56:39 +00009104static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9105 bool isLittleEndian, uint32_t cputype) {
9106 if (t.cmd == MachO::LC_THREAD)
9107 outs() << " cmd LC_THREAD\n";
9108 else if (t.cmd == MachO::LC_UNIXTHREAD)
9109 outs() << " cmd LC_UNIXTHREAD\n";
9110 else
9111 outs() << " cmd " << t.cmd << " (unknown)\n";
9112 outs() << " cmdsize " << t.cmdsize;
9113 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9114 outs() << " Incorrect size\n";
9115 else
9116 outs() << "\n";
9117
9118 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9119 const char *end = Ptr + t.cmdsize;
9120 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009121 if (cputype == MachO::CPU_TYPE_I386) {
9122 while (begin < end) {
9123 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9124 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9125 begin += sizeof(uint32_t);
9126 } else {
9127 flavor = 0;
9128 begin = end;
9129 }
9130 if (isLittleEndian != sys::IsLittleEndianHost)
9131 sys::swapByteOrder(flavor);
9132 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9133 memcpy((char *)&count, begin, sizeof(uint32_t));
9134 begin += sizeof(uint32_t);
9135 } else {
9136 count = 0;
9137 begin = end;
9138 }
9139 if (isLittleEndian != sys::IsLittleEndianHost)
9140 sys::swapByteOrder(count);
9141 if (flavor == MachO::x86_THREAD_STATE32) {
9142 outs() << " flavor i386_THREAD_STATE\n";
9143 if (count == MachO::x86_THREAD_STATE32_COUNT)
9144 outs() << " count i386_THREAD_STATE_COUNT\n";
9145 else
9146 outs() << " count " << count
9147 << " (not x86_THREAD_STATE32_COUNT)\n";
9148 MachO::x86_thread_state32_t cpu32;
9149 left = end - begin;
9150 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9151 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9152 begin += sizeof(MachO::x86_thread_state32_t);
9153 } else {
9154 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9155 memcpy(&cpu32, begin, left);
9156 begin += left;
9157 }
9158 if (isLittleEndian != sys::IsLittleEndianHost)
9159 swapStruct(cpu32);
9160 Print_x86_thread_state32_t(cpu32);
9161 } else if (flavor == MachO::x86_THREAD_STATE) {
9162 outs() << " flavor x86_THREAD_STATE\n";
9163 if (count == MachO::x86_THREAD_STATE_COUNT)
9164 outs() << " count x86_THREAD_STATE_COUNT\n";
9165 else
9166 outs() << " count " << count
9167 << " (not x86_THREAD_STATE_COUNT)\n";
9168 struct MachO::x86_thread_state_t ts;
9169 left = end - begin;
9170 if (left >= sizeof(MachO::x86_thread_state_t)) {
9171 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9172 begin += sizeof(MachO::x86_thread_state_t);
9173 } else {
9174 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9175 memcpy(&ts, begin, left);
9176 begin += left;
9177 }
9178 if (isLittleEndian != sys::IsLittleEndianHost)
9179 swapStruct(ts);
9180 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9181 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9182 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9183 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9184 else
9185 outs() << "tsh.count " << ts.tsh.count
9186 << " (not x86_THREAD_STATE32_COUNT\n";
9187 Print_x86_thread_state32_t(ts.uts.ts32);
9188 } else {
9189 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9190 << ts.tsh.count << "\n";
9191 }
9192 } else {
9193 outs() << " flavor " << flavor << " (unknown)\n";
9194 outs() << " count " << count << "\n";
9195 outs() << " state (unknown)\n";
9196 begin += count * sizeof(uint32_t);
9197 }
9198 }
9199 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009200 while (begin < end) {
9201 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9202 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9203 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009204 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009205 flavor = 0;
9206 begin = end;
9207 }
9208 if (isLittleEndian != sys::IsLittleEndianHost)
9209 sys::swapByteOrder(flavor);
9210 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9211 memcpy((char *)&count, begin, sizeof(uint32_t));
9212 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009213 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009214 count = 0;
9215 begin = end;
9216 }
9217 if (isLittleEndian != sys::IsLittleEndianHost)
9218 sys::swapByteOrder(count);
9219 if (flavor == MachO::x86_THREAD_STATE64) {
9220 outs() << " flavor x86_THREAD_STATE64\n";
9221 if (count == MachO::x86_THREAD_STATE64_COUNT)
9222 outs() << " count x86_THREAD_STATE64_COUNT\n";
9223 else
9224 outs() << " count " << count
9225 << " (not x86_THREAD_STATE64_COUNT)\n";
9226 MachO::x86_thread_state64_t cpu64;
9227 left = end - begin;
9228 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9229 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9230 begin += sizeof(MachO::x86_thread_state64_t);
9231 } else {
9232 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9233 memcpy(&cpu64, begin, left);
9234 begin += left;
9235 }
9236 if (isLittleEndian != sys::IsLittleEndianHost)
9237 swapStruct(cpu64);
9238 Print_x86_thread_state64_t(cpu64);
9239 } else if (flavor == MachO::x86_THREAD_STATE) {
9240 outs() << " flavor x86_THREAD_STATE\n";
9241 if (count == MachO::x86_THREAD_STATE_COUNT)
9242 outs() << " count x86_THREAD_STATE_COUNT\n";
9243 else
9244 outs() << " count " << count
9245 << " (not x86_THREAD_STATE_COUNT)\n";
9246 struct MachO::x86_thread_state_t ts;
9247 left = end - begin;
9248 if (left >= sizeof(MachO::x86_thread_state_t)) {
9249 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9250 begin += sizeof(MachO::x86_thread_state_t);
9251 } else {
9252 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9253 memcpy(&ts, begin, left);
9254 begin += left;
9255 }
9256 if (isLittleEndian != sys::IsLittleEndianHost)
9257 swapStruct(ts);
9258 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9259 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9260 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9261 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9262 else
9263 outs() << "tsh.count " << ts.tsh.count
9264 << " (not x86_THREAD_STATE64_COUNT\n";
9265 Print_x86_thread_state64_t(ts.uts.ts64);
9266 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009267 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9268 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009269 }
9270 } else if (flavor == MachO::x86_FLOAT_STATE) {
9271 outs() << " flavor x86_FLOAT_STATE\n";
9272 if (count == MachO::x86_FLOAT_STATE_COUNT)
9273 outs() << " count x86_FLOAT_STATE_COUNT\n";
9274 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009275 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009276 struct MachO::x86_float_state_t fs;
9277 left = end - begin;
9278 if (left >= sizeof(MachO::x86_float_state_t)) {
9279 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9280 begin += sizeof(MachO::x86_float_state_t);
9281 } else {
9282 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9283 memcpy(&fs, begin, left);
9284 begin += left;
9285 }
9286 if (isLittleEndian != sys::IsLittleEndianHost)
9287 swapStruct(fs);
9288 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9289 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009290 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009291 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9292 else
9293 outs() << "fsh.count " << fs.fsh.count
9294 << " (not x86_FLOAT_STATE64_COUNT\n";
9295 Print_x86_float_state_t(fs.ufs.fs64);
9296 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009297 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9298 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009299 }
9300 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9301 outs() << " flavor x86_EXCEPTION_STATE\n";
9302 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9303 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9304 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009305 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009306 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9307 struct MachO::x86_exception_state_t es;
9308 left = end - begin;
9309 if (left >= sizeof(MachO::x86_exception_state_t)) {
9310 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9311 begin += sizeof(MachO::x86_exception_state_t);
9312 } else {
9313 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9314 memcpy(&es, begin, left);
9315 begin += left;
9316 }
9317 if (isLittleEndian != sys::IsLittleEndianHost)
9318 swapStruct(es);
9319 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9320 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009321 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009322 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9323 else
9324 outs() << "\t esh.count " << es.esh.count
9325 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9326 Print_x86_exception_state_t(es.ues.es64);
9327 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009328 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9329 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009330 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009331 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9332 outs() << " flavor x86_EXCEPTION_STATE64\n";
9333 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9334 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9335 else
9336 outs() << " count " << count
9337 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9338 struct MachO::x86_exception_state64_t es64;
9339 left = end - begin;
9340 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9341 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9342 begin += sizeof(MachO::x86_exception_state64_t);
9343 } else {
9344 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9345 memcpy(&es64, begin, left);
9346 begin += left;
9347 }
9348 if (isLittleEndian != sys::IsLittleEndianHost)
9349 swapStruct(es64);
9350 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009351 } else {
9352 outs() << " flavor " << flavor << " (unknown)\n";
9353 outs() << " count " << count << "\n";
9354 outs() << " state (unknown)\n";
9355 begin += count * sizeof(uint32_t);
9356 }
9357 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009358 } else if (cputype == MachO::CPU_TYPE_ARM) {
9359 while (begin < end) {
9360 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9361 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9362 begin += sizeof(uint32_t);
9363 } else {
9364 flavor = 0;
9365 begin = end;
9366 }
9367 if (isLittleEndian != sys::IsLittleEndianHost)
9368 sys::swapByteOrder(flavor);
9369 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9370 memcpy((char *)&count, begin, sizeof(uint32_t));
9371 begin += sizeof(uint32_t);
9372 } else {
9373 count = 0;
9374 begin = end;
9375 }
9376 if (isLittleEndian != sys::IsLittleEndianHost)
9377 sys::swapByteOrder(count);
9378 if (flavor == MachO::ARM_THREAD_STATE) {
9379 outs() << " flavor ARM_THREAD_STATE\n";
9380 if (count == MachO::ARM_THREAD_STATE_COUNT)
9381 outs() << " count ARM_THREAD_STATE_COUNT\n";
9382 else
9383 outs() << " count " << count
9384 << " (not ARM_THREAD_STATE_COUNT)\n";
9385 MachO::arm_thread_state32_t cpu32;
9386 left = end - begin;
9387 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9388 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9389 begin += sizeof(MachO::arm_thread_state32_t);
9390 } else {
9391 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9392 memcpy(&cpu32, begin, left);
9393 begin += left;
9394 }
9395 if (isLittleEndian != sys::IsLittleEndianHost)
9396 swapStruct(cpu32);
9397 Print_arm_thread_state32_t(cpu32);
9398 } else {
9399 outs() << " flavor " << flavor << " (unknown)\n";
9400 outs() << " count " << count << "\n";
9401 outs() << " state (unknown)\n";
9402 begin += count * sizeof(uint32_t);
9403 }
9404 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009405 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9406 while (begin < end) {
9407 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9408 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9409 begin += sizeof(uint32_t);
9410 } else {
9411 flavor = 0;
9412 begin = end;
9413 }
9414 if (isLittleEndian != sys::IsLittleEndianHost)
9415 sys::swapByteOrder(flavor);
9416 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9417 memcpy((char *)&count, begin, sizeof(uint32_t));
9418 begin += sizeof(uint32_t);
9419 } else {
9420 count = 0;
9421 begin = end;
9422 }
9423 if (isLittleEndian != sys::IsLittleEndianHost)
9424 sys::swapByteOrder(count);
9425 if (flavor == MachO::ARM_THREAD_STATE64) {
9426 outs() << " flavor ARM_THREAD_STATE64\n";
9427 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9428 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9429 else
9430 outs() << " count " << count
9431 << " (not ARM_THREAD_STATE64_COUNT)\n";
9432 MachO::arm_thread_state64_t cpu64;
9433 left = end - begin;
9434 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9435 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9436 begin += sizeof(MachO::arm_thread_state64_t);
9437 } else {
9438 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9439 memcpy(&cpu64, begin, left);
9440 begin += left;
9441 }
9442 if (isLittleEndian != sys::IsLittleEndianHost)
9443 swapStruct(cpu64);
9444 Print_arm_thread_state64_t(cpu64);
9445 } else {
9446 outs() << " flavor " << flavor << " (unknown)\n";
9447 outs() << " count " << count << "\n";
9448 outs() << " state (unknown)\n";
9449 begin += count * sizeof(uint32_t);
9450 }
9451 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009452 } else {
9453 while (begin < end) {
9454 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9455 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9456 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009457 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009458 flavor = 0;
9459 begin = end;
9460 }
9461 if (isLittleEndian != sys::IsLittleEndianHost)
9462 sys::swapByteOrder(flavor);
9463 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9464 memcpy((char *)&count, begin, sizeof(uint32_t));
9465 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009466 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009467 count = 0;
9468 begin = end;
9469 }
9470 if (isLittleEndian != sys::IsLittleEndianHost)
9471 sys::swapByteOrder(count);
9472 outs() << " flavor " << flavor << "\n";
9473 outs() << " count " << count << "\n";
9474 outs() << " state (Unknown cputype/cpusubtype)\n";
9475 begin += count * sizeof(uint32_t);
9476 }
9477 }
9478}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009479
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009480static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9481 if (dl.cmd == MachO::LC_ID_DYLIB)
9482 outs() << " cmd LC_ID_DYLIB\n";
9483 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9484 outs() << " cmd LC_LOAD_DYLIB\n";
9485 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9486 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9487 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9488 outs() << " cmd LC_REEXPORT_DYLIB\n";
9489 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9490 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9491 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9492 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9493 else
9494 outs() << " cmd " << dl.cmd << " (unknown)\n";
9495 outs() << " cmdsize " << dl.cmdsize;
9496 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9497 outs() << " Incorrect size\n";
9498 else
9499 outs() << "\n";
9500 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009501 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009502 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9503 } else {
9504 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9505 }
9506 outs() << " time stamp " << dl.dylib.timestamp << " ";
9507 time_t t = dl.dylib.timestamp;
9508 outs() << ctime(&t);
9509 outs() << " current version ";
9510 if (dl.dylib.current_version == 0xffffffff)
9511 outs() << "n/a\n";
9512 else
9513 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9514 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9515 << (dl.dylib.current_version & 0xff) << "\n";
9516 outs() << "compatibility version ";
9517 if (dl.dylib.compatibility_version == 0xffffffff)
9518 outs() << "n/a\n";
9519 else
9520 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9521 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9522 << (dl.dylib.compatibility_version & 0xff) << "\n";
9523}
9524
9525static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9526 uint32_t object_size) {
9527 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009528 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009529 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9530 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9531 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9532 outs() << " cmd LC_FUNCTION_STARTS\n";
9533 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9534 outs() << " cmd LC_DATA_IN_CODE\n";
9535 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9536 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9537 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9538 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9539 else
9540 outs() << " cmd " << ld.cmd << " (?)\n";
9541 outs() << " cmdsize " << ld.cmdsize;
9542 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9543 outs() << " Incorrect size\n";
9544 else
9545 outs() << "\n";
9546 outs() << " dataoff " << ld.dataoff;
9547 if (ld.dataoff > object_size)
9548 outs() << " (past end of file)\n";
9549 else
9550 outs() << "\n";
9551 outs() << " datasize " << ld.datasize;
9552 uint64_t big_size = ld.dataoff;
9553 big_size += ld.datasize;
9554 if (big_size > object_size)
9555 outs() << " (past end of file)\n";
9556 else
9557 outs() << "\n";
9558}
9559
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009560static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9561 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009562 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009563 unsigned Index = 0;
9564 for (const auto &Command : Obj->load_commands()) {
9565 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009566 if (Command.C.cmd == MachO::LC_SEGMENT) {
9567 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9568 const char *sg_segname = SLC.segname;
9569 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9570 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9571 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9572 verbose);
9573 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009574 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009575 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9576 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9577 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9578 }
9579 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9580 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9581 const char *sg_segname = SLC_64.segname;
9582 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9583 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9584 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9585 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9586 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9587 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9588 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9589 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9590 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9591 sg_segname, filetype, Buf.size(), verbose);
9592 }
9593 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9594 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009595 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009596 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9597 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9598 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009599 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9600 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009601 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9602 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9603 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9604 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9605 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9606 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9607 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9608 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9609 PrintDyldLoadCommand(Dyld, Command.Ptr);
9610 } else if (Command.C.cmd == MachO::LC_UUID) {
9611 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9612 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009613 } else if (Command.C.cmd == MachO::LC_RPATH) {
9614 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9615 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009616 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009617 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9618 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9619 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009620 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9621 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009622 } else if (Command.C.cmd == MachO::LC_NOTE) {
9623 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9624 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009625 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9626 MachO::build_version_command Bv =
9627 Obj->getBuildVersionLoadCommand(Command);
9628 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009629 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9630 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9631 PrintSourceVersionCommand(Sd);
9632 } else if (Command.C.cmd == MachO::LC_MAIN) {
9633 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9634 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009635 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009636 MachO::encryption_info_command Ei =
9637 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009638 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009639 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009640 MachO::encryption_info_command_64 Ei =
9641 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009642 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009643 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009644 MachO::linker_option_command Lo =
9645 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009646 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009647 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9648 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9649 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009650 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9651 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9652 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009653 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9654 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9655 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009656 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9657 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9658 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009659 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9660 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9661 PrintRoutinesCommand(Rc);
9662 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9663 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9664 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009665 } else if (Command.C.cmd == MachO::LC_THREAD ||
9666 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9667 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9668 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009669 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9670 Command.C.cmd == MachO::LC_ID_DYLIB ||
9671 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9672 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9673 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9674 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009675 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9676 PrintDylibCommand(Dl, Command.Ptr);
9677 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9678 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9679 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9680 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9681 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9682 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9683 MachO::linkedit_data_command Ld =
9684 Obj->getLinkeditDataLoadCommand(Command);
9685 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009686 } else {
9687 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9688 << ")\n";
9689 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9690 // TODO: get and print the raw bytes of the load command.
9691 }
9692 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009693 }
9694}
9695
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009696static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009697 if (Obj->is64Bit()) {
9698 MachO::mach_header_64 H_64;
9699 H_64 = Obj->getHeader64();
9700 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9701 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9702 } else {
9703 MachO::mach_header H;
9704 H = Obj->getHeader();
9705 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9706 H.sizeofcmds, H.flags, verbose);
9707 }
9708}
9709
9710void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9711 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009712 PrintMachHeader(file, !NonVerbose);
9713}
9714
9715void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9716 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009717 uint32_t filetype = 0;
9718 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009719 if (file->is64Bit()) {
9720 MachO::mach_header_64 H_64;
9721 H_64 = file->getHeader64();
9722 filetype = H_64.filetype;
9723 cputype = H_64.cputype;
9724 } else {
9725 MachO::mach_header H;
9726 H = file->getHeader();
9727 filetype = H.filetype;
9728 cputype = H.cputype;
9729 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009730 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009731}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009732
9733//===----------------------------------------------------------------------===//
9734// export trie dumping
9735//===----------------------------------------------------------------------===//
9736
9737void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009738 uint64_t BaseSegmentAddress = 0;
9739 for (const auto &Command : Obj->load_commands()) {
9740 if (Command.C.cmd == MachO::LC_SEGMENT) {
9741 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9742 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9743 BaseSegmentAddress = Seg.vmaddr;
9744 break;
9745 }
9746 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9747 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9748 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9749 BaseSegmentAddress = Seg.vmaddr;
9750 break;
9751 }
9752 }
9753 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009754 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009755 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009756 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009757 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9758 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9759 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9760 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9761 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9762 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9763 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9764 if (ReExport)
9765 outs() << "[re-export] ";
9766 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009767 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009768 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009769 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009770 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009771 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009772 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009773 if (WeakDef) {
9774 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009775 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009776 }
9777 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009778 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009779 outs() << ", ";
9780 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009781 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009782 }
9783 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009784 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009785 outs() << ", ";
9786 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009787 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009788 }
9789 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009790 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009791 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009792 outs() << format("resolver=0x%08llX", Entry.other());
9793 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009794 }
9795 outs() << "]";
9796 }
9797 if (ReExport) {
9798 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009799 int Ordinal = Entry.other() - 1;
9800 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9801 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009802 outs() << " (from " << DylibName << ")";
9803 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009804 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009805 }
9806 outs() << "\n";
9807 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009808 if (Err)
9809 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009810}
Nick Kledzikac431442014-09-12 21:34:15 +00009811
Nick Kledzikac431442014-09-12 21:34:15 +00009812//===----------------------------------------------------------------------===//
9813// rebase table dumping
9814//===----------------------------------------------------------------------===//
9815
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009816void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009817 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009818 Error Err = Error::success();
9819 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9820 StringRef SegmentName = Entry.segmentName();
9821 StringRef SectionName = Entry.sectionName();
9822 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009823
9824 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009825 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9826 SegmentName.str().c_str(), SectionName.str().c_str(),
9827 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009828 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009829 if (Err)
9830 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009831}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009832
9833static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9834 StringRef DylibName;
9835 switch (Ordinal) {
9836 case MachO::BIND_SPECIAL_DYLIB_SELF:
9837 return "this-image";
9838 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9839 return "main-executable";
9840 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9841 return "flat-namespace";
9842 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009843 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009844 std::error_code EC =
9845 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009846 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009847 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009848 return DylibName;
9849 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009850 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009851 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009852}
9853
9854//===----------------------------------------------------------------------===//
9855// bind table dumping
9856//===----------------------------------------------------------------------===//
9857
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009858void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009859 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009860 outs() << "segment section address type "
9861 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009862 Error Err = Error::success();
9863 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009864 StringRef SegmentName = Entry.segmentName();
9865 StringRef SectionName = Entry.sectionName();
9866 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009867
9868 // Table lines look like:
9869 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009870 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009871 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009872 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009873 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009874 << left_justify(SectionName, 18) << " "
9875 << format_hex(Address, 10, true) << " "
9876 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009877 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009878 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009879 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009880 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009881 if (Err)
9882 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009883}
9884
9885//===----------------------------------------------------------------------===//
9886// lazy bind table dumping
9887//===----------------------------------------------------------------------===//
9888
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009889void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009890 outs() << "segment section address "
9891 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009892 Error Err = Error::success();
9893 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009894 StringRef SegmentName = Entry.segmentName();
9895 StringRef SectionName = Entry.sectionName();
9896 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009897
9898 // Table lines look like:
9899 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009900 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009901 << left_justify(SectionName, 18) << " "
9902 << format_hex(Address, 10, true) << " "
9903 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009904 << Entry.symbolName() << "\n";
9905 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009906 if (Err)
9907 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009908}
9909
Nick Kledzik56ebef42014-09-16 01:41:51 +00009910//===----------------------------------------------------------------------===//
9911// weak bind table dumping
9912//===----------------------------------------------------------------------===//
9913
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009914void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009915 outs() << "segment section address "
9916 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009917 Error Err = Error::success();
9918 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009919 // Strong symbols don't have a location to update.
9920 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009921 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009922 << Entry.symbolName() << "\n";
9923 continue;
9924 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009925 StringRef SegmentName = Entry.segmentName();
9926 StringRef SectionName = Entry.sectionName();
9927 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009928
9929 // Table lines look like:
9930 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009931 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009932 << left_justify(SectionName, 18) << " "
9933 << format_hex(Address, 10, true) << " "
9934 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009935 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9936 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009937 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009938 if (Err)
9939 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009940}
9941
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009942// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9943// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9944// information for that address. If the address is found its binding symbol
9945// name is returned. If not nullptr is returned.
9946static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9947 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009948 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009949 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009950 Error Err = Error::success();
9951 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009952 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009953 StringRef name = Entry.symbolName();
9954 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009955 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009956 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009957 if (Err)
9958 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009959 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009960 auto name = info->bindtable->lookup(ReferenceValue);
9961 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009962}
Michael Trent1854ecc2017-12-05 07:50:00 +00009963