blob: f44e4324c5cb86ea0c64a77219622ad171e0e4a8 [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;
2162 char *method = nullptr;
2163 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->method != nullptr)
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002763 delete info->method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002764 if (info->class_name != nullptr) {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002765 info->method = new char[5 + strlen(info->class_name) +
2766 strlen(info->selector_name)];
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002767 if (info->method != nullptr) {
2768 strcpy(info->method, "+[");
2769 strcat(info->method, info->class_name);
2770 strcat(info->method, " ");
2771 strcat(info->method, info->selector_name);
2772 strcat(info->method, "]");
2773 *ReferenceName = info->method;
2774 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2775 }
2776 } else {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002777 info->method = new char[9 + strlen(info->selector_name)];
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002778 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002779 if (Arch == Triple::x86_64)
2780 strcpy(info->method, "-[%rdi ");
2781 else if (Arch == Triple::aarch64)
2782 strcpy(info->method, "-[x0 ");
2783 else
2784 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002785 strcat(info->method, info->selector_name);
2786 strcat(info->method, "]");
2787 *ReferenceName = info->method;
2788 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2789 }
2790 }
2791 info->class_name = nullptr;
2792 }
2793 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002794 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002795 if (info->method != nullptr)
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002796 delete info->method;
2797 info->method = new char[17 + strlen(info->selector_name)];
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002798 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002799 if (Arch == Triple::x86_64)
2800 strcpy(info->method, "-[[%rdi super] ");
2801 else if (Arch == Triple::aarch64)
2802 strcpy(info->method, "-[[x0 super] ");
2803 else
2804 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002805 strcat(info->method, info->selector_name);
2806 strcat(info->method, "]");
2807 *ReferenceName = info->method;
2808 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2809 }
2810 info->class_name = nullptr;
2811 }
2812 }
2813 }
2814}
2815
2816// GuessPointerPointer() is passed the address of what might be a pointer to
2817// a reference to an Objective-C class, selector, message ref or cfstring.
2818// If so the value of the pointer is returned and one of the booleans are set
2819// to true. If not zero is returned and all the booleans are set to false.
2820static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2821 struct DisassembleInfo *info,
2822 bool &classref, bool &selref, bool &msgref,
2823 bool &cfstring) {
2824 classref = false;
2825 selref = false;
2826 msgref = false;
2827 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002828 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002829 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2830 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2831 for (unsigned J = 0; J < Seg.nsects; ++J) {
2832 MachO::section_64 Sec = info->O->getSection64(Load, J);
2833 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2834 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2835 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2836 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2837 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2838 ReferenceValue >= Sec.addr &&
2839 ReferenceValue < Sec.addr + Sec.size) {
2840 uint64_t sect_offset = ReferenceValue - Sec.addr;
2841 uint64_t object_offset = Sec.offset + sect_offset;
2842 StringRef MachOContents = info->O->getData();
2843 uint64_t object_size = MachOContents.size();
2844 const char *object_addr = (const char *)MachOContents.data();
2845 if (object_offset < object_size) {
2846 uint64_t pointer_value;
2847 memcpy(&pointer_value, object_addr + object_offset,
2848 sizeof(uint64_t));
2849 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2850 sys::swapByteOrder(pointer_value);
2851 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2852 selref = true;
2853 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2854 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2855 classref = true;
2856 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2857 ReferenceValue + 8 < Sec.addr + Sec.size) {
2858 msgref = true;
2859 memcpy(&pointer_value, object_addr + object_offset + 8,
2860 sizeof(uint64_t));
2861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2862 sys::swapByteOrder(pointer_value);
2863 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2864 cfstring = true;
2865 return pointer_value;
2866 } else {
2867 return 0;
2868 }
2869 }
2870 }
2871 }
2872 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002873 }
2874 return 0;
2875}
2876
2877// get_pointer_64 returns a pointer to the bytes in the object file at the
2878// Address from a section in the Mach-O file. And indirectly returns the
2879// offset into the section, number of bytes left in the section past the offset
2880// and which section is was being referenced. If the Address is not in a
2881// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002882static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2883 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002884 DisassembleInfo *info,
2885 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002886 offset = 0;
2887 left = 0;
2888 S = SectionRef();
2889 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2890 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2891 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002892 if (SectSize == 0)
2893 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002894 if (objc_only) {
2895 StringRef SectName;
2896 ((*(info->Sections))[SectIdx]).getName(SectName);
2897 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2898 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2899 if (SegName != "__OBJC" && SectName != "__cstring")
2900 continue;
2901 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002902 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2903 S = (*(info->Sections))[SectIdx];
2904 offset = Address - SectAddress;
2905 left = SectSize - offset;
2906 StringRef SectContents;
2907 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2908 return SectContents.data() + offset;
2909 }
2910 }
2911 return nullptr;
2912}
2913
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002914static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2915 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002916 DisassembleInfo *info,
2917 bool objc_only = false) {
2918 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002919}
2920
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002921// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2922// the symbol indirectly through n_value. Based on the relocation information
2923// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002924// If no relocation information is found and a non-zero ReferenceValue for the
2925// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002926static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2927 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002928 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002929 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002930 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002931 return nullptr;
2932
2933 // See if there is an external relocation entry at the sect_offset.
2934 bool reloc_found = false;
2935 DataRefImpl Rel;
2936 MachO::any_relocation_info RE;
2937 bool isExtern = false;
2938 SymbolRef Symbol;
2939 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002940 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002941 if (RelocOffset == sect_offset) {
2942 Rel = Reloc.getRawDataRefImpl();
2943 RE = info->O->getRelocation(Rel);
2944 if (info->O->isRelocationScattered(RE))
2945 continue;
2946 isExtern = info->O->getPlainRelocationExternal(RE);
2947 if (isExtern) {
2948 symbol_iterator RelocSym = Reloc.getSymbol();
2949 Symbol = *RelocSym;
2950 }
2951 reloc_found = true;
2952 break;
2953 }
2954 }
2955 // If there is an external relocation entry for a symbol in this section
2956 // at this section_offset then use that symbol's value for the n_value
2957 // and return its name.
2958 const char *SymbolName = nullptr;
2959 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002960 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002961 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002962 if (!NameOrError)
2963 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002964 StringRef Name = *NameOrError;
2965 if (!Name.empty()) {
2966 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002967 return SymbolName;
2968 }
2969 }
2970
2971 // TODO: For fully linked images, look through the external relocation
2972 // entries off the dynamic symtab command. For these the r_offset is from the
2973 // start of the first writeable segment in the Mach-O file. So the offset
2974 // to this section from that segment is passed to this routine by the caller,
2975 // as the database_offset. Which is the difference of the section's starting
2976 // address and the first writable segment.
2977 //
2978 // NOTE: need add passing the database_offset to this routine.
2979
Kevin Enderby0fc11822015-04-01 20:57:01 +00002980 // We did not find an external relocation entry so look up the ReferenceValue
2981 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002982 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002983
2984 return SymbolName;
2985}
2986
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002987static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2988 DisassembleInfo *info,
2989 uint32_t ReferenceValue) {
2990 uint64_t n_value64;
2991 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2992}
2993
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002994// These are structs in the Objective-C meta data and read to produce the
2995// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00002996// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
2997// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002998
2999// The cfstring object in a 64-bit Mach-O file.
3000struct cfstring64_t {
3001 uint64_t isa; // class64_t * (64-bit pointer)
3002 uint64_t flags; // flag bits
3003 uint64_t characters; // char * (64-bit pointer)
3004 uint64_t length; // number of non-NULL characters in above
3005};
3006
3007// The class object in a 64-bit Mach-O file.
3008struct class64_t {
3009 uint64_t isa; // class64_t * (64-bit pointer)
3010 uint64_t superclass; // class64_t * (64-bit pointer)
3011 uint64_t cache; // Cache (64-bit pointer)
3012 uint64_t vtable; // IMP * (64-bit pointer)
3013 uint64_t data; // class_ro64_t * (64-bit pointer)
3014};
3015
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003016struct class32_t {
3017 uint32_t isa; /* class32_t * (32-bit pointer) */
3018 uint32_t superclass; /* class32_t * (32-bit pointer) */
3019 uint32_t cache; /* Cache (32-bit pointer) */
3020 uint32_t vtable; /* IMP * (32-bit pointer) */
3021 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3022};
3023
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003024struct class_ro64_t {
3025 uint32_t flags;
3026 uint32_t instanceStart;
3027 uint32_t instanceSize;
3028 uint32_t reserved;
3029 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3030 uint64_t name; // const char * (64-bit pointer)
3031 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3032 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3033 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3034 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3035 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3036};
3037
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003038struct class_ro32_t {
3039 uint32_t flags;
3040 uint32_t instanceStart;
3041 uint32_t instanceSize;
3042 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3043 uint32_t name; /* const char * (32-bit pointer) */
3044 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3045 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3046 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3047 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3048 uint32_t baseProperties; /* const struct objc_property_list *
3049 (32-bit pointer) */
3050};
3051
3052/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003053#define RO_META (1 << 0)
3054#define RO_ROOT (1 << 1)
3055#define RO_HAS_CXX_STRUCTORS (1 << 2)
3056
3057struct method_list64_t {
3058 uint32_t entsize;
3059 uint32_t count;
3060 /* struct method64_t first; These structures follow inline */
3061};
3062
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003063struct method_list32_t {
3064 uint32_t entsize;
3065 uint32_t count;
3066 /* struct method32_t first; These structures follow inline */
3067};
3068
Kevin Enderby0fc11822015-04-01 20:57:01 +00003069struct method64_t {
3070 uint64_t name; /* SEL (64-bit pointer) */
3071 uint64_t types; /* const char * (64-bit pointer) */
3072 uint64_t imp; /* IMP (64-bit pointer) */
3073};
3074
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003075struct method32_t {
3076 uint32_t name; /* SEL (32-bit pointer) */
3077 uint32_t types; /* const char * (32-bit pointer) */
3078 uint32_t imp; /* IMP (32-bit pointer) */
3079};
3080
Kevin Enderby0fc11822015-04-01 20:57:01 +00003081struct protocol_list64_t {
3082 uint64_t count; /* uintptr_t (a 64-bit value) */
3083 /* struct protocol64_t * list[0]; These pointers follow inline */
3084};
3085
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003086struct protocol_list32_t {
3087 uint32_t count; /* uintptr_t (a 32-bit value) */
3088 /* struct protocol32_t * list[0]; These pointers follow inline */
3089};
3090
Kevin Enderby0fc11822015-04-01 20:57:01 +00003091struct protocol64_t {
3092 uint64_t isa; /* id * (64-bit pointer) */
3093 uint64_t name; /* const char * (64-bit pointer) */
3094 uint64_t protocols; /* struct protocol_list64_t *
3095 (64-bit pointer) */
3096 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3097 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3098 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3099 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3100 uint64_t instanceProperties; /* struct objc_property_list *
3101 (64-bit pointer) */
3102};
3103
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003104struct protocol32_t {
3105 uint32_t isa; /* id * (32-bit pointer) */
3106 uint32_t name; /* const char * (32-bit pointer) */
3107 uint32_t protocols; /* struct protocol_list_t *
3108 (32-bit pointer) */
3109 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3110 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3111 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3112 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3113 uint32_t instanceProperties; /* struct objc_property_list *
3114 (32-bit pointer) */
3115};
3116
Kevin Enderby0fc11822015-04-01 20:57:01 +00003117struct ivar_list64_t {
3118 uint32_t entsize;
3119 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003120 /* struct ivar64_t first; These structures follow inline */
3121};
3122
3123struct ivar_list32_t {
3124 uint32_t entsize;
3125 uint32_t count;
3126 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003127};
3128
3129struct ivar64_t {
3130 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3131 uint64_t name; /* const char * (64-bit pointer) */
3132 uint64_t type; /* const char * (64-bit pointer) */
3133 uint32_t alignment;
3134 uint32_t size;
3135};
3136
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003137struct ivar32_t {
3138 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3139 uint32_t name; /* const char * (32-bit pointer) */
3140 uint32_t type; /* const char * (32-bit pointer) */
3141 uint32_t alignment;
3142 uint32_t size;
3143};
3144
Kevin Enderby0fc11822015-04-01 20:57:01 +00003145struct objc_property_list64 {
3146 uint32_t entsize;
3147 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003148 /* struct objc_property64 first; These structures follow inline */
3149};
3150
3151struct objc_property_list32 {
3152 uint32_t entsize;
3153 uint32_t count;
3154 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003155};
3156
3157struct objc_property64 {
3158 uint64_t name; /* const char * (64-bit pointer) */
3159 uint64_t attributes; /* const char * (64-bit pointer) */
3160};
3161
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003162struct objc_property32 {
3163 uint32_t name; /* const char * (32-bit pointer) */
3164 uint32_t attributes; /* const char * (32-bit pointer) */
3165};
3166
Kevin Enderby0fc11822015-04-01 20:57:01 +00003167struct category64_t {
3168 uint64_t name; /* const char * (64-bit pointer) */
3169 uint64_t cls; /* struct class_t * (64-bit pointer) */
3170 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3171 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3172 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3173 uint64_t instanceProperties; /* struct objc_property_list *
3174 (64-bit pointer) */
3175};
3176
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003177struct category32_t {
3178 uint32_t name; /* const char * (32-bit pointer) */
3179 uint32_t cls; /* struct class_t * (32-bit pointer) */
3180 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3181 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3182 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3183 uint32_t instanceProperties; /* struct objc_property_list *
3184 (32-bit pointer) */
3185};
3186
Kevin Enderby0fc11822015-04-01 20:57:01 +00003187struct objc_image_info64 {
3188 uint32_t version;
3189 uint32_t flags;
3190};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003191struct objc_image_info32 {
3192 uint32_t version;
3193 uint32_t flags;
3194};
Kevin Enderby846c0002015-04-16 17:19:59 +00003195struct imageInfo_t {
3196 uint32_t version;
3197 uint32_t flags;
3198};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003199/* masks for objc_image_info.flags */
3200#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3201#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3202
3203struct message_ref64 {
3204 uint64_t imp; /* IMP (64-bit pointer) */
3205 uint64_t sel; /* SEL (64-bit pointer) */
3206};
3207
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003208struct message_ref32 {
3209 uint32_t imp; /* IMP (32-bit pointer) */
3210 uint32_t sel; /* SEL (32-bit pointer) */
3211};
3212
Kevin Enderby846c0002015-04-16 17:19:59 +00003213// Objective-C 1 (32-bit only) meta data structs.
3214
3215struct objc_module_t {
3216 uint32_t version;
3217 uint32_t size;
3218 uint32_t name; /* char * (32-bit pointer) */
3219 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3220};
3221
3222struct objc_symtab_t {
3223 uint32_t sel_ref_cnt;
3224 uint32_t refs; /* SEL * (32-bit pointer) */
3225 uint16_t cls_def_cnt;
3226 uint16_t cat_def_cnt;
3227 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3228};
3229
3230struct objc_class_t {
3231 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3232 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3233 uint32_t name; /* const char * (32-bit pointer) */
3234 int32_t version;
3235 int32_t info;
3236 int32_t instance_size;
3237 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3238 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3239 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3240 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3241};
3242
3243#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3244// class is not a metaclass
3245#define CLS_CLASS 0x1
3246// class is a metaclass
3247#define CLS_META 0x2
3248
3249struct objc_category_t {
3250 uint32_t category_name; /* char * (32-bit pointer) */
3251 uint32_t class_name; /* char * (32-bit pointer) */
3252 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3253 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3254 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3255};
3256
3257struct objc_ivar_t {
3258 uint32_t ivar_name; /* char * (32-bit pointer) */
3259 uint32_t ivar_type; /* char * (32-bit pointer) */
3260 int32_t ivar_offset;
3261};
3262
3263struct objc_ivar_list_t {
3264 int32_t ivar_count;
3265 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3266};
3267
3268struct objc_method_list_t {
3269 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3270 int32_t method_count;
3271 // struct objc_method_t method_list[1]; /* variable length structure */
3272};
3273
3274struct objc_method_t {
3275 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3276 uint32_t method_types; /* char * (32-bit pointer) */
3277 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3278 (32-bit pointer) */
3279};
3280
3281struct objc_protocol_list_t {
3282 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3283 int32_t count;
3284 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3285 // (32-bit pointer) */
3286};
3287
3288struct objc_protocol_t {
3289 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3290 uint32_t protocol_name; /* char * (32-bit pointer) */
3291 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3292 uint32_t instance_methods; /* struct objc_method_description_list *
3293 (32-bit pointer) */
3294 uint32_t class_methods; /* struct objc_method_description_list *
3295 (32-bit pointer) */
3296};
3297
3298struct objc_method_description_list_t {
3299 int32_t count;
3300 // struct objc_method_description_t list[1];
3301};
3302
3303struct objc_method_description_t {
3304 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3305 uint32_t types; /* char * (32-bit pointer) */
3306};
3307
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003308inline void swapStruct(struct cfstring64_t &cfs) {
3309 sys::swapByteOrder(cfs.isa);
3310 sys::swapByteOrder(cfs.flags);
3311 sys::swapByteOrder(cfs.characters);
3312 sys::swapByteOrder(cfs.length);
3313}
3314
3315inline void swapStruct(struct class64_t &c) {
3316 sys::swapByteOrder(c.isa);
3317 sys::swapByteOrder(c.superclass);
3318 sys::swapByteOrder(c.cache);
3319 sys::swapByteOrder(c.vtable);
3320 sys::swapByteOrder(c.data);
3321}
3322
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003323inline void swapStruct(struct class32_t &c) {
3324 sys::swapByteOrder(c.isa);
3325 sys::swapByteOrder(c.superclass);
3326 sys::swapByteOrder(c.cache);
3327 sys::swapByteOrder(c.vtable);
3328 sys::swapByteOrder(c.data);
3329}
3330
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003331inline void swapStruct(struct class_ro64_t &cro) {
3332 sys::swapByteOrder(cro.flags);
3333 sys::swapByteOrder(cro.instanceStart);
3334 sys::swapByteOrder(cro.instanceSize);
3335 sys::swapByteOrder(cro.reserved);
3336 sys::swapByteOrder(cro.ivarLayout);
3337 sys::swapByteOrder(cro.name);
3338 sys::swapByteOrder(cro.baseMethods);
3339 sys::swapByteOrder(cro.baseProtocols);
3340 sys::swapByteOrder(cro.ivars);
3341 sys::swapByteOrder(cro.weakIvarLayout);
3342 sys::swapByteOrder(cro.baseProperties);
3343}
3344
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003345inline void swapStruct(struct class_ro32_t &cro) {
3346 sys::swapByteOrder(cro.flags);
3347 sys::swapByteOrder(cro.instanceStart);
3348 sys::swapByteOrder(cro.instanceSize);
3349 sys::swapByteOrder(cro.ivarLayout);
3350 sys::swapByteOrder(cro.name);
3351 sys::swapByteOrder(cro.baseMethods);
3352 sys::swapByteOrder(cro.baseProtocols);
3353 sys::swapByteOrder(cro.ivars);
3354 sys::swapByteOrder(cro.weakIvarLayout);
3355 sys::swapByteOrder(cro.baseProperties);
3356}
3357
Kevin Enderby0fc11822015-04-01 20:57:01 +00003358inline void swapStruct(struct method_list64_t &ml) {
3359 sys::swapByteOrder(ml.entsize);
3360 sys::swapByteOrder(ml.count);
3361}
3362
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003363inline void swapStruct(struct method_list32_t &ml) {
3364 sys::swapByteOrder(ml.entsize);
3365 sys::swapByteOrder(ml.count);
3366}
3367
Kevin Enderby0fc11822015-04-01 20:57:01 +00003368inline void swapStruct(struct method64_t &m) {
3369 sys::swapByteOrder(m.name);
3370 sys::swapByteOrder(m.types);
3371 sys::swapByteOrder(m.imp);
3372}
3373
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003374inline void swapStruct(struct method32_t &m) {
3375 sys::swapByteOrder(m.name);
3376 sys::swapByteOrder(m.types);
3377 sys::swapByteOrder(m.imp);
3378}
3379
Kevin Enderby0fc11822015-04-01 20:57:01 +00003380inline void swapStruct(struct protocol_list64_t &pl) {
3381 sys::swapByteOrder(pl.count);
3382}
3383
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003384inline void swapStruct(struct protocol_list32_t &pl) {
3385 sys::swapByteOrder(pl.count);
3386}
3387
Kevin Enderby0fc11822015-04-01 20:57:01 +00003388inline void swapStruct(struct protocol64_t &p) {
3389 sys::swapByteOrder(p.isa);
3390 sys::swapByteOrder(p.name);
3391 sys::swapByteOrder(p.protocols);
3392 sys::swapByteOrder(p.instanceMethods);
3393 sys::swapByteOrder(p.classMethods);
3394 sys::swapByteOrder(p.optionalInstanceMethods);
3395 sys::swapByteOrder(p.optionalClassMethods);
3396 sys::swapByteOrder(p.instanceProperties);
3397}
3398
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003399inline void swapStruct(struct protocol32_t &p) {
3400 sys::swapByteOrder(p.isa);
3401 sys::swapByteOrder(p.name);
3402 sys::swapByteOrder(p.protocols);
3403 sys::swapByteOrder(p.instanceMethods);
3404 sys::swapByteOrder(p.classMethods);
3405 sys::swapByteOrder(p.optionalInstanceMethods);
3406 sys::swapByteOrder(p.optionalClassMethods);
3407 sys::swapByteOrder(p.instanceProperties);
3408}
3409
Kevin Enderby0fc11822015-04-01 20:57:01 +00003410inline void swapStruct(struct ivar_list64_t &il) {
3411 sys::swapByteOrder(il.entsize);
3412 sys::swapByteOrder(il.count);
3413}
3414
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003415inline void swapStruct(struct ivar_list32_t &il) {
3416 sys::swapByteOrder(il.entsize);
3417 sys::swapByteOrder(il.count);
3418}
3419
Kevin Enderby0fc11822015-04-01 20:57:01 +00003420inline void swapStruct(struct ivar64_t &i) {
3421 sys::swapByteOrder(i.offset);
3422 sys::swapByteOrder(i.name);
3423 sys::swapByteOrder(i.type);
3424 sys::swapByteOrder(i.alignment);
3425 sys::swapByteOrder(i.size);
3426}
3427
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003428inline void swapStruct(struct ivar32_t &i) {
3429 sys::swapByteOrder(i.offset);
3430 sys::swapByteOrder(i.name);
3431 sys::swapByteOrder(i.type);
3432 sys::swapByteOrder(i.alignment);
3433 sys::swapByteOrder(i.size);
3434}
3435
Kevin Enderby0fc11822015-04-01 20:57:01 +00003436inline void swapStruct(struct objc_property_list64 &pl) {
3437 sys::swapByteOrder(pl.entsize);
3438 sys::swapByteOrder(pl.count);
3439}
3440
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003441inline void swapStruct(struct objc_property_list32 &pl) {
3442 sys::swapByteOrder(pl.entsize);
3443 sys::swapByteOrder(pl.count);
3444}
3445
Kevin Enderby0fc11822015-04-01 20:57:01 +00003446inline void swapStruct(struct objc_property64 &op) {
3447 sys::swapByteOrder(op.name);
3448 sys::swapByteOrder(op.attributes);
3449}
3450
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003451inline void swapStruct(struct objc_property32 &op) {
3452 sys::swapByteOrder(op.name);
3453 sys::swapByteOrder(op.attributes);
3454}
3455
Kevin Enderby0fc11822015-04-01 20:57:01 +00003456inline void swapStruct(struct category64_t &c) {
3457 sys::swapByteOrder(c.name);
3458 sys::swapByteOrder(c.cls);
3459 sys::swapByteOrder(c.instanceMethods);
3460 sys::swapByteOrder(c.classMethods);
3461 sys::swapByteOrder(c.protocols);
3462 sys::swapByteOrder(c.instanceProperties);
3463}
3464
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003465inline void swapStruct(struct category32_t &c) {
3466 sys::swapByteOrder(c.name);
3467 sys::swapByteOrder(c.cls);
3468 sys::swapByteOrder(c.instanceMethods);
3469 sys::swapByteOrder(c.classMethods);
3470 sys::swapByteOrder(c.protocols);
3471 sys::swapByteOrder(c.instanceProperties);
3472}
3473
Kevin Enderby0fc11822015-04-01 20:57:01 +00003474inline void swapStruct(struct objc_image_info64 &o) {
3475 sys::swapByteOrder(o.version);
3476 sys::swapByteOrder(o.flags);
3477}
3478
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003479inline void swapStruct(struct objc_image_info32 &o) {
3480 sys::swapByteOrder(o.version);
3481 sys::swapByteOrder(o.flags);
3482}
3483
Kevin Enderby846c0002015-04-16 17:19:59 +00003484inline void swapStruct(struct imageInfo_t &o) {
3485 sys::swapByteOrder(o.version);
3486 sys::swapByteOrder(o.flags);
3487}
3488
Kevin Enderby0fc11822015-04-01 20:57:01 +00003489inline void swapStruct(struct message_ref64 &mr) {
3490 sys::swapByteOrder(mr.imp);
3491 sys::swapByteOrder(mr.sel);
3492}
3493
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003494inline void swapStruct(struct message_ref32 &mr) {
3495 sys::swapByteOrder(mr.imp);
3496 sys::swapByteOrder(mr.sel);
3497}
3498
Kevin Enderby846c0002015-04-16 17:19:59 +00003499inline void swapStruct(struct objc_module_t &module) {
3500 sys::swapByteOrder(module.version);
3501 sys::swapByteOrder(module.size);
3502 sys::swapByteOrder(module.name);
3503 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003504}
Kevin Enderby846c0002015-04-16 17:19:59 +00003505
3506inline void swapStruct(struct objc_symtab_t &symtab) {
3507 sys::swapByteOrder(symtab.sel_ref_cnt);
3508 sys::swapByteOrder(symtab.refs);
3509 sys::swapByteOrder(symtab.cls_def_cnt);
3510 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003511}
Kevin Enderby846c0002015-04-16 17:19:59 +00003512
3513inline void swapStruct(struct objc_class_t &objc_class) {
3514 sys::swapByteOrder(objc_class.isa);
3515 sys::swapByteOrder(objc_class.super_class);
3516 sys::swapByteOrder(objc_class.name);
3517 sys::swapByteOrder(objc_class.version);
3518 sys::swapByteOrder(objc_class.info);
3519 sys::swapByteOrder(objc_class.instance_size);
3520 sys::swapByteOrder(objc_class.ivars);
3521 sys::swapByteOrder(objc_class.methodLists);
3522 sys::swapByteOrder(objc_class.cache);
3523 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003524}
Kevin Enderby846c0002015-04-16 17:19:59 +00003525
3526inline void swapStruct(struct objc_category_t &objc_category) {
3527 sys::swapByteOrder(objc_category.category_name);
3528 sys::swapByteOrder(objc_category.class_name);
3529 sys::swapByteOrder(objc_category.instance_methods);
3530 sys::swapByteOrder(objc_category.class_methods);
3531 sys::swapByteOrder(objc_category.protocols);
3532}
3533
3534inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3535 sys::swapByteOrder(objc_ivar_list.ivar_count);
3536}
3537
3538inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3539 sys::swapByteOrder(objc_ivar.ivar_name);
3540 sys::swapByteOrder(objc_ivar.ivar_type);
3541 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003542}
Kevin Enderby846c0002015-04-16 17:19:59 +00003543
3544inline void swapStruct(struct objc_method_list_t &method_list) {
3545 sys::swapByteOrder(method_list.obsolete);
3546 sys::swapByteOrder(method_list.method_count);
3547}
3548
3549inline void swapStruct(struct objc_method_t &method) {
3550 sys::swapByteOrder(method.method_name);
3551 sys::swapByteOrder(method.method_types);
3552 sys::swapByteOrder(method.method_imp);
3553}
3554
3555inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3556 sys::swapByteOrder(protocol_list.next);
3557 sys::swapByteOrder(protocol_list.count);
3558}
3559
3560inline void swapStruct(struct objc_protocol_t &protocol) {
3561 sys::swapByteOrder(protocol.isa);
3562 sys::swapByteOrder(protocol.protocol_name);
3563 sys::swapByteOrder(protocol.protocol_list);
3564 sys::swapByteOrder(protocol.instance_methods);
3565 sys::swapByteOrder(protocol.class_methods);
3566}
3567
3568inline void swapStruct(struct objc_method_description_list_t &mdl) {
3569 sys::swapByteOrder(mdl.count);
3570}
3571
3572inline void swapStruct(struct objc_method_description_t &md) {
3573 sys::swapByteOrder(md.name);
3574 sys::swapByteOrder(md.types);
3575}
3576
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003577static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3578 struct DisassembleInfo *info);
3579
3580// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3581// to an Objective-C class and returns the class name. It is also passed the
3582// address of the pointer, so when the pointer is zero as it can be in an .o
3583// file, that is used to look for an external relocation entry with a symbol
3584// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003585static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3586 uint64_t ReferenceValue,
3587 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003588 const char *r;
3589 uint32_t offset, left;
3590 SectionRef S;
3591
3592 // The pointer_value can be 0 in an object file and have a relocation
3593 // entry for the class symbol at the ReferenceValue (the address of the
3594 // pointer).
3595 if (pointer_value == 0) {
3596 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3597 if (r == nullptr || left < sizeof(uint64_t))
3598 return nullptr;
3599 uint64_t n_value;
3600 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3601 if (symbol_name == nullptr)
3602 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003603 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003604 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3605 return class_name + 2;
3606 else
3607 return nullptr;
3608 }
3609
3610 // The case were the pointer_value is non-zero and points to a class defined
3611 // in this Mach-O file.
3612 r = get_pointer_64(pointer_value, offset, left, S, info);
3613 if (r == nullptr || left < sizeof(struct class64_t))
3614 return nullptr;
3615 struct class64_t c;
3616 memcpy(&c, r, sizeof(struct class64_t));
3617 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3618 swapStruct(c);
3619 if (c.data == 0)
3620 return nullptr;
3621 r = get_pointer_64(c.data, offset, left, S, info);
3622 if (r == nullptr || left < sizeof(struct class_ro64_t))
3623 return nullptr;
3624 struct class_ro64_t cro;
3625 memcpy(&cro, r, sizeof(struct class_ro64_t));
3626 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3627 swapStruct(cro);
3628 if (cro.name == 0)
3629 return nullptr;
3630 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3631 return name;
3632}
3633
3634// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3635// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003636static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3637 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003638 const char *r, *name;
3639 uint32_t offset, left;
3640 SectionRef S;
3641 struct cfstring64_t cfs;
3642 uint64_t cfs_characters;
3643
3644 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3645 if (r == nullptr || left < sizeof(struct cfstring64_t))
3646 return nullptr;
3647 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3648 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3649 swapStruct(cfs);
3650 if (cfs.characters == 0) {
3651 uint64_t n_value;
3652 const char *symbol_name = get_symbol_64(
3653 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3654 if (symbol_name == nullptr)
3655 return nullptr;
3656 cfs_characters = n_value;
3657 } else
3658 cfs_characters = cfs.characters;
3659 name = get_pointer_64(cfs_characters, offset, left, S, info);
3660
3661 return name;
3662}
3663
3664// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3665// of a pointer to an Objective-C selector reference when the pointer value is
3666// zero as in a .o file and is likely to have a external relocation entry with
3667// who's symbol's n_value is the real pointer to the selector name. If that is
3668// the case the real pointer to the selector name is returned else 0 is
3669// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003670static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3671 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003672 uint32_t offset, left;
3673 SectionRef S;
3674
3675 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3676 if (r == nullptr || left < sizeof(uint64_t))
3677 return 0;
3678 uint64_t n_value;
3679 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3680 if (symbol_name == nullptr)
3681 return 0;
3682 return n_value;
3683}
3684
Kevin Enderby0fc11822015-04-01 20:57:01 +00003685static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3686 const char *sectname) {
3687 for (const SectionRef &Section : O->sections()) {
3688 StringRef SectName;
3689 Section.getName(SectName);
3690 DataRefImpl Ref = Section.getRawDataRefImpl();
3691 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3692 if (SegName == segname && SectName == sectname)
3693 return Section;
3694 }
3695 return SectionRef();
3696}
3697
3698static void
3699walk_pointer_list_64(const char *listname, const SectionRef S,
3700 MachOObjectFile *O, struct DisassembleInfo *info,
3701 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3702 if (S == SectionRef())
3703 return;
3704
3705 StringRef SectName;
3706 S.getName(SectName);
3707 DataRefImpl Ref = S.getRawDataRefImpl();
3708 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3709 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3710
3711 StringRef BytesStr;
3712 S.getContents(BytesStr);
3713 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3714
3715 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3716 uint32_t left = S.getSize() - i;
3717 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3718 uint64_t p = 0;
3719 memcpy(&p, Contents + i, size);
3720 if (i + sizeof(uint64_t) > S.getSize())
3721 outs() << listname << " list pointer extends past end of (" << SegName
3722 << "," << SectName << ") section\n";
3723 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3724
3725 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3726 sys::swapByteOrder(p);
3727
3728 uint64_t n_value = 0;
3729 const char *name = get_symbol_64(i, S, info, n_value, p);
3730 if (name == nullptr)
3731 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3732
3733 if (n_value != 0) {
3734 outs() << format("0x%" PRIx64, n_value);
3735 if (p != 0)
3736 outs() << " + " << format("0x%" PRIx64, p);
3737 } else
3738 outs() << format("0x%" PRIx64, p);
3739 if (name != nullptr)
3740 outs() << " " << name;
3741 outs() << "\n";
3742
3743 p += n_value;
3744 if (func)
3745 func(p, info);
3746 }
3747}
3748
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003749static void
3750walk_pointer_list_32(const char *listname, const SectionRef S,
3751 MachOObjectFile *O, struct DisassembleInfo *info,
3752 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3753 if (S == SectionRef())
3754 return;
3755
3756 StringRef SectName;
3757 S.getName(SectName);
3758 DataRefImpl Ref = S.getRawDataRefImpl();
3759 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3760 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3761
3762 StringRef BytesStr;
3763 S.getContents(BytesStr);
3764 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3765
3766 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3767 uint32_t left = S.getSize() - i;
3768 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3769 uint32_t p = 0;
3770 memcpy(&p, Contents + i, size);
3771 if (i + sizeof(uint32_t) > S.getSize())
3772 outs() << listname << " list pointer extends past end of (" << SegName
3773 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003774 uint32_t Address = S.getAddress() + i;
3775 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003776
3777 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3778 sys::swapByteOrder(p);
3779 outs() << format("0x%" PRIx32, p);
3780
3781 const char *name = get_symbol_32(i, S, info, p);
3782 if (name != nullptr)
3783 outs() << " " << name;
3784 outs() << "\n";
3785
3786 if (func)
3787 func(p, info);
3788 }
3789}
3790
3791static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003792 if (layout_map == nullptr)
3793 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003794 outs() << " layout map: ";
3795 do {
3796 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3797 left--;
3798 layout_map++;
3799 } while (*layout_map != '\0' && left != 0);
3800 outs() << "\n";
3801}
3802
Kevin Enderby0fc11822015-04-01 20:57:01 +00003803static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3804 uint32_t offset, left;
3805 SectionRef S;
3806 const char *layout_map;
3807
3808 if (p == 0)
3809 return;
3810 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003811 print_layout_map(layout_map, left);
3812}
3813
3814static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3815 uint32_t offset, left;
3816 SectionRef S;
3817 const char *layout_map;
3818
3819 if (p == 0)
3820 return;
3821 layout_map = get_pointer_32(p, offset, left, S, info);
3822 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003823}
3824
3825static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3826 const char *indent) {
3827 struct method_list64_t ml;
3828 struct method64_t m;
3829 const char *r;
3830 uint32_t offset, xoffset, left, i;
3831 SectionRef S, xS;
3832 const char *name, *sym_name;
3833 uint64_t n_value;
3834
3835 r = get_pointer_64(p, offset, left, S, info);
3836 if (r == nullptr)
3837 return;
3838 memset(&ml, '\0', sizeof(struct method_list64_t));
3839 if (left < sizeof(struct method_list64_t)) {
3840 memcpy(&ml, r, left);
3841 outs() << " (method_list_t entends past the end of the section)\n";
3842 } else
3843 memcpy(&ml, r, sizeof(struct method_list64_t));
3844 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3845 swapStruct(ml);
3846 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3847 outs() << indent << "\t\t count " << ml.count << "\n";
3848
3849 p += sizeof(struct method_list64_t);
3850 offset += sizeof(struct method_list64_t);
3851 for (i = 0; i < ml.count; i++) {
3852 r = get_pointer_64(p, offset, left, S, info);
3853 if (r == nullptr)
3854 return;
3855 memset(&m, '\0', sizeof(struct method64_t));
3856 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003857 memcpy(&m, r, left);
3858 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003859 } else
3860 memcpy(&m, r, sizeof(struct method64_t));
3861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3862 swapStruct(m);
3863
3864 outs() << indent << "\t\t name ";
3865 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3866 info, n_value, m.name);
3867 if (n_value != 0) {
3868 if (info->verbose && sym_name != nullptr)
3869 outs() << sym_name;
3870 else
3871 outs() << format("0x%" PRIx64, n_value);
3872 if (m.name != 0)
3873 outs() << " + " << format("0x%" PRIx64, m.name);
3874 } else
3875 outs() << format("0x%" PRIx64, m.name);
3876 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3877 if (name != nullptr)
3878 outs() << format(" %.*s", left, name);
3879 outs() << "\n";
3880
3881 outs() << indent << "\t\t types ";
3882 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3883 info, n_value, m.types);
3884 if (n_value != 0) {
3885 if (info->verbose && sym_name != nullptr)
3886 outs() << sym_name;
3887 else
3888 outs() << format("0x%" PRIx64, n_value);
3889 if (m.types != 0)
3890 outs() << " + " << format("0x%" PRIx64, m.types);
3891 } else
3892 outs() << format("0x%" PRIx64, m.types);
3893 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3894 if (name != nullptr)
3895 outs() << format(" %.*s", left, name);
3896 outs() << "\n";
3897
3898 outs() << indent << "\t\t imp ";
3899 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3900 n_value, m.imp);
3901 if (info->verbose && name == nullptr) {
3902 if (n_value != 0) {
3903 outs() << format("0x%" PRIx64, n_value) << " ";
3904 if (m.imp != 0)
3905 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3906 } else
3907 outs() << format("0x%" PRIx64, m.imp) << " ";
3908 }
3909 if (name != nullptr)
3910 outs() << name;
3911 outs() << "\n";
3912
3913 p += sizeof(struct method64_t);
3914 offset += sizeof(struct method64_t);
3915 }
3916}
3917
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003918static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3919 const char *indent) {
3920 struct method_list32_t ml;
3921 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003922 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003923 uint32_t offset, xoffset, left, i;
3924 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003925
3926 r = get_pointer_32(p, offset, left, S, info);
3927 if (r == nullptr)
3928 return;
3929 memset(&ml, '\0', sizeof(struct method_list32_t));
3930 if (left < sizeof(struct method_list32_t)) {
3931 memcpy(&ml, r, left);
3932 outs() << " (method_list_t entends past the end of the section)\n";
3933 } else
3934 memcpy(&ml, r, sizeof(struct method_list32_t));
3935 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3936 swapStruct(ml);
3937 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3938 outs() << indent << "\t\t count " << ml.count << "\n";
3939
3940 p += sizeof(struct method_list32_t);
3941 offset += sizeof(struct method_list32_t);
3942 for (i = 0; i < ml.count; i++) {
3943 r = get_pointer_32(p, offset, left, S, info);
3944 if (r == nullptr)
3945 return;
3946 memset(&m, '\0', sizeof(struct method32_t));
3947 if (left < sizeof(struct method32_t)) {
3948 memcpy(&ml, r, left);
3949 outs() << indent << " (method_t entends past the end of the section)\n";
3950 } else
3951 memcpy(&m, r, sizeof(struct method32_t));
3952 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3953 swapStruct(m);
3954
3955 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3956 name = get_pointer_32(m.name, xoffset, left, xS, info);
3957 if (name != nullptr)
3958 outs() << format(" %.*s", left, name);
3959 outs() << "\n";
3960
3961 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3962 name = get_pointer_32(m.types, xoffset, left, xS, info);
3963 if (name != nullptr)
3964 outs() << format(" %.*s", left, name);
3965 outs() << "\n";
3966
3967 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3968 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3969 m.imp);
3970 if (name != nullptr)
3971 outs() << " " << name;
3972 outs() << "\n";
3973
3974 p += sizeof(struct method32_t);
3975 offset += sizeof(struct method32_t);
3976 }
3977}
3978
Kevin Enderby846c0002015-04-16 17:19:59 +00003979static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3980 uint32_t offset, left, xleft;
3981 SectionRef S;
3982 struct objc_method_list_t method_list;
3983 struct objc_method_t method;
3984 const char *r, *methods, *name, *SymbolName;
3985 int32_t i;
3986
3987 r = get_pointer_32(p, offset, left, S, info, true);
3988 if (r == nullptr)
3989 return true;
3990
3991 outs() << "\n";
3992 if (left > sizeof(struct objc_method_list_t)) {
3993 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3994 } else {
3995 outs() << "\t\t objc_method_list extends past end of the section\n";
3996 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3997 memcpy(&method_list, r, left);
3998 }
3999 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4000 swapStruct(method_list);
4001
4002 outs() << "\t\t obsolete "
4003 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4004 outs() << "\t\t method_count " << method_list.method_count << "\n";
4005
4006 methods = r + sizeof(struct objc_method_list_t);
4007 for (i = 0; i < method_list.method_count; i++) {
4008 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4009 outs() << "\t\t remaining method's extend past the of the section\n";
4010 break;
4011 }
4012 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4013 sizeof(struct objc_method_t));
4014 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4015 swapStruct(method);
4016
4017 outs() << "\t\t method_name "
4018 << format("0x%08" PRIx32, method.method_name);
4019 if (info->verbose) {
4020 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4021 if (name != nullptr)
4022 outs() << format(" %.*s", xleft, name);
4023 else
4024 outs() << " (not in an __OBJC section)";
4025 }
4026 outs() << "\n";
4027
4028 outs() << "\t\t method_types "
4029 << format("0x%08" PRIx32, method.method_types);
4030 if (info->verbose) {
4031 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4032 if (name != nullptr)
4033 outs() << format(" %.*s", xleft, name);
4034 else
4035 outs() << " (not in an __OBJC section)";
4036 }
4037 outs() << "\n";
4038
4039 outs() << "\t\t method_imp "
4040 << format("0x%08" PRIx32, method.method_imp) << " ";
4041 if (info->verbose) {
4042 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4043 if (SymbolName != nullptr)
4044 outs() << SymbolName;
4045 }
4046 outs() << "\n";
4047 }
4048 return false;
4049}
4050
Kevin Enderby0fc11822015-04-01 20:57:01 +00004051static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4052 struct protocol_list64_t pl;
4053 uint64_t q, n_value;
4054 struct protocol64_t pc;
4055 const char *r;
4056 uint32_t offset, xoffset, left, i;
4057 SectionRef S, xS;
4058 const char *name, *sym_name;
4059
4060 r = get_pointer_64(p, offset, left, S, info);
4061 if (r == nullptr)
4062 return;
4063 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4064 if (left < sizeof(struct protocol_list64_t)) {
4065 memcpy(&pl, r, left);
4066 outs() << " (protocol_list_t entends past the end of the section)\n";
4067 } else
4068 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4069 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4070 swapStruct(pl);
4071 outs() << " count " << pl.count << "\n";
4072
4073 p += sizeof(struct protocol_list64_t);
4074 offset += sizeof(struct protocol_list64_t);
4075 for (i = 0; i < pl.count; i++) {
4076 r = get_pointer_64(p, offset, left, S, info);
4077 if (r == nullptr)
4078 return;
4079 q = 0;
4080 if (left < sizeof(uint64_t)) {
4081 memcpy(&q, r, left);
4082 outs() << " (protocol_t * entends past the end of the section)\n";
4083 } else
4084 memcpy(&q, r, sizeof(uint64_t));
4085 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4086 sys::swapByteOrder(q);
4087
4088 outs() << "\t\t list[" << i << "] ";
4089 sym_name = get_symbol_64(offset, S, info, n_value, q);
4090 if (n_value != 0) {
4091 if (info->verbose && sym_name != nullptr)
4092 outs() << sym_name;
4093 else
4094 outs() << format("0x%" PRIx64, n_value);
4095 if (q != 0)
4096 outs() << " + " << format("0x%" PRIx64, q);
4097 } else
4098 outs() << format("0x%" PRIx64, q);
4099 outs() << " (struct protocol_t *)\n";
4100
4101 r = get_pointer_64(q + n_value, offset, left, S, info);
4102 if (r == nullptr)
4103 return;
4104 memset(&pc, '\0', sizeof(struct protocol64_t));
4105 if (left < sizeof(struct protocol64_t)) {
4106 memcpy(&pc, r, left);
4107 outs() << " (protocol_t entends past the end of the section)\n";
4108 } else
4109 memcpy(&pc, r, sizeof(struct protocol64_t));
4110 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4111 swapStruct(pc);
4112
4113 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4114
4115 outs() << "\t\t\t name ";
4116 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4117 info, n_value, pc.name);
4118 if (n_value != 0) {
4119 if (info->verbose && sym_name != nullptr)
4120 outs() << sym_name;
4121 else
4122 outs() << format("0x%" PRIx64, n_value);
4123 if (pc.name != 0)
4124 outs() << " + " << format("0x%" PRIx64, pc.name);
4125 } else
4126 outs() << format("0x%" PRIx64, pc.name);
4127 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4128 if (name != nullptr)
4129 outs() << format(" %.*s", left, name);
4130 outs() << "\n";
4131
4132 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4133
4134 outs() << "\t\t instanceMethods ";
4135 sym_name =
4136 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4137 S, info, n_value, pc.instanceMethods);
4138 if (n_value != 0) {
4139 if (info->verbose && sym_name != nullptr)
4140 outs() << sym_name;
4141 else
4142 outs() << format("0x%" PRIx64, n_value);
4143 if (pc.instanceMethods != 0)
4144 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4145 } else
4146 outs() << format("0x%" PRIx64, pc.instanceMethods);
4147 outs() << " (struct method_list_t *)\n";
4148 if (pc.instanceMethods + n_value != 0)
4149 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4150
4151 outs() << "\t\t classMethods ";
4152 sym_name =
4153 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4154 info, n_value, pc.classMethods);
4155 if (n_value != 0) {
4156 if (info->verbose && sym_name != nullptr)
4157 outs() << sym_name;
4158 else
4159 outs() << format("0x%" PRIx64, n_value);
4160 if (pc.classMethods != 0)
4161 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4162 } else
4163 outs() << format("0x%" PRIx64, pc.classMethods);
4164 outs() << " (struct method_list_t *)\n";
4165 if (pc.classMethods + n_value != 0)
4166 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4167
4168 outs() << "\t optionalInstanceMethods "
4169 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4170 outs() << "\t optionalClassMethods "
4171 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4172 outs() << "\t instanceProperties "
4173 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4174
4175 p += sizeof(uint64_t);
4176 offset += sizeof(uint64_t);
4177 }
4178}
4179
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004180static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4181 struct protocol_list32_t pl;
4182 uint32_t q;
4183 struct protocol32_t pc;
4184 const char *r;
4185 uint32_t offset, xoffset, left, i;
4186 SectionRef S, xS;
4187 const char *name;
4188
4189 r = get_pointer_32(p, offset, left, S, info);
4190 if (r == nullptr)
4191 return;
4192 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4193 if (left < sizeof(struct protocol_list32_t)) {
4194 memcpy(&pl, r, left);
4195 outs() << " (protocol_list_t entends past the end of the section)\n";
4196 } else
4197 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4198 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4199 swapStruct(pl);
4200 outs() << " count " << pl.count << "\n";
4201
4202 p += sizeof(struct protocol_list32_t);
4203 offset += sizeof(struct protocol_list32_t);
4204 for (i = 0; i < pl.count; i++) {
4205 r = get_pointer_32(p, offset, left, S, info);
4206 if (r == nullptr)
4207 return;
4208 q = 0;
4209 if (left < sizeof(uint32_t)) {
4210 memcpy(&q, r, left);
4211 outs() << " (protocol_t * entends past the end of the section)\n";
4212 } else
4213 memcpy(&q, r, sizeof(uint32_t));
4214 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4215 sys::swapByteOrder(q);
4216 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4217 << " (struct protocol_t *)\n";
4218 r = get_pointer_32(q, offset, left, S, info);
4219 if (r == nullptr)
4220 return;
4221 memset(&pc, '\0', sizeof(struct protocol32_t));
4222 if (left < sizeof(struct protocol32_t)) {
4223 memcpy(&pc, r, left);
4224 outs() << " (protocol_t entends past the end of the section)\n";
4225 } else
4226 memcpy(&pc, r, sizeof(struct protocol32_t));
4227 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4228 swapStruct(pc);
4229 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4230 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4231 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4232 if (name != nullptr)
4233 outs() << format(" %.*s", left, name);
4234 outs() << "\n";
4235 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4236 outs() << "\t\t instanceMethods "
4237 << format("0x%" PRIx32, pc.instanceMethods)
4238 << " (struct method_list_t *)\n";
4239 if (pc.instanceMethods != 0)
4240 print_method_list32_t(pc.instanceMethods, info, "\t");
4241 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4242 << " (struct method_list_t *)\n";
4243 if (pc.classMethods != 0)
4244 print_method_list32_t(pc.classMethods, info, "\t");
4245 outs() << "\t optionalInstanceMethods "
4246 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4247 outs() << "\t optionalClassMethods "
4248 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4249 outs() << "\t instanceProperties "
4250 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4251 p += sizeof(uint32_t);
4252 offset += sizeof(uint32_t);
4253 }
4254}
4255
Kevin Enderby846c0002015-04-16 17:19:59 +00004256static void print_indent(uint32_t indent) {
4257 for (uint32_t i = 0; i < indent;) {
4258 if (indent - i >= 8) {
4259 outs() << "\t";
4260 i += 8;
4261 } else {
4262 for (uint32_t j = i; j < indent; j++)
4263 outs() << " ";
4264 return;
4265 }
4266 }
4267}
4268
4269static bool print_method_description_list(uint32_t p, uint32_t indent,
4270 struct DisassembleInfo *info) {
4271 uint32_t offset, left, xleft;
4272 SectionRef S;
4273 struct objc_method_description_list_t mdl;
4274 struct objc_method_description_t md;
4275 const char *r, *list, *name;
4276 int32_t i;
4277
4278 r = get_pointer_32(p, offset, left, S, info, true);
4279 if (r == nullptr)
4280 return true;
4281
4282 outs() << "\n";
4283 if (left > sizeof(struct objc_method_description_list_t)) {
4284 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4285 } else {
4286 print_indent(indent);
4287 outs() << " objc_method_description_list extends past end of the section\n";
4288 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4289 memcpy(&mdl, r, left);
4290 }
4291 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4292 swapStruct(mdl);
4293
4294 print_indent(indent);
4295 outs() << " count " << mdl.count << "\n";
4296
4297 list = r + sizeof(struct objc_method_description_list_t);
4298 for (i = 0; i < mdl.count; i++) {
4299 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4300 print_indent(indent);
4301 outs() << " remaining list entries extend past the of the section\n";
4302 break;
4303 }
4304 print_indent(indent);
4305 outs() << " list[" << i << "]\n";
4306 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4307 sizeof(struct objc_method_description_t));
4308 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4309 swapStruct(md);
4310
4311 print_indent(indent);
4312 outs() << " name " << format("0x%08" PRIx32, md.name);
4313 if (info->verbose) {
4314 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4315 if (name != nullptr)
4316 outs() << format(" %.*s", xleft, name);
4317 else
4318 outs() << " (not in an __OBJC section)";
4319 }
4320 outs() << "\n";
4321
4322 print_indent(indent);
4323 outs() << " types " << format("0x%08" PRIx32, md.types);
4324 if (info->verbose) {
4325 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4326 if (name != nullptr)
4327 outs() << format(" %.*s", xleft, name);
4328 else
4329 outs() << " (not in an __OBJC section)";
4330 }
4331 outs() << "\n";
4332 }
4333 return false;
4334}
4335
4336static bool print_protocol_list(uint32_t p, uint32_t indent,
4337 struct DisassembleInfo *info);
4338
4339static bool print_protocol(uint32_t p, uint32_t indent,
4340 struct DisassembleInfo *info) {
4341 uint32_t offset, left;
4342 SectionRef S;
4343 struct objc_protocol_t protocol;
4344 const char *r, *name;
4345
4346 r = get_pointer_32(p, offset, left, S, info, true);
4347 if (r == nullptr)
4348 return true;
4349
4350 outs() << "\n";
4351 if (left >= sizeof(struct objc_protocol_t)) {
4352 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4353 } else {
4354 print_indent(indent);
4355 outs() << " Protocol extends past end of the section\n";
4356 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4357 memcpy(&protocol, r, left);
4358 }
4359 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4360 swapStruct(protocol);
4361
4362 print_indent(indent);
4363 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4364 << "\n";
4365
4366 print_indent(indent);
4367 outs() << " protocol_name "
4368 << format("0x%08" PRIx32, protocol.protocol_name);
4369 if (info->verbose) {
4370 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4371 if (name != nullptr)
4372 outs() << format(" %.*s", left, name);
4373 else
4374 outs() << " (not in an __OBJC section)";
4375 }
4376 outs() << "\n";
4377
4378 print_indent(indent);
4379 outs() << " protocol_list "
4380 << format("0x%08" PRIx32, protocol.protocol_list);
4381 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4382 outs() << " (not in an __OBJC section)\n";
4383
4384 print_indent(indent);
4385 outs() << " instance_methods "
4386 << format("0x%08" PRIx32, protocol.instance_methods);
4387 if (print_method_description_list(protocol.instance_methods, indent, info))
4388 outs() << " (not in an __OBJC section)\n";
4389
4390 print_indent(indent);
4391 outs() << " class_methods "
4392 << format("0x%08" PRIx32, protocol.class_methods);
4393 if (print_method_description_list(protocol.class_methods, indent, info))
4394 outs() << " (not in an __OBJC section)\n";
4395
4396 return false;
4397}
4398
4399static bool print_protocol_list(uint32_t p, uint32_t indent,
4400 struct DisassembleInfo *info) {
4401 uint32_t offset, left, l;
4402 SectionRef S;
4403 struct objc_protocol_list_t protocol_list;
4404 const char *r, *list;
4405 int32_t i;
4406
4407 r = get_pointer_32(p, offset, left, S, info, true);
4408 if (r == nullptr)
4409 return true;
4410
4411 outs() << "\n";
4412 if (left > sizeof(struct objc_protocol_list_t)) {
4413 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4414 } else {
4415 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4416 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4417 memcpy(&protocol_list, r, left);
4418 }
4419 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4420 swapStruct(protocol_list);
4421
4422 print_indent(indent);
4423 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4424 << "\n";
4425 print_indent(indent);
4426 outs() << " count " << protocol_list.count << "\n";
4427
4428 list = r + sizeof(struct objc_protocol_list_t);
4429 for (i = 0; i < protocol_list.count; i++) {
4430 if ((i + 1) * sizeof(uint32_t) > left) {
4431 outs() << "\t\t remaining list entries extend past the of the section\n";
4432 break;
4433 }
4434 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4435 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4436 sys::swapByteOrder(l);
4437
4438 print_indent(indent);
4439 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4440 if (print_protocol(l, indent, info))
4441 outs() << "(not in an __OBJC section)\n";
4442 }
4443 return false;
4444}
4445
Kevin Enderby0fc11822015-04-01 20:57:01 +00004446static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4447 struct ivar_list64_t il;
4448 struct ivar64_t i;
4449 const char *r;
4450 uint32_t offset, xoffset, left, j;
4451 SectionRef S, xS;
4452 const char *name, *sym_name, *ivar_offset_p;
4453 uint64_t ivar_offset, n_value;
4454
4455 r = get_pointer_64(p, offset, left, S, info);
4456 if (r == nullptr)
4457 return;
4458 memset(&il, '\0', sizeof(struct ivar_list64_t));
4459 if (left < sizeof(struct ivar_list64_t)) {
4460 memcpy(&il, r, left);
4461 outs() << " (ivar_list_t entends past the end of the section)\n";
4462 } else
4463 memcpy(&il, r, sizeof(struct ivar_list64_t));
4464 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4465 swapStruct(il);
4466 outs() << " entsize " << il.entsize << "\n";
4467 outs() << " count " << il.count << "\n";
4468
4469 p += sizeof(struct ivar_list64_t);
4470 offset += sizeof(struct ivar_list64_t);
4471 for (j = 0; j < il.count; j++) {
4472 r = get_pointer_64(p, offset, left, S, info);
4473 if (r == nullptr)
4474 return;
4475 memset(&i, '\0', sizeof(struct ivar64_t));
4476 if (left < sizeof(struct ivar64_t)) {
4477 memcpy(&i, r, left);
4478 outs() << " (ivar_t entends past the end of the section)\n";
4479 } else
4480 memcpy(&i, r, sizeof(struct ivar64_t));
4481 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4482 swapStruct(i);
4483
4484 outs() << "\t\t\t offset ";
4485 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4486 info, n_value, i.offset);
4487 if (n_value != 0) {
4488 if (info->verbose && sym_name != nullptr)
4489 outs() << sym_name;
4490 else
4491 outs() << format("0x%" PRIx64, n_value);
4492 if (i.offset != 0)
4493 outs() << " + " << format("0x%" PRIx64, i.offset);
4494 } else
4495 outs() << format("0x%" PRIx64, i.offset);
4496 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4497 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4498 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4499 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4500 sys::swapByteOrder(ivar_offset);
4501 outs() << " " << ivar_offset << "\n";
4502 } else
4503 outs() << "\n";
4504
4505 outs() << "\t\t\t name ";
4506 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4507 n_value, i.name);
4508 if (n_value != 0) {
4509 if (info->verbose && sym_name != nullptr)
4510 outs() << sym_name;
4511 else
4512 outs() << format("0x%" PRIx64, n_value);
4513 if (i.name != 0)
4514 outs() << " + " << format("0x%" PRIx64, i.name);
4515 } else
4516 outs() << format("0x%" PRIx64, i.name);
4517 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4518 if (name != nullptr)
4519 outs() << format(" %.*s", left, name);
4520 outs() << "\n";
4521
4522 outs() << "\t\t\t type ";
4523 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4524 n_value, i.name);
4525 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4526 if (n_value != 0) {
4527 if (info->verbose && sym_name != nullptr)
4528 outs() << sym_name;
4529 else
4530 outs() << format("0x%" PRIx64, n_value);
4531 if (i.type != 0)
4532 outs() << " + " << format("0x%" PRIx64, i.type);
4533 } else
4534 outs() << format("0x%" PRIx64, i.type);
4535 if (name != nullptr)
4536 outs() << format(" %.*s", left, name);
4537 outs() << "\n";
4538
4539 outs() << "\t\t\talignment " << i.alignment << "\n";
4540 outs() << "\t\t\t size " << i.size << "\n";
4541
4542 p += sizeof(struct ivar64_t);
4543 offset += sizeof(struct ivar64_t);
4544 }
4545}
4546
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004547static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4548 struct ivar_list32_t il;
4549 struct ivar32_t i;
4550 const char *r;
4551 uint32_t offset, xoffset, left, j;
4552 SectionRef S, xS;
4553 const char *name, *ivar_offset_p;
4554 uint32_t ivar_offset;
4555
4556 r = get_pointer_32(p, offset, left, S, info);
4557 if (r == nullptr)
4558 return;
4559 memset(&il, '\0', sizeof(struct ivar_list32_t));
4560 if (left < sizeof(struct ivar_list32_t)) {
4561 memcpy(&il, r, left);
4562 outs() << " (ivar_list_t entends past the end of the section)\n";
4563 } else
4564 memcpy(&il, r, sizeof(struct ivar_list32_t));
4565 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4566 swapStruct(il);
4567 outs() << " entsize " << il.entsize << "\n";
4568 outs() << " count " << il.count << "\n";
4569
4570 p += sizeof(struct ivar_list32_t);
4571 offset += sizeof(struct ivar_list32_t);
4572 for (j = 0; j < il.count; j++) {
4573 r = get_pointer_32(p, offset, left, S, info);
4574 if (r == nullptr)
4575 return;
4576 memset(&i, '\0', sizeof(struct ivar32_t));
4577 if (left < sizeof(struct ivar32_t)) {
4578 memcpy(&i, r, left);
4579 outs() << " (ivar_t entends past the end of the section)\n";
4580 } else
4581 memcpy(&i, r, sizeof(struct ivar32_t));
4582 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4583 swapStruct(i);
4584
4585 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4586 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4587 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4588 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4589 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4590 sys::swapByteOrder(ivar_offset);
4591 outs() << " " << ivar_offset << "\n";
4592 } else
4593 outs() << "\n";
4594
4595 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4596 name = get_pointer_32(i.name, xoffset, left, xS, info);
4597 if (name != nullptr)
4598 outs() << format(" %.*s", left, name);
4599 outs() << "\n";
4600
4601 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4602 name = get_pointer_32(i.type, xoffset, left, xS, info);
4603 if (name != nullptr)
4604 outs() << format(" %.*s", left, name);
4605 outs() << "\n";
4606
4607 outs() << "\t\t\talignment " << i.alignment << "\n";
4608 outs() << "\t\t\t size " << i.size << "\n";
4609
4610 p += sizeof(struct ivar32_t);
4611 offset += sizeof(struct ivar32_t);
4612 }
4613}
4614
Kevin Enderby0fc11822015-04-01 20:57:01 +00004615static void print_objc_property_list64(uint64_t p,
4616 struct DisassembleInfo *info) {
4617 struct objc_property_list64 opl;
4618 struct objc_property64 op;
4619 const char *r;
4620 uint32_t offset, xoffset, left, j;
4621 SectionRef S, xS;
4622 const char *name, *sym_name;
4623 uint64_t n_value;
4624
4625 r = get_pointer_64(p, offset, left, S, info);
4626 if (r == nullptr)
4627 return;
4628 memset(&opl, '\0', sizeof(struct objc_property_list64));
4629 if (left < sizeof(struct objc_property_list64)) {
4630 memcpy(&opl, r, left);
4631 outs() << " (objc_property_list entends past the end of the section)\n";
4632 } else
4633 memcpy(&opl, r, sizeof(struct objc_property_list64));
4634 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4635 swapStruct(opl);
4636 outs() << " entsize " << opl.entsize << "\n";
4637 outs() << " count " << opl.count << "\n";
4638
4639 p += sizeof(struct objc_property_list64);
4640 offset += sizeof(struct objc_property_list64);
4641 for (j = 0; j < opl.count; j++) {
4642 r = get_pointer_64(p, offset, left, S, info);
4643 if (r == nullptr)
4644 return;
4645 memset(&op, '\0', sizeof(struct objc_property64));
4646 if (left < sizeof(struct objc_property64)) {
4647 memcpy(&op, r, left);
4648 outs() << " (objc_property entends past the end of the section)\n";
4649 } else
4650 memcpy(&op, r, sizeof(struct objc_property64));
4651 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4652 swapStruct(op);
4653
4654 outs() << "\t\t\t name ";
4655 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4656 info, n_value, op.name);
4657 if (n_value != 0) {
4658 if (info->verbose && sym_name != nullptr)
4659 outs() << sym_name;
4660 else
4661 outs() << format("0x%" PRIx64, n_value);
4662 if (op.name != 0)
4663 outs() << " + " << format("0x%" PRIx64, op.name);
4664 } else
4665 outs() << format("0x%" PRIx64, op.name);
4666 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4667 if (name != nullptr)
4668 outs() << format(" %.*s", left, name);
4669 outs() << "\n";
4670
4671 outs() << "\t\t\tattributes ";
4672 sym_name =
4673 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4674 info, n_value, op.attributes);
4675 if (n_value != 0) {
4676 if (info->verbose && sym_name != nullptr)
4677 outs() << sym_name;
4678 else
4679 outs() << format("0x%" PRIx64, n_value);
4680 if (op.attributes != 0)
4681 outs() << " + " << format("0x%" PRIx64, op.attributes);
4682 } else
4683 outs() << format("0x%" PRIx64, op.attributes);
4684 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4685 if (name != nullptr)
4686 outs() << format(" %.*s", left, name);
4687 outs() << "\n";
4688
4689 p += sizeof(struct objc_property64);
4690 offset += sizeof(struct objc_property64);
4691 }
4692}
4693
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004694static void print_objc_property_list32(uint32_t p,
4695 struct DisassembleInfo *info) {
4696 struct objc_property_list32 opl;
4697 struct objc_property32 op;
4698 const char *r;
4699 uint32_t offset, xoffset, left, j;
4700 SectionRef S, xS;
4701 const char *name;
4702
4703 r = get_pointer_32(p, offset, left, S, info);
4704 if (r == nullptr)
4705 return;
4706 memset(&opl, '\0', sizeof(struct objc_property_list32));
4707 if (left < sizeof(struct objc_property_list32)) {
4708 memcpy(&opl, r, left);
4709 outs() << " (objc_property_list entends past the end of the section)\n";
4710 } else
4711 memcpy(&opl, r, sizeof(struct objc_property_list32));
4712 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4713 swapStruct(opl);
4714 outs() << " entsize " << opl.entsize << "\n";
4715 outs() << " count " << opl.count << "\n";
4716
4717 p += sizeof(struct objc_property_list32);
4718 offset += sizeof(struct objc_property_list32);
4719 for (j = 0; j < opl.count; j++) {
4720 r = get_pointer_32(p, offset, left, S, info);
4721 if (r == nullptr)
4722 return;
4723 memset(&op, '\0', sizeof(struct objc_property32));
4724 if (left < sizeof(struct objc_property32)) {
4725 memcpy(&op, r, left);
4726 outs() << " (objc_property entends past the end of the section)\n";
4727 } else
4728 memcpy(&op, r, sizeof(struct objc_property32));
4729 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4730 swapStruct(op);
4731
4732 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4733 name = get_pointer_32(op.name, xoffset, left, xS, info);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", left, name);
4736 outs() << "\n";
4737
4738 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4739 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4740 if (name != nullptr)
4741 outs() << format(" %.*s", left, name);
4742 outs() << "\n";
4743
4744 p += sizeof(struct objc_property32);
4745 offset += sizeof(struct objc_property32);
4746 }
4747}
4748
Richard Smith81ff44d2015-10-09 22:09:56 +00004749static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004750 bool &is_meta_class) {
4751 struct class_ro64_t cro;
4752 const char *r;
4753 uint32_t offset, xoffset, left;
4754 SectionRef S, xS;
4755 const char *name, *sym_name;
4756 uint64_t n_value;
4757
4758 r = get_pointer_64(p, offset, left, S, info);
4759 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004760 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004761 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004762 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4763 swapStruct(cro);
4764 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4765 if (cro.flags & RO_META)
4766 outs() << " RO_META";
4767 if (cro.flags & RO_ROOT)
4768 outs() << " RO_ROOT";
4769 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4770 outs() << " RO_HAS_CXX_STRUCTORS";
4771 outs() << "\n";
4772 outs() << " instanceStart " << cro.instanceStart << "\n";
4773 outs() << " instanceSize " << cro.instanceSize << "\n";
4774 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4775 << "\n";
4776 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4777 << "\n";
4778 print_layout_map64(cro.ivarLayout, info);
4779
4780 outs() << " name ";
4781 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4782 info, n_value, cro.name);
4783 if (n_value != 0) {
4784 if (info->verbose && sym_name != nullptr)
4785 outs() << sym_name;
4786 else
4787 outs() << format("0x%" PRIx64, n_value);
4788 if (cro.name != 0)
4789 outs() << " + " << format("0x%" PRIx64, cro.name);
4790 } else
4791 outs() << format("0x%" PRIx64, cro.name);
4792 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4793 if (name != nullptr)
4794 outs() << format(" %.*s", left, name);
4795 outs() << "\n";
4796
4797 outs() << " baseMethods ";
4798 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4799 S, info, n_value, cro.baseMethods);
4800 if (n_value != 0) {
4801 if (info->verbose && sym_name != nullptr)
4802 outs() << sym_name;
4803 else
4804 outs() << format("0x%" PRIx64, n_value);
4805 if (cro.baseMethods != 0)
4806 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4807 } else
4808 outs() << format("0x%" PRIx64, cro.baseMethods);
4809 outs() << " (struct method_list_t *)\n";
4810 if (cro.baseMethods + n_value != 0)
4811 print_method_list64_t(cro.baseMethods + n_value, info, "");
4812
4813 outs() << " baseProtocols ";
4814 sym_name =
4815 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4816 info, n_value, cro.baseProtocols);
4817 if (n_value != 0) {
4818 if (info->verbose && sym_name != nullptr)
4819 outs() << sym_name;
4820 else
4821 outs() << format("0x%" PRIx64, n_value);
4822 if (cro.baseProtocols != 0)
4823 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4824 } else
4825 outs() << format("0x%" PRIx64, cro.baseProtocols);
4826 outs() << "\n";
4827 if (cro.baseProtocols + n_value != 0)
4828 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4829
4830 outs() << " ivars ";
4831 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004832 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004833 if (n_value != 0) {
4834 if (info->verbose && sym_name != nullptr)
4835 outs() << sym_name;
4836 else
4837 outs() << format("0x%" PRIx64, n_value);
4838 if (cro.ivars != 0)
4839 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4840 } else
4841 outs() << format("0x%" PRIx64, cro.ivars);
4842 outs() << "\n";
4843 if (cro.ivars + n_value != 0)
4844 print_ivar_list64_t(cro.ivars + n_value, info);
4845
4846 outs() << " weakIvarLayout ";
4847 sym_name =
4848 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4849 info, n_value, cro.weakIvarLayout);
4850 if (n_value != 0) {
4851 if (info->verbose && sym_name != nullptr)
4852 outs() << sym_name;
4853 else
4854 outs() << format("0x%" PRIx64, n_value);
4855 if (cro.weakIvarLayout != 0)
4856 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4857 } else
4858 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4859 outs() << "\n";
4860 print_layout_map64(cro.weakIvarLayout + n_value, info);
4861
4862 outs() << " baseProperties ";
4863 sym_name =
4864 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4865 info, n_value, cro.baseProperties);
4866 if (n_value != 0) {
4867 if (info->verbose && sym_name != nullptr)
4868 outs() << sym_name;
4869 else
4870 outs() << format("0x%" PRIx64, n_value);
4871 if (cro.baseProperties != 0)
4872 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4873 } else
4874 outs() << format("0x%" PRIx64, cro.baseProperties);
4875 outs() << "\n";
4876 if (cro.baseProperties + n_value != 0)
4877 print_objc_property_list64(cro.baseProperties + n_value, info);
4878
Rafael Espindolab9091322015-10-24 23:19:10 +00004879 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004880 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004881}
4882
Richard Smith81ff44d2015-10-09 22:09:56 +00004883static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004884 bool &is_meta_class) {
4885 struct class_ro32_t cro;
4886 const char *r;
4887 uint32_t offset, xoffset, left;
4888 SectionRef S, xS;
4889 const char *name;
4890
4891 r = get_pointer_32(p, offset, left, S, info);
4892 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004893 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004894 memset(&cro, '\0', sizeof(struct class_ro32_t));
4895 if (left < sizeof(struct class_ro32_t)) {
4896 memcpy(&cro, r, left);
4897 outs() << " (class_ro_t entends past the end of the section)\n";
4898 } else
4899 memcpy(&cro, r, sizeof(struct class_ro32_t));
4900 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4901 swapStruct(cro);
4902 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4903 if (cro.flags & RO_META)
4904 outs() << " RO_META";
4905 if (cro.flags & RO_ROOT)
4906 outs() << " RO_ROOT";
4907 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4908 outs() << " RO_HAS_CXX_STRUCTORS";
4909 outs() << "\n";
4910 outs() << " instanceStart " << cro.instanceStart << "\n";
4911 outs() << " instanceSize " << cro.instanceSize << "\n";
4912 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4913 << "\n";
4914 print_layout_map32(cro.ivarLayout, info);
4915
4916 outs() << " name " << format("0x%" PRIx32, cro.name);
4917 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4918 if (name != nullptr)
4919 outs() << format(" %.*s", left, name);
4920 outs() << "\n";
4921
4922 outs() << " baseMethods "
4923 << format("0x%" PRIx32, cro.baseMethods)
4924 << " (struct method_list_t *)\n";
4925 if (cro.baseMethods != 0)
4926 print_method_list32_t(cro.baseMethods, info, "");
4927
4928 outs() << " baseProtocols "
4929 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4930 if (cro.baseProtocols != 0)
4931 print_protocol_list32_t(cro.baseProtocols, info);
4932 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4933 << "\n";
4934 if (cro.ivars != 0)
4935 print_ivar_list32_t(cro.ivars, info);
4936 outs() << " weakIvarLayout "
4937 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4938 print_layout_map32(cro.weakIvarLayout, info);
4939 outs() << " baseProperties "
4940 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4941 if (cro.baseProperties != 0)
4942 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004943 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004944 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004945}
4946
Kevin Enderby0fc11822015-04-01 20:57:01 +00004947static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4948 struct class64_t c;
4949 const char *r;
4950 uint32_t offset, left;
4951 SectionRef S;
4952 const char *name;
4953 uint64_t isa_n_value, n_value;
4954
4955 r = get_pointer_64(p, offset, left, S, info);
4956 if (r == nullptr || left < sizeof(struct class64_t))
4957 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004958 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4960 swapStruct(c);
4961
4962 outs() << " isa " << format("0x%" PRIx64, c.isa);
4963 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4964 isa_n_value, c.isa);
4965 if (name != nullptr)
4966 outs() << " " << name;
4967 outs() << "\n";
4968
4969 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4970 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4971 n_value, c.superclass);
4972 if (name != nullptr)
4973 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00004974 else {
4975 name = get_dyld_bind_info_symbolname(S.getAddress() +
4976 offset + offsetof(struct class64_t, superclass), info);
4977 if (name != nullptr)
4978 outs() << " " << name;
4979 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00004980 outs() << "\n";
4981
4982 outs() << " cache " << format("0x%" PRIx64, c.cache);
4983 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4984 n_value, c.cache);
4985 if (name != nullptr)
4986 outs() << " " << name;
4987 outs() << "\n";
4988
4989 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4990 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4991 n_value, c.vtable);
4992 if (name != nullptr)
4993 outs() << " " << name;
4994 outs() << "\n";
4995
4996 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4997 n_value, c.data);
4998 outs() << " data ";
4999 if (n_value != 0) {
5000 if (info->verbose && name != nullptr)
5001 outs() << name;
5002 else
5003 outs() << format("0x%" PRIx64, n_value);
5004 if (c.data != 0)
5005 outs() << " + " << format("0x%" PRIx64, c.data);
5006 } else
5007 outs() << format("0x%" PRIx64, c.data);
5008 outs() << " (struct class_ro_t *)";
5009
5010 // This is a Swift class if some of the low bits of the pointer are set.
5011 if ((c.data + n_value) & 0x7)
5012 outs() << " Swift class";
5013 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005014 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005015 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5016 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005017
Kevin Enderbyaac75382015-10-08 16:56:35 +00005018 if (!is_meta_class &&
5019 c.isa + isa_n_value != p &&
5020 c.isa + isa_n_value != 0 &&
5021 info->depth < 100) {
5022 info->depth++;
5023 outs() << "Meta Class\n";
5024 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005025 }
5026}
5027
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005028static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5029 struct class32_t c;
5030 const char *r;
5031 uint32_t offset, left;
5032 SectionRef S;
5033 const char *name;
5034
5035 r = get_pointer_32(p, offset, left, S, info);
5036 if (r == nullptr)
5037 return;
5038 memset(&c, '\0', sizeof(struct class32_t));
5039 if (left < sizeof(struct class32_t)) {
5040 memcpy(&c, r, left);
5041 outs() << " (class_t entends past the end of the section)\n";
5042 } else
5043 memcpy(&c, r, sizeof(struct class32_t));
5044 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5045 swapStruct(c);
5046
5047 outs() << " isa " << format("0x%" PRIx32, c.isa);
5048 name =
5049 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5050 if (name != nullptr)
5051 outs() << " " << name;
5052 outs() << "\n";
5053
5054 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5055 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5056 c.superclass);
5057 if (name != nullptr)
5058 outs() << " " << name;
5059 outs() << "\n";
5060
5061 outs() << " cache " << format("0x%" PRIx32, c.cache);
5062 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5063 c.cache);
5064 if (name != nullptr)
5065 outs() << " " << name;
5066 outs() << "\n";
5067
5068 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5069 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5070 c.vtable);
5071 if (name != nullptr)
5072 outs() << " " << name;
5073 outs() << "\n";
5074
5075 name =
5076 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5077 outs() << " data " << format("0x%" PRIx32, c.data)
5078 << " (struct class_ro_t *)";
5079
5080 // This is a Swift class if some of the low bits of the pointer are set.
5081 if (c.data & 0x3)
5082 outs() << " Swift class";
5083 outs() << "\n";
5084 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005085 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5086 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005087
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005088 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005089 outs() << "Meta Class\n";
5090 print_class32_t(c.isa, info);
5091 }
5092}
5093
Kevin Enderby846c0002015-04-16 17:19:59 +00005094static void print_objc_class_t(struct objc_class_t *objc_class,
5095 struct DisassembleInfo *info) {
5096 uint32_t offset, left, xleft;
5097 const char *name, *p, *ivar_list;
5098 SectionRef S;
5099 int32_t i;
5100 struct objc_ivar_list_t objc_ivar_list;
5101 struct objc_ivar_t ivar;
5102
5103 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5104 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5105 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5106 if (name != nullptr)
5107 outs() << format(" %.*s", left, name);
5108 else
5109 outs() << " (not in an __OBJC section)";
5110 }
5111 outs() << "\n";
5112
5113 outs() << "\t super_class "
5114 << format("0x%08" PRIx32, objc_class->super_class);
5115 if (info->verbose) {
5116 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5117 if (name != nullptr)
5118 outs() << format(" %.*s", left, name);
5119 else
5120 outs() << " (not in an __OBJC section)";
5121 }
5122 outs() << "\n";
5123
5124 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5125 if (info->verbose) {
5126 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5127 if (name != nullptr)
5128 outs() << format(" %.*s", left, name);
5129 else
5130 outs() << " (not in an __OBJC section)";
5131 }
5132 outs() << "\n";
5133
5134 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5135 << "\n";
5136
5137 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5138 if (info->verbose) {
5139 if (CLS_GETINFO(objc_class, CLS_CLASS))
5140 outs() << " CLS_CLASS";
5141 else if (CLS_GETINFO(objc_class, CLS_META))
5142 outs() << " CLS_META";
5143 }
5144 outs() << "\n";
5145
5146 outs() << "\t instance_size "
5147 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5148
5149 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5150 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5151 if (p != nullptr) {
5152 if (left > sizeof(struct objc_ivar_list_t)) {
5153 outs() << "\n";
5154 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5155 } else {
5156 outs() << " (entends past the end of the section)\n";
5157 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5158 memcpy(&objc_ivar_list, p, left);
5159 }
5160 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5161 swapStruct(objc_ivar_list);
5162 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5163 ivar_list = p + sizeof(struct objc_ivar_list_t);
5164 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5165 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5166 outs() << "\t\t remaining ivar's extend past the of the section\n";
5167 break;
5168 }
5169 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5170 sizeof(struct objc_ivar_t));
5171 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5172 swapStruct(ivar);
5173
5174 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5175 if (info->verbose) {
5176 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5177 if (name != nullptr)
5178 outs() << format(" %.*s", xleft, name);
5179 else
5180 outs() << " (not in an __OBJC section)";
5181 }
5182 outs() << "\n";
5183
5184 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5185 if (info->verbose) {
5186 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5187 if (name != nullptr)
5188 outs() << format(" %.*s", xleft, name);
5189 else
5190 outs() << " (not in an __OBJC section)";
5191 }
5192 outs() << "\n";
5193
5194 outs() << "\t\t ivar_offset "
5195 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5196 }
5197 } else {
5198 outs() << " (not in an __OBJC section)\n";
5199 }
5200
5201 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5202 if (print_method_list(objc_class->methodLists, info))
5203 outs() << " (not in an __OBJC section)\n";
5204
5205 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5206 << "\n";
5207
5208 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5209 if (print_protocol_list(objc_class->protocols, 16, info))
5210 outs() << " (not in an __OBJC section)\n";
5211}
5212
5213static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5214 struct DisassembleInfo *info) {
5215 uint32_t offset, left;
5216 const char *name;
5217 SectionRef S;
5218
5219 outs() << "\t category name "
5220 << format("0x%08" PRIx32, objc_category->category_name);
5221 if (info->verbose) {
5222 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5223 true);
5224 if (name != nullptr)
5225 outs() << format(" %.*s", left, name);
5226 else
5227 outs() << " (not in an __OBJC section)";
5228 }
5229 outs() << "\n";
5230
5231 outs() << "\t\t class name "
5232 << format("0x%08" PRIx32, objc_category->class_name);
5233 if (info->verbose) {
5234 name =
5235 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5236 if (name != nullptr)
5237 outs() << format(" %.*s", left, name);
5238 else
5239 outs() << " (not in an __OBJC section)";
5240 }
5241 outs() << "\n";
5242
5243 outs() << "\t instance methods "
5244 << format("0x%08" PRIx32, objc_category->instance_methods);
5245 if (print_method_list(objc_category->instance_methods, info))
5246 outs() << " (not in an __OBJC section)\n";
5247
5248 outs() << "\t class methods "
5249 << format("0x%08" PRIx32, objc_category->class_methods);
5250 if (print_method_list(objc_category->class_methods, info))
5251 outs() << " (not in an __OBJC section)\n";
5252}
5253
Kevin Enderby0fc11822015-04-01 20:57:01 +00005254static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5255 struct category64_t c;
5256 const char *r;
5257 uint32_t offset, xoffset, left;
5258 SectionRef S, xS;
5259 const char *name, *sym_name;
5260 uint64_t n_value;
5261
5262 r = get_pointer_64(p, offset, left, S, info);
5263 if (r == nullptr)
5264 return;
5265 memset(&c, '\0', sizeof(struct category64_t));
5266 if (left < sizeof(struct category64_t)) {
5267 memcpy(&c, r, left);
5268 outs() << " (category_t entends past the end of the section)\n";
5269 } else
5270 memcpy(&c, r, sizeof(struct category64_t));
5271 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5272 swapStruct(c);
5273
5274 outs() << " name ";
5275 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5276 info, n_value, c.name);
5277 if (n_value != 0) {
5278 if (info->verbose && sym_name != nullptr)
5279 outs() << sym_name;
5280 else
5281 outs() << format("0x%" PRIx64, n_value);
5282 if (c.name != 0)
5283 outs() << " + " << format("0x%" PRIx64, c.name);
5284 } else
5285 outs() << format("0x%" PRIx64, c.name);
5286 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5287 if (name != nullptr)
5288 outs() << format(" %.*s", left, name);
5289 outs() << "\n";
5290
5291 outs() << " cls ";
5292 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5293 n_value, c.cls);
5294 if (n_value != 0) {
5295 if (info->verbose && sym_name != nullptr)
5296 outs() << sym_name;
5297 else
5298 outs() << format("0x%" PRIx64, n_value);
5299 if (c.cls != 0)
5300 outs() << " + " << format("0x%" PRIx64, c.cls);
5301 } else
5302 outs() << format("0x%" PRIx64, c.cls);
5303 outs() << "\n";
5304 if (c.cls + n_value != 0)
5305 print_class64_t(c.cls + n_value, info);
5306
5307 outs() << " instanceMethods ";
5308 sym_name =
5309 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5310 info, n_value, c.instanceMethods);
5311 if (n_value != 0) {
5312 if (info->verbose && sym_name != nullptr)
5313 outs() << sym_name;
5314 else
5315 outs() << format("0x%" PRIx64, n_value);
5316 if (c.instanceMethods != 0)
5317 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5318 } else
5319 outs() << format("0x%" PRIx64, c.instanceMethods);
5320 outs() << "\n";
5321 if (c.instanceMethods + n_value != 0)
5322 print_method_list64_t(c.instanceMethods + n_value, info, "");
5323
5324 outs() << " classMethods ";
5325 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5326 S, info, n_value, c.classMethods);
5327 if (n_value != 0) {
5328 if (info->verbose && sym_name != nullptr)
5329 outs() << sym_name;
5330 else
5331 outs() << format("0x%" PRIx64, n_value);
5332 if (c.classMethods != 0)
5333 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5334 } else
5335 outs() << format("0x%" PRIx64, c.classMethods);
5336 outs() << "\n";
5337 if (c.classMethods + n_value != 0)
5338 print_method_list64_t(c.classMethods + n_value, info, "");
5339
5340 outs() << " protocols ";
5341 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5342 info, n_value, c.protocols);
5343 if (n_value != 0) {
5344 if (info->verbose && sym_name != nullptr)
5345 outs() << sym_name;
5346 else
5347 outs() << format("0x%" PRIx64, n_value);
5348 if (c.protocols != 0)
5349 outs() << " + " << format("0x%" PRIx64, c.protocols);
5350 } else
5351 outs() << format("0x%" PRIx64, c.protocols);
5352 outs() << "\n";
5353 if (c.protocols + n_value != 0)
5354 print_protocol_list64_t(c.protocols + n_value, info);
5355
5356 outs() << "instanceProperties ";
5357 sym_name =
5358 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5359 S, info, n_value, c.instanceProperties);
5360 if (n_value != 0) {
5361 if (info->verbose && sym_name != nullptr)
5362 outs() << sym_name;
5363 else
5364 outs() << format("0x%" PRIx64, n_value);
5365 if (c.instanceProperties != 0)
5366 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5367 } else
5368 outs() << format("0x%" PRIx64, c.instanceProperties);
5369 outs() << "\n";
5370 if (c.instanceProperties + n_value != 0)
5371 print_objc_property_list64(c.instanceProperties + n_value, info);
5372}
5373
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005374static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5375 struct category32_t c;
5376 const char *r;
5377 uint32_t offset, left;
5378 SectionRef S, xS;
5379 const char *name;
5380
5381 r = get_pointer_32(p, offset, left, S, info);
5382 if (r == nullptr)
5383 return;
5384 memset(&c, '\0', sizeof(struct category32_t));
5385 if (left < sizeof(struct category32_t)) {
5386 memcpy(&c, r, left);
5387 outs() << " (category_t entends past the end of the section)\n";
5388 } else
5389 memcpy(&c, r, sizeof(struct category32_t));
5390 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5391 swapStruct(c);
5392
5393 outs() << " name " << format("0x%" PRIx32, c.name);
5394 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5395 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005396 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005397 outs() << " " << name;
5398 outs() << "\n";
5399
5400 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5401 if (c.cls != 0)
5402 print_class32_t(c.cls, info);
5403 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5404 << "\n";
5405 if (c.instanceMethods != 0)
5406 print_method_list32_t(c.instanceMethods, info, "");
5407 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5408 << "\n";
5409 if (c.classMethods != 0)
5410 print_method_list32_t(c.classMethods, info, "");
5411 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5412 if (c.protocols != 0)
5413 print_protocol_list32_t(c.protocols, info);
5414 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5415 << "\n";
5416 if (c.instanceProperties != 0)
5417 print_objc_property_list32(c.instanceProperties, info);
5418}
5419
Kevin Enderby0fc11822015-04-01 20:57:01 +00005420static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5421 uint32_t i, left, offset, xoffset;
5422 uint64_t p, n_value;
5423 struct message_ref64 mr;
5424 const char *name, *sym_name;
5425 const char *r;
5426 SectionRef xS;
5427
5428 if (S == SectionRef())
5429 return;
5430
5431 StringRef SectName;
5432 S.getName(SectName);
5433 DataRefImpl Ref = S.getRawDataRefImpl();
5434 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5435 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5436 offset = 0;
5437 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5438 p = S.getAddress() + i;
5439 r = get_pointer_64(p, offset, left, S, info);
5440 if (r == nullptr)
5441 return;
5442 memset(&mr, '\0', sizeof(struct message_ref64));
5443 if (left < sizeof(struct message_ref64)) {
5444 memcpy(&mr, r, left);
5445 outs() << " (message_ref entends past the end of the section)\n";
5446 } else
5447 memcpy(&mr, r, sizeof(struct message_ref64));
5448 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5449 swapStruct(mr);
5450
5451 outs() << " imp ";
5452 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5453 n_value, mr.imp);
5454 if (n_value != 0) {
5455 outs() << format("0x%" PRIx64, n_value) << " ";
5456 if (mr.imp != 0)
5457 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5458 } else
5459 outs() << format("0x%" PRIx64, mr.imp) << " ";
5460 if (name != nullptr)
5461 outs() << " " << name;
5462 outs() << "\n";
5463
5464 outs() << " sel ";
5465 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5466 info, n_value, mr.sel);
5467 if (n_value != 0) {
5468 if (info->verbose && sym_name != nullptr)
5469 outs() << sym_name;
5470 else
5471 outs() << format("0x%" PRIx64, n_value);
5472 if (mr.sel != 0)
5473 outs() << " + " << format("0x%" PRIx64, mr.sel);
5474 } else
5475 outs() << format("0x%" PRIx64, mr.sel);
5476 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5477 if (name != nullptr)
5478 outs() << format(" %.*s", left, name);
5479 outs() << "\n";
5480
5481 offset += sizeof(struct message_ref64);
5482 }
5483}
5484
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005485static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5486 uint32_t i, left, offset, xoffset, p;
5487 struct message_ref32 mr;
5488 const char *name, *r;
5489 SectionRef xS;
5490
5491 if (S == SectionRef())
5492 return;
5493
5494 StringRef SectName;
5495 S.getName(SectName);
5496 DataRefImpl Ref = S.getRawDataRefImpl();
5497 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5498 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5499 offset = 0;
5500 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5501 p = S.getAddress() + i;
5502 r = get_pointer_32(p, offset, left, S, info);
5503 if (r == nullptr)
5504 return;
5505 memset(&mr, '\0', sizeof(struct message_ref32));
5506 if (left < sizeof(struct message_ref32)) {
5507 memcpy(&mr, r, left);
5508 outs() << " (message_ref entends past the end of the section)\n";
5509 } else
5510 memcpy(&mr, r, sizeof(struct message_ref32));
5511 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5512 swapStruct(mr);
5513
5514 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5515 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5516 mr.imp);
5517 if (name != nullptr)
5518 outs() << " " << name;
5519 outs() << "\n";
5520
5521 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5522 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5523 if (name != nullptr)
5524 outs() << " " << name;
5525 outs() << "\n";
5526
5527 offset += sizeof(struct message_ref32);
5528 }
5529}
5530
Kevin Enderby0fc11822015-04-01 20:57:01 +00005531static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5532 uint32_t left, offset, swift_version;
5533 uint64_t p;
5534 struct objc_image_info64 o;
5535 const char *r;
5536
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005537 if (S == SectionRef())
5538 return;
5539
Kevin Enderby0fc11822015-04-01 20:57:01 +00005540 StringRef SectName;
5541 S.getName(SectName);
5542 DataRefImpl Ref = S.getRawDataRefImpl();
5543 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5544 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5545 p = S.getAddress();
5546 r = get_pointer_64(p, offset, left, S, info);
5547 if (r == nullptr)
5548 return;
5549 memset(&o, '\0', sizeof(struct objc_image_info64));
5550 if (left < sizeof(struct objc_image_info64)) {
5551 memcpy(&o, r, left);
5552 outs() << " (objc_image_info entends past the end of the section)\n";
5553 } else
5554 memcpy(&o, r, sizeof(struct objc_image_info64));
5555 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5556 swapStruct(o);
5557 outs() << " version " << o.version << "\n";
5558 outs() << " flags " << format("0x%" PRIx32, o.flags);
5559 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5560 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5561 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5562 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5563 swift_version = (o.flags >> 8) & 0xff;
5564 if (swift_version != 0) {
5565 if (swift_version == 1)
5566 outs() << " Swift 1.0";
5567 else if (swift_version == 2)
5568 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005569 else if(swift_version == 3)
5570 outs() << " Swift 2.0";
5571 else if(swift_version == 4)
5572 outs() << " Swift 3.0";
5573 else if(swift_version == 5)
5574 outs() << " Swift 4.0";
5575 else if(swift_version == 6)
5576 outs() << " Swift 4.1";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005577 else
5578 outs() << " unknown future Swift version (" << swift_version << ")";
5579 }
5580 outs() << "\n";
5581}
5582
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005583static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5584 uint32_t left, offset, swift_version, p;
5585 struct objc_image_info32 o;
5586 const char *r;
5587
Kevin Enderby19be2512016-04-21 19:49:29 +00005588 if (S == SectionRef())
5589 return;
5590
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005591 StringRef SectName;
5592 S.getName(SectName);
5593 DataRefImpl Ref = S.getRawDataRefImpl();
5594 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5595 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5596 p = S.getAddress();
5597 r = get_pointer_32(p, offset, left, S, info);
5598 if (r == nullptr)
5599 return;
5600 memset(&o, '\0', sizeof(struct objc_image_info32));
5601 if (left < sizeof(struct objc_image_info32)) {
5602 memcpy(&o, r, left);
5603 outs() << " (objc_image_info entends past the end of the section)\n";
5604 } else
5605 memcpy(&o, r, sizeof(struct objc_image_info32));
5606 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5607 swapStruct(o);
5608 outs() << " version " << o.version << "\n";
5609 outs() << " flags " << format("0x%" PRIx32, o.flags);
5610 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5611 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5612 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5613 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5614 swift_version = (o.flags >> 8) & 0xff;
5615 if (swift_version != 0) {
5616 if (swift_version == 1)
5617 outs() << " Swift 1.0";
5618 else if (swift_version == 2)
5619 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005620 else if(swift_version == 3)
5621 outs() << " Swift 2.0";
5622 else if(swift_version == 4)
5623 outs() << " Swift 3.0";
5624 else if(swift_version == 5)
5625 outs() << " Swift 4.0";
5626 else if(swift_version == 6)
5627 outs() << " Swift 4.1";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005628 else
5629 outs() << " unknown future Swift version (" << swift_version << ")";
5630 }
5631 outs() << "\n";
5632}
5633
Kevin Enderby846c0002015-04-16 17:19:59 +00005634static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5635 uint32_t left, offset, p;
5636 struct imageInfo_t o;
5637 const char *r;
5638
5639 StringRef SectName;
5640 S.getName(SectName);
5641 DataRefImpl Ref = S.getRawDataRefImpl();
5642 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5643 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5644 p = S.getAddress();
5645 r = get_pointer_32(p, offset, left, S, info);
5646 if (r == nullptr)
5647 return;
5648 memset(&o, '\0', sizeof(struct imageInfo_t));
5649 if (left < sizeof(struct imageInfo_t)) {
5650 memcpy(&o, r, left);
5651 outs() << " (imageInfo entends past the end of the section)\n";
5652 } else
5653 memcpy(&o, r, sizeof(struct imageInfo_t));
5654 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5655 swapStruct(o);
5656 outs() << " version " << o.version << "\n";
5657 outs() << " flags " << format("0x%" PRIx32, o.flags);
5658 if (o.flags & 0x1)
5659 outs() << " F&C";
5660 if (o.flags & 0x2)
5661 outs() << " GC";
5662 if (o.flags & 0x4)
5663 outs() << " GC-only";
5664 else
5665 outs() << " RR";
5666 outs() << "\n";
5667}
5668
Kevin Enderby0fc11822015-04-01 20:57:01 +00005669static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5670 SymbolAddressMap AddrMap;
5671 if (verbose)
5672 CreateSymbolAddressMap(O, &AddrMap);
5673
5674 std::vector<SectionRef> Sections;
5675 for (const SectionRef &Section : O->sections()) {
5676 StringRef SectName;
5677 Section.getName(SectName);
5678 Sections.push_back(Section);
5679 }
5680
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005681 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005682
Davide Italiano62507042015-12-11 22:27:59 +00005683 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5684 if (CL == SectionRef())
5685 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005686 if (CL == SectionRef())
5687 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5688 if (CL == SectionRef())
5689 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005690 info.S = CL;
5691 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005692
Davide Italiano62507042015-12-11 22:27:59 +00005693 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5694 if (CR == SectionRef())
5695 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005696 if (CR == SectionRef())
5697 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5698 if (CR == SectionRef())
5699 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005700 info.S = CR;
5701 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005702
Davide Italiano62507042015-12-11 22:27:59 +00005703 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5704 if (SR == SectionRef())
5705 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005706 if (SR == SectionRef())
5707 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5708 if (SR == SectionRef())
5709 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005710 info.S = SR;
5711 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005712
Davide Italiano62507042015-12-11 22:27:59 +00005713 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5714 if (CA == SectionRef())
5715 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005716 if (CA == SectionRef())
5717 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5718 if (CA == SectionRef())
5719 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005720 info.S = CA;
5721 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005722
Davide Italiano62507042015-12-11 22:27:59 +00005723 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5724 if (PL == SectionRef())
5725 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005726 if (PL == SectionRef())
5727 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5728 if (PL == SectionRef())
5729 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005730 info.S = PL;
5731 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005732
Davide Italiano62507042015-12-11 22:27:59 +00005733 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5734 if (MR == SectionRef())
5735 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005736 if (MR == SectionRef())
5737 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5738 if (MR == SectionRef())
5739 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005740 info.S = MR;
5741 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005742
Davide Italiano62507042015-12-11 22:27:59 +00005743 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5744 if (II == SectionRef())
5745 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005746 if (II == SectionRef())
5747 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5748 if (II == SectionRef())
5749 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005750 info.S = II;
5751 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005752}
5753
5754static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005755 SymbolAddressMap AddrMap;
5756 if (verbose)
5757 CreateSymbolAddressMap(O, &AddrMap);
5758
5759 std::vector<SectionRef> Sections;
5760 for (const SectionRef &Section : O->sections()) {
5761 StringRef SectName;
5762 Section.getName(SectName);
5763 Sections.push_back(Section);
5764 }
5765
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005766 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005767
Kevin Enderby5879a482017-02-09 17:56:26 +00005768 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5769 if (CL == SectionRef())
5770 CL = get_section(O, "__DATA", "__objc_classlist");
5771 if (CL == SectionRef())
5772 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5773 if (CL == SectionRef())
5774 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5775 info.S = CL;
5776 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005777
Kevin Enderby5879a482017-02-09 17:56:26 +00005778 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5779 if (CR == SectionRef())
5780 CR = get_section(O, "__DATA", "__objc_classrefs");
5781 if (CR == SectionRef())
5782 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5783 if (CR == SectionRef())
5784 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5785 info.S = CR;
5786 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005787
Kevin Enderby5879a482017-02-09 17:56:26 +00005788 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5789 if (SR == SectionRef())
5790 SR = get_section(O, "__DATA", "__objc_superrefs");
5791 if (SR == SectionRef())
5792 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5793 if (SR == SectionRef())
5794 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5795 info.S = SR;
5796 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005797
Kevin Enderby5879a482017-02-09 17:56:26 +00005798 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5799 if (CA == SectionRef())
5800 CA = get_section(O, "__DATA", "__objc_catlist");
5801 if (CA == SectionRef())
5802 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5803 if (CA == SectionRef())
5804 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5805 info.S = CA;
5806 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005807
Kevin Enderby5879a482017-02-09 17:56:26 +00005808 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5809 if (PL == SectionRef())
5810 PL = get_section(O, "__DATA", "__objc_protolist");
5811 if (PL == SectionRef())
5812 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5813 if (PL == SectionRef())
5814 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5815 info.S = PL;
5816 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005817
Kevin Enderby5879a482017-02-09 17:56:26 +00005818 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5819 if (MR == SectionRef())
5820 MR = get_section(O, "__DATA", "__objc_msgrefs");
5821 if (MR == SectionRef())
5822 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5823 if (MR == SectionRef())
5824 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5825 info.S = MR;
5826 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005827
Kevin Enderby5879a482017-02-09 17:56:26 +00005828 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5829 if (II == SectionRef())
5830 II = get_section(O, "__DATA", "__objc_imageinfo");
5831 if (II == SectionRef())
5832 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5833 if (II == SectionRef())
5834 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5835 info.S = II;
5836 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005837}
5838
5839static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005840 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5841 const char *r, *name, *defs;
5842 struct objc_module_t module;
5843 SectionRef S, xS;
5844 struct objc_symtab_t symtab;
5845 struct objc_class_t objc_class;
5846 struct objc_category_t objc_category;
5847
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005848 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005849 S = get_section(O, "__OBJC", "__module_info");
5850 if (S == SectionRef())
5851 return false;
5852
5853 SymbolAddressMap AddrMap;
5854 if (verbose)
5855 CreateSymbolAddressMap(O, &AddrMap);
5856
5857 std::vector<SectionRef> Sections;
5858 for (const SectionRef &Section : O->sections()) {
5859 StringRef SectName;
5860 Section.getName(SectName);
5861 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005862 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005863
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005864 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00005865
5866 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5867 p = S.getAddress() + i;
5868 r = get_pointer_32(p, offset, left, S, &info, true);
5869 if (r == nullptr)
5870 return true;
5871 memset(&module, '\0', sizeof(struct objc_module_t));
5872 if (left < sizeof(struct objc_module_t)) {
5873 memcpy(&module, r, left);
5874 outs() << " (module extends past end of __module_info section)\n";
5875 } else
5876 memcpy(&module, r, sizeof(struct objc_module_t));
5877 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5878 swapStruct(module);
5879
5880 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5881 outs() << " version " << module.version << "\n";
5882 outs() << " size " << module.size << "\n";
5883 outs() << " name ";
5884 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5885 if (name != nullptr)
5886 outs() << format("%.*s", left, name);
5887 else
5888 outs() << format("0x%08" PRIx32, module.name)
5889 << "(not in an __OBJC section)";
5890 outs() << "\n";
5891
5892 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5893 if (module.symtab == 0 || r == nullptr) {
5894 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5895 << " (not in an __OBJC section)\n";
5896 continue;
5897 }
5898 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5899 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5900 defs_left = 0;
5901 defs = nullptr;
5902 if (left < sizeof(struct objc_symtab_t)) {
5903 memcpy(&symtab, r, left);
5904 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5905 } else {
5906 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5907 if (left > sizeof(struct objc_symtab_t)) {
5908 defs_left = left - sizeof(struct objc_symtab_t);
5909 defs = r + sizeof(struct objc_symtab_t);
5910 }
5911 }
5912 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5913 swapStruct(symtab);
5914
5915 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5916 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5917 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5918 if (r == nullptr)
5919 outs() << " (not in an __OBJC section)";
5920 outs() << "\n";
5921 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5922 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5923 if (symtab.cls_def_cnt > 0)
5924 outs() << "\tClass Definitions\n";
5925 for (j = 0; j < symtab.cls_def_cnt; j++) {
5926 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5927 outs() << "\t(remaining class defs entries entends past the end of the "
5928 << "section)\n";
5929 break;
5930 }
5931 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5932 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5933 sys::swapByteOrder(def);
5934
5935 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5936 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5937 if (r != nullptr) {
5938 if (left > sizeof(struct objc_class_t)) {
5939 outs() << "\n";
5940 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5941 } else {
5942 outs() << " (entends past the end of the section)\n";
5943 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5944 memcpy(&objc_class, r, left);
5945 }
5946 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5947 swapStruct(objc_class);
5948 print_objc_class_t(&objc_class, &info);
5949 } else {
5950 outs() << "(not in an __OBJC section)\n";
5951 }
5952
5953 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5954 outs() << "\tMeta Class";
5955 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5956 if (r != nullptr) {
5957 if (left > sizeof(struct objc_class_t)) {
5958 outs() << "\n";
5959 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5960 } else {
5961 outs() << " (entends past the end of the section)\n";
5962 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5963 memcpy(&objc_class, r, left);
5964 }
5965 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5966 swapStruct(objc_class);
5967 print_objc_class_t(&objc_class, &info);
5968 } else {
5969 outs() << "(not in an __OBJC section)\n";
5970 }
5971 }
5972 }
5973 if (symtab.cat_def_cnt > 0)
5974 outs() << "\tCategory Definitions\n";
5975 for (j = 0; j < symtab.cat_def_cnt; j++) {
5976 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5977 outs() << "\t(remaining category defs entries entends past the end of "
5978 << "the section)\n";
5979 break;
5980 }
5981 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5982 sizeof(uint32_t));
5983 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5984 sys::swapByteOrder(def);
5985
5986 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5987 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5988 << format("0x%08" PRIx32, def);
5989 if (r != nullptr) {
5990 if (left > sizeof(struct objc_category_t)) {
5991 outs() << "\n";
5992 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5993 } else {
5994 outs() << " (entends past the end of the section)\n";
5995 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5996 memcpy(&objc_category, r, left);
5997 }
5998 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5999 swapStruct(objc_category);
6000 print_objc_objc_category_t(&objc_category, &info);
6001 } else {
6002 outs() << "(not in an __OBJC section)\n";
6003 }
6004 }
6005 }
6006 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6007 if (II != SectionRef())
6008 print_image_info(II, &info);
6009
6010 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006011}
6012
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006013static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6014 uint32_t size, uint32_t addr) {
6015 SymbolAddressMap AddrMap;
6016 CreateSymbolAddressMap(O, &AddrMap);
6017
6018 std::vector<SectionRef> Sections;
6019 for (const SectionRef &Section : O->sections()) {
6020 StringRef SectName;
6021 Section.getName(SectName);
6022 Sections.push_back(Section);
6023 }
6024
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006025 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006026
6027 const char *p;
6028 struct objc_protocol_t protocol;
6029 uint32_t left, paddr;
6030 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6031 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6032 left = size - (p - sect);
6033 if (left < sizeof(struct objc_protocol_t)) {
6034 outs() << "Protocol extends past end of __protocol section\n";
6035 memcpy(&protocol, p, left);
6036 } else
6037 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6038 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6039 swapStruct(protocol);
6040 paddr = addr + (p - sect);
6041 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6042 if (print_protocol(paddr, 0, &info))
6043 outs() << "(not in an __OBJC section)\n";
6044 }
6045}
6046
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006047#ifdef HAVE_LIBXAR
6048inline void swapStruct(struct xar_header &xar) {
6049 sys::swapByteOrder(xar.magic);
6050 sys::swapByteOrder(xar.size);
6051 sys::swapByteOrder(xar.version);
6052 sys::swapByteOrder(xar.toc_length_compressed);
6053 sys::swapByteOrder(xar.toc_length_uncompressed);
6054 sys::swapByteOrder(xar.cksum_alg);
6055}
6056
6057static void PrintModeVerbose(uint32_t mode) {
6058 switch(mode & S_IFMT){
6059 case S_IFDIR:
6060 outs() << "d";
6061 break;
6062 case S_IFCHR:
6063 outs() << "c";
6064 break;
6065 case S_IFBLK:
6066 outs() << "b";
6067 break;
6068 case S_IFREG:
6069 outs() << "-";
6070 break;
6071 case S_IFLNK:
6072 outs() << "l";
6073 break;
6074 case S_IFSOCK:
6075 outs() << "s";
6076 break;
6077 default:
6078 outs() << "?";
6079 break;
6080 }
6081
6082 /* owner permissions */
6083 if(mode & S_IREAD)
6084 outs() << "r";
6085 else
6086 outs() << "-";
6087 if(mode & S_IWRITE)
6088 outs() << "w";
6089 else
6090 outs() << "-";
6091 if(mode & S_ISUID)
6092 outs() << "s";
6093 else if(mode & S_IEXEC)
6094 outs() << "x";
6095 else
6096 outs() << "-";
6097
6098 /* group permissions */
6099 if(mode & (S_IREAD >> 3))
6100 outs() << "r";
6101 else
6102 outs() << "-";
6103 if(mode & (S_IWRITE >> 3))
6104 outs() << "w";
6105 else
6106 outs() << "-";
6107 if(mode & S_ISGID)
6108 outs() << "s";
6109 else if(mode & (S_IEXEC >> 3))
6110 outs() << "x";
6111 else
6112 outs() << "-";
6113
6114 /* other permissions */
6115 if(mode & (S_IREAD >> 6))
6116 outs() << "r";
6117 else
6118 outs() << "-";
6119 if(mode & (S_IWRITE >> 6))
6120 outs() << "w";
6121 else
6122 outs() << "-";
6123 if(mode & S_ISVTX)
6124 outs() << "t";
6125 else if(mode & (S_IEXEC >> 6))
6126 outs() << "x";
6127 else
6128 outs() << "-";
6129}
6130
6131static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006132 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006133 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6134 char *endp;
6135 uint32_t mode_value;
6136
Francis Ricci6f942972017-10-06 15:33:28 +00006137 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006138 if (!xi) {
6139 errs() << "Can't obtain an xar iterator for xar archive "
6140 << XarFilename << "\n";
6141 return;
6142 }
6143
6144 // Go through the xar's files.
6145 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006146 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006147 if(!xp){
6148 errs() << "Can't obtain an xar iterator for xar archive "
6149 << XarFilename << "\n";
6150 return;
6151 }
6152 type = nullptr;
6153 mode = nullptr;
6154 user = nullptr;
6155 group = nullptr;
6156 size = nullptr;
6157 mtime = nullptr;
6158 name = nullptr;
6159 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006160 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006161 xar_prop_get(xf, key, &val);
6162#if 0 // Useful for debugging.
6163 outs() << "key: " << key << " value: " << val << "\n";
6164#endif
6165 if(strcmp(key, "type") == 0)
6166 type = val;
6167 if(strcmp(key, "mode") == 0)
6168 mode = val;
6169 if(strcmp(key, "user") == 0)
6170 user = val;
6171 if(strcmp(key, "group") == 0)
6172 group = val;
6173 if(strcmp(key, "data/size") == 0)
6174 size = val;
6175 if(strcmp(key, "mtime") == 0)
6176 mtime = val;
6177 if(strcmp(key, "name") == 0)
6178 name = val;
6179 }
6180 if(mode != nullptr){
6181 mode_value = strtoul(mode, &endp, 8);
6182 if(*endp != '\0')
6183 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6184 if(strcmp(type, "file") == 0)
6185 mode_value |= S_IFREG;
6186 PrintModeVerbose(mode_value);
6187 outs() << " ";
6188 }
6189 if(user != nullptr)
6190 outs() << format("%10s/", user);
6191 if(group != nullptr)
6192 outs() << format("%-10s ", group);
6193 if(size != nullptr)
6194 outs() << format("%7s ", size);
6195 if(mtime != nullptr){
6196 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6197 outs() << *m;
6198 if(*m == 'T')
6199 m++;
6200 outs() << " ";
6201 for( ; *m != 'Z' && *m != '\0'; m++)
6202 outs() << *m;
6203 outs() << " ";
6204 }
6205 if(name != nullptr)
6206 outs() << name;
6207 outs() << "\n";
6208 }
6209}
6210
6211static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6212 uint32_t size, bool verbose,
6213 bool PrintXarHeader, bool PrintXarFileHeaders,
6214 std::string XarMemberName) {
6215 if(size < sizeof(struct xar_header)) {
6216 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6217 "of struct xar_header)\n";
6218 return;
6219 }
6220 struct xar_header XarHeader;
6221 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6222 if (sys::IsLittleEndianHost)
6223 swapStruct(XarHeader);
6224 if (PrintXarHeader) {
6225 if (!XarMemberName.empty())
6226 outs() << "In xar member " << XarMemberName << ": ";
6227 else
6228 outs() << "For (__LLVM,__bundle) section: ";
6229 outs() << "xar header\n";
6230 if (XarHeader.magic == XAR_HEADER_MAGIC)
6231 outs() << " magic XAR_HEADER_MAGIC\n";
6232 else
6233 outs() << " magic "
6234 << format_hex(XarHeader.magic, 10, true)
6235 << " (not XAR_HEADER_MAGIC)\n";
6236 outs() << " size " << XarHeader.size << "\n";
6237 outs() << " version " << XarHeader.version << "\n";
6238 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6239 << "\n";
6240 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6241 << "\n";
6242 outs() << " cksum_alg ";
6243 switch (XarHeader.cksum_alg) {
6244 case XAR_CKSUM_NONE:
6245 outs() << "XAR_CKSUM_NONE\n";
6246 break;
6247 case XAR_CKSUM_SHA1:
6248 outs() << "XAR_CKSUM_SHA1\n";
6249 break;
6250 case XAR_CKSUM_MD5:
6251 outs() << "XAR_CKSUM_MD5\n";
6252 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006253#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006254 case XAR_CKSUM_SHA256:
6255 outs() << "XAR_CKSUM_SHA256\n";
6256 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006257#endif
6258#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006259 case XAR_CKSUM_SHA512:
6260 outs() << "XAR_CKSUM_SHA512\n";
6261 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006262#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006263 default:
6264 outs() << XarHeader.cksum_alg << "\n";
6265 }
6266 }
6267
6268 SmallString<128> XarFilename;
6269 int FD;
6270 std::error_code XarEC =
6271 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6272 if (XarEC) {
6273 errs() << XarEC.message() << "\n";
6274 return;
6275 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006276 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006277 raw_fd_ostream &XarOut = XarFile.os();
6278 StringRef XarContents(sect, size);
6279 XarOut << XarContents;
6280 XarOut.close();
6281 if (XarOut.has_error())
6282 return;
6283
Francis Ricci6f942972017-10-06 15:33:28 +00006284 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006285 if (!xar) {
6286 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
6287 return;
6288 }
6289
6290 SmallString<128> TocFilename;
6291 std::error_code TocEC =
6292 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6293 if (TocEC) {
6294 errs() << TocEC.message() << "\n";
6295 return;
6296 }
6297 xar_serialize(xar, TocFilename.c_str());
6298
6299 if (PrintXarFileHeaders) {
6300 if (!XarMemberName.empty())
6301 outs() << "In xar member " << XarMemberName << ": ";
6302 else
6303 outs() << "For (__LLVM,__bundle) section: ";
6304 outs() << "xar archive files:\n";
6305 PrintXarFilesSummary(XarFilename.c_str(), xar);
6306 }
6307
6308 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6309 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6310 if (std::error_code EC = FileOrErr.getError()) {
6311 errs() << EC.message() << "\n";
6312 return;
6313 }
6314 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6315
6316 if (!XarMemberName.empty())
6317 outs() << "In xar member " << XarMemberName << ": ";
6318 else
6319 outs() << "For (__LLVM,__bundle) section: ";
6320 outs() << "xar table of contents:\n";
6321 outs() << Buffer->getBuffer() << "\n";
6322
6323 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006324 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006325 if(!xi){
6326 errs() << "Can't obtain an xar iterator for xar archive "
6327 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006328 return;
6329 }
6330 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6331 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006332 const char *member_name, *member_type, *member_size_string;
6333 size_t member_size;
6334
Francis Ricci6f942972017-10-06 15:33:28 +00006335 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006336 if(!xp){
6337 errs() << "Can't obtain an xar iterator for xar archive "
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006338 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006339 return;
6340 }
6341 member_name = NULL;
6342 member_type = NULL;
6343 member_size_string = NULL;
6344 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006345 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006346 xar_prop_get(xf, key, &val);
6347#if 0 // Useful for debugging.
6348 outs() << "key: " << key << " value: " << val << "\n";
6349#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006350 if (strcmp(key, "name") == 0)
6351 member_name = val;
6352 if (strcmp(key, "type") == 0)
6353 member_type = val;
6354 if (strcmp(key, "data/size") == 0)
6355 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006356 }
6357 /*
6358 * If we find a file with a name, date/size and type properties
6359 * and with the type being "file" see if that is a xar file.
6360 */
6361 if (member_name != NULL && member_type != NULL &&
6362 strcmp(member_type, "file") == 0 &&
6363 member_size_string != NULL){
6364 // Extract the file into a buffer.
6365 char *endptr;
6366 member_size = strtoul(member_size_string, &endptr, 10);
6367 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006368 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006369 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006370#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006371 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006372#endif
6373 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006374 std::string OldXarMemberName;
6375 // If XarMemberName is already set this is nested. So
6376 // save the old name and create the nested name.
6377 if (!XarMemberName.empty()) {
6378 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006379 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006380 (Twine("[") + XarMemberName + "]" + member_name).str();
6381 } else {
6382 OldXarMemberName = "";
6383 XarMemberName = member_name;
6384 }
6385 // See if this is could be a xar file (nested).
6386 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006387#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006388 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006389#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006390 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006391 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006392 swapStruct(XarHeader);
6393 if (XarHeader.magic == XAR_HEADER_MAGIC)
6394 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006395 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006396 XarMemberName);
6397 }
6398 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006399 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006400 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006401 }
6402 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006403 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006404}
6405#endif // defined(HAVE_LIBXAR)
6406
Kevin Enderby0fc11822015-04-01 20:57:01 +00006407static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6408 if (O->is64Bit())
6409 printObjc2_64bit_MetaData(O, verbose);
6410 else {
6411 MachO::mach_header H;
6412 H = O->getHeader();
6413 if (H.cputype == MachO::CPU_TYPE_ARM)
6414 printObjc2_32bit_MetaData(O, verbose);
6415 else {
6416 // This is the 32-bit non-arm cputype case. Which is normally
6417 // the first Objective-C ABI. But it may be the case of a
6418 // binary for the iOS simulator which is the second Objective-C
6419 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6420 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006421 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006422 printObjc2_32bit_MetaData(O, verbose);
6423 }
6424 }
6425}
6426
Kevin Enderbybf246f52014-09-24 23:08:22 +00006427// GuessLiteralPointer returns a string which for the item in the Mach-O file
6428// for the address passed in as ReferenceValue for printing as a comment with
6429// the instruction and also returns the corresponding type of that item
6430// indirectly through ReferenceType.
6431//
6432// If ReferenceValue is an address of literal cstring then a pointer to the
6433// cstring is returned and ReferenceType is set to
6434// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6435//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006436// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6437// Class ref that name is returned and the ReferenceType is set accordingly.
6438//
6439// Lastly, literals which are Symbol address in a literal pool are looked for
6440// and if found the symbol name is returned and ReferenceType is set to
6441// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6442//
6443// If there is no item in the Mach-O file for the address passed in as
6444// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006445static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6446 uint64_t ReferencePC,
6447 uint64_t *ReferenceType,
6448 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006449 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006450 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6451 uint64_t sect_addr = info->S.getAddress();
6452 uint64_t sect_offset = ReferencePC - sect_addr;
6453 bool reloc_found = false;
6454 DataRefImpl Rel;
6455 MachO::any_relocation_info RE;
6456 bool isExtern = false;
6457 SymbolRef Symbol;
6458 for (const RelocationRef &Reloc : info->S.relocations()) {
6459 uint64_t RelocOffset = Reloc.getOffset();
6460 if (RelocOffset == sect_offset) {
6461 Rel = Reloc.getRawDataRefImpl();
6462 RE = info->O->getRelocation(Rel);
6463 if (info->O->isRelocationScattered(RE))
6464 continue;
6465 isExtern = info->O->getPlainRelocationExternal(RE);
6466 if (isExtern) {
6467 symbol_iterator RelocSym = Reloc.getSymbol();
6468 Symbol = *RelocSym;
6469 }
6470 reloc_found = true;
6471 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006472 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006473 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006474 // If there is an external relocation entry for a symbol in a section
6475 // then used that symbol's value for the value of the reference.
6476 if (reloc_found && isExtern) {
6477 if (info->O->getAnyRelocationPCRel(RE)) {
6478 unsigned Type = info->O->getAnyRelocationType(RE);
6479 if (Type == MachO::X86_64_RELOC_SIGNED) {
6480 ReferenceValue = Symbol.getValue();
6481 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006482 }
6483 }
6484 }
6485
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006486 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6487 // Message refs and Class refs.
6488 bool classref, selref, msgref, cfstring;
6489 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6490 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006491 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006492 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6493 // And the pointer_value in that section is typically zero as it will be
6494 // set by dyld as part of the "bind information".
6495 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6496 if (name != nullptr) {
6497 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006498 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006499 if (class_name != nullptr && class_name[1] == '_' &&
6500 class_name[2] != '\0') {
6501 info->class_name = class_name + 2;
6502 return name;
6503 }
6504 }
6505 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006506
David Blaikie33dd45d02015-03-23 18:39:02 +00006507 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006508 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6509 const char *name =
6510 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6511 if (name != nullptr)
6512 info->class_name = name;
6513 else
6514 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006515 return name;
6516 }
6517
David Blaikie33dd45d02015-03-23 18:39:02 +00006518 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006519 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6520 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6521 return name;
6522 }
6523
David Blaikie33dd45d02015-03-23 18:39:02 +00006524 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006525 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6526
6527 if (pointer_value != 0)
6528 ReferenceValue = pointer_value;
6529
6530 const char *name = GuessCstringPointer(ReferenceValue, info);
6531 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006532 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006533 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6534 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006535 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006536 info->class_name = nullptr;
6537 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6538 info->selector_name = name;
6539 } else
6540 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6541 return name;
6542 }
6543
6544 // Lastly look for an indirect symbol with this ReferenceValue which is in
6545 // a literal pool. If found return that symbol name.
6546 name = GuessIndirectSymbol(ReferenceValue, info);
6547 if (name) {
6548 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6549 return name;
6550 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006551
6552 return nullptr;
6553}
6554
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006555// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006556// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006557// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6558// is created and returns the symbol name that matches the ReferenceValue or
6559// nullptr if none. The ReferenceType is passed in for the IN type of
6560// reference the instruction is making from the values in defined in the header
6561// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6562// Out type and the ReferenceName will also be set which is added as a comment
6563// to the disassembled instruction.
6564//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006565// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006566// returned through ReferenceName and ReferenceType is set to
6567// LLVMDisassembler_ReferenceType_DeMangled_Name .
6568//
6569// When this is called to get a symbol name for a branch target then the
6570// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6571// SymbolValue will be looked for in the indirect symbol table to determine if
6572// it is an address for a symbol stub. If so then the symbol name for that
6573// stub is returned indirectly through ReferenceName and then ReferenceType is
6574// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6575//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006576// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006577// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6578// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6579// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006580// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006581static const char *SymbolizerSymbolLookUp(void *DisInfo,
6582 uint64_t ReferenceValue,
6583 uint64_t *ReferenceType,
6584 uint64_t ReferencePC,
6585 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006586 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006587 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006588 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006589 *ReferenceName = nullptr;
6590 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006591 return nullptr;
6592 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006593
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006594 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006595
Kevin Enderby85974882014-09-26 22:20:44 +00006596 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6597 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006598 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006599 method_reference(info, ReferenceType, ReferenceName);
6600 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6601 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006602 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006603 if (info->demangled_name != nullptr)
6604 free(info->demangled_name);
6605 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006606 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006607 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006608 if (info->demangled_name != nullptr) {
6609 *ReferenceName = info->demangled_name;
6610 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6611 } else
6612 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6613 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006614 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6615 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6616 *ReferenceName =
6617 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006618 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006619 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006620 else
6621 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006622 // If this is arm64 and the reference is an adrp instruction save the
6623 // instruction, passed in ReferenceValue and the address of the instruction
6624 // for use later if we see and add immediate instruction.
6625 } else if (info->O->getArch() == Triple::aarch64 &&
6626 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6627 info->adrp_inst = ReferenceValue;
6628 info->adrp_addr = ReferencePC;
6629 SymbolName = nullptr;
6630 *ReferenceName = nullptr;
6631 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6632 // If this is arm64 and reference is an add immediate instruction and we
6633 // have
6634 // seen an adrp instruction just before it and the adrp's Xd register
6635 // matches
6636 // this add's Xn register reconstruct the value being referenced and look to
6637 // see if it is a literal pointer. Note the add immediate instruction is
6638 // passed in ReferenceValue.
6639 } else if (info->O->getArch() == Triple::aarch64 &&
6640 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6641 ReferencePC - 4 == info->adrp_addr &&
6642 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6643 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6644 uint32_t addxri_inst;
6645 uint64_t adrp_imm, addxri_imm;
6646
6647 adrp_imm =
6648 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6649 if (info->adrp_inst & 0x0200000)
6650 adrp_imm |= 0xfffffffffc000000LL;
6651
6652 addxri_inst = ReferenceValue;
6653 addxri_imm = (addxri_inst >> 10) & 0xfff;
6654 if (((addxri_inst >> 22) & 0x3) == 1)
6655 addxri_imm <<= 12;
6656
6657 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6658 (adrp_imm << 12) + addxri_imm;
6659
6660 *ReferenceName =
6661 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6662 if (*ReferenceName == nullptr)
6663 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6664 // If this is arm64 and the reference is a load register instruction and we
6665 // have seen an adrp instruction just before it and the adrp's Xd register
6666 // matches this add's Xn register reconstruct the value being referenced and
6667 // look to see if it is a literal pointer. Note the load register
6668 // instruction is passed in ReferenceValue.
6669 } else if (info->O->getArch() == Triple::aarch64 &&
6670 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6671 ReferencePC - 4 == info->adrp_addr &&
6672 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6673 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6674 uint32_t ldrxui_inst;
6675 uint64_t adrp_imm, ldrxui_imm;
6676
6677 adrp_imm =
6678 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6679 if (info->adrp_inst & 0x0200000)
6680 adrp_imm |= 0xfffffffffc000000LL;
6681
6682 ldrxui_inst = ReferenceValue;
6683 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6684
6685 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6686 (adrp_imm << 12) + (ldrxui_imm << 3);
6687
6688 *ReferenceName =
6689 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6690 if (*ReferenceName == nullptr)
6691 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6692 }
6693 // If this arm64 and is an load register (PC-relative) instruction the
6694 // ReferenceValue is the PC plus the immediate value.
6695 else if (info->O->getArch() == Triple::aarch64 &&
6696 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6697 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6698 *ReferenceName =
6699 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6700 if (*ReferenceName == nullptr)
6701 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006702 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006703 if (info->demangled_name != nullptr)
6704 free(info->demangled_name);
6705 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006706 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006707 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006708 if (info->demangled_name != nullptr) {
6709 *ReferenceName = info->demangled_name;
6710 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6711 }
6712 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006713 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006714 *ReferenceName = nullptr;
6715 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6716 }
6717
6718 return SymbolName;
6719}
6720
Kevin Enderbybf246f52014-09-24 23:08:22 +00006721/// \brief Emits the comments that are stored in the CommentStream.
6722/// Each comment in the CommentStream must end with a newline.
6723static void emitComments(raw_svector_ostream &CommentStream,
6724 SmallString<128> &CommentsToEmit,
6725 formatted_raw_ostream &FormattedOS,
6726 const MCAsmInfo &MAI) {
6727 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006728 StringRef Comments = CommentsToEmit.str();
6729 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006730 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006731 unsigned CommentColumn = MAI.getCommentColumn();
6732 bool IsFirst = true;
6733 while (!Comments.empty()) {
6734 if (!IsFirst)
6735 FormattedOS << '\n';
6736 // Emit a line of comments.
6737 FormattedOS.PadToColumn(CommentColumn);
6738 size_t Position = Comments.find('\n');
6739 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6740 // Move after the newline character.
6741 Comments = Comments.substr(Position + 1);
6742 IsFirst = false;
6743 }
6744 FormattedOS.flush();
6745
6746 // Tell the comment stream that the vector changed underneath it.
6747 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006748}
6749
Kevin Enderby95df54c2015-02-04 01:01:38 +00006750static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6751 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006752 const char *McpuDefault = nullptr;
6753 const Target *ThumbTarget = nullptr;
6754 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006755 if (!TheTarget) {
6756 // GetTarget prints out stuff.
6757 return;
6758 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006759 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006760 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006761 MachOMCPU = McpuDefault;
6762 else
6763 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006764
Ahmed Charles56440fd2014-03-06 05:51:42 +00006765 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006766 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006767 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006768 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006769
Kevin Enderbyc9595622014-08-06 23:24:41 +00006770 // Package up features to be passed to target/subtarget
6771 std::string FeaturesStr;
6772 if (MAttrs.size()) {
6773 SubtargetFeatures Features;
6774 for (unsigned i = 0; i != MAttrs.size(); ++i)
6775 Features.AddFeature(MAttrs[i]);
6776 FeaturesStr = Features.getString();
6777 }
6778
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006779 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006780 std::unique_ptr<const MCRegisterInfo> MRI(
6781 TheTarget->createMCRegInfo(TripleName));
6782 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006783 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006784 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006785 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006786 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006787 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006788 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006789 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006790 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006791 std::unique_ptr<MCRelocationInfo> RelInfo(
6792 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6793 if (RelInfo) {
6794 Symbolizer.reset(TheTarget->createMCSymbolizer(
6795 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006796 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006797 DisAsm->setSymbolizer(std::move(Symbolizer));
6798 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006799 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006800 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006801 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006802 // Set the display preference for hex vs. decimal immediates.
6803 IP->setPrintImmHex(PrintImmHex);
6804 // Comment stream and backing vector.
6805 SmallString<128> CommentsToEmit;
6806 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006807 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6808 // if it is done then arm64 comments for string literals don't get printed
6809 // and some constant get printed instead and not setting it causes intel
6810 // (32-bit and 64-bit) comments printed with different spacing before the
6811 // comment causing different diffs with the 'C' disassembler library API.
6812 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006813
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006814 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006815 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006816 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006817 return;
6818 }
6819
Tim Northover09ca33e2016-04-22 23:23:31 +00006820 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006821 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6822 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6823 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006824 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006825 std::unique_ptr<MCInstPrinter> ThumbIP;
6826 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006827 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006828 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006829 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006830 if (ThumbTarget) {
6831 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6832 ThumbAsmInfo.reset(
6833 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6834 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006835 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6836 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006837 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6838 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006839 MCContext *PtrThumbCtx = ThumbCtx.get();
6840 ThumbRelInfo.reset(
6841 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6842 if (ThumbRelInfo) {
6843 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6844 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006845 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006846 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6847 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006848 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6849 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006850 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6851 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006852 // Set the display preference for hex vs. decimal immediates.
6853 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006854 }
6855
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006856 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006857 errs() << "error: couldn't initialize disassembler for target "
6858 << ThumbTripleName << '\n';
6859 return;
6860 }
6861
Charles Davis8bdfafd2013-09-01 04:28:48 +00006862 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006863
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006864 // FIXME: Using the -cfg command line option, this code used to be able to
6865 // annotate relocations with the referenced symbol's name, and if this was
6866 // inside a __[cf]string section, the data it points to. This is now replaced
6867 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006868 std::vector<SectionRef> Sections;
6869 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006870 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006871 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006872
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006873 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006874 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006875
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006876 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006877 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006878
Kevin Enderby273ae012013-06-06 17:20:50 +00006879 // Build a data in code table that is sorted on by the address of each entry.
6880 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006881 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006882 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006883 else
6884 BaseAddress = BaseSegmentAddress;
6885 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006886 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006887 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006888 uint32_t Offset;
6889 DI->getOffset(Offset);
6890 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6891 }
6892 array_pod_sort(Dices.begin(), Dices.end());
6893
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006894#ifndef NDEBUG
6895 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6896#else
6897 raw_ostream &DebugOut = nulls();
6898#endif
6899
Ahmed Charles56440fd2014-03-06 05:51:42 +00006900 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006901 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006902 // Try to find debug info and set up the DIContext for it.
6903 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006904 // A separate DSym file path was specified, parse it as a macho file,
6905 // get the sections and supply it to the section name parsing machinery.
6906 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006907 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006908 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006909 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006910 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006911 return;
6912 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006913 DbgObj =
6914 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6915 .get()
6916 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006917 }
6918
Eric Christopher7370b552012-11-12 21:40:38 +00006919 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006920 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006921 }
6922
Colin LeMahieufcc32762015-07-29 19:08:10 +00006923 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006924 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006925
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006926 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006927 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006928 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6929 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006930
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006931 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006932
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006933 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006934 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006935 continue;
6936
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006937 StringRef BytesStr;
6938 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006939 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6940 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006941 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006942
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006943 bool symbolTableWorked = false;
6944
Kevin Enderbybf246f52014-09-24 23:08:22 +00006945 // Create a map of symbol addresses to symbol names for use by
6946 // the SymbolizerSymbolLookUp() routine.
6947 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006948 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006949 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006950 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006951 if (!STOrErr)
6952 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006953 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006954 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6955 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006956 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006957 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006958 if (!SymNameOrErr)
6959 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006960 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006961 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006962 if (!DisSymName.empty() && DisSymName == SymName)
6963 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006964 }
6965 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006966 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006967 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6968 return;
6969 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006970 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006971 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006972 SymbolizerInfo.O = MachOOF;
6973 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006974 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006975 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006976 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006977 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006978 ThumbSymbolizerInfo.O = MachOOF;
6979 ThumbSymbolizerInfo.S = Sections[SectIdx];
6980 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6981 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006982
Kevin Enderby4b627be2016-04-28 20:14:13 +00006983 unsigned int Arch = MachOOF->getArch();
6984
Tim Northoverf203ab52016-07-14 22:13:32 +00006985 // Skip all symbols if this is a stubs file.
6986 if (Bytes.size() == 0)
6987 return;
6988
Kevin Enderbyc138da32017-02-06 18:43:18 +00006989 // If the section has symbols but no symbol at the start of the section
6990 // these are used to make sure the bytes before the first symbol are
6991 // disassembled.
6992 bool FirstSymbol = true;
6993 bool FirstSymbolAtSectionStart = true;
6994
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006995 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006996 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006997 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006998 if (!SymNameOrErr)
6999 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007000 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007001
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007002 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007003 if (!STOrErr)
7004 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007005 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007006 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007007 continue;
7008
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007009 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007010 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007011 if (!containsSym) {
7012 if (!DisSymName.empty() && DisSymName == SymName) {
7013 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7014 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007015 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007016 continue;
7017 }
7018 // The __mh_execute_header is special and we need to deal with that fact
7019 // this symbol is before the start of the (__TEXT,__text) section and at the
7020 // address of the start of the __TEXT segment. This is because this symbol
7021 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7022 // start of the section in a standard MH_EXECUTE filetype.
7023 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7024 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7025 return;
7026 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007027 // When this code is trying to disassemble a symbol at a time and in the
7028 // case there is only the __mh_execute_header symbol left as in a stripped
7029 // executable, we need to deal with this by ignoring this symbol so the
7030 // whole section is disassembled and this symbol is then not displayed.
7031 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7032 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7033 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007034 continue;
7035
Kevin Enderby6a221752015-03-17 17:10:57 +00007036 // If we are only disassembling one symbol see if this is that symbol.
7037 if (!DisSymName.empty() && DisSymName != SymName)
7038 continue;
7039
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007040 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007041 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007042 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007043 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007044 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007045
Tim Northoverf203ab52016-07-14 22:13:32 +00007046 if (Start > SectSize) {
7047 outs() << "section data ends, " << SymName
7048 << " lies outside valid range\n";
7049 return;
7050 }
7051
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007052 // Stop disassembling either at the beginning of the next symbol or at
7053 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007054 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007055 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007056 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007057 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007058 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007059 if (!STOrErr)
7060 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007061 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007062 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007063 containsNextSym =
7064 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007065 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007066 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007067 break;
7068 }
7069 ++NextSymIdx;
7070 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007071
Tim Northoverf203ab52016-07-14 22:13:32 +00007072 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007073 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007074
7075 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007076
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007077 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007078 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7079
7080 // We only need the dedicated Thumb target if there's a real choice
7081 // (i.e. we're not targeting M-class) and the function is Thumb.
7082 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007083
Kevin Enderbyc138da32017-02-06 18:43:18 +00007084 // If we are not specifying a symbol to start disassembly with and this
7085 // is the first symbol in the section but not at the start of the section
7086 // then move the disassembly index to the start of the section and
7087 // don't print the symbol name just yet. This is so the bytes before the
7088 // first symbol are disassembled.
7089 uint64_t SymbolStart = Start;
7090 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7091 FirstSymbolAtSectionStart = false;
7092 Start = 0;
7093 }
7094 else
7095 outs() << SymName << ":\n";
7096
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007097 DILineInfo lastLine;
7098 for (uint64_t Index = Start; Index < End; Index += Size) {
7099 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007100
Kevin Enderbyc138da32017-02-06 18:43:18 +00007101 // If this is the first symbol in the section and it was not at the
7102 // start of the section, see if we are at its Index now and if so print
7103 // the symbol name.
7104 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7105 outs() << SymName << ":\n";
7106
Kevin Enderbybf246f52014-09-24 23:08:22 +00007107 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007108 if (!NoLeadingAddr) {
7109 if (FullLeadingAddr) {
7110 if (MachOOF->is64Bit())
7111 outs() << format("%016" PRIx64, PC);
7112 else
7113 outs() << format("%08" PRIx64, PC);
7114 } else {
7115 outs() << format("%8" PRIx64 ":", PC);
7116 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007117 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007118 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007119 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007120
7121 // Check the data in code table here to see if this is data not an
7122 // instruction to be disassembled.
7123 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007124 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007125 dice_table_iterator DTI =
7126 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7127 compareDiceTableEntries);
7128 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007129 uint16_t Length;
7130 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007131 uint16_t Kind;
7132 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007133 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007134 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7135 (PC == (DTI->first + Length - 1)) && (Length & 1))
7136 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007137 continue;
7138 }
7139
Kevin Enderbybf246f52014-09-24 23:08:22 +00007140 SmallVector<char, 64> AnnotationsBytes;
7141 raw_svector_ostream Annotations(AnnotationsBytes);
7142
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007143 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007144 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007145 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007146 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007147 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007148 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007149 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007150 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007151 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007152 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007153 }
7154 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007155 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007156 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007157 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007158 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007159 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007160 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007161
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007162 // Print debug info.
7163 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007164 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007165 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007166 if (dli != lastLine && dli.Line != 0)
7167 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7168 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007169 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007170 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007171 outs() << "\n";
7172 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007173 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007174 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007175 outs() << format("\t.byte 0x%02x #bad opcode\n",
7176 *(Bytes.data() + Index) & 0xff);
7177 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007178 } else if (Arch == Triple::aarch64 ||
7179 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007180 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7181 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7182 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7183 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7184 outs() << format("\t.long\t0x%08x\n", opcode);
7185 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007186 } else if (Arch == Triple::arm) {
7187 assert(IsThumb && "ARM mode should have been dealt with above");
7188 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7189 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7190 outs() << format("\t.short\t0x%04x\n", opcode);
7191 Size = 2;
7192 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007193 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7194 if (Size == 0)
7195 Size = 1; // skip illegible bytes
7196 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007197 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007198 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007199 // Now that we are done disassembled the first symbol set the bool that
7200 // were doing this to false.
7201 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007202 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007203 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007204 // Reading the symbol table didn't work, disassemble the whole section.
7205 uint64_t SectAddress = Sections[SectIdx].getAddress();
7206 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007207 uint64_t InstSize;
7208 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007209 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007210
Kevin Enderbybf246f52014-09-24 23:08:22 +00007211 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007212 SmallVector<char, 64> AnnotationsBytes;
7213 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007214 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007215 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007216 if (!NoLeadingAddr) {
7217 if (FullLeadingAddr) {
7218 if (MachOOF->is64Bit())
7219 outs() << format("%016" PRIx64, PC);
7220 else
7221 outs() << format("%08" PRIx64, PC);
7222 } else {
7223 outs() << format("%8" PRIx64 ":", PC);
7224 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007225 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007226 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007227 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007228 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007229 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007230 StringRef AnnotationsStr = Annotations.str();
7231 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007232 outs() << "\n";
7233 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007234 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007235 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007236 outs() << format("\t.byte 0x%02x #bad opcode\n",
7237 *(Bytes.data() + Index) & 0xff);
7238 InstSize = 1; // skip exactly one illegible byte and move on.
7239 } else {
7240 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7241 if (InstSize == 0)
7242 InstSize = 1; // skip illegible bytes
7243 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007244 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007245 }
7246 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007247 // The TripleName's need to be reset if we are called again for a different
7248 // archtecture.
7249 TripleName = "";
7250 ThumbTripleName = "";
7251
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007252 if (SymbolizerInfo.method != nullptr)
7253 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007254 if (SymbolizerInfo.demangled_name != nullptr)
7255 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007256 if (ThumbSymbolizerInfo.method != nullptr)
7257 free(ThumbSymbolizerInfo.method);
7258 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7259 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007260 }
7261}
Tim Northover4bd286a2014-08-01 13:07:19 +00007262
Tim Northover39c70bb2014-08-12 11:52:59 +00007263//===----------------------------------------------------------------------===//
7264// __compact_unwind section dumping
7265//===----------------------------------------------------------------------===//
7266
Tim Northover4bd286a2014-08-01 13:07:19 +00007267namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007268
Tim Northover3a4e1c72018-01-23 13:51:57 +00007269template <typename T>
7270static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007271 using llvm::support::little;
7272 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007273
Tim Northover3a4e1c72018-01-23 13:51:57 +00007274 if (Offset + sizeof(T) > Contents.size()) {
7275 outs() << "warning: attempt to read past end of buffer\n";
7276 return T();
7277 }
7278
7279 uint64_t Val =
7280 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7281 return Val;
7282}
7283
7284template <typename T>
7285static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7286 T Val = read<T>(Contents, Offset);
7287 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007288 return Val;
7289}
Tim Northover39c70bb2014-08-12 11:52:59 +00007290
Tim Northover4bd286a2014-08-01 13:07:19 +00007291struct CompactUnwindEntry {
7292 uint32_t OffsetInSection;
7293
7294 uint64_t FunctionAddr;
7295 uint32_t Length;
7296 uint32_t CompactEncoding;
7297 uint64_t PersonalityAddr;
7298 uint64_t LSDAAddr;
7299
7300 RelocationRef FunctionReloc;
7301 RelocationRef PersonalityReloc;
7302 RelocationRef LSDAReloc;
7303
7304 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007305 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007306 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007307 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007308 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007309 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007310 }
7311
7312private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007313 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7314 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7315 Length = readNext<uint32_t>(Contents, Offset);
7316 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7317 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7318 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007319 }
7320};
7321}
7322
7323/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7324/// and data being relocated, determine the best base Name and Addend to use for
7325/// display purposes.
7326///
7327/// 1. An Extern relocation will directly reference a symbol (and the data is
7328/// then already an addend), so use that.
7329/// 2. Otherwise the data is an offset in the object file's layout; try to find
7330// a symbol before it in the same section, and use the offset from there.
7331/// 3. Finally, if all that fails, fall back to an offset from the start of the
7332/// referenced section.
7333static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7334 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007335 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007336 StringRef &Name, uint64_t &Addend) {
7337 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007338 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007339 if (!NameOrErr)
7340 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007341 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007342 Addend = Addr;
7343 return;
7344 }
7345
7346 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007347 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007348
Rafael Espindola80291272014-10-08 15:28:58 +00007349 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007350
7351 auto Sym = Symbols.upper_bound(Addr);
7352 if (Sym == Symbols.begin()) {
7353 // The first symbol in the object is after this reference, the best we can
7354 // do is section-relative notation.
7355 RelocSection.getName(Name);
7356 Addend = Addr - SectionAddr;
7357 return;
7358 }
7359
7360 // Go back one so that SymbolAddress <= Addr.
7361 --Sym;
7362
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007363 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007364 if (!SectOrErr)
7365 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007366 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007367 if (RelocSection == *SymSection) {
7368 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007369 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007370 if (!NameOrErr)
7371 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007372 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007373 Addend = Addr - Sym->first;
7374 return;
7375 }
7376
7377 // There is a symbol before this reference, but it's in a different
7378 // section. Probably not helpful to mention it, so use the section name.
7379 RelocSection.getName(Name);
7380 Addend = Addr - SectionAddr;
7381}
7382
7383static void printUnwindRelocDest(const MachOObjectFile *Obj,
7384 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007385 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007386 StringRef Name;
7387 uint64_t Addend;
7388
Rafael Espindola854038e2015-06-26 14:51:16 +00007389 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007390 return;
7391
Tim Northover4bd286a2014-08-01 13:07:19 +00007392 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7393
7394 outs() << Name;
7395 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007396 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007397}
7398
7399static void
7400printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7401 std::map<uint64_t, SymbolRef> &Symbols,
7402 const SectionRef &CompactUnwind) {
7403
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007404 if (!Obj->isLittleEndian()) {
7405 outs() << "Skipping big-endian __compact_unwind section\n";
7406 return;
7407 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007408
7409 bool Is64 = Obj->is64Bit();
7410 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7411 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7412
7413 StringRef Contents;
7414 CompactUnwind.getContents(Contents);
7415
7416 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7417
7418 // First populate the initial raw offsets, encodings and so on from the entry.
7419 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007420 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007421 CompactUnwinds.push_back(Entry);
7422 }
7423
7424 // Next we need to look at the relocations to find out what objects are
7425 // actually being referred to.
7426 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007427 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007428
7429 uint32_t EntryIdx = RelocAddress / EntrySize;
7430 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7431 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7432
7433 if (OffsetInEntry == 0)
7434 Entry.FunctionReloc = Reloc;
7435 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7436 Entry.PersonalityReloc = Reloc;
7437 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7438 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007439 else {
7440 outs() << "Invalid relocation in __compact_unwind section\n";
7441 return;
7442 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007443 }
7444
7445 // Finally, we're ready to print the data we've gathered.
7446 outs() << "Contents of __compact_unwind section:\n";
7447 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007448 outs() << " Entry at offset "
7449 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007450
7451 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007452 outs() << " start: " << format("0x%" PRIx64,
7453 Entry.FunctionAddr) << ' ';
7454 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007455 outs() << '\n';
7456
7457 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007458 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7459 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007460 // 3. The 32-bit compact encoding.
7461 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007462 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007463
7464 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007465 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007466 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007467 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007468 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7469 Entry.PersonalityAddr);
7470 outs() << '\n';
7471 }
7472
7473 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007474 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007475 outs() << " LSDA: " << format("0x%" PRIx64,
7476 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007477 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7478 outs() << '\n';
7479 }
7480 }
7481}
7482
Tim Northover39c70bb2014-08-12 11:52:59 +00007483//===----------------------------------------------------------------------===//
7484// __unwind_info section dumping
7485//===----------------------------------------------------------------------===//
7486
Tim Northover3a4e1c72018-01-23 13:51:57 +00007487static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7488 ptrdiff_t Pos = 0;
7489 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007490 (void)Kind;
7491 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7492
Tim Northover3a4e1c72018-01-23 13:51:57 +00007493 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7494 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007495
Tim Northover3a4e1c72018-01-23 13:51:57 +00007496 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007497 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007498 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7499 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007500
7501 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007502 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7503 << ", "
7504 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007505 }
7506}
7507
7508static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007509 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007510 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007511 ptrdiff_t Pos = 0;
7512 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007513 (void)Kind;
7514 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7515
Tim Northover3a4e1c72018-01-23 13:51:57 +00007516 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7517 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007518
Tim Northover3a4e1c72018-01-23 13:51:57 +00007519 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7520 readNext<uint16_t>(PageData, Pos);
7521 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007522
Tim Northover3a4e1c72018-01-23 13:51:57 +00007523 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007524 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007525 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007526 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7527 uint32_t EncodingIdx = Entry >> 24;
7528
7529 uint32_t Encoding;
7530 if (EncodingIdx < CommonEncodings.size())
7531 Encoding = CommonEncodings[EncodingIdx];
7532 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007533 Encoding = read<uint32_t>(PageEncodings,
7534 sizeof(uint32_t) *
7535 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007536
7537 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007538 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7539 << ", "
7540 << "encoding[" << EncodingIdx
7541 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007542 }
7543}
7544
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007545static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7546 std::map<uint64_t, SymbolRef> &Symbols,
7547 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007548
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007549 if (!Obj->isLittleEndian()) {
7550 outs() << "Skipping big-endian __unwind_info section\n";
7551 return;
7552 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007553
7554 outs() << "Contents of __unwind_info section:\n";
7555
7556 StringRef Contents;
7557 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007558 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007559
7560 //===----------------------------------
7561 // Section header
7562 //===----------------------------------
7563
Tim Northover3a4e1c72018-01-23 13:51:57 +00007564 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007565 outs() << " Version: "
7566 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007567 if (Version != 1) {
7568 outs() << " Skipping section with unknown version\n";
7569 return;
7570 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007571
Tim Northover3a4e1c72018-01-23 13:51:57 +00007572 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007573 outs() << " Common encodings array section offset: "
7574 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007575 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007576 outs() << " Number of common encodings in array: "
7577 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7578
Tim Northover3a4e1c72018-01-23 13:51:57 +00007579 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007580 outs() << " Personality function array section offset: "
7581 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007582 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007583 outs() << " Number of personality functions in array: "
7584 << format("0x%" PRIx32, NumPersonalities) << '\n';
7585
Tim Northover3a4e1c72018-01-23 13:51:57 +00007586 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007587 outs() << " Index array section offset: "
7588 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007589 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007590 outs() << " Number of indices in array: "
7591 << format("0x%" PRIx32, NumIndices) << '\n';
7592
7593 //===----------------------------------
7594 // A shared list of common encodings
7595 //===----------------------------------
7596
7597 // These occupy indices in the range [0, N] whenever an encoding is referenced
7598 // from a compressed 2nd level index table. In practice the linker only
7599 // creates ~128 of these, so that indices are available to embed encodings in
7600 // the 2nd level index.
7601
7602 SmallVector<uint32_t, 64> CommonEncodings;
7603 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007604 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007605 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007606 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007607 CommonEncodings.push_back(Encoding);
7608
7609 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7610 << '\n';
7611 }
7612
Tim Northover39c70bb2014-08-12 11:52:59 +00007613 //===----------------------------------
7614 // Personality functions used in this executable
7615 //===----------------------------------
7616
7617 // There should be only a handful of these (one per source language,
7618 // roughly). Particularly since they only get 2 bits in the compact encoding.
7619
7620 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007621 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007622 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007623 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007624 outs() << " personality[" << i + 1
7625 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7626 }
7627
7628 //===----------------------------------
7629 // The level 1 index entries
7630 //===----------------------------------
7631
7632 // These specify an approximate place to start searching for the more detailed
7633 // information, sorted by PC.
7634
7635 struct IndexEntry {
7636 uint32_t FunctionOffset;
7637 uint32_t SecondLevelPageStart;
7638 uint32_t LSDAStart;
7639 };
7640
7641 SmallVector<IndexEntry, 4> IndexEntries;
7642
7643 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007644 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007645 for (unsigned i = 0; i < NumIndices; ++i) {
7646 IndexEntry Entry;
7647
Tim Northover3a4e1c72018-01-23 13:51:57 +00007648 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7649 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7650 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007651 IndexEntries.push_back(Entry);
7652
7653 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007654 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7655 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007656 << "2nd level page offset="
7657 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007658 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007659 }
7660
Tim Northover39c70bb2014-08-12 11:52:59 +00007661 //===----------------------------------
7662 // Next come the LSDA tables
7663 //===----------------------------------
7664
7665 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7666 // the first top-level index's LSDAOffset to the last (sentinel).
7667
7668 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007669 Pos = IndexEntries[0].LSDAStart;
7670 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7671 int NumLSDAs =
7672 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7673
Tim Northover39c70bb2014-08-12 11:52:59 +00007674 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007675 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7676 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007677 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007678 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7679 << ", "
7680 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007681 }
7682
7683 //===----------------------------------
7684 // Finally, the 2nd level indices
7685 //===----------------------------------
7686
7687 // Generally these are 4K in size, and have 2 possible forms:
7688 // + Regular stores up to 511 entries with disparate encodings
7689 // + Compressed stores up to 1021 entries if few enough compact encoding
7690 // values are used.
7691 outs() << " Second level indices:\n";
7692 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7693 // The final sentinel top-level index has no associated 2nd level page
7694 if (IndexEntries[i].SecondLevelPageStart == 0)
7695 break;
7696
7697 outs() << " Second level index[" << i << "]: "
7698 << "offset in section="
7699 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7700 << ", "
7701 << "base function offset="
7702 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7703
Tim Northover3a4e1c72018-01-23 13:51:57 +00007704 Pos = IndexEntries[i].SecondLevelPageStart;
7705 if (Pos + sizeof(uint32_t) > Contents.size()) {
7706 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7707 continue;
7708 }
7709
7710 uint32_t Kind =
7711 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007712 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007713 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007714 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007715 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7716 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007717 CommonEncodings);
7718 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007719 outs() << " Skipping 2nd level page with unknown kind " << Kind
7720 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007721 }
7722}
7723
Tim Northover4bd286a2014-08-01 13:07:19 +00007724void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7725 std::map<uint64_t, SymbolRef> Symbols;
7726 for (const SymbolRef &SymRef : Obj->symbols()) {
7727 // Discard any undefined or absolute symbols. They're not going to take part
7728 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007729 auto SectOrErr = SymRef.getSection();
7730 if (!SectOrErr) {
7731 // TODO: Actually report errors helpfully.
7732 consumeError(SectOrErr.takeError());
7733 continue;
7734 }
7735 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007736 if (Section == Obj->section_end())
7737 continue;
7738
Rafael Espindoladea00162015-07-03 17:44:18 +00007739 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007740 Symbols.insert(std::make_pair(Addr, SymRef));
7741 }
7742
7743 for (const SectionRef &Section : Obj->sections()) {
7744 StringRef SectName;
7745 Section.getName(SectName);
7746 if (SectName == "__compact_unwind")
7747 printMachOCompactUnwindSection(Obj, Symbols, Section);
7748 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007749 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007750 }
7751}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007752
7753static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7754 uint32_t cpusubtype, uint32_t filetype,
7755 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7756 bool verbose) {
7757 outs() << "Mach header\n";
7758 outs() << " magic cputype cpusubtype caps filetype ncmds "
7759 "sizeofcmds flags\n";
7760 if (verbose) {
7761 if (magic == MachO::MH_MAGIC)
7762 outs() << " MH_MAGIC";
7763 else if (magic == MachO::MH_MAGIC_64)
7764 outs() << "MH_MAGIC_64";
7765 else
7766 outs() << format(" 0x%08" PRIx32, magic);
7767 switch (cputype) {
7768 case MachO::CPU_TYPE_I386:
7769 outs() << " I386";
7770 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7771 case MachO::CPU_SUBTYPE_I386_ALL:
7772 outs() << " ALL";
7773 break;
7774 default:
7775 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7776 break;
7777 }
7778 break;
7779 case MachO::CPU_TYPE_X86_64:
7780 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007781 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7782 case MachO::CPU_SUBTYPE_X86_64_ALL:
7783 outs() << " ALL";
7784 break;
7785 case MachO::CPU_SUBTYPE_X86_64_H:
7786 outs() << " Haswell";
7787 break;
7788 default:
7789 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7790 break;
7791 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007792 break;
7793 case MachO::CPU_TYPE_ARM:
7794 outs() << " ARM";
7795 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7796 case MachO::CPU_SUBTYPE_ARM_ALL:
7797 outs() << " ALL";
7798 break;
7799 case MachO::CPU_SUBTYPE_ARM_V4T:
7800 outs() << " V4T";
7801 break;
7802 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7803 outs() << " V5TEJ";
7804 break;
7805 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7806 outs() << " XSCALE";
7807 break;
7808 case MachO::CPU_SUBTYPE_ARM_V6:
7809 outs() << " V6";
7810 break;
7811 case MachO::CPU_SUBTYPE_ARM_V6M:
7812 outs() << " V6M";
7813 break;
7814 case MachO::CPU_SUBTYPE_ARM_V7:
7815 outs() << " V7";
7816 break;
7817 case MachO::CPU_SUBTYPE_ARM_V7EM:
7818 outs() << " V7EM";
7819 break;
7820 case MachO::CPU_SUBTYPE_ARM_V7K:
7821 outs() << " V7K";
7822 break;
7823 case MachO::CPU_SUBTYPE_ARM_V7M:
7824 outs() << " V7M";
7825 break;
7826 case MachO::CPU_SUBTYPE_ARM_V7S:
7827 outs() << " V7S";
7828 break;
7829 default:
7830 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7831 break;
7832 }
7833 break;
7834 case MachO::CPU_TYPE_ARM64:
7835 outs() << " ARM64";
7836 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7837 case MachO::CPU_SUBTYPE_ARM64_ALL:
7838 outs() << " ALL";
7839 break;
7840 default:
7841 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7842 break;
7843 }
7844 break;
7845 case MachO::CPU_TYPE_POWERPC:
7846 outs() << " PPC";
7847 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7848 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7849 outs() << " ALL";
7850 break;
7851 default:
7852 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7853 break;
7854 }
7855 break;
7856 case MachO::CPU_TYPE_POWERPC64:
7857 outs() << " PPC64";
7858 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7859 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7860 outs() << " ALL";
7861 break;
7862 default:
7863 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7864 break;
7865 }
7866 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007867 default:
7868 outs() << format(" %7d", cputype);
7869 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7870 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007871 }
7872 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007873 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007874 } else {
7875 outs() << format(" 0x%02" PRIx32,
7876 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7877 }
7878 switch (filetype) {
7879 case MachO::MH_OBJECT:
7880 outs() << " OBJECT";
7881 break;
7882 case MachO::MH_EXECUTE:
7883 outs() << " EXECUTE";
7884 break;
7885 case MachO::MH_FVMLIB:
7886 outs() << " FVMLIB";
7887 break;
7888 case MachO::MH_CORE:
7889 outs() << " CORE";
7890 break;
7891 case MachO::MH_PRELOAD:
7892 outs() << " PRELOAD";
7893 break;
7894 case MachO::MH_DYLIB:
7895 outs() << " DYLIB";
7896 break;
7897 case MachO::MH_DYLIB_STUB:
7898 outs() << " DYLIB_STUB";
7899 break;
7900 case MachO::MH_DYLINKER:
7901 outs() << " DYLINKER";
7902 break;
7903 case MachO::MH_BUNDLE:
7904 outs() << " BUNDLE";
7905 break;
7906 case MachO::MH_DSYM:
7907 outs() << " DSYM";
7908 break;
7909 case MachO::MH_KEXT_BUNDLE:
7910 outs() << " KEXTBUNDLE";
7911 break;
7912 default:
7913 outs() << format(" %10u", filetype);
7914 break;
7915 }
7916 outs() << format(" %5u", ncmds);
7917 outs() << format(" %10u", sizeofcmds);
7918 uint32_t f = flags;
7919 if (f & MachO::MH_NOUNDEFS) {
7920 outs() << " NOUNDEFS";
7921 f &= ~MachO::MH_NOUNDEFS;
7922 }
7923 if (f & MachO::MH_INCRLINK) {
7924 outs() << " INCRLINK";
7925 f &= ~MachO::MH_INCRLINK;
7926 }
7927 if (f & MachO::MH_DYLDLINK) {
7928 outs() << " DYLDLINK";
7929 f &= ~MachO::MH_DYLDLINK;
7930 }
7931 if (f & MachO::MH_BINDATLOAD) {
7932 outs() << " BINDATLOAD";
7933 f &= ~MachO::MH_BINDATLOAD;
7934 }
7935 if (f & MachO::MH_PREBOUND) {
7936 outs() << " PREBOUND";
7937 f &= ~MachO::MH_PREBOUND;
7938 }
7939 if (f & MachO::MH_SPLIT_SEGS) {
7940 outs() << " SPLIT_SEGS";
7941 f &= ~MachO::MH_SPLIT_SEGS;
7942 }
7943 if (f & MachO::MH_LAZY_INIT) {
7944 outs() << " LAZY_INIT";
7945 f &= ~MachO::MH_LAZY_INIT;
7946 }
7947 if (f & MachO::MH_TWOLEVEL) {
7948 outs() << " TWOLEVEL";
7949 f &= ~MachO::MH_TWOLEVEL;
7950 }
7951 if (f & MachO::MH_FORCE_FLAT) {
7952 outs() << " FORCE_FLAT";
7953 f &= ~MachO::MH_FORCE_FLAT;
7954 }
7955 if (f & MachO::MH_NOMULTIDEFS) {
7956 outs() << " NOMULTIDEFS";
7957 f &= ~MachO::MH_NOMULTIDEFS;
7958 }
7959 if (f & MachO::MH_NOFIXPREBINDING) {
7960 outs() << " NOFIXPREBINDING";
7961 f &= ~MachO::MH_NOFIXPREBINDING;
7962 }
7963 if (f & MachO::MH_PREBINDABLE) {
7964 outs() << " PREBINDABLE";
7965 f &= ~MachO::MH_PREBINDABLE;
7966 }
7967 if (f & MachO::MH_ALLMODSBOUND) {
7968 outs() << " ALLMODSBOUND";
7969 f &= ~MachO::MH_ALLMODSBOUND;
7970 }
7971 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7972 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7973 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7974 }
7975 if (f & MachO::MH_CANONICAL) {
7976 outs() << " CANONICAL";
7977 f &= ~MachO::MH_CANONICAL;
7978 }
7979 if (f & MachO::MH_WEAK_DEFINES) {
7980 outs() << " WEAK_DEFINES";
7981 f &= ~MachO::MH_WEAK_DEFINES;
7982 }
7983 if (f & MachO::MH_BINDS_TO_WEAK) {
7984 outs() << " BINDS_TO_WEAK";
7985 f &= ~MachO::MH_BINDS_TO_WEAK;
7986 }
7987 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7988 outs() << " ALLOW_STACK_EXECUTION";
7989 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7990 }
7991 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7992 outs() << " DEAD_STRIPPABLE_DYLIB";
7993 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7994 }
7995 if (f & MachO::MH_PIE) {
7996 outs() << " PIE";
7997 f &= ~MachO::MH_PIE;
7998 }
7999 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8000 outs() << " NO_REEXPORTED_DYLIBS";
8001 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8002 }
8003 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8004 outs() << " MH_HAS_TLV_DESCRIPTORS";
8005 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8006 }
8007 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8008 outs() << " MH_NO_HEAP_EXECUTION";
8009 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8010 }
8011 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8012 outs() << " APP_EXTENSION_SAFE";
8013 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8014 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008015 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8016 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8017 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8018 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008019 if (f != 0 || flags == 0)
8020 outs() << format(" 0x%08" PRIx32, f);
8021 } else {
8022 outs() << format(" 0x%08" PRIx32, magic);
8023 outs() << format(" %7d", cputype);
8024 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8025 outs() << format(" 0x%02" PRIx32,
8026 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8027 outs() << format(" %10u", filetype);
8028 outs() << format(" %5u", ncmds);
8029 outs() << format(" %10u", sizeofcmds);
8030 outs() << format(" 0x%08" PRIx32, flags);
8031 }
8032 outs() << "\n";
8033}
8034
Kevin Enderby956366c2014-08-29 22:30:52 +00008035static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8036 StringRef SegName, uint64_t vmaddr,
8037 uint64_t vmsize, uint64_t fileoff,
8038 uint64_t filesize, uint32_t maxprot,
8039 uint32_t initprot, uint32_t nsects,
8040 uint32_t flags, uint32_t object_size,
8041 bool verbose) {
8042 uint64_t expected_cmdsize;
8043 if (cmd == MachO::LC_SEGMENT) {
8044 outs() << " cmd LC_SEGMENT\n";
8045 expected_cmdsize = nsects;
8046 expected_cmdsize *= sizeof(struct MachO::section);
8047 expected_cmdsize += sizeof(struct MachO::segment_command);
8048 } else {
8049 outs() << " cmd LC_SEGMENT_64\n";
8050 expected_cmdsize = nsects;
8051 expected_cmdsize *= sizeof(struct MachO::section_64);
8052 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8053 }
8054 outs() << " cmdsize " << cmdsize;
8055 if (cmdsize != expected_cmdsize)
8056 outs() << " Inconsistent size\n";
8057 else
8058 outs() << "\n";
8059 outs() << " segname " << SegName << "\n";
8060 if (cmd == MachO::LC_SEGMENT_64) {
8061 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8062 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8063 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008064 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8065 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008066 }
8067 outs() << " fileoff " << fileoff;
8068 if (fileoff > object_size)
8069 outs() << " (past end of file)\n";
8070 else
8071 outs() << "\n";
8072 outs() << " filesize " << filesize;
8073 if (fileoff + filesize > object_size)
8074 outs() << " (past end of file)\n";
8075 else
8076 outs() << "\n";
8077 if (verbose) {
8078 if ((maxprot &
8079 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8080 MachO::VM_PROT_EXECUTE)) != 0)
8081 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8082 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008083 outs() << " maxprot ";
8084 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8085 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8086 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008087 }
8088 if ((initprot &
8089 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8090 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008091 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008092 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008093 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008094 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8095 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8096 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008097 }
8098 } else {
8099 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8100 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8101 }
8102 outs() << " nsects " << nsects << "\n";
8103 if (verbose) {
8104 outs() << " flags";
8105 if (flags == 0)
8106 outs() << " (none)\n";
8107 else {
8108 if (flags & MachO::SG_HIGHVM) {
8109 outs() << " HIGHVM";
8110 flags &= ~MachO::SG_HIGHVM;
8111 }
8112 if (flags & MachO::SG_FVMLIB) {
8113 outs() << " FVMLIB";
8114 flags &= ~MachO::SG_FVMLIB;
8115 }
8116 if (flags & MachO::SG_NORELOC) {
8117 outs() << " NORELOC";
8118 flags &= ~MachO::SG_NORELOC;
8119 }
8120 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8121 outs() << " PROTECTED_VERSION_1";
8122 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8123 }
8124 if (flags)
8125 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8126 else
8127 outs() << "\n";
8128 }
8129 } else {
8130 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8131 }
8132}
8133
8134static void PrintSection(const char *sectname, const char *segname,
8135 uint64_t addr, uint64_t size, uint32_t offset,
8136 uint32_t align, uint32_t reloff, uint32_t nreloc,
8137 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8138 uint32_t cmd, const char *sg_segname,
8139 uint32_t filetype, uint32_t object_size,
8140 bool verbose) {
8141 outs() << "Section\n";
8142 outs() << " sectname " << format("%.16s\n", sectname);
8143 outs() << " segname " << format("%.16s", segname);
8144 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8145 outs() << " (does not match segment)\n";
8146 else
8147 outs() << "\n";
8148 if (cmd == MachO::LC_SEGMENT_64) {
8149 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8150 outs() << " size " << format("0x%016" PRIx64, size);
8151 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008152 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8153 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008154 }
8155 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8156 outs() << " (past end of file)\n";
8157 else
8158 outs() << "\n";
8159 outs() << " offset " << offset;
8160 if (offset > object_size)
8161 outs() << " (past end of file)\n";
8162 else
8163 outs() << "\n";
8164 uint32_t align_shifted = 1 << align;
8165 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8166 outs() << " reloff " << reloff;
8167 if (reloff > object_size)
8168 outs() << " (past end of file)\n";
8169 else
8170 outs() << "\n";
8171 outs() << " nreloc " << nreloc;
8172 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8173 outs() << " (past end of file)\n";
8174 else
8175 outs() << "\n";
8176 uint32_t section_type = flags & MachO::SECTION_TYPE;
8177 if (verbose) {
8178 outs() << " type";
8179 if (section_type == MachO::S_REGULAR)
8180 outs() << " S_REGULAR\n";
8181 else if (section_type == MachO::S_ZEROFILL)
8182 outs() << " S_ZEROFILL\n";
8183 else if (section_type == MachO::S_CSTRING_LITERALS)
8184 outs() << " S_CSTRING_LITERALS\n";
8185 else if (section_type == MachO::S_4BYTE_LITERALS)
8186 outs() << " S_4BYTE_LITERALS\n";
8187 else if (section_type == MachO::S_8BYTE_LITERALS)
8188 outs() << " S_8BYTE_LITERALS\n";
8189 else if (section_type == MachO::S_16BYTE_LITERALS)
8190 outs() << " S_16BYTE_LITERALS\n";
8191 else if (section_type == MachO::S_LITERAL_POINTERS)
8192 outs() << " S_LITERAL_POINTERS\n";
8193 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8194 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8195 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8196 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8197 else if (section_type == MachO::S_SYMBOL_STUBS)
8198 outs() << " S_SYMBOL_STUBS\n";
8199 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8200 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8201 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8202 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8203 else if (section_type == MachO::S_COALESCED)
8204 outs() << " S_COALESCED\n";
8205 else if (section_type == MachO::S_INTERPOSING)
8206 outs() << " S_INTERPOSING\n";
8207 else if (section_type == MachO::S_DTRACE_DOF)
8208 outs() << " S_DTRACE_DOF\n";
8209 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8210 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8211 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8212 outs() << " S_THREAD_LOCAL_REGULAR\n";
8213 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8214 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8215 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8216 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8217 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8218 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8219 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8220 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8221 else
8222 outs() << format("0x%08" PRIx32, section_type) << "\n";
8223 outs() << "attributes";
8224 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8225 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8226 outs() << " PURE_INSTRUCTIONS";
8227 if (section_attributes & MachO::S_ATTR_NO_TOC)
8228 outs() << " NO_TOC";
8229 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8230 outs() << " STRIP_STATIC_SYMS";
8231 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8232 outs() << " NO_DEAD_STRIP";
8233 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8234 outs() << " LIVE_SUPPORT";
8235 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8236 outs() << " SELF_MODIFYING_CODE";
8237 if (section_attributes & MachO::S_ATTR_DEBUG)
8238 outs() << " DEBUG";
8239 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8240 outs() << " SOME_INSTRUCTIONS";
8241 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8242 outs() << " EXT_RELOC";
8243 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8244 outs() << " LOC_RELOC";
8245 if (section_attributes == 0)
8246 outs() << " (none)";
8247 outs() << "\n";
8248 } else
8249 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8250 outs() << " reserved1 " << reserved1;
8251 if (section_type == MachO::S_SYMBOL_STUBS ||
8252 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8253 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8254 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8255 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8256 outs() << " (index into indirect symbol table)\n";
8257 else
8258 outs() << "\n";
8259 outs() << " reserved2 " << reserved2;
8260 if (section_type == MachO::S_SYMBOL_STUBS)
8261 outs() << " (size of stubs)\n";
8262 else
8263 outs() << "\n";
8264}
8265
David Majnemer73cc6ff2014-11-13 19:48:56 +00008266static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008267 uint32_t object_size) {
8268 outs() << " cmd LC_SYMTAB\n";
8269 outs() << " cmdsize " << st.cmdsize;
8270 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8271 outs() << " Incorrect size\n";
8272 else
8273 outs() << "\n";
8274 outs() << " symoff " << st.symoff;
8275 if (st.symoff > object_size)
8276 outs() << " (past end of file)\n";
8277 else
8278 outs() << "\n";
8279 outs() << " nsyms " << st.nsyms;
8280 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008281 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008282 big_size = st.nsyms;
8283 big_size *= sizeof(struct MachO::nlist_64);
8284 big_size += st.symoff;
8285 if (big_size > object_size)
8286 outs() << " (past end of file)\n";
8287 else
8288 outs() << "\n";
8289 } else {
8290 big_size = st.nsyms;
8291 big_size *= sizeof(struct MachO::nlist);
8292 big_size += st.symoff;
8293 if (big_size > object_size)
8294 outs() << " (past end of file)\n";
8295 else
8296 outs() << "\n";
8297 }
8298 outs() << " stroff " << st.stroff;
8299 if (st.stroff > object_size)
8300 outs() << " (past end of file)\n";
8301 else
8302 outs() << "\n";
8303 outs() << " strsize " << st.strsize;
8304 big_size = st.stroff;
8305 big_size += st.strsize;
8306 if (big_size > object_size)
8307 outs() << " (past end of file)\n";
8308 else
8309 outs() << "\n";
8310}
8311
8312static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8313 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008314 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008315 outs() << " cmd LC_DYSYMTAB\n";
8316 outs() << " cmdsize " << dyst.cmdsize;
8317 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8318 outs() << " Incorrect size\n";
8319 else
8320 outs() << "\n";
8321 outs() << " ilocalsym " << dyst.ilocalsym;
8322 if (dyst.ilocalsym > nsyms)
8323 outs() << " (greater than the number of symbols)\n";
8324 else
8325 outs() << "\n";
8326 outs() << " nlocalsym " << dyst.nlocalsym;
8327 uint64_t big_size;
8328 big_size = dyst.ilocalsym;
8329 big_size += dyst.nlocalsym;
8330 if (big_size > nsyms)
8331 outs() << " (past the end of the symbol table)\n";
8332 else
8333 outs() << "\n";
8334 outs() << " iextdefsym " << dyst.iextdefsym;
8335 if (dyst.iextdefsym > nsyms)
8336 outs() << " (greater than the number of symbols)\n";
8337 else
8338 outs() << "\n";
8339 outs() << " nextdefsym " << dyst.nextdefsym;
8340 big_size = dyst.iextdefsym;
8341 big_size += dyst.nextdefsym;
8342 if (big_size > nsyms)
8343 outs() << " (past the end of the symbol table)\n";
8344 else
8345 outs() << "\n";
8346 outs() << " iundefsym " << dyst.iundefsym;
8347 if (dyst.iundefsym > nsyms)
8348 outs() << " (greater than the number of symbols)\n";
8349 else
8350 outs() << "\n";
8351 outs() << " nundefsym " << dyst.nundefsym;
8352 big_size = dyst.iundefsym;
8353 big_size += dyst.nundefsym;
8354 if (big_size > nsyms)
8355 outs() << " (past the end of the symbol table)\n";
8356 else
8357 outs() << "\n";
8358 outs() << " tocoff " << dyst.tocoff;
8359 if (dyst.tocoff > object_size)
8360 outs() << " (past end of file)\n";
8361 else
8362 outs() << "\n";
8363 outs() << " ntoc " << dyst.ntoc;
8364 big_size = dyst.ntoc;
8365 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8366 big_size += dyst.tocoff;
8367 if (big_size > object_size)
8368 outs() << " (past end of file)\n";
8369 else
8370 outs() << "\n";
8371 outs() << " modtaboff " << dyst.modtaboff;
8372 if (dyst.modtaboff > object_size)
8373 outs() << " (past end of file)\n";
8374 else
8375 outs() << "\n";
8376 outs() << " nmodtab " << dyst.nmodtab;
8377 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008378 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008379 modtabend = dyst.nmodtab;
8380 modtabend *= sizeof(struct MachO::dylib_module_64);
8381 modtabend += dyst.modtaboff;
8382 } else {
8383 modtabend = dyst.nmodtab;
8384 modtabend *= sizeof(struct MachO::dylib_module);
8385 modtabend += dyst.modtaboff;
8386 }
8387 if (modtabend > object_size)
8388 outs() << " (past end of file)\n";
8389 else
8390 outs() << "\n";
8391 outs() << " extrefsymoff " << dyst.extrefsymoff;
8392 if (dyst.extrefsymoff > object_size)
8393 outs() << " (past end of file)\n";
8394 else
8395 outs() << "\n";
8396 outs() << " nextrefsyms " << dyst.nextrefsyms;
8397 big_size = dyst.nextrefsyms;
8398 big_size *= sizeof(struct MachO::dylib_reference);
8399 big_size += dyst.extrefsymoff;
8400 if (big_size > object_size)
8401 outs() << " (past end of file)\n";
8402 else
8403 outs() << "\n";
8404 outs() << " indirectsymoff " << dyst.indirectsymoff;
8405 if (dyst.indirectsymoff > object_size)
8406 outs() << " (past end of file)\n";
8407 else
8408 outs() << "\n";
8409 outs() << " nindirectsyms " << dyst.nindirectsyms;
8410 big_size = dyst.nindirectsyms;
8411 big_size *= sizeof(uint32_t);
8412 big_size += dyst.indirectsymoff;
8413 if (big_size > object_size)
8414 outs() << " (past end of file)\n";
8415 else
8416 outs() << "\n";
8417 outs() << " extreloff " << dyst.extreloff;
8418 if (dyst.extreloff > object_size)
8419 outs() << " (past end of file)\n";
8420 else
8421 outs() << "\n";
8422 outs() << " nextrel " << dyst.nextrel;
8423 big_size = dyst.nextrel;
8424 big_size *= sizeof(struct MachO::relocation_info);
8425 big_size += dyst.extreloff;
8426 if (big_size > object_size)
8427 outs() << " (past end of file)\n";
8428 else
8429 outs() << "\n";
8430 outs() << " locreloff " << dyst.locreloff;
8431 if (dyst.locreloff > object_size)
8432 outs() << " (past end of file)\n";
8433 else
8434 outs() << "\n";
8435 outs() << " nlocrel " << dyst.nlocrel;
8436 big_size = dyst.nlocrel;
8437 big_size *= sizeof(struct MachO::relocation_info);
8438 big_size += dyst.locreloff;
8439 if (big_size > object_size)
8440 outs() << " (past end of file)\n";
8441 else
8442 outs() << "\n";
8443}
8444
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008445static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8446 uint32_t object_size) {
8447 if (dc.cmd == MachO::LC_DYLD_INFO)
8448 outs() << " cmd LC_DYLD_INFO\n";
8449 else
8450 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8451 outs() << " cmdsize " << dc.cmdsize;
8452 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8453 outs() << " Incorrect size\n";
8454 else
8455 outs() << "\n";
8456 outs() << " rebase_off " << dc.rebase_off;
8457 if (dc.rebase_off > object_size)
8458 outs() << " (past end of file)\n";
8459 else
8460 outs() << "\n";
8461 outs() << " rebase_size " << dc.rebase_size;
8462 uint64_t big_size;
8463 big_size = dc.rebase_off;
8464 big_size += dc.rebase_size;
8465 if (big_size > object_size)
8466 outs() << " (past end of file)\n";
8467 else
8468 outs() << "\n";
8469 outs() << " bind_off " << dc.bind_off;
8470 if (dc.bind_off > object_size)
8471 outs() << " (past end of file)\n";
8472 else
8473 outs() << "\n";
8474 outs() << " bind_size " << dc.bind_size;
8475 big_size = dc.bind_off;
8476 big_size += dc.bind_size;
8477 if (big_size > object_size)
8478 outs() << " (past end of file)\n";
8479 else
8480 outs() << "\n";
8481 outs() << " weak_bind_off " << dc.weak_bind_off;
8482 if (dc.weak_bind_off > object_size)
8483 outs() << " (past end of file)\n";
8484 else
8485 outs() << "\n";
8486 outs() << " weak_bind_size " << dc.weak_bind_size;
8487 big_size = dc.weak_bind_off;
8488 big_size += dc.weak_bind_size;
8489 if (big_size > object_size)
8490 outs() << " (past end of file)\n";
8491 else
8492 outs() << "\n";
8493 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8494 if (dc.lazy_bind_off > object_size)
8495 outs() << " (past end of file)\n";
8496 else
8497 outs() << "\n";
8498 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8499 big_size = dc.lazy_bind_off;
8500 big_size += dc.lazy_bind_size;
8501 if (big_size > object_size)
8502 outs() << " (past end of file)\n";
8503 else
8504 outs() << "\n";
8505 outs() << " export_off " << dc.export_off;
8506 if (dc.export_off > object_size)
8507 outs() << " (past end of file)\n";
8508 else
8509 outs() << "\n";
8510 outs() << " export_size " << dc.export_size;
8511 big_size = dc.export_off;
8512 big_size += dc.export_size;
8513 if (big_size > object_size)
8514 outs() << " (past end of file)\n";
8515 else
8516 outs() << "\n";
8517}
8518
8519static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8520 const char *Ptr) {
8521 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8522 outs() << " cmd LC_ID_DYLINKER\n";
8523 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8524 outs() << " cmd LC_LOAD_DYLINKER\n";
8525 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8526 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8527 else
8528 outs() << " cmd ?(" << dyld.cmd << ")\n";
8529 outs() << " cmdsize " << dyld.cmdsize;
8530 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8531 outs() << " Incorrect size\n";
8532 else
8533 outs() << "\n";
8534 if (dyld.name >= dyld.cmdsize)
8535 outs() << " name ?(bad offset " << dyld.name << ")\n";
8536 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008537 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008538 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8539 }
8540}
8541
8542static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8543 outs() << " cmd LC_UUID\n";
8544 outs() << " cmdsize " << uuid.cmdsize;
8545 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8546 outs() << " Incorrect size\n";
8547 else
8548 outs() << "\n";
8549 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008550 for (int i = 0; i < 16; ++i) {
8551 outs() << format("%02" PRIX32, uuid.uuid[i]);
8552 if (i == 3 || i == 5 || i == 7 || i == 9)
8553 outs() << "-";
8554 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008555 outs() << "\n";
8556}
8557
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008558static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008559 outs() << " cmd LC_RPATH\n";
8560 outs() << " cmdsize " << rpath.cmdsize;
8561 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8562 outs() << " Incorrect size\n";
8563 else
8564 outs() << "\n";
8565 if (rpath.path >= rpath.cmdsize)
8566 outs() << " path ?(bad offset " << rpath.path << ")\n";
8567 else {
8568 const char *P = (const char *)(Ptr) + rpath.path;
8569 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8570 }
8571}
8572
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008573static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008574 StringRef LoadCmdName;
8575 switch (vd.cmd) {
8576 case MachO::LC_VERSION_MIN_MACOSX:
8577 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8578 break;
8579 case MachO::LC_VERSION_MIN_IPHONEOS:
8580 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8581 break;
8582 case MachO::LC_VERSION_MIN_TVOS:
8583 LoadCmdName = "LC_VERSION_MIN_TVOS";
8584 break;
8585 case MachO::LC_VERSION_MIN_WATCHOS:
8586 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8587 break;
8588 default:
8589 llvm_unreachable("Unknown version min load command");
8590 }
8591
8592 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008593 outs() << " cmdsize " << vd.cmdsize;
8594 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8595 outs() << " Incorrect size\n";
8596 else
8597 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008598 outs() << " version "
8599 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8600 << MachOObjectFile::getVersionMinMinor(vd, false);
8601 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8602 if (Update != 0)
8603 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008604 outs() << "\n";
8605 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008606 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008607 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008608 outs() << " sdk "
8609 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8610 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008611 }
Davide Italiano56baef32015-08-26 12:26:11 +00008612 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8613 if (Update != 0)
8614 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008615 outs() << "\n";
8616}
8617
Kevin Enderbya4579c42017-01-19 17:36:31 +00008618static void PrintNoteLoadCommand(MachO::note_command Nt) {
8619 outs() << " cmd LC_NOTE\n";
8620 outs() << " cmdsize " << Nt.cmdsize;
8621 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8622 outs() << " Incorrect size\n";
8623 else
8624 outs() << "\n";
8625 const char *d = Nt.data_owner;
8626 outs() << "data_owner " << format("%.16s\n", d);
8627 outs() << " offset " << Nt.offset << "\n";
8628 outs() << " size " << Nt.size << "\n";
8629}
8630
Steven Wu5b54a422017-01-23 20:07:55 +00008631static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8632 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8633 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8634 << "\n";
8635}
8636
8637static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8638 MachO::build_version_command bd) {
8639 outs() << " cmd LC_BUILD_VERSION\n";
8640 outs() << " cmdsize " << bd.cmdsize;
8641 if (bd.cmdsize !=
8642 sizeof(struct MachO::build_version_command) +
8643 bd.ntools * sizeof(struct MachO::build_tool_version))
8644 outs() << " Incorrect size\n";
8645 else
8646 outs() << "\n";
8647 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8648 << "\n";
8649 if (bd.sdk)
8650 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8651 << "\n";
8652 else
8653 outs() << " sdk n/a\n";
8654 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8655 << "\n";
8656 outs() << " ntools " << bd.ntools << "\n";
8657 for (unsigned i = 0; i < bd.ntools; ++i) {
8658 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8659 PrintBuildToolVersion(bv);
8660 }
8661}
8662
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008663static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8664 outs() << " cmd LC_SOURCE_VERSION\n";
8665 outs() << " cmdsize " << sd.cmdsize;
8666 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8667 outs() << " Incorrect size\n";
8668 else
8669 outs() << "\n";
8670 uint64_t a = (sd.version >> 40) & 0xffffff;
8671 uint64_t b = (sd.version >> 30) & 0x3ff;
8672 uint64_t c = (sd.version >> 20) & 0x3ff;
8673 uint64_t d = (sd.version >> 10) & 0x3ff;
8674 uint64_t e = sd.version & 0x3ff;
8675 outs() << " version " << a << "." << b;
8676 if (e != 0)
8677 outs() << "." << c << "." << d << "." << e;
8678 else if (d != 0)
8679 outs() << "." << c << "." << d;
8680 else if (c != 0)
8681 outs() << "." << c;
8682 outs() << "\n";
8683}
8684
8685static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8686 outs() << " cmd LC_MAIN\n";
8687 outs() << " cmdsize " << ep.cmdsize;
8688 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8689 outs() << " Incorrect size\n";
8690 else
8691 outs() << "\n";
8692 outs() << " entryoff " << ep.entryoff << "\n";
8693 outs() << " stacksize " << ep.stacksize << "\n";
8694}
8695
Kevin Enderby0804f4672014-12-16 23:25:52 +00008696static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8697 uint32_t object_size) {
8698 outs() << " cmd LC_ENCRYPTION_INFO\n";
8699 outs() << " cmdsize " << ec.cmdsize;
8700 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8701 outs() << " Incorrect size\n";
8702 else
8703 outs() << "\n";
8704 outs() << " cryptoff " << ec.cryptoff;
8705 if (ec.cryptoff > object_size)
8706 outs() << " (past end of file)\n";
8707 else
8708 outs() << "\n";
8709 outs() << " cryptsize " << ec.cryptsize;
8710 if (ec.cryptsize > object_size)
8711 outs() << " (past end of file)\n";
8712 else
8713 outs() << "\n";
8714 outs() << " cryptid " << ec.cryptid << "\n";
8715}
8716
Kevin Enderby57538292014-12-17 01:01:30 +00008717static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008718 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008719 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8720 outs() << " cmdsize " << ec.cmdsize;
8721 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8722 outs() << " Incorrect size\n";
8723 else
8724 outs() << "\n";
8725 outs() << " cryptoff " << ec.cryptoff;
8726 if (ec.cryptoff > object_size)
8727 outs() << " (past end of file)\n";
8728 else
8729 outs() << "\n";
8730 outs() << " cryptsize " << ec.cryptsize;
8731 if (ec.cryptsize > object_size)
8732 outs() << " (past end of file)\n";
8733 else
8734 outs() << "\n";
8735 outs() << " cryptid " << ec.cryptid << "\n";
8736 outs() << " pad " << ec.pad << "\n";
8737}
8738
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008739static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8740 const char *Ptr) {
8741 outs() << " cmd LC_LINKER_OPTION\n";
8742 outs() << " cmdsize " << lo.cmdsize;
8743 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8744 outs() << " Incorrect size\n";
8745 else
8746 outs() << "\n";
8747 outs() << " count " << lo.count << "\n";
8748 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8749 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8750 uint32_t i = 0;
8751 while (left > 0) {
8752 while (*string == '\0' && left > 0) {
8753 string++;
8754 left--;
8755 }
8756 if (left > 0) {
8757 i++;
8758 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008759 uint32_t NullPos = StringRef(string, left).find('\0');
8760 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008761 string += len;
8762 left -= len;
8763 }
8764 }
8765 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008766 outs() << " count " << lo.count << " does not match number of strings "
8767 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008768}
8769
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008770static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8771 const char *Ptr) {
8772 outs() << " cmd LC_SUB_FRAMEWORK\n";
8773 outs() << " cmdsize " << sub.cmdsize;
8774 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8775 outs() << " Incorrect size\n";
8776 else
8777 outs() << "\n";
8778 if (sub.umbrella < sub.cmdsize) {
8779 const char *P = Ptr + sub.umbrella;
8780 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8781 } else {
8782 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8783 }
8784}
8785
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008786static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8787 const char *Ptr) {
8788 outs() << " cmd LC_SUB_UMBRELLA\n";
8789 outs() << " cmdsize " << sub.cmdsize;
8790 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8791 outs() << " Incorrect size\n";
8792 else
8793 outs() << "\n";
8794 if (sub.sub_umbrella < sub.cmdsize) {
8795 const char *P = Ptr + sub.sub_umbrella;
8796 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8797 } else {
8798 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8799 }
8800}
8801
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008802static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008803 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008804 outs() << " cmd LC_SUB_LIBRARY\n";
8805 outs() << " cmdsize " << sub.cmdsize;
8806 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8807 outs() << " Incorrect size\n";
8808 else
8809 outs() << "\n";
8810 if (sub.sub_library < sub.cmdsize) {
8811 const char *P = Ptr + sub.sub_library;
8812 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8813 } else {
8814 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8815 }
8816}
8817
Kevin Enderby186eac32014-12-19 21:06:24 +00008818static void PrintSubClientCommand(MachO::sub_client_command sub,
8819 const char *Ptr) {
8820 outs() << " cmd LC_SUB_CLIENT\n";
8821 outs() << " cmdsize " << sub.cmdsize;
8822 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8823 outs() << " Incorrect size\n";
8824 else
8825 outs() << "\n";
8826 if (sub.client < sub.cmdsize) {
8827 const char *P = Ptr + sub.client;
8828 outs() << " client " << P << " (offset " << sub.client << ")\n";
8829 } else {
8830 outs() << " client ?(bad offset " << sub.client << ")\n";
8831 }
8832}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008833
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008834static void PrintRoutinesCommand(MachO::routines_command r) {
8835 outs() << " cmd LC_ROUTINES\n";
8836 outs() << " cmdsize " << r.cmdsize;
8837 if (r.cmdsize != sizeof(struct MachO::routines_command))
8838 outs() << " Incorrect size\n";
8839 else
8840 outs() << "\n";
8841 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8842 outs() << " init_module " << r.init_module << "\n";
8843 outs() << " reserved1 " << r.reserved1 << "\n";
8844 outs() << " reserved2 " << r.reserved2 << "\n";
8845 outs() << " reserved3 " << r.reserved3 << "\n";
8846 outs() << " reserved4 " << r.reserved4 << "\n";
8847 outs() << " reserved5 " << r.reserved5 << "\n";
8848 outs() << " reserved6 " << r.reserved6 << "\n";
8849}
8850
8851static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8852 outs() << " cmd LC_ROUTINES_64\n";
8853 outs() << " cmdsize " << r.cmdsize;
8854 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8855 outs() << " Incorrect size\n";
8856 else
8857 outs() << "\n";
8858 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8859 outs() << " init_module " << r.init_module << "\n";
8860 outs() << " reserved1 " << r.reserved1 << "\n";
8861 outs() << " reserved2 " << r.reserved2 << "\n";
8862 outs() << " reserved3 " << r.reserved3 << "\n";
8863 outs() << " reserved4 " << r.reserved4 << "\n";
8864 outs() << " reserved5 " << r.reserved5 << "\n";
8865 outs() << " reserved6 " << r.reserved6 << "\n";
8866}
8867
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008868static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8869 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8870 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8871 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8872 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8873 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8874 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8875 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8876 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8877 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8878 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8879 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8880 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8881 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8882 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8883 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8884 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8885}
8886
Kevin Enderby48ef5342014-12-23 22:56:39 +00008887static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8888 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8889 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8890 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8891 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8892 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8893 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8894 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8895 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8896 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8897 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8898 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8899 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8900 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8901 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8902 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8903 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8904 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8905 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8906 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8907 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8908 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8909}
8910
Kevin Enderby227df342014-12-23 23:43:59 +00008911static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008912 uint32_t f;
8913 outs() << "\t mmst_reg ";
8914 for (f = 0; f < 10; f++)
8915 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8916 outs() << "\n";
8917 outs() << "\t mmst_rsrv ";
8918 for (f = 0; f < 6; f++)
8919 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8920 outs() << "\n";
8921}
8922
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008923static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008924 uint32_t f;
8925 outs() << "\t xmm_reg ";
8926 for (f = 0; f < 16; f++)
8927 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8928 outs() << "\n";
8929}
8930
8931static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8932 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8933 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8934 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8935 outs() << " denorm " << fpu.fpu_fcw.denorm;
8936 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8937 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8938 outs() << " undfl " << fpu.fpu_fcw.undfl;
8939 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8940 outs() << "\t\t pc ";
8941 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8942 outs() << "FP_PREC_24B ";
8943 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8944 outs() << "FP_PREC_53B ";
8945 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8946 outs() << "FP_PREC_64B ";
8947 else
8948 outs() << fpu.fpu_fcw.pc << " ";
8949 outs() << "rc ";
8950 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8951 outs() << "FP_RND_NEAR ";
8952 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8953 outs() << "FP_RND_DOWN ";
8954 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8955 outs() << "FP_RND_UP ";
8956 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008957 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008958 outs() << "\n";
8959 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8960 outs() << " denorm " << fpu.fpu_fsw.denorm;
8961 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8962 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8963 outs() << " undfl " << fpu.fpu_fsw.undfl;
8964 outs() << " precis " << fpu.fpu_fsw.precis;
8965 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8966 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8967 outs() << " c0 " << fpu.fpu_fsw.c0;
8968 outs() << " c1 " << fpu.fpu_fsw.c1;
8969 outs() << " c2 " << fpu.fpu_fsw.c2;
8970 outs() << " tos " << fpu.fpu_fsw.tos;
8971 outs() << " c3 " << fpu.fpu_fsw.c3;
8972 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8973 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8974 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8975 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8976 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8977 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8978 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8979 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8980 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8981 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8982 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8983 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8984 outs() << "\n";
8985 outs() << "\t fpu_stmm0:\n";
8986 Print_mmst_reg(fpu.fpu_stmm0);
8987 outs() << "\t fpu_stmm1:\n";
8988 Print_mmst_reg(fpu.fpu_stmm1);
8989 outs() << "\t fpu_stmm2:\n";
8990 Print_mmst_reg(fpu.fpu_stmm2);
8991 outs() << "\t fpu_stmm3:\n";
8992 Print_mmst_reg(fpu.fpu_stmm3);
8993 outs() << "\t fpu_stmm4:\n";
8994 Print_mmst_reg(fpu.fpu_stmm4);
8995 outs() << "\t fpu_stmm5:\n";
8996 Print_mmst_reg(fpu.fpu_stmm5);
8997 outs() << "\t fpu_stmm6:\n";
8998 Print_mmst_reg(fpu.fpu_stmm6);
8999 outs() << "\t fpu_stmm7:\n";
9000 Print_mmst_reg(fpu.fpu_stmm7);
9001 outs() << "\t fpu_xmm0:\n";
9002 Print_xmm_reg(fpu.fpu_xmm0);
9003 outs() << "\t fpu_xmm1:\n";
9004 Print_xmm_reg(fpu.fpu_xmm1);
9005 outs() << "\t fpu_xmm2:\n";
9006 Print_xmm_reg(fpu.fpu_xmm2);
9007 outs() << "\t fpu_xmm3:\n";
9008 Print_xmm_reg(fpu.fpu_xmm3);
9009 outs() << "\t fpu_xmm4:\n";
9010 Print_xmm_reg(fpu.fpu_xmm4);
9011 outs() << "\t fpu_xmm5:\n";
9012 Print_xmm_reg(fpu.fpu_xmm5);
9013 outs() << "\t fpu_xmm6:\n";
9014 Print_xmm_reg(fpu.fpu_xmm6);
9015 outs() << "\t fpu_xmm7:\n";
9016 Print_xmm_reg(fpu.fpu_xmm7);
9017 outs() << "\t fpu_xmm8:\n";
9018 Print_xmm_reg(fpu.fpu_xmm8);
9019 outs() << "\t fpu_xmm9:\n";
9020 Print_xmm_reg(fpu.fpu_xmm9);
9021 outs() << "\t fpu_xmm10:\n";
9022 Print_xmm_reg(fpu.fpu_xmm10);
9023 outs() << "\t fpu_xmm11:\n";
9024 Print_xmm_reg(fpu.fpu_xmm11);
9025 outs() << "\t fpu_xmm12:\n";
9026 Print_xmm_reg(fpu.fpu_xmm12);
9027 outs() << "\t fpu_xmm13:\n";
9028 Print_xmm_reg(fpu.fpu_xmm13);
9029 outs() << "\t fpu_xmm14:\n";
9030 Print_xmm_reg(fpu.fpu_xmm14);
9031 outs() << "\t fpu_xmm15:\n";
9032 Print_xmm_reg(fpu.fpu_xmm15);
9033 outs() << "\t fpu_rsrv4:\n";
9034 for (uint32_t f = 0; f < 6; f++) {
9035 outs() << "\t ";
9036 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009037 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009038 outs() << "\n";
9039 }
9040 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9041 outs() << "\n";
9042}
9043
9044static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9045 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9046 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9047 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9048}
9049
Kevin Enderby41c9c002016-10-21 18:22:35 +00009050static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9051 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9052 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9053 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9054 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9055 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9056 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9057 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9058 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9059 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9060 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9061 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9062 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9063 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9064 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9065 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9066 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9067 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9068}
9069
Kevin Enderby7747cb52016-11-03 20:51:28 +00009070static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9071 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9072 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9073 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9074 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9075 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9076 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9077 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9078 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9079 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9080 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9081 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9082 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9083 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9084 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9085 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9086 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9087 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9088 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9089 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9090 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9091 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9092 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9093 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9094 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9095 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9096 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9097 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9098 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9099 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9100 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9101 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9102 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9103 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9104 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9105}
9106
Kevin Enderby48ef5342014-12-23 22:56:39 +00009107static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9108 bool isLittleEndian, uint32_t cputype) {
9109 if (t.cmd == MachO::LC_THREAD)
9110 outs() << " cmd LC_THREAD\n";
9111 else if (t.cmd == MachO::LC_UNIXTHREAD)
9112 outs() << " cmd LC_UNIXTHREAD\n";
9113 else
9114 outs() << " cmd " << t.cmd << " (unknown)\n";
9115 outs() << " cmdsize " << t.cmdsize;
9116 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9117 outs() << " Incorrect size\n";
9118 else
9119 outs() << "\n";
9120
9121 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9122 const char *end = Ptr + t.cmdsize;
9123 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009124 if (cputype == MachO::CPU_TYPE_I386) {
9125 while (begin < end) {
9126 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9127 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9128 begin += sizeof(uint32_t);
9129 } else {
9130 flavor = 0;
9131 begin = end;
9132 }
9133 if (isLittleEndian != sys::IsLittleEndianHost)
9134 sys::swapByteOrder(flavor);
9135 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9136 memcpy((char *)&count, begin, sizeof(uint32_t));
9137 begin += sizeof(uint32_t);
9138 } else {
9139 count = 0;
9140 begin = end;
9141 }
9142 if (isLittleEndian != sys::IsLittleEndianHost)
9143 sys::swapByteOrder(count);
9144 if (flavor == MachO::x86_THREAD_STATE32) {
9145 outs() << " flavor i386_THREAD_STATE\n";
9146 if (count == MachO::x86_THREAD_STATE32_COUNT)
9147 outs() << " count i386_THREAD_STATE_COUNT\n";
9148 else
9149 outs() << " count " << count
9150 << " (not x86_THREAD_STATE32_COUNT)\n";
9151 MachO::x86_thread_state32_t cpu32;
9152 left = end - begin;
9153 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9154 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9155 begin += sizeof(MachO::x86_thread_state32_t);
9156 } else {
9157 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9158 memcpy(&cpu32, begin, left);
9159 begin += left;
9160 }
9161 if (isLittleEndian != sys::IsLittleEndianHost)
9162 swapStruct(cpu32);
9163 Print_x86_thread_state32_t(cpu32);
9164 } else if (flavor == MachO::x86_THREAD_STATE) {
9165 outs() << " flavor x86_THREAD_STATE\n";
9166 if (count == MachO::x86_THREAD_STATE_COUNT)
9167 outs() << " count x86_THREAD_STATE_COUNT\n";
9168 else
9169 outs() << " count " << count
9170 << " (not x86_THREAD_STATE_COUNT)\n";
9171 struct MachO::x86_thread_state_t ts;
9172 left = end - begin;
9173 if (left >= sizeof(MachO::x86_thread_state_t)) {
9174 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9175 begin += sizeof(MachO::x86_thread_state_t);
9176 } else {
9177 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9178 memcpy(&ts, begin, left);
9179 begin += left;
9180 }
9181 if (isLittleEndian != sys::IsLittleEndianHost)
9182 swapStruct(ts);
9183 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9184 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9185 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9186 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9187 else
9188 outs() << "tsh.count " << ts.tsh.count
9189 << " (not x86_THREAD_STATE32_COUNT\n";
9190 Print_x86_thread_state32_t(ts.uts.ts32);
9191 } else {
9192 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9193 << ts.tsh.count << "\n";
9194 }
9195 } else {
9196 outs() << " flavor " << flavor << " (unknown)\n";
9197 outs() << " count " << count << "\n";
9198 outs() << " state (unknown)\n";
9199 begin += count * sizeof(uint32_t);
9200 }
9201 }
9202 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009203 while (begin < end) {
9204 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9205 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9206 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009207 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009208 flavor = 0;
9209 begin = end;
9210 }
9211 if (isLittleEndian != sys::IsLittleEndianHost)
9212 sys::swapByteOrder(flavor);
9213 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9214 memcpy((char *)&count, begin, sizeof(uint32_t));
9215 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009216 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009217 count = 0;
9218 begin = end;
9219 }
9220 if (isLittleEndian != sys::IsLittleEndianHost)
9221 sys::swapByteOrder(count);
9222 if (flavor == MachO::x86_THREAD_STATE64) {
9223 outs() << " flavor x86_THREAD_STATE64\n";
9224 if (count == MachO::x86_THREAD_STATE64_COUNT)
9225 outs() << " count x86_THREAD_STATE64_COUNT\n";
9226 else
9227 outs() << " count " << count
9228 << " (not x86_THREAD_STATE64_COUNT)\n";
9229 MachO::x86_thread_state64_t cpu64;
9230 left = end - begin;
9231 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9232 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9233 begin += sizeof(MachO::x86_thread_state64_t);
9234 } else {
9235 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9236 memcpy(&cpu64, begin, left);
9237 begin += left;
9238 }
9239 if (isLittleEndian != sys::IsLittleEndianHost)
9240 swapStruct(cpu64);
9241 Print_x86_thread_state64_t(cpu64);
9242 } else if (flavor == MachO::x86_THREAD_STATE) {
9243 outs() << " flavor x86_THREAD_STATE\n";
9244 if (count == MachO::x86_THREAD_STATE_COUNT)
9245 outs() << " count x86_THREAD_STATE_COUNT\n";
9246 else
9247 outs() << " count " << count
9248 << " (not x86_THREAD_STATE_COUNT)\n";
9249 struct MachO::x86_thread_state_t ts;
9250 left = end - begin;
9251 if (left >= sizeof(MachO::x86_thread_state_t)) {
9252 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9253 begin += sizeof(MachO::x86_thread_state_t);
9254 } else {
9255 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9256 memcpy(&ts, begin, left);
9257 begin += left;
9258 }
9259 if (isLittleEndian != sys::IsLittleEndianHost)
9260 swapStruct(ts);
9261 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9262 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9263 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9264 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9265 else
9266 outs() << "tsh.count " << ts.tsh.count
9267 << " (not x86_THREAD_STATE64_COUNT\n";
9268 Print_x86_thread_state64_t(ts.uts.ts64);
9269 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009270 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9271 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009272 }
9273 } else if (flavor == MachO::x86_FLOAT_STATE) {
9274 outs() << " flavor x86_FLOAT_STATE\n";
9275 if (count == MachO::x86_FLOAT_STATE_COUNT)
9276 outs() << " count x86_FLOAT_STATE_COUNT\n";
9277 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009278 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009279 struct MachO::x86_float_state_t fs;
9280 left = end - begin;
9281 if (left >= sizeof(MachO::x86_float_state_t)) {
9282 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9283 begin += sizeof(MachO::x86_float_state_t);
9284 } else {
9285 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9286 memcpy(&fs, begin, left);
9287 begin += left;
9288 }
9289 if (isLittleEndian != sys::IsLittleEndianHost)
9290 swapStruct(fs);
9291 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9292 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009293 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009294 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9295 else
9296 outs() << "fsh.count " << fs.fsh.count
9297 << " (not x86_FLOAT_STATE64_COUNT\n";
9298 Print_x86_float_state_t(fs.ufs.fs64);
9299 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009300 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9301 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009302 }
9303 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9304 outs() << " flavor x86_EXCEPTION_STATE\n";
9305 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9306 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9307 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009308 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009309 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9310 struct MachO::x86_exception_state_t es;
9311 left = end - begin;
9312 if (left >= sizeof(MachO::x86_exception_state_t)) {
9313 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9314 begin += sizeof(MachO::x86_exception_state_t);
9315 } else {
9316 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9317 memcpy(&es, begin, left);
9318 begin += left;
9319 }
9320 if (isLittleEndian != sys::IsLittleEndianHost)
9321 swapStruct(es);
9322 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9323 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009324 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009325 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9326 else
9327 outs() << "\t esh.count " << es.esh.count
9328 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9329 Print_x86_exception_state_t(es.ues.es64);
9330 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009331 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9332 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009333 }
9334 } else {
9335 outs() << " flavor " << flavor << " (unknown)\n";
9336 outs() << " count " << count << "\n";
9337 outs() << " state (unknown)\n";
9338 begin += count * sizeof(uint32_t);
9339 }
9340 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009341 } else if (cputype == MachO::CPU_TYPE_ARM) {
9342 while (begin < end) {
9343 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9344 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9345 begin += sizeof(uint32_t);
9346 } else {
9347 flavor = 0;
9348 begin = end;
9349 }
9350 if (isLittleEndian != sys::IsLittleEndianHost)
9351 sys::swapByteOrder(flavor);
9352 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9353 memcpy((char *)&count, begin, sizeof(uint32_t));
9354 begin += sizeof(uint32_t);
9355 } else {
9356 count = 0;
9357 begin = end;
9358 }
9359 if (isLittleEndian != sys::IsLittleEndianHost)
9360 sys::swapByteOrder(count);
9361 if (flavor == MachO::ARM_THREAD_STATE) {
9362 outs() << " flavor ARM_THREAD_STATE\n";
9363 if (count == MachO::ARM_THREAD_STATE_COUNT)
9364 outs() << " count ARM_THREAD_STATE_COUNT\n";
9365 else
9366 outs() << " count " << count
9367 << " (not ARM_THREAD_STATE_COUNT)\n";
9368 MachO::arm_thread_state32_t cpu32;
9369 left = end - begin;
9370 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9371 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9372 begin += sizeof(MachO::arm_thread_state32_t);
9373 } else {
9374 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9375 memcpy(&cpu32, begin, left);
9376 begin += left;
9377 }
9378 if (isLittleEndian != sys::IsLittleEndianHost)
9379 swapStruct(cpu32);
9380 Print_arm_thread_state32_t(cpu32);
9381 } else {
9382 outs() << " flavor " << flavor << " (unknown)\n";
9383 outs() << " count " << count << "\n";
9384 outs() << " state (unknown)\n";
9385 begin += count * sizeof(uint32_t);
9386 }
9387 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009388 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9389 while (begin < end) {
9390 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9391 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9392 begin += sizeof(uint32_t);
9393 } else {
9394 flavor = 0;
9395 begin = end;
9396 }
9397 if (isLittleEndian != sys::IsLittleEndianHost)
9398 sys::swapByteOrder(flavor);
9399 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9400 memcpy((char *)&count, begin, sizeof(uint32_t));
9401 begin += sizeof(uint32_t);
9402 } else {
9403 count = 0;
9404 begin = end;
9405 }
9406 if (isLittleEndian != sys::IsLittleEndianHost)
9407 sys::swapByteOrder(count);
9408 if (flavor == MachO::ARM_THREAD_STATE64) {
9409 outs() << " flavor ARM_THREAD_STATE64\n";
9410 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9411 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9412 else
9413 outs() << " count " << count
9414 << " (not ARM_THREAD_STATE64_COUNT)\n";
9415 MachO::arm_thread_state64_t cpu64;
9416 left = end - begin;
9417 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9418 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9419 begin += sizeof(MachO::arm_thread_state64_t);
9420 } else {
9421 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9422 memcpy(&cpu64, begin, left);
9423 begin += left;
9424 }
9425 if (isLittleEndian != sys::IsLittleEndianHost)
9426 swapStruct(cpu64);
9427 Print_arm_thread_state64_t(cpu64);
9428 } else {
9429 outs() << " flavor " << flavor << " (unknown)\n";
9430 outs() << " count " << count << "\n";
9431 outs() << " state (unknown)\n";
9432 begin += count * sizeof(uint32_t);
9433 }
9434 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009435 } else {
9436 while (begin < end) {
9437 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9438 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9439 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009440 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009441 flavor = 0;
9442 begin = end;
9443 }
9444 if (isLittleEndian != sys::IsLittleEndianHost)
9445 sys::swapByteOrder(flavor);
9446 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9447 memcpy((char *)&count, begin, sizeof(uint32_t));
9448 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009449 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009450 count = 0;
9451 begin = end;
9452 }
9453 if (isLittleEndian != sys::IsLittleEndianHost)
9454 sys::swapByteOrder(count);
9455 outs() << " flavor " << flavor << "\n";
9456 outs() << " count " << count << "\n";
9457 outs() << " state (Unknown cputype/cpusubtype)\n";
9458 begin += count * sizeof(uint32_t);
9459 }
9460 }
9461}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009462
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009463static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9464 if (dl.cmd == MachO::LC_ID_DYLIB)
9465 outs() << " cmd LC_ID_DYLIB\n";
9466 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9467 outs() << " cmd LC_LOAD_DYLIB\n";
9468 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9469 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9470 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9471 outs() << " cmd LC_REEXPORT_DYLIB\n";
9472 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9473 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9474 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9475 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9476 else
9477 outs() << " cmd " << dl.cmd << " (unknown)\n";
9478 outs() << " cmdsize " << dl.cmdsize;
9479 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9480 outs() << " Incorrect size\n";
9481 else
9482 outs() << "\n";
9483 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009484 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009485 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9486 } else {
9487 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9488 }
9489 outs() << " time stamp " << dl.dylib.timestamp << " ";
9490 time_t t = dl.dylib.timestamp;
9491 outs() << ctime(&t);
9492 outs() << " current version ";
9493 if (dl.dylib.current_version == 0xffffffff)
9494 outs() << "n/a\n";
9495 else
9496 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9497 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9498 << (dl.dylib.current_version & 0xff) << "\n";
9499 outs() << "compatibility version ";
9500 if (dl.dylib.compatibility_version == 0xffffffff)
9501 outs() << "n/a\n";
9502 else
9503 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9504 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9505 << (dl.dylib.compatibility_version & 0xff) << "\n";
9506}
9507
9508static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9509 uint32_t object_size) {
9510 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009511 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009512 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9513 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9514 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9515 outs() << " cmd LC_FUNCTION_STARTS\n";
9516 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9517 outs() << " cmd LC_DATA_IN_CODE\n";
9518 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9519 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9520 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9521 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9522 else
9523 outs() << " cmd " << ld.cmd << " (?)\n";
9524 outs() << " cmdsize " << ld.cmdsize;
9525 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9526 outs() << " Incorrect size\n";
9527 else
9528 outs() << "\n";
9529 outs() << " dataoff " << ld.dataoff;
9530 if (ld.dataoff > object_size)
9531 outs() << " (past end of file)\n";
9532 else
9533 outs() << "\n";
9534 outs() << " datasize " << ld.datasize;
9535 uint64_t big_size = ld.dataoff;
9536 big_size += ld.datasize;
9537 if (big_size > object_size)
9538 outs() << " (past end of file)\n";
9539 else
9540 outs() << "\n";
9541}
9542
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009543static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9544 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009545 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009546 unsigned Index = 0;
9547 for (const auto &Command : Obj->load_commands()) {
9548 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009549 if (Command.C.cmd == MachO::LC_SEGMENT) {
9550 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9551 const char *sg_segname = SLC.segname;
9552 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9553 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9554 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9555 verbose);
9556 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009557 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009558 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9559 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9560 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9561 }
9562 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9563 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9564 const char *sg_segname = SLC_64.segname;
9565 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9566 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9567 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9568 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9569 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9570 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9571 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9572 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9573 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9574 sg_segname, filetype, Buf.size(), verbose);
9575 }
9576 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9577 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009578 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009579 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9580 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9581 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009582 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9583 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009584 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9585 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9586 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9587 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9588 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9589 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9590 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9591 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9592 PrintDyldLoadCommand(Dyld, Command.Ptr);
9593 } else if (Command.C.cmd == MachO::LC_UUID) {
9594 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9595 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009596 } else if (Command.C.cmd == MachO::LC_RPATH) {
9597 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9598 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009599 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009600 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9601 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9602 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009603 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9604 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009605 } else if (Command.C.cmd == MachO::LC_NOTE) {
9606 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9607 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009608 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9609 MachO::build_version_command Bv =
9610 Obj->getBuildVersionLoadCommand(Command);
9611 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009612 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9613 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9614 PrintSourceVersionCommand(Sd);
9615 } else if (Command.C.cmd == MachO::LC_MAIN) {
9616 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9617 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009618 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009619 MachO::encryption_info_command Ei =
9620 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009621 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009622 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009623 MachO::encryption_info_command_64 Ei =
9624 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009625 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009626 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009627 MachO::linker_option_command Lo =
9628 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009629 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009630 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9631 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9632 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009633 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9634 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9635 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009636 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9637 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9638 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009639 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9640 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9641 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009642 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9643 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9644 PrintRoutinesCommand(Rc);
9645 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9646 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9647 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009648 } else if (Command.C.cmd == MachO::LC_THREAD ||
9649 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9650 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9651 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009652 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9653 Command.C.cmd == MachO::LC_ID_DYLIB ||
9654 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9655 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9656 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9657 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009658 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9659 PrintDylibCommand(Dl, Command.Ptr);
9660 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9661 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9662 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9663 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9664 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9665 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9666 MachO::linkedit_data_command Ld =
9667 Obj->getLinkeditDataLoadCommand(Command);
9668 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009669 } else {
9670 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9671 << ")\n";
9672 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9673 // TODO: get and print the raw bytes of the load command.
9674 }
9675 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009676 }
9677}
9678
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009679static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009680 if (Obj->is64Bit()) {
9681 MachO::mach_header_64 H_64;
9682 H_64 = Obj->getHeader64();
9683 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9684 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9685 } else {
9686 MachO::mach_header H;
9687 H = Obj->getHeader();
9688 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9689 H.sizeofcmds, H.flags, verbose);
9690 }
9691}
9692
9693void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9694 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009695 PrintMachHeader(file, !NonVerbose);
9696}
9697
9698void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9699 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009700 uint32_t filetype = 0;
9701 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009702 if (file->is64Bit()) {
9703 MachO::mach_header_64 H_64;
9704 H_64 = file->getHeader64();
9705 filetype = H_64.filetype;
9706 cputype = H_64.cputype;
9707 } else {
9708 MachO::mach_header H;
9709 H = file->getHeader();
9710 filetype = H.filetype;
9711 cputype = H.cputype;
9712 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009713 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009714}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009715
9716//===----------------------------------------------------------------------===//
9717// export trie dumping
9718//===----------------------------------------------------------------------===//
9719
9720void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009721 uint64_t BaseSegmentAddress = 0;
9722 for (const auto &Command : Obj->load_commands()) {
9723 if (Command.C.cmd == MachO::LC_SEGMENT) {
9724 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9725 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9726 BaseSegmentAddress = Seg.vmaddr;
9727 break;
9728 }
9729 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9730 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9731 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9732 BaseSegmentAddress = Seg.vmaddr;
9733 break;
9734 }
9735 }
9736 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009737 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009738 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009739 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009740 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9741 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9742 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9743 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9744 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9745 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9746 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9747 if (ReExport)
9748 outs() << "[re-export] ";
9749 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009750 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009751 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009752 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009753 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009754 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009755 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009756 if (WeakDef) {
9757 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009758 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009759 }
9760 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009761 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009762 outs() << ", ";
9763 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009764 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009765 }
9766 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009767 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009768 outs() << ", ";
9769 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009770 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009771 }
9772 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009773 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009774 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009775 outs() << format("resolver=0x%08llX", Entry.other());
9776 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009777 }
9778 outs() << "]";
9779 }
9780 if (ReExport) {
9781 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009782 int Ordinal = Entry.other() - 1;
9783 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9784 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009785 outs() << " (from " << DylibName << ")";
9786 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009787 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009788 }
9789 outs() << "\n";
9790 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009791 if (Err)
9792 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009793}
Nick Kledzikac431442014-09-12 21:34:15 +00009794
Nick Kledzikac431442014-09-12 21:34:15 +00009795//===----------------------------------------------------------------------===//
9796// rebase table dumping
9797//===----------------------------------------------------------------------===//
9798
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009799void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009800 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009801 Error Err = Error::success();
9802 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9803 StringRef SegmentName = Entry.segmentName();
9804 StringRef SectionName = Entry.sectionName();
9805 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009806
9807 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009808 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9809 SegmentName.str().c_str(), SectionName.str().c_str(),
9810 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009811 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009812 if (Err)
9813 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009814}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009815
9816static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9817 StringRef DylibName;
9818 switch (Ordinal) {
9819 case MachO::BIND_SPECIAL_DYLIB_SELF:
9820 return "this-image";
9821 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9822 return "main-executable";
9823 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9824 return "flat-namespace";
9825 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009826 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009827 std::error_code EC =
9828 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009829 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009830 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009831 return DylibName;
9832 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009833 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009834 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009835}
9836
9837//===----------------------------------------------------------------------===//
9838// bind table dumping
9839//===----------------------------------------------------------------------===//
9840
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009841void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009842 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009843 outs() << "segment section address type "
9844 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009845 Error Err = Error::success();
9846 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009847 StringRef SegmentName = Entry.segmentName();
9848 StringRef SectionName = Entry.sectionName();
9849 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009850
9851 // Table lines look like:
9852 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009853 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009854 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009855 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009856 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009857 << left_justify(SectionName, 18) << " "
9858 << format_hex(Address, 10, true) << " "
9859 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009860 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009861 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009862 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009863 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009864 if (Err)
9865 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009866}
9867
9868//===----------------------------------------------------------------------===//
9869// lazy bind table dumping
9870//===----------------------------------------------------------------------===//
9871
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009872void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009873 outs() << "segment section address "
9874 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009875 Error Err = Error::success();
9876 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009877 StringRef SegmentName = Entry.segmentName();
9878 StringRef SectionName = Entry.sectionName();
9879 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009880
9881 // Table lines look like:
9882 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009883 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009884 << left_justify(SectionName, 18) << " "
9885 << format_hex(Address, 10, true) << " "
9886 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009887 << Entry.symbolName() << "\n";
9888 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009889 if (Err)
9890 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009891}
9892
Nick Kledzik56ebef42014-09-16 01:41:51 +00009893//===----------------------------------------------------------------------===//
9894// weak bind table dumping
9895//===----------------------------------------------------------------------===//
9896
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009897void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009898 outs() << "segment section address "
9899 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009900 Error Err = Error::success();
9901 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009902 // Strong symbols don't have a location to update.
9903 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009904 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009905 << Entry.symbolName() << "\n";
9906 continue;
9907 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009908 StringRef SegmentName = Entry.segmentName();
9909 StringRef SectionName = Entry.sectionName();
9910 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009911
9912 // Table lines look like:
9913 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009914 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009915 << left_justify(SectionName, 18) << " "
9916 << format_hex(Address, 10, true) << " "
9917 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009918 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9919 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009920 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009921 if (Err)
9922 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009923}
9924
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009925// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9926// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9927// information for that address. If the address is found its binding symbol
9928// name is returned. If not nullptr is returned.
9929static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9930 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009931 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009932 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009933 Error Err = Error::success();
9934 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009935 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009936 StringRef name = Entry.symbolName();
9937 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009938 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009939 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009940 if (Err)
9941 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009942 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009943 auto name = info->bindtable->lookup(ReferenceValue);
9944 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009945}
Michael Trent1854ecc2017-12-05 07:50:00 +00009946