blob: 9e39ad2178c831ca2ba732fe1f21454953a091cc [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 Trentde5209b2017-12-08 17:51:04 +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 section index
697 llvm::object::DataRefImpl DRI;
698 DRI.d.a = r_symbolnum-1;
699 StringRef SegName = O->getSectionFinalSegmentName(DRI);
700 StringRef SectName;
701 if (O->getSectionName(DRI, SectName))
702 outs() << "(?,?)\n";
703 else
704 outs() << "(" << SegName << "," << SectName << ")\n";
705 }
706 }
707 }
708 if (cputype == MachO::CPU_TYPE_ARM &&
709 (r_type == llvm::MachO::ARM_RELOC_HALF ||
710 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
711 previous_arm_half = true;
712 else
713 previous_arm_half = false;
714 }
715 else {
716 // plain: address pcrel length extern type scattered symbolnum/section
717 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
718 (unsigned int)r_address, r_pcrel, r_length, r_extern,
719 r_type, r_symbolnum);
720 }
721 }
722 }
723}
724
725static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
726 const uint64_t cputype = O->getHeader().cputype;
727 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
728 if (Dysymtab.nextrel != 0) {
729 outs() << "External relocation information " << Dysymtab.nextrel
730 << " entries";
731 outs() << "\naddress pcrel length extern type scattered "
732 "symbolnum/value\n";
733 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
734 verbose);
735 }
736 if (Dysymtab.nlocrel != 0) {
737 outs() << format("Local relocation information %u entries",
738 Dysymtab.nlocrel);
739 outs() << format("\naddress pcrel length extern type scattered "
740 "symbolnum/value\n");
741 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
742 verbose);
743 }
744 for (const auto &Load : O->load_commands()) {
745 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
746 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
747 for (unsigned J = 0; J < Seg.nsects; ++J) {
748 const MachO::section_64 Sec = O->getSection64(Load, J);
749 if (Sec.nreloc != 0) {
750 DataRefImpl DRI;
751 DRI.d.a = J;
752 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
753 StringRef SectName;
754 if (O->getSectionName(DRI, SectName))
755 outs() << "Relocation information (" << SegName << ",?) "
756 << format("%u entries", Sec.nreloc);
757 else
758 outs() << "Relocation information (" << SegName << ","
759 << SectName << format(") %u entries", Sec.nreloc);
760 outs() << "\naddress pcrel length extern type scattered "
761 "symbolnum/value\n";
762 PrintRelocationEntries(O, O->section_rel_begin(DRI),
763 O->section_rel_end(DRI), cputype, verbose);
764 }
765 }
766 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
767 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
768 for (unsigned J = 0; J < Seg.nsects; ++J) {
769 const MachO::section Sec = O->getSection(Load, J);
770 if (Sec.nreloc != 0) {
771 DataRefImpl DRI;
772 DRI.d.a = J;
773 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
774 StringRef SectName;
775 if (O->getSectionName(DRI, SectName))
776 outs() << "Relocation information (" << SegName << ",?) "
777 << format("%u entries", Sec.nreloc);
778 else
779 outs() << "Relocation information (" << SegName << ","
780 << SectName << format(") %u entries", Sec.nreloc);
781 outs() << "\naddress pcrel length extern type scattered "
782 "symbolnum/value\n";
783 PrintRelocationEntries(O, O->section_rel_begin(DRI),
784 O->section_rel_end(DRI), cputype, verbose);
785 }
786 }
787 }
788 }
789}
790
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000791static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
792 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
793 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
794 outs() << "Data in code table (" << nentries << " entries)\n";
795 outs() << "offset length kind\n";
796 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
797 ++DI) {
798 uint32_t Offset;
799 DI->getOffset(Offset);
800 outs() << format("0x%08" PRIx32, Offset) << " ";
801 uint16_t Length;
802 DI->getLength(Length);
803 outs() << format("%6u", Length) << " ";
804 uint16_t Kind;
805 DI->getKind(Kind);
806 if (verbose) {
807 switch (Kind) {
808 case MachO::DICE_KIND_DATA:
809 outs() << "DATA";
810 break;
811 case MachO::DICE_KIND_JUMP_TABLE8:
812 outs() << "JUMP_TABLE8";
813 break;
814 case MachO::DICE_KIND_JUMP_TABLE16:
815 outs() << "JUMP_TABLE16";
816 break;
817 case MachO::DICE_KIND_JUMP_TABLE32:
818 outs() << "JUMP_TABLE32";
819 break;
820 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
821 outs() << "ABS_JUMP_TABLE32";
822 break;
823 default:
824 outs() << format("0x%04" PRIx32, Kind);
825 break;
826 }
827 } else
828 outs() << format("0x%04" PRIx32, Kind);
829 outs() << "\n";
830 }
831}
832
Kevin Enderby9a509442015-01-27 21:28:24 +0000833static void PrintLinkOptHints(MachOObjectFile *O) {
834 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
835 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
836 uint32_t nloh = LohLC.datasize;
837 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
838 for (uint32_t i = 0; i < nloh;) {
839 unsigned n;
840 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
841 i += n;
842 outs() << " identifier " << identifier << " ";
843 if (i >= nloh)
844 return;
845 switch (identifier) {
846 case 1:
847 outs() << "AdrpAdrp\n";
848 break;
849 case 2:
850 outs() << "AdrpLdr\n";
851 break;
852 case 3:
853 outs() << "AdrpAddLdr\n";
854 break;
855 case 4:
856 outs() << "AdrpLdrGotLdr\n";
857 break;
858 case 5:
859 outs() << "AdrpAddStr\n";
860 break;
861 case 6:
862 outs() << "AdrpLdrGotStr\n";
863 break;
864 case 7:
865 outs() << "AdrpAdd\n";
866 break;
867 case 8:
868 outs() << "AdrpLdrGot\n";
869 break;
870 default:
871 outs() << "Unknown identifier value\n";
872 break;
873 }
874 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
875 i += n;
876 outs() << " narguments " << narguments << "\n";
877 if (i >= nloh)
878 return;
879
880 for (uint32_t j = 0; j < narguments; j++) {
881 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
882 i += n;
883 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
884 if (i >= nloh)
885 return;
886 }
887 }
888}
889
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000890static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000891 unsigned Index = 0;
892 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000893 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
894 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
895 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
896 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
897 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
898 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
899 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
900 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
901 if (dl.dylib.name < dl.cmdsize) {
902 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
903 if (JustId)
904 outs() << p << "\n";
905 else {
906 outs() << "\t" << p;
907 outs() << " (compatibility version "
908 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
909 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
910 << (dl.dylib.compatibility_version & 0xff) << ",";
911 outs() << " current version "
912 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
913 << ((dl.dylib.current_version >> 8) & 0xff) << "."
914 << (dl.dylib.current_version & 0xff) << ")\n";
915 }
916 } else {
917 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
918 if (Load.C.cmd == MachO::LC_ID_DYLIB)
919 outs() << "LC_ID_DYLIB ";
920 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
921 outs() << "LC_LOAD_DYLIB ";
922 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
923 outs() << "LC_LOAD_WEAK_DYLIB ";
924 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
925 outs() << "LC_LAZY_LOAD_DYLIB ";
926 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
927 outs() << "LC_REEXPORT_DYLIB ";
928 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
929 outs() << "LC_LOAD_UPWARD_DYLIB ";
930 else
931 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000932 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000933 }
934 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000935 }
936}
937
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000938typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
939
940static void CreateSymbolAddressMap(MachOObjectFile *O,
941 SymbolAddressMap *AddrMap) {
942 // Create a map of symbol addresses to symbol names.
943 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000944 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000945 if (!STOrErr)
946 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000947 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000948 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
949 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000950 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000951 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000952 if (!SymNameOrErr)
953 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000954 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000955 if (!SymName.startswith(".objc"))
956 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000957 }
958 }
959}
960
961// GuessSymbolName is passed the address of what might be a symbol and a
962// pointer to the SymbolAddressMap. It returns the name of a symbol
963// with that address or nullptr if no symbol is found with that address.
964static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
965 const char *SymbolName = nullptr;
966 // A DenseMap can't lookup up some values.
967 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
968 StringRef name = AddrMap->lookup(value);
969 if (!name.empty())
970 SymbolName = name.data();
971 }
972 return SymbolName;
973}
974
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000975static void DumpCstringChar(const char c) {
976 char p[2];
977 p[0] = c;
978 p[1] = '\0';
979 outs().write_escaped(p);
980}
981
Kevin Enderby10ba0412015-02-04 21:38:42 +0000982static void DumpCstringSection(MachOObjectFile *O, const char *sect,
983 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000984 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000985 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000986 if (print_addresses) {
987 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000988 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000989 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000990 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000991 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000992 for (; i < sect_size && sect[i] != '\0'; i++)
993 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000994 if (i < sect_size && sect[i] == '\0')
995 outs() << "\n";
996 }
997}
998
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000999static void DumpLiteral4(uint32_t l, float f) {
1000 outs() << format("0x%08" PRIx32, l);
1001 if ((l & 0x7f800000) != 0x7f800000)
1002 outs() << format(" (%.16e)\n", f);
1003 else {
1004 if (l == 0x7f800000)
1005 outs() << " (+Infinity)\n";
1006 else if (l == 0xff800000)
1007 outs() << " (-Infinity)\n";
1008 else if ((l & 0x00400000) == 0x00400000)
1009 outs() << " (non-signaling Not-a-Number)\n";
1010 else
1011 outs() << " (signaling Not-a-Number)\n";
1012 }
1013}
1014
1015static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1016 uint32_t sect_size, uint64_t sect_addr,
1017 bool print_addresses) {
1018 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1019 if (print_addresses) {
1020 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001021 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001022 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001023 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001024 }
1025 float f;
1026 memcpy(&f, sect + i, sizeof(float));
1027 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1028 sys::swapByteOrder(f);
1029 uint32_t l;
1030 memcpy(&l, sect + i, sizeof(uint32_t));
1031 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1032 sys::swapByteOrder(l);
1033 DumpLiteral4(l, f);
1034 }
1035}
1036
1037static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1038 double d) {
1039 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1040 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001041 Hi = (O->isLittleEndian()) ? l1 : l0;
1042 Lo = (O->isLittleEndian()) ? l0 : l1;
1043
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001044 // Hi is the high word, so this is equivalent to if(isfinite(d))
1045 if ((Hi & 0x7ff00000) != 0x7ff00000)
1046 outs() << format(" (%.16e)\n", d);
1047 else {
1048 if (Hi == 0x7ff00000 && Lo == 0)
1049 outs() << " (+Infinity)\n";
1050 else if (Hi == 0xfff00000 && Lo == 0)
1051 outs() << " (-Infinity)\n";
1052 else if ((Hi & 0x00080000) == 0x00080000)
1053 outs() << " (non-signaling Not-a-Number)\n";
1054 else
1055 outs() << " (signaling Not-a-Number)\n";
1056 }
1057}
1058
1059static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1060 uint32_t sect_size, uint64_t sect_addr,
1061 bool print_addresses) {
1062 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1063 if (print_addresses) {
1064 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001065 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001066 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001067 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001068 }
1069 double d;
1070 memcpy(&d, sect + i, sizeof(double));
1071 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1072 sys::swapByteOrder(d);
1073 uint32_t l0, l1;
1074 memcpy(&l0, sect + i, sizeof(uint32_t));
1075 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1076 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1077 sys::swapByteOrder(l0);
1078 sys::swapByteOrder(l1);
1079 }
1080 DumpLiteral8(O, l0, l1, d);
1081 }
1082}
1083
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001084static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1085 outs() << format("0x%08" PRIx32, l0) << " ";
1086 outs() << format("0x%08" PRIx32, l1) << " ";
1087 outs() << format("0x%08" PRIx32, l2) << " ";
1088 outs() << format("0x%08" PRIx32, l3) << "\n";
1089}
1090
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001091static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1092 uint32_t sect_size, uint64_t sect_addr,
1093 bool print_addresses) {
1094 for (uint32_t i = 0; i < sect_size; i += 16) {
1095 if (print_addresses) {
1096 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001097 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001098 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001099 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 }
1101 uint32_t l0, l1, l2, l3;
1102 memcpy(&l0, sect + i, sizeof(uint32_t));
1103 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1104 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1105 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1106 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1107 sys::swapByteOrder(l0);
1108 sys::swapByteOrder(l1);
1109 sys::swapByteOrder(l2);
1110 sys::swapByteOrder(l3);
1111 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001112 DumpLiteral16(l0, l1, l2, l3);
1113 }
1114}
1115
1116static void DumpLiteralPointerSection(MachOObjectFile *O,
1117 const SectionRef &Section,
1118 const char *sect, uint32_t sect_size,
1119 uint64_t sect_addr,
1120 bool print_addresses) {
1121 // Collect the literal sections in this Mach-O file.
1122 std::vector<SectionRef> LiteralSections;
1123 for (const SectionRef &Section : O->sections()) {
1124 DataRefImpl Ref = Section.getRawDataRefImpl();
1125 uint32_t section_type;
1126 if (O->is64Bit()) {
1127 const MachO::section_64 Sec = O->getSection64(Ref);
1128 section_type = Sec.flags & MachO::SECTION_TYPE;
1129 } else {
1130 const MachO::section Sec = O->getSection(Ref);
1131 section_type = Sec.flags & MachO::SECTION_TYPE;
1132 }
1133 if (section_type == MachO::S_CSTRING_LITERALS ||
1134 section_type == MachO::S_4BYTE_LITERALS ||
1135 section_type == MachO::S_8BYTE_LITERALS ||
1136 section_type == MachO::S_16BYTE_LITERALS)
1137 LiteralSections.push_back(Section);
1138 }
1139
1140 // Set the size of the literal pointer.
1141 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1142
Eric Christopher572e03a2015-06-19 01:53:21 +00001143 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001144 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1145 for (const RelocationRef &Reloc : Section.relocations()) {
1146 DataRefImpl Rel;
1147 MachO::any_relocation_info RE;
1148 bool isExtern = false;
1149 Rel = Reloc.getRawDataRefImpl();
1150 RE = O->getRelocation(Rel);
1151 isExtern = O->getPlainRelocationExternal(RE);
1152 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001153 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001154 symbol_iterator RelocSym = Reloc.getSymbol();
1155 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1156 }
1157 }
1158 array_pod_sort(Relocs.begin(), Relocs.end());
1159
1160 // Dump each literal pointer.
1161 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1162 if (print_addresses) {
1163 if (O->is64Bit())
1164 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1165 else
1166 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1167 }
1168 uint64_t lp;
1169 if (O->is64Bit()) {
1170 memcpy(&lp, sect + i, sizeof(uint64_t));
1171 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1172 sys::swapByteOrder(lp);
1173 } else {
1174 uint32_t li;
1175 memcpy(&li, sect + i, sizeof(uint32_t));
1176 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1177 sys::swapByteOrder(li);
1178 lp = li;
1179 }
1180
1181 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001182 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1183 return P.first == i;
1184 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001185 if (Reloc != Relocs.end()) {
1186 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001187 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001188 if (!SymName)
1189 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001190 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001191 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001192 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001193
1194 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001195 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1196 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1197 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001198 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001199 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001200 continue;
1201 }
1202
1203 uint64_t SectAddress = Sect->getAddress();
1204 uint64_t SectSize = Sect->getSize();
1205
1206 StringRef SectName;
1207 Sect->getName(SectName);
1208 DataRefImpl Ref = Sect->getRawDataRefImpl();
1209 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1210 outs() << SegmentName << ":" << SectName << ":";
1211
1212 uint32_t section_type;
1213 if (O->is64Bit()) {
1214 const MachO::section_64 Sec = O->getSection64(Ref);
1215 section_type = Sec.flags & MachO::SECTION_TYPE;
1216 } else {
1217 const MachO::section Sec = O->getSection(Ref);
1218 section_type = Sec.flags & MachO::SECTION_TYPE;
1219 }
1220
1221 StringRef BytesStr;
1222 Sect->getContents(BytesStr);
1223 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1224
1225 switch (section_type) {
1226 case MachO::S_CSTRING_LITERALS:
1227 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1228 i++) {
1229 DumpCstringChar(Contents[i]);
1230 }
1231 outs() << "\n";
1232 break;
1233 case MachO::S_4BYTE_LITERALS:
1234 float f;
1235 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1236 uint32_t l;
1237 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1238 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1239 sys::swapByteOrder(f);
1240 sys::swapByteOrder(l);
1241 }
1242 DumpLiteral4(l, f);
1243 break;
1244 case MachO::S_8BYTE_LITERALS: {
1245 double d;
1246 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1247 uint32_t l0, l1;
1248 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1249 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1250 sizeof(uint32_t));
1251 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1252 sys::swapByteOrder(f);
1253 sys::swapByteOrder(l0);
1254 sys::swapByteOrder(l1);
1255 }
1256 DumpLiteral8(O, l0, l1, d);
1257 break;
1258 }
1259 case MachO::S_16BYTE_LITERALS: {
1260 uint32_t l0, l1, l2, l3;
1261 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1262 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1263 sizeof(uint32_t));
1264 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1265 sizeof(uint32_t));
1266 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1267 sizeof(uint32_t));
1268 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1269 sys::swapByteOrder(l0);
1270 sys::swapByteOrder(l1);
1271 sys::swapByteOrder(l2);
1272 sys::swapByteOrder(l3);
1273 }
1274 DumpLiteral16(l0, l1, l2, l3);
1275 break;
1276 }
1277 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001278 }
1279}
1280
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001281static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
1282 uint32_t sect_size, uint64_t sect_addr,
1283 SymbolAddressMap *AddrMap,
1284 bool verbose) {
1285 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001286 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001287 for (uint32_t i = 0; i < sect_size; i += stride) {
1288 const char *SymbolName = nullptr;
1289 if (O->is64Bit()) {
1290 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1291 uint64_t pointer_value;
1292 memcpy(&pointer_value, sect + i, stride);
1293 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1294 sys::swapByteOrder(pointer_value);
1295 outs() << format("0x%016" PRIx64, pointer_value);
1296 if (verbose)
1297 SymbolName = GuessSymbolName(pointer_value, AddrMap);
1298 } else {
1299 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1300 uint32_t pointer_value;
1301 memcpy(&pointer_value, sect + i, stride);
1302 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1303 sys::swapByteOrder(pointer_value);
1304 outs() << format("0x%08" PRIx32, pointer_value);
1305 if (verbose)
1306 SymbolName = GuessSymbolName(pointer_value, AddrMap);
1307 }
1308 if (SymbolName)
1309 outs() << " " << SymbolName;
1310 outs() << "\n";
1311 }
1312}
1313
1314static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1315 uint32_t size, uint64_t addr) {
1316 uint32_t cputype = O->getHeader().cputype;
1317 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1318 uint32_t j;
1319 for (uint32_t i = 0; i < size; i += j, addr += j) {
1320 if (O->is64Bit())
1321 outs() << format("%016" PRIx64, addr) << "\t";
1322 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001323 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001324 for (j = 0; j < 16 && i + j < size; j++) {
1325 uint8_t byte_word = *(sect + i + j);
1326 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1327 }
1328 outs() << "\n";
1329 }
1330 } else {
1331 uint32_t j;
1332 for (uint32_t i = 0; i < size; i += j, addr += j) {
1333 if (O->is64Bit())
1334 outs() << format("%016" PRIx64, addr) << "\t";
1335 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001336 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001337 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1338 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001339 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001340 uint32_t long_word;
1341 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1342 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1343 sys::swapByteOrder(long_word);
1344 outs() << format("%08" PRIx32, long_word) << " ";
1345 } else {
1346 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001347 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001348 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1349 }
1350 }
1351 }
1352 outs() << "\n";
1353 }
1354 }
1355}
1356
Kevin Enderby95df54c2015-02-04 01:01:38 +00001357static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1358 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001359static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1360 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001361#ifdef HAVE_LIBXAR
1362static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1363 uint32_t size, bool verbose,
1364 bool PrintXarHeader, bool PrintXarFileHeaders,
1365 std::string XarMemberName);
1366#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001367
1368static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1369 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001370 SymbolAddressMap AddrMap;
1371 if (verbose)
1372 CreateSymbolAddressMap(O, &AddrMap);
1373
Colin LeMahieufcc32762015-07-29 19:08:10 +00001374 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1375 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001376 std::pair<StringRef, StringRef> DumpSegSectName;
1377 DumpSegSectName = DumpSection.split(',');
1378 StringRef DumpSegName, DumpSectName;
1379 if (DumpSegSectName.second.size()) {
1380 DumpSegName = DumpSegSectName.first;
1381 DumpSectName = DumpSegSectName.second;
1382 } else {
1383 DumpSegName = "";
1384 DumpSectName = DumpSegSectName.first;
1385 }
1386 for (const SectionRef &Section : O->sections()) {
1387 StringRef SectName;
1388 Section.getName(SectName);
1389 DataRefImpl Ref = Section.getRawDataRefImpl();
1390 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1391 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1392 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001393
Kevin Enderby95df54c2015-02-04 01:01:38 +00001394 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001395 if (O->is64Bit()) {
1396 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001397 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001398
1399 } else {
1400 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001401 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001402 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001403 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001404
1405 StringRef BytesStr;
1406 Section.getContents(BytesStr);
1407 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1408 uint32_t sect_size = BytesStr.size();
1409 uint64_t sect_addr = Section.getAddress();
1410
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001411 outs() << "Contents of (" << SegName << "," << SectName
1412 << ") section\n";
1413
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001414 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001415 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1416 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1417 DisassembleMachO(Filename, O, SegName, SectName);
1418 continue;
1419 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001420 if (SegName == "__TEXT" && SectName == "__info_plist") {
1421 outs() << sect;
1422 continue;
1423 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001424 if (SegName == "__OBJC" && SectName == "__protocol") {
1425 DumpProtocolSection(O, sect, sect_size, sect_addr);
1426 continue;
1427 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001428#ifdef HAVE_LIBXAR
1429 if (SegName == "__LLVM" && SectName == "__bundle") {
1430 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1431 ArchiveHeaders, "");
1432 continue;
1433 }
1434#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001435 switch (section_type) {
1436 case MachO::S_REGULAR:
1437 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1438 break;
1439 case MachO::S_ZEROFILL:
1440 outs() << "zerofill section and has no contents in the file\n";
1441 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001442 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001443 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001444 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001445 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001446 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001447 break;
1448 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001449 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001450 break;
1451 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001452 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1453 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001454 case MachO::S_LITERAL_POINTERS:
1455 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001456 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001457 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001458 case MachO::S_MOD_INIT_FUNC_POINTERS:
1459 case MachO::S_MOD_TERM_FUNC_POINTERS:
1460 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1461 verbose);
1462 break;
1463 default:
1464 outs() << "Unknown section type ("
1465 << format("0x%08" PRIx32, section_type) << ")\n";
1466 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1467 break;
1468 }
1469 } else {
1470 if (section_type == MachO::S_ZEROFILL)
1471 outs() << "zerofill section and has no contents in the file\n";
1472 else
1473 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1474 }
1475 }
1476 }
1477 }
1478}
1479
Kevin Enderbycd66be52015-03-11 22:06:32 +00001480static void DumpInfoPlistSectionContents(StringRef Filename,
1481 MachOObjectFile *O) {
1482 for (const SectionRef &Section : O->sections()) {
1483 StringRef SectName;
1484 Section.getName(SectName);
1485 DataRefImpl Ref = Section.getRawDataRefImpl();
1486 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1487 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001488 if (!NoLeadingHeaders)
1489 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001490 StringRef BytesStr;
1491 Section.getContents(BytesStr);
1492 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001493 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001494 return;
1495 }
1496 }
1497}
1498
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001499// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1500// and if it is and there is a list of architecture flags is specified then
1501// check to make sure this Mach-O file is one of those architectures or all
1502// architectures were specified. If not then an error is generated and this
1503// routine returns false. Else it returns true.
1504static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001505 auto *MachO = dyn_cast<MachOObjectFile>(O);
1506
1507 if (!MachO || ArchAll || ArchFlags.empty())
1508 return true;
1509
1510 MachO::mach_header H;
1511 MachO::mach_header_64 H_64;
1512 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001513 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001514 if (MachO->is64Bit()) {
1515 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001516 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1517 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001518 } else {
1519 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001520 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1521 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001522 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001523 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001524 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001525 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001526 })) {
1527 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1528 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001529 }
1530 return true;
1531}
1532
Kevin Enderby0fc11822015-04-01 20:57:01 +00001533static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1534
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001535// ProcessMachO() is passed a single opened Mach-O file, which may be an
1536// archive member and or in a slice of a universal file. It prints the
1537// the file name and header info and then processes it according to the
1538// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001539static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001540 StringRef ArchiveMemberName = StringRef(),
1541 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001542 // If we are doing some processing here on the Mach-O file print the header
1543 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001544 // UniversalHeaders or ArchiveHeaders.
Michael Trentde5209b2017-12-08 17:51:04 +00001545 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1546 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1547 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1548 (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001549 if (!NoLeadingHeaders) {
1550 outs() << Name;
1551 if (!ArchiveMemberName.empty())
1552 outs() << '(' << ArchiveMemberName << ')';
1553 if (!ArchitectureName.empty())
1554 outs() << " (architecture " << ArchitectureName << ")";
1555 outs() << ":\n";
1556 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001557 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001558 // To use the report_error() form with an ArchiveName and FileName set
1559 // these up based on what is passed for Name and ArchiveMemberName.
1560 StringRef ArchiveName;
1561 StringRef FileName;
1562 if (!ArchiveMemberName.empty()) {
1563 ArchiveName = Name;
1564 FileName = ArchiveMemberName;
1565 } else {
1566 ArchiveName = StringRef();
1567 FileName = Name;
1568 }
1569
1570 // If we need the symbol table to do the operation then check it here to
1571 // produce a good error message as to where the Mach-O file comes from in
1572 // the error message.
1573 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1574 UnwindInfo)
1575 if (Error Err = MachOOF->checkSymbolTable())
1576 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001577
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001578 if (Disassemble) {
1579 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001580 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001581 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1582 else
1583 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1584 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001585 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001586 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001587 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001588 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001589 if (LinkOptHints)
1590 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001591 if (Relocations)
Michael Trentde5209b2017-12-08 17:51:04 +00001592 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001593 if (SectionHeaders)
1594 PrintSectionHeaders(MachOOF);
1595 if (SectionContents)
1596 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001597 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001598 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001599 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001600 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001601 if (DylibsUsed)
1602 PrintDylibs(MachOOF, false);
1603 if (DylibId)
1604 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001605 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001606 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001607 if (UnwindInfo)
1608 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001609 if (PrivateHeaders) {
1610 printMachOFileHeader(MachOOF);
1611 printMachOLoadCommands(MachOOF);
1612 }
1613 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001614 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001615 if (ObjcMetaData)
1616 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001617 if (ExportsTrie)
1618 printExportsTrie(MachOOF);
1619 if (Rebase)
1620 printRebaseTable(MachOOF);
1621 if (Bind)
1622 printBindTable(MachOOF);
1623 if (LazyBind)
1624 printLazyBindTable(MachOOF);
1625 if (WeakBind)
1626 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001627
1628 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001629 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001630 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001631 DIDumpOptions DumpOpts;
1632 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001633 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001634 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001635}
1636
Kevin Enderby131d1772015-01-09 19:22:37 +00001637// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1638static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1639 outs() << " cputype (" << cputype << ")\n";
1640 outs() << " cpusubtype (" << cpusubtype << ")\n";
1641}
1642
1643// printCPUType() helps print_fat_headers by printing the cputype and
1644// pusubtype (symbolically for the one's it knows about).
1645static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1646 switch (cputype) {
1647 case MachO::CPU_TYPE_I386:
1648 switch (cpusubtype) {
1649 case MachO::CPU_SUBTYPE_I386_ALL:
1650 outs() << " cputype CPU_TYPE_I386\n";
1651 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1652 break;
1653 default:
1654 printUnknownCPUType(cputype, cpusubtype);
1655 break;
1656 }
1657 break;
1658 case MachO::CPU_TYPE_X86_64:
1659 switch (cpusubtype) {
1660 case MachO::CPU_SUBTYPE_X86_64_ALL:
1661 outs() << " cputype CPU_TYPE_X86_64\n";
1662 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1663 break;
1664 case MachO::CPU_SUBTYPE_X86_64_H:
1665 outs() << " cputype CPU_TYPE_X86_64\n";
1666 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1667 break;
1668 default:
1669 printUnknownCPUType(cputype, cpusubtype);
1670 break;
1671 }
1672 break;
1673 case MachO::CPU_TYPE_ARM:
1674 switch (cpusubtype) {
1675 case MachO::CPU_SUBTYPE_ARM_ALL:
1676 outs() << " cputype CPU_TYPE_ARM\n";
1677 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1678 break;
1679 case MachO::CPU_SUBTYPE_ARM_V4T:
1680 outs() << " cputype CPU_TYPE_ARM\n";
1681 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1682 break;
1683 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1684 outs() << " cputype CPU_TYPE_ARM\n";
1685 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1686 break;
1687 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1688 outs() << " cputype CPU_TYPE_ARM\n";
1689 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1690 break;
1691 case MachO::CPU_SUBTYPE_ARM_V6:
1692 outs() << " cputype CPU_TYPE_ARM\n";
1693 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1694 break;
1695 case MachO::CPU_SUBTYPE_ARM_V6M:
1696 outs() << " cputype CPU_TYPE_ARM\n";
1697 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1698 break;
1699 case MachO::CPU_SUBTYPE_ARM_V7:
1700 outs() << " cputype CPU_TYPE_ARM\n";
1701 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1702 break;
1703 case MachO::CPU_SUBTYPE_ARM_V7EM:
1704 outs() << " cputype CPU_TYPE_ARM\n";
1705 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1706 break;
1707 case MachO::CPU_SUBTYPE_ARM_V7K:
1708 outs() << " cputype CPU_TYPE_ARM\n";
1709 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1710 break;
1711 case MachO::CPU_SUBTYPE_ARM_V7M:
1712 outs() << " cputype CPU_TYPE_ARM\n";
1713 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1714 break;
1715 case MachO::CPU_SUBTYPE_ARM_V7S:
1716 outs() << " cputype CPU_TYPE_ARM\n";
1717 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1718 break;
1719 default:
1720 printUnknownCPUType(cputype, cpusubtype);
1721 break;
1722 }
1723 break;
1724 case MachO::CPU_TYPE_ARM64:
1725 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1726 case MachO::CPU_SUBTYPE_ARM64_ALL:
1727 outs() << " cputype CPU_TYPE_ARM64\n";
1728 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1729 break;
1730 default:
1731 printUnknownCPUType(cputype, cpusubtype);
1732 break;
1733 }
1734 break;
1735 default:
1736 printUnknownCPUType(cputype, cpusubtype);
1737 break;
1738 }
1739}
1740
1741static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1742 bool verbose) {
1743 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001744 if (verbose) {
1745 if (UB->getMagic() == MachO::FAT_MAGIC)
1746 outs() << "fat_magic FAT_MAGIC\n";
1747 else // UB->getMagic() == MachO::FAT_MAGIC_64
1748 outs() << "fat_magic FAT_MAGIC_64\n";
1749 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001750 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1751
1752 uint32_t nfat_arch = UB->getNumberOfObjects();
1753 StringRef Buf = UB->getData();
1754 uint64_t size = Buf.size();
1755 uint64_t big_size = sizeof(struct MachO::fat_header) +
1756 nfat_arch * sizeof(struct MachO::fat_arch);
1757 outs() << "nfat_arch " << UB->getNumberOfObjects();
1758 if (nfat_arch == 0)
1759 outs() << " (malformed, contains zero architecture types)\n";
1760 else if (big_size > size)
1761 outs() << " (malformed, architectures past end of file)\n";
1762 else
1763 outs() << "\n";
1764
1765 for (uint32_t i = 0; i < nfat_arch; ++i) {
1766 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1767 uint32_t cputype = OFA.getCPUType();
1768 uint32_t cpusubtype = OFA.getCPUSubType();
1769 outs() << "architecture ";
1770 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1771 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1772 uint32_t other_cputype = other_OFA.getCPUType();
1773 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001774 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001775 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001776 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001777 outs() << "(illegal duplicate architecture) ";
1778 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001779 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001780 }
1781 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001782 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001783 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1784 } else {
1785 outs() << i << "\n";
1786 outs() << " cputype " << cputype << "\n";
1787 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1788 << "\n";
1789 }
1790 if (verbose &&
1791 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1792 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1793 else
1794 outs() << " capabilities "
1795 << format("0x%" PRIx32,
1796 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1797 outs() << " offset " << OFA.getOffset();
1798 if (OFA.getOffset() > size)
1799 outs() << " (past end of file)";
1800 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1801 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1802 outs() << "\n";
1803 outs() << " size " << OFA.getSize();
1804 big_size = OFA.getOffset() + OFA.getSize();
1805 if (big_size > size)
1806 outs() << " (past end of file)";
1807 outs() << "\n";
1808 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1809 << ")\n";
1810 }
1811}
1812
Kevin Enderby6524bd82016-07-19 20:47:07 +00001813static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1814 bool verbose, bool print_offset,
1815 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001816 if (print_offset)
1817 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001818 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1819 if (!ModeOrErr)
1820 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1821 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001822 if (verbose) {
1823 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1824 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1825 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001826 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1827 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1828 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1829 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1830 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1831 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1832 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1833 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1834 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001835 } else {
1836 outs() << format("0%o ", Mode);
1837 }
1838
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001839 Expected<unsigned> UIDOrErr = C.getUID();
1840 if (!UIDOrErr)
1841 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1842 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001843 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001844 Expected<unsigned> GIDOrErr = C.getGID();
1845 if (!GIDOrErr)
1846 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1847 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001848 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001849 Expected<uint64_t> Size = C.getRawSize();
1850 if (!Size)
1851 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001852 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001853
1854 StringRef RawLastModified = C.getRawLastModified();
1855 if (verbose) {
1856 unsigned Seconds;
1857 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001858 outs() << "(date: \"" << RawLastModified
1859 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001860 else {
1861 // Since cime(3) returns a 26 character string of the form:
1862 // "Sun Sep 16 01:03:52 1973\n\0"
1863 // just print 24 characters.
1864 time_t t = Seconds;
1865 outs() << format("%.24s ", ctime(&t));
1866 }
1867 } else {
1868 outs() << RawLastModified << " ";
1869 }
1870
1871 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001872 Expected<StringRef> NameOrErr = C.getName();
1873 if (!NameOrErr) {
1874 consumeError(NameOrErr.takeError());
1875 Expected<StringRef> NameOrErr = C.getRawName();
1876 if (!NameOrErr)
1877 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1878 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001879 outs() << RawName << "\n";
1880 } else {
1881 StringRef Name = NameOrErr.get();
1882 outs() << Name << "\n";
1883 }
1884 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001885 Expected<StringRef> NameOrErr = C.getRawName();
1886 if (!NameOrErr)
1887 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1888 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001889 outs() << RawName << "\n";
1890 }
1891}
1892
Kevin Enderby6524bd82016-07-19 20:47:07 +00001893static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1894 bool print_offset,
1895 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001896 Error Err = Error::success();
1897 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001898 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001899 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1900
Lang Hamesfc209622016-07-14 02:24:01 +00001901 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001902 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001903}
1904
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001905// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1906// -arch flags selecting just those slices as specified by them and also parses
1907// archive files. Then for each individual Mach-O file ProcessMachO() is
1908// called to process the file based on the command line options.
1909void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001910 // Check for -arch all and verifiy the -arch flags are valid.
1911 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1912 if (ArchFlags[i] == "all") {
1913 ArchAll = true;
1914 } else {
1915 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1916 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1917 "'for the -arch option\n";
1918 return;
1919 }
1920 }
1921 }
1922
1923 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001924 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001925 if (!BinaryOrErr) {
1926 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1927 report_error(Filename, std::move(E));
1928 else
1929 outs() << Filename << ": is not an object file\n";
1930 return;
1931 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001932 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001933
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001934 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1935 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001936 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001937 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1938
Mehdi Amini41af4302016-11-11 04:28:40 +00001939 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001940 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001941 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1942 if (!ChildOrErr) {
1943 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1944 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001945 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001946 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001947 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1948 if (!checkMachOAndArchFlags(O, Filename))
1949 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001950 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001951 }
1952 }
Lang Hamesfc209622016-07-14 02:24:01 +00001953 if (Err)
1954 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001955 return;
1956 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001957 if (UniversalHeaders) {
1958 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001959 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001960 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001961 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1962 // If we have a list of architecture flags specified dump only those.
1963 if (!ArchAll && ArchFlags.size() != 0) {
1964 // Look for a slice in the universal binary that matches each ArchFlag.
1965 bool ArchFound;
1966 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1967 ArchFound = false;
1968 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1969 E = UB->end_objects();
1970 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001971 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001972 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001973 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001974 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001975 std::string ArchitectureName = "";
1976 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001977 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001978 if (ObjOrErr) {
1979 ObjectFile &O = *ObjOrErr.get();
1980 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001981 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001982 } else if (auto E = isNotObjectErrorInvalidFileType(
1983 ObjOrErr.takeError())) {
1984 report_error(Filename, StringRef(), std::move(E),
1985 ArchitectureName);
1986 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001987 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001988 I->getAsArchive()) {
1989 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001990 outs() << "Archive : " << Filename;
1991 if (!ArchitectureName.empty())
1992 outs() << " (architecture " << ArchitectureName << ")";
1993 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001994 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001995 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1996 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001997 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001998 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001999 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2000 if (!ChildOrErr) {
2001 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00002002 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002003 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002004 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002005 if (MachOObjectFile *O =
2006 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002007 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002008 }
Lang Hamesfc209622016-07-14 02:24:01 +00002009 if (Err)
2010 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002011 } else {
2012 consumeError(AOrErr.takeError());
2013 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002014 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002015 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002016 }
2017 }
2018 }
2019 if (!ArchFound) {
2020 errs() << "llvm-objdump: file: " + Filename + " does not contain "
2021 << "architecture: " + ArchFlags[i] + "\n";
2022 return;
2023 }
2024 }
2025 return;
2026 }
2027 // No architecture flags were specified so if this contains a slice that
2028 // matches the host architecture dump only that.
2029 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002030 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2031 E = UB->end_objects();
2032 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00002033 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00002034 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00002035 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002036 std::string ArchiveName;
2037 ArchiveName.clear();
2038 if (ObjOrErr) {
2039 ObjectFile &O = *ObjOrErr.get();
2040 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002041 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00002042 } else if (auto E = isNotObjectErrorInvalidFileType(
2043 ObjOrErr.takeError())) {
2044 report_error(Filename, std::move(E));
2045 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00002046 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00002047 I->getAsArchive()) {
2048 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002049 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002050 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002051 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2052 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00002053 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002054 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002055 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2056 if (!ChildOrErr) {
2057 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2058 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002059 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002060 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002061 if (MachOObjectFile *O =
2062 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002063 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002064 }
Lang Hamesfc209622016-07-14 02:24:01 +00002065 if (Err)
2066 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002067 } else {
2068 consumeError(AOrErr.takeError());
2069 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002070 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002071 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002072 }
2073 return;
2074 }
2075 }
2076 }
2077 // Either all architectures have been specified or none have been specified
2078 // and this does not contain the host architecture so dump all the slices.
2079 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2080 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2081 E = UB->end_objects();
2082 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00002083 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002084 std::string ArchitectureName = "";
2085 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00002086 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002087 if (ObjOrErr) {
2088 ObjectFile &Obj = *ObjOrErr.get();
2089 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002090 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00002091 } else if (auto E = isNotObjectErrorInvalidFileType(
2092 ObjOrErr.takeError())) {
2093 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
2094 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00002095 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2096 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00002097 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002098 outs() << "Archive : " << Filename;
2099 if (!ArchitectureName.empty())
2100 outs() << " (architecture " << ArchitectureName << ")";
2101 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002102 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002103 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2104 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00002105 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002106 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002107 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2108 if (!ChildOrErr) {
2109 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00002110 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002111 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002112 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002113 if (MachOObjectFile *O =
2114 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2115 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002116 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2117 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002118 }
2119 }
Lang Hamesfc209622016-07-14 02:24:01 +00002120 if (Err)
2121 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00002122 } else {
2123 consumeError(AOrErr.takeError());
2124 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00002125 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00002126 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002127 }
2128 }
2129 return;
2130 }
2131 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2132 if (!checkMachOAndArchFlags(O, Filename))
2133 return;
2134 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002135 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002136 } else
2137 errs() << "llvm-objdump: '" << Filename << "': "
2138 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002139 return;
2140 }
2141 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002142}
2143
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002144// The block of info used by the Symbolizer call backs.
2145struct DisassembleInfo {
2146 bool verbose;
2147 MachOObjectFile *O;
2148 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002149 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002150 std::vector<SectionRef> *Sections;
2151 const char *class_name;
2152 const char *selector_name;
2153 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00002154 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002155 uint64_t adrp_addr;
2156 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002157 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00002158 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002159};
2160
2161// SymbolizerGetOpInfo() is the operand information call back function.
2162// This is called to get the symbolic information for operand(s) of an
2163// instruction when it is being done. This routine does this from
2164// the relocation information, symbol table, etc. That block of information
2165// is a pointer to the struct DisassembleInfo that was passed when the
2166// disassembler context was created and passed to back to here when
2167// called back by the disassembler for instruction operands that could have
2168// relocation information. The address of the instruction containing operand is
2169// at the Pc parameter. The immediate value the operand has is passed in
2170// op_info->Value and is at Offset past the start of the instruction and has a
2171// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2172// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2173// names and addends of the symbolic expression to add for the operand. The
2174// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2175// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002176static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2177 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002178 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2179 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002180 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002181
2182 // Make sure all fields returned are zero if we don't set them.
2183 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2184 op_info->Value = value;
2185
2186 // If the TagType is not the value 1 which it code knows about or if no
2187 // verbose symbolic information is wanted then just return 0, indicating no
2188 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002189 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002190 return 0;
2191
2192 unsigned int Arch = info->O->getArch();
2193 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002194 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2195 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002196 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2197 // TODO:
2198 // Search the external relocation entries of a fully linked image
2199 // (if any) for an entry that matches this segment offset.
2200 // uint32_t seg_offset = (Pc + Offset);
2201 return 0;
2202 }
2203 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2204 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002205 uint32_t sect_addr = info->S.getAddress();
2206 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2207 bool reloc_found = false;
2208 DataRefImpl Rel;
2209 MachO::any_relocation_info RE;
2210 bool isExtern = false;
2211 SymbolRef Symbol;
2212 bool r_scattered = false;
2213 uint32_t r_value, pair_r_value, r_type;
2214 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002215 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002216 if (RelocOffset == sect_offset) {
2217 Rel = Reloc.getRawDataRefImpl();
2218 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002219 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002220 r_scattered = info->O->isRelocationScattered(RE);
2221 if (r_scattered) {
2222 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002223 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2224 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2225 DataRefImpl RelNext = Rel;
2226 info->O->moveRelocationNext(RelNext);
2227 MachO::any_relocation_info RENext;
2228 RENext = info->O->getRelocation(RelNext);
2229 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002230 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002231 else
2232 return 0;
2233 }
2234 } else {
2235 isExtern = info->O->getPlainRelocationExternal(RE);
2236 if (isExtern) {
2237 symbol_iterator RelocSym = Reloc.getSymbol();
2238 Symbol = *RelocSym;
2239 }
2240 }
2241 reloc_found = true;
2242 break;
2243 }
2244 }
2245 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002246 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002247 if (!SymName)
2248 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002249 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002250 op_info->AddSymbol.Present = 1;
2251 op_info->AddSymbol.Name = name;
2252 // For i386 extern relocation entries the value in the instruction is
2253 // the offset from the symbol, and value is already set in op_info->Value.
2254 return 1;
2255 }
2256 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2257 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002258 const char *add = GuessSymbolName(r_value, info->AddrMap);
2259 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002260 uint32_t offset = value - (r_value - pair_r_value);
2261 op_info->AddSymbol.Present = 1;
2262 if (add != nullptr)
2263 op_info->AddSymbol.Name = add;
2264 else
2265 op_info->AddSymbol.Value = r_value;
2266 op_info->SubtractSymbol.Present = 1;
2267 if (sub != nullptr)
2268 op_info->SubtractSymbol.Name = sub;
2269 else
2270 op_info->SubtractSymbol.Value = pair_r_value;
2271 op_info->Value = offset;
2272 return 1;
2273 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002274 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002275 }
2276 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002277 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2278 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002279 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2280 // relocation entries of a linked image (if any) for an entry that matches
2281 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002282 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002283 uint64_t seg_offset = Pc + Offset;
2284 bool reloc_found = false;
2285 DataRefImpl Rel;
2286 MachO::any_relocation_info RE;
2287 bool isExtern = false;
2288 SymbolRef Symbol;
2289 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2290 uint64_t RelocOffset = Reloc.getOffset();
2291 if (RelocOffset == seg_offset) {
2292 Rel = Reloc.getRawDataRefImpl();
2293 RE = info->O->getRelocation(Rel);
2294 // external relocation entries should always be external.
2295 isExtern = info->O->getPlainRelocationExternal(RE);
2296 if (isExtern) {
2297 symbol_iterator RelocSym = Reloc.getSymbol();
2298 Symbol = *RelocSym;
2299 }
2300 reloc_found = true;
2301 break;
2302 }
2303 }
2304 if (reloc_found && isExtern) {
2305 // The Value passed in will be adjusted by the Pc if the instruction
2306 // adds the Pc. But for x86_64 external relocation entries the Value
2307 // is the offset from the external symbol.
2308 if (info->O->getAnyRelocationPCRel(RE))
2309 op_info->Value -= Pc + Offset + Size;
2310 Expected<StringRef> SymName = Symbol.getName();
2311 if (!SymName)
2312 report_error(info->O->getFileName(), SymName.takeError());
2313 const char *name = SymName->data();
2314 op_info->AddSymbol.Present = 1;
2315 op_info->AddSymbol.Name = name;
2316 return 1;
2317 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002318 return 0;
2319 }
2320 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2321 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002322 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002323 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2324 bool reloc_found = false;
2325 DataRefImpl Rel;
2326 MachO::any_relocation_info RE;
2327 bool isExtern = false;
2328 SymbolRef Symbol;
2329 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002330 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002331 if (RelocOffset == sect_offset) {
2332 Rel = Reloc.getRawDataRefImpl();
2333 RE = info->O->getRelocation(Rel);
2334 // NOTE: Scattered relocations don't exist on x86_64.
2335 isExtern = info->O->getPlainRelocationExternal(RE);
2336 if (isExtern) {
2337 symbol_iterator RelocSym = Reloc.getSymbol();
2338 Symbol = *RelocSym;
2339 }
2340 reloc_found = true;
2341 break;
2342 }
2343 }
2344 if (reloc_found && isExtern) {
2345 // The Value passed in will be adjusted by the Pc if the instruction
2346 // adds the Pc. But for x86_64 external relocation entries the Value
2347 // is the offset from the external symbol.
2348 if (info->O->getAnyRelocationPCRel(RE))
2349 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002350 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002351 if (!SymName)
2352 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002353 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002354 unsigned Type = info->O->getAnyRelocationType(RE);
2355 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2356 DataRefImpl RelNext = Rel;
2357 info->O->moveRelocationNext(RelNext);
2358 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2359 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2360 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2361 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2362 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2363 op_info->SubtractSymbol.Present = 1;
2364 op_info->SubtractSymbol.Name = name;
2365 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2366 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002367 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002368 if (!SymNameNext)
2369 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002370 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002371 }
2372 }
2373 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2374 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2375 op_info->AddSymbol.Present = 1;
2376 op_info->AddSymbol.Name = name;
2377 return 1;
2378 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002379 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002380 }
2381 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002382 if (Offset != 0 || (Size != 4 && Size != 2))
2383 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002384 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2385 // TODO:
2386 // Search the external relocation entries of a fully linked image
2387 // (if any) for an entry that matches this segment offset.
2388 // uint32_t seg_offset = (Pc + Offset);
2389 return 0;
2390 }
2391 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2392 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002393 uint32_t sect_addr = info->S.getAddress();
2394 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002395 DataRefImpl Rel;
2396 MachO::any_relocation_info RE;
2397 bool isExtern = false;
2398 SymbolRef Symbol;
2399 bool r_scattered = false;
2400 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002401 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002402 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2403 uint64_t RelocOffset = Reloc.getOffset();
2404 return RelocOffset == sect_offset;
2405 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002406
2407 if (Reloc == info->S.relocations().end())
2408 return 0;
2409
2410 Rel = Reloc->getRawDataRefImpl();
2411 RE = info->O->getRelocation(Rel);
2412 r_length = info->O->getAnyRelocationLength(RE);
2413 r_scattered = info->O->isRelocationScattered(RE);
2414 if (r_scattered) {
2415 r_value = info->O->getScatteredRelocationValue(RE);
2416 r_type = info->O->getScatteredRelocationType(RE);
2417 } else {
2418 r_type = info->O->getAnyRelocationType(RE);
2419 isExtern = info->O->getPlainRelocationExternal(RE);
2420 if (isExtern) {
2421 symbol_iterator RelocSym = Reloc->getSymbol();
2422 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002423 }
2424 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002425 if (r_type == MachO::ARM_RELOC_HALF ||
2426 r_type == MachO::ARM_RELOC_SECTDIFF ||
2427 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2428 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2429 DataRefImpl RelNext = Rel;
2430 info->O->moveRelocationNext(RelNext);
2431 MachO::any_relocation_info RENext;
2432 RENext = info->O->getRelocation(RelNext);
2433 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2434 if (info->O->isRelocationScattered(RENext))
2435 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2436 }
2437
2438 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002439 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002440 if (!SymName)
2441 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002442 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002443 op_info->AddSymbol.Present = 1;
2444 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002445 switch (r_type) {
2446 case MachO::ARM_RELOC_HALF:
2447 if ((r_length & 0x1) == 1) {
2448 op_info->Value = value << 16 | other_half;
2449 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2450 } else {
2451 op_info->Value = other_half << 16 | value;
2452 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002453 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002454 break;
2455 default:
2456 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002457 }
2458 return 1;
2459 }
2460 // If we have a branch that is not an external relocation entry then
2461 // return 0 so the code in tryAddingSymbolicOperand() can use the
2462 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002463 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002464 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2465 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002466 return 0;
2467
2468 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002469 if (r_type == MachO::ARM_RELOC_HALF ||
2470 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2471 if ((r_length & 0x1) == 1)
2472 value = value << 16 | other_half;
2473 else
2474 value = other_half << 16 | value;
2475 }
2476 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2477 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2478 offset = value - r_value;
2479 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002480 }
2481
David Blaikie33dd45d02015-03-23 18:39:02 +00002482 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002483 if ((r_length & 0x1) == 1)
2484 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2485 else
2486 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002487 const char *add = GuessSymbolName(r_value, info->AddrMap);
2488 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002489 int32_t offset = value - (r_value - pair_r_value);
2490 op_info->AddSymbol.Present = 1;
2491 if (add != nullptr)
2492 op_info->AddSymbol.Name = add;
2493 else
2494 op_info->AddSymbol.Value = r_value;
2495 op_info->SubtractSymbol.Present = 1;
2496 if (sub != nullptr)
2497 op_info->SubtractSymbol.Name = sub;
2498 else
2499 op_info->SubtractSymbol.Value = pair_r_value;
2500 op_info->Value = offset;
2501 return 1;
2502 }
2503
Kevin Enderby930fdc72014-11-06 19:00:13 +00002504 op_info->AddSymbol.Present = 1;
2505 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002506 if (r_type == MachO::ARM_RELOC_HALF) {
2507 if ((r_length & 0x1) == 1)
2508 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2509 else
2510 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002511 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002512 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002513 if (add != nullptr) {
2514 op_info->AddSymbol.Name = add;
2515 return 1;
2516 }
2517 op_info->AddSymbol.Value = value;
2518 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002519 }
2520 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002521 if (Offset != 0 || Size != 4)
2522 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002523 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2524 // TODO:
2525 // Search the external relocation entries of a fully linked image
2526 // (if any) for an entry that matches this segment offset.
2527 // uint64_t seg_offset = (Pc + Offset);
2528 return 0;
2529 }
2530 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2531 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002532 uint64_t sect_addr = info->S.getAddress();
2533 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002534 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002535 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2536 uint64_t RelocOffset = Reloc.getOffset();
2537 return RelocOffset == sect_offset;
2538 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002539
David Blaikie33dd45d02015-03-23 18:39:02 +00002540 if (Reloc == info->S.relocations().end())
2541 return 0;
2542
2543 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2544 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2545 uint32_t r_type = info->O->getAnyRelocationType(RE);
2546 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2547 DataRefImpl RelNext = Rel;
2548 info->O->moveRelocationNext(RelNext);
2549 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2550 if (value == 0) {
2551 value = info->O->getPlainRelocationSymbolNum(RENext);
2552 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002553 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002554 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002555 // NOTE: Scattered relocations don't exist on arm64.
2556 if (!info->O->getPlainRelocationExternal(RE))
2557 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002558 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002559 if (!SymName)
2560 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002561 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002562 op_info->AddSymbol.Present = 1;
2563 op_info->AddSymbol.Name = name;
2564
2565 switch (r_type) {
2566 case MachO::ARM64_RELOC_PAGE21:
2567 /* @page */
2568 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2569 break;
2570 case MachO::ARM64_RELOC_PAGEOFF12:
2571 /* @pageoff */
2572 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2573 break;
2574 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2575 /* @gotpage */
2576 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2577 break;
2578 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2579 /* @gotpageoff */
2580 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2581 break;
2582 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2583 /* @tvlppage is not implemented in llvm-mc */
2584 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2585 break;
2586 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2587 /* @tvlppageoff is not implemented in llvm-mc */
2588 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2589 break;
2590 default:
2591 case MachO::ARM64_RELOC_BRANCH26:
2592 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2593 break;
2594 }
2595 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002596 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002597 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002598}
2599
Kevin Enderbybf246f52014-09-24 23:08:22 +00002600// GuessCstringPointer is passed the address of what might be a pointer to a
2601// literal string in a cstring section. If that address is in a cstring section
2602// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002603static const char *GuessCstringPointer(uint64_t ReferenceValue,
2604 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002605 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002606 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2607 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2608 for (unsigned J = 0; J < Seg.nsects; ++J) {
2609 MachO::section_64 Sec = info->O->getSection64(Load, J);
2610 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2611 if (section_type == MachO::S_CSTRING_LITERALS &&
2612 ReferenceValue >= Sec.addr &&
2613 ReferenceValue < Sec.addr + Sec.size) {
2614 uint64_t sect_offset = ReferenceValue - Sec.addr;
2615 uint64_t object_offset = Sec.offset + sect_offset;
2616 StringRef MachOContents = info->O->getData();
2617 uint64_t object_size = MachOContents.size();
2618 const char *object_addr = (const char *)MachOContents.data();
2619 if (object_offset < object_size) {
2620 const char *name = object_addr + object_offset;
2621 return name;
2622 } else {
2623 return nullptr;
2624 }
2625 }
2626 }
2627 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2628 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2629 for (unsigned J = 0; J < Seg.nsects; ++J) {
2630 MachO::section Sec = info->O->getSection(Load, J);
2631 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2632 if (section_type == MachO::S_CSTRING_LITERALS &&
2633 ReferenceValue >= Sec.addr &&
2634 ReferenceValue < Sec.addr + Sec.size) {
2635 uint64_t sect_offset = ReferenceValue - Sec.addr;
2636 uint64_t object_offset = Sec.offset + sect_offset;
2637 StringRef MachOContents = info->O->getData();
2638 uint64_t object_size = MachOContents.size();
2639 const char *object_addr = (const char *)MachOContents.data();
2640 if (object_offset < object_size) {
2641 const char *name = object_addr + object_offset;
2642 return name;
2643 } else {
2644 return nullptr;
2645 }
2646 }
2647 }
2648 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002649 }
2650 return nullptr;
2651}
2652
Kevin Enderby85974882014-09-26 22:20:44 +00002653// GuessIndirectSymbol returns the name of the indirect symbol for the
2654// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2655// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2656// symbol name being referenced by the stub or pointer.
2657static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2658 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002659 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2660 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002661 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002662 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2663 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2664 for (unsigned J = 0; J < Seg.nsects; ++J) {
2665 MachO::section_64 Sec = info->O->getSection64(Load, J);
2666 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2667 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2668 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2669 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2670 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2671 section_type == MachO::S_SYMBOL_STUBS) &&
2672 ReferenceValue >= Sec.addr &&
2673 ReferenceValue < Sec.addr + Sec.size) {
2674 uint32_t stride;
2675 if (section_type == MachO::S_SYMBOL_STUBS)
2676 stride = Sec.reserved2;
2677 else
2678 stride = 8;
2679 if (stride == 0)
2680 return nullptr;
2681 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2682 if (index < Dysymtab.nindirectsyms) {
2683 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002684 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002685 if (indirect_symbol < Symtab.nsyms) {
2686 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2687 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002688 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002689 if (!SymName)
2690 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002691 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002692 return name;
2693 }
2694 }
2695 }
2696 }
2697 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2698 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2699 for (unsigned J = 0; J < Seg.nsects; ++J) {
2700 MachO::section Sec = info->O->getSection(Load, J);
2701 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2702 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2703 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2704 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2705 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2706 section_type == MachO::S_SYMBOL_STUBS) &&
2707 ReferenceValue >= Sec.addr &&
2708 ReferenceValue < Sec.addr + Sec.size) {
2709 uint32_t stride;
2710 if (section_type == MachO::S_SYMBOL_STUBS)
2711 stride = Sec.reserved2;
2712 else
2713 stride = 4;
2714 if (stride == 0)
2715 return nullptr;
2716 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2717 if (index < Dysymtab.nindirectsyms) {
2718 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002719 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002720 if (indirect_symbol < Symtab.nsyms) {
2721 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2722 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002723 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002724 if (!SymName)
2725 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002726 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002727 return name;
2728 }
2729 }
2730 }
2731 }
2732 }
Kevin Enderby85974882014-09-26 22:20:44 +00002733 }
2734 return nullptr;
2735}
2736
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002737// method_reference() is called passing it the ReferenceName that might be
2738// a reference it to an Objective-C method call. If so then it allocates and
2739// assembles a method call string with the values last seen and saved in
2740// the DisassembleInfo's class_name and selector_name fields. This is saved
2741// into the method field of the info and any previous string is free'ed.
2742// Then the class_name field in the info is set to nullptr. The method call
2743// string is set into ReferenceName and ReferenceType is set to
2744// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2745// then both ReferenceType and ReferenceName are left unchanged.
2746static void method_reference(struct DisassembleInfo *info,
2747 uint64_t *ReferenceType,
2748 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002749 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002750 if (*ReferenceName != nullptr) {
2751 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002752 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002753 if (info->method != nullptr)
2754 free(info->method);
2755 if (info->class_name != nullptr) {
2756 info->method = (char *)malloc(5 + strlen(info->class_name) +
2757 strlen(info->selector_name));
2758 if (info->method != nullptr) {
2759 strcpy(info->method, "+[");
2760 strcat(info->method, info->class_name);
2761 strcat(info->method, " ");
2762 strcat(info->method, info->selector_name);
2763 strcat(info->method, "]");
2764 *ReferenceName = info->method;
2765 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2766 }
2767 } else {
2768 info->method = (char *)malloc(9 + strlen(info->selector_name));
2769 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002770 if (Arch == Triple::x86_64)
2771 strcpy(info->method, "-[%rdi ");
2772 else if (Arch == Triple::aarch64)
2773 strcpy(info->method, "-[x0 ");
2774 else
2775 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002776 strcat(info->method, info->selector_name);
2777 strcat(info->method, "]");
2778 *ReferenceName = info->method;
2779 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2780 }
2781 }
2782 info->class_name = nullptr;
2783 }
2784 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002785 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002786 if (info->method != nullptr)
2787 free(info->method);
2788 info->method = (char *)malloc(17 + strlen(info->selector_name));
2789 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002790 if (Arch == Triple::x86_64)
2791 strcpy(info->method, "-[[%rdi super] ");
2792 else if (Arch == Triple::aarch64)
2793 strcpy(info->method, "-[[x0 super] ");
2794 else
2795 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002796 strcat(info->method, info->selector_name);
2797 strcat(info->method, "]");
2798 *ReferenceName = info->method;
2799 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2800 }
2801 info->class_name = nullptr;
2802 }
2803 }
2804 }
2805}
2806
2807// GuessPointerPointer() is passed the address of what might be a pointer to
2808// a reference to an Objective-C class, selector, message ref or cfstring.
2809// If so the value of the pointer is returned and one of the booleans are set
2810// to true. If not zero is returned and all the booleans are set to false.
2811static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2812 struct DisassembleInfo *info,
2813 bool &classref, bool &selref, bool &msgref,
2814 bool &cfstring) {
2815 classref = false;
2816 selref = false;
2817 msgref = false;
2818 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002819 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002820 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2821 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2822 for (unsigned J = 0; J < Seg.nsects; ++J) {
2823 MachO::section_64 Sec = info->O->getSection64(Load, J);
2824 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2825 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2826 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2827 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2828 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2829 ReferenceValue >= Sec.addr &&
2830 ReferenceValue < Sec.addr + Sec.size) {
2831 uint64_t sect_offset = ReferenceValue - Sec.addr;
2832 uint64_t object_offset = Sec.offset + sect_offset;
2833 StringRef MachOContents = info->O->getData();
2834 uint64_t object_size = MachOContents.size();
2835 const char *object_addr = (const char *)MachOContents.data();
2836 if (object_offset < object_size) {
2837 uint64_t pointer_value;
2838 memcpy(&pointer_value, object_addr + object_offset,
2839 sizeof(uint64_t));
2840 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2841 sys::swapByteOrder(pointer_value);
2842 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2843 selref = true;
2844 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2845 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2846 classref = true;
2847 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2848 ReferenceValue + 8 < Sec.addr + Sec.size) {
2849 msgref = true;
2850 memcpy(&pointer_value, object_addr + object_offset + 8,
2851 sizeof(uint64_t));
2852 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2853 sys::swapByteOrder(pointer_value);
2854 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2855 cfstring = true;
2856 return pointer_value;
2857 } else {
2858 return 0;
2859 }
2860 }
2861 }
2862 }
2863 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002864 }
2865 return 0;
2866}
2867
2868// get_pointer_64 returns a pointer to the bytes in the object file at the
2869// Address from a section in the Mach-O file. And indirectly returns the
2870// offset into the section, number of bytes left in the section past the offset
2871// and which section is was being referenced. If the Address is not in a
2872// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002873static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2874 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002875 DisassembleInfo *info,
2876 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002877 offset = 0;
2878 left = 0;
2879 S = SectionRef();
2880 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2881 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2882 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002883 if (SectSize == 0)
2884 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002885 if (objc_only) {
2886 StringRef SectName;
2887 ((*(info->Sections))[SectIdx]).getName(SectName);
2888 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2889 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2890 if (SegName != "__OBJC" && SectName != "__cstring")
2891 continue;
2892 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002893 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2894 S = (*(info->Sections))[SectIdx];
2895 offset = Address - SectAddress;
2896 left = SectSize - offset;
2897 StringRef SectContents;
2898 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2899 return SectContents.data() + offset;
2900 }
2901 }
2902 return nullptr;
2903}
2904
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002905static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2906 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002907 DisassembleInfo *info,
2908 bool objc_only = false) {
2909 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002910}
2911
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002912// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2913// the symbol indirectly through n_value. Based on the relocation information
2914// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002915// If no relocation information is found and a non-zero ReferenceValue for the
2916// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002917static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2918 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002919 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002920 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002921 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002922 return nullptr;
2923
2924 // See if there is an external relocation entry at the sect_offset.
2925 bool reloc_found = false;
2926 DataRefImpl Rel;
2927 MachO::any_relocation_info RE;
2928 bool isExtern = false;
2929 SymbolRef Symbol;
2930 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002931 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002932 if (RelocOffset == sect_offset) {
2933 Rel = Reloc.getRawDataRefImpl();
2934 RE = info->O->getRelocation(Rel);
2935 if (info->O->isRelocationScattered(RE))
2936 continue;
2937 isExtern = info->O->getPlainRelocationExternal(RE);
2938 if (isExtern) {
2939 symbol_iterator RelocSym = Reloc.getSymbol();
2940 Symbol = *RelocSym;
2941 }
2942 reloc_found = true;
2943 break;
2944 }
2945 }
2946 // If there is an external relocation entry for a symbol in this section
2947 // at this section_offset then use that symbol's value for the n_value
2948 // and return its name.
2949 const char *SymbolName = nullptr;
2950 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002951 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002952 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002953 if (!NameOrError)
2954 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002955 StringRef Name = *NameOrError;
2956 if (!Name.empty()) {
2957 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002958 return SymbolName;
2959 }
2960 }
2961
2962 // TODO: For fully linked images, look through the external relocation
2963 // entries off the dynamic symtab command. For these the r_offset is from the
2964 // start of the first writeable segment in the Mach-O file. So the offset
2965 // to this section from that segment is passed to this routine by the caller,
2966 // as the database_offset. Which is the difference of the section's starting
2967 // address and the first writable segment.
2968 //
2969 // NOTE: need add passing the database_offset to this routine.
2970
Kevin Enderby0fc11822015-04-01 20:57:01 +00002971 // We did not find an external relocation entry so look up the ReferenceValue
2972 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002973 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002974
2975 return SymbolName;
2976}
2977
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002978static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2979 DisassembleInfo *info,
2980 uint32_t ReferenceValue) {
2981 uint64_t n_value64;
2982 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2983}
2984
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002985// These are structs in the Objective-C meta data and read to produce the
2986// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00002987// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
2988// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002989
2990// The cfstring object in a 64-bit Mach-O file.
2991struct cfstring64_t {
2992 uint64_t isa; // class64_t * (64-bit pointer)
2993 uint64_t flags; // flag bits
2994 uint64_t characters; // char * (64-bit pointer)
2995 uint64_t length; // number of non-NULL characters in above
2996};
2997
2998// The class object in a 64-bit Mach-O file.
2999struct class64_t {
3000 uint64_t isa; // class64_t * (64-bit pointer)
3001 uint64_t superclass; // class64_t * (64-bit pointer)
3002 uint64_t cache; // Cache (64-bit pointer)
3003 uint64_t vtable; // IMP * (64-bit pointer)
3004 uint64_t data; // class_ro64_t * (64-bit pointer)
3005};
3006
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003007struct class32_t {
3008 uint32_t isa; /* class32_t * (32-bit pointer) */
3009 uint32_t superclass; /* class32_t * (32-bit pointer) */
3010 uint32_t cache; /* Cache (32-bit pointer) */
3011 uint32_t vtable; /* IMP * (32-bit pointer) */
3012 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3013};
3014
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003015struct class_ro64_t {
3016 uint32_t flags;
3017 uint32_t instanceStart;
3018 uint32_t instanceSize;
3019 uint32_t reserved;
3020 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3021 uint64_t name; // const char * (64-bit pointer)
3022 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3023 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3024 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3025 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3026 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3027};
3028
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003029struct class_ro32_t {
3030 uint32_t flags;
3031 uint32_t instanceStart;
3032 uint32_t instanceSize;
3033 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3034 uint32_t name; /* const char * (32-bit pointer) */
3035 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3036 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3037 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3038 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3039 uint32_t baseProperties; /* const struct objc_property_list *
3040 (32-bit pointer) */
3041};
3042
3043/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003044#define RO_META (1 << 0)
3045#define RO_ROOT (1 << 1)
3046#define RO_HAS_CXX_STRUCTORS (1 << 2)
3047
3048struct method_list64_t {
3049 uint32_t entsize;
3050 uint32_t count;
3051 /* struct method64_t first; These structures follow inline */
3052};
3053
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003054struct method_list32_t {
3055 uint32_t entsize;
3056 uint32_t count;
3057 /* struct method32_t first; These structures follow inline */
3058};
3059
Kevin Enderby0fc11822015-04-01 20:57:01 +00003060struct method64_t {
3061 uint64_t name; /* SEL (64-bit pointer) */
3062 uint64_t types; /* const char * (64-bit pointer) */
3063 uint64_t imp; /* IMP (64-bit pointer) */
3064};
3065
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003066struct method32_t {
3067 uint32_t name; /* SEL (32-bit pointer) */
3068 uint32_t types; /* const char * (32-bit pointer) */
3069 uint32_t imp; /* IMP (32-bit pointer) */
3070};
3071
Kevin Enderby0fc11822015-04-01 20:57:01 +00003072struct protocol_list64_t {
3073 uint64_t count; /* uintptr_t (a 64-bit value) */
3074 /* struct protocol64_t * list[0]; These pointers follow inline */
3075};
3076
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003077struct protocol_list32_t {
3078 uint32_t count; /* uintptr_t (a 32-bit value) */
3079 /* struct protocol32_t * list[0]; These pointers follow inline */
3080};
3081
Kevin Enderby0fc11822015-04-01 20:57:01 +00003082struct protocol64_t {
3083 uint64_t isa; /* id * (64-bit pointer) */
3084 uint64_t name; /* const char * (64-bit pointer) */
3085 uint64_t protocols; /* struct protocol_list64_t *
3086 (64-bit pointer) */
3087 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3088 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3089 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3090 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3091 uint64_t instanceProperties; /* struct objc_property_list *
3092 (64-bit pointer) */
3093};
3094
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003095struct protocol32_t {
3096 uint32_t isa; /* id * (32-bit pointer) */
3097 uint32_t name; /* const char * (32-bit pointer) */
3098 uint32_t protocols; /* struct protocol_list_t *
3099 (32-bit pointer) */
3100 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3101 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3102 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3103 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3104 uint32_t instanceProperties; /* struct objc_property_list *
3105 (32-bit pointer) */
3106};
3107
Kevin Enderby0fc11822015-04-01 20:57:01 +00003108struct ivar_list64_t {
3109 uint32_t entsize;
3110 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003111 /* struct ivar64_t first; These structures follow inline */
3112};
3113
3114struct ivar_list32_t {
3115 uint32_t entsize;
3116 uint32_t count;
3117 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003118};
3119
3120struct ivar64_t {
3121 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3122 uint64_t name; /* const char * (64-bit pointer) */
3123 uint64_t type; /* const char * (64-bit pointer) */
3124 uint32_t alignment;
3125 uint32_t size;
3126};
3127
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003128struct ivar32_t {
3129 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3130 uint32_t name; /* const char * (32-bit pointer) */
3131 uint32_t type; /* const char * (32-bit pointer) */
3132 uint32_t alignment;
3133 uint32_t size;
3134};
3135
Kevin Enderby0fc11822015-04-01 20:57:01 +00003136struct objc_property_list64 {
3137 uint32_t entsize;
3138 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003139 /* struct objc_property64 first; These structures follow inline */
3140};
3141
3142struct objc_property_list32 {
3143 uint32_t entsize;
3144 uint32_t count;
3145 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003146};
3147
3148struct objc_property64 {
3149 uint64_t name; /* const char * (64-bit pointer) */
3150 uint64_t attributes; /* const char * (64-bit pointer) */
3151};
3152
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003153struct objc_property32 {
3154 uint32_t name; /* const char * (32-bit pointer) */
3155 uint32_t attributes; /* const char * (32-bit pointer) */
3156};
3157
Kevin Enderby0fc11822015-04-01 20:57:01 +00003158struct category64_t {
3159 uint64_t name; /* const char * (64-bit pointer) */
3160 uint64_t cls; /* struct class_t * (64-bit pointer) */
3161 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3162 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3163 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3164 uint64_t instanceProperties; /* struct objc_property_list *
3165 (64-bit pointer) */
3166};
3167
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003168struct category32_t {
3169 uint32_t name; /* const char * (32-bit pointer) */
3170 uint32_t cls; /* struct class_t * (32-bit pointer) */
3171 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3172 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3173 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3174 uint32_t instanceProperties; /* struct objc_property_list *
3175 (32-bit pointer) */
3176};
3177
Kevin Enderby0fc11822015-04-01 20:57:01 +00003178struct objc_image_info64 {
3179 uint32_t version;
3180 uint32_t flags;
3181};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003182struct objc_image_info32 {
3183 uint32_t version;
3184 uint32_t flags;
3185};
Kevin Enderby846c0002015-04-16 17:19:59 +00003186struct imageInfo_t {
3187 uint32_t version;
3188 uint32_t flags;
3189};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003190/* masks for objc_image_info.flags */
3191#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3192#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3193
3194struct message_ref64 {
3195 uint64_t imp; /* IMP (64-bit pointer) */
3196 uint64_t sel; /* SEL (64-bit pointer) */
3197};
3198
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003199struct message_ref32 {
3200 uint32_t imp; /* IMP (32-bit pointer) */
3201 uint32_t sel; /* SEL (32-bit pointer) */
3202};
3203
Kevin Enderby846c0002015-04-16 17:19:59 +00003204// Objective-C 1 (32-bit only) meta data structs.
3205
3206struct objc_module_t {
3207 uint32_t version;
3208 uint32_t size;
3209 uint32_t name; /* char * (32-bit pointer) */
3210 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3211};
3212
3213struct objc_symtab_t {
3214 uint32_t sel_ref_cnt;
3215 uint32_t refs; /* SEL * (32-bit pointer) */
3216 uint16_t cls_def_cnt;
3217 uint16_t cat_def_cnt;
3218 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3219};
3220
3221struct objc_class_t {
3222 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3223 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3224 uint32_t name; /* const char * (32-bit pointer) */
3225 int32_t version;
3226 int32_t info;
3227 int32_t instance_size;
3228 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3229 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3230 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3231 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3232};
3233
3234#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3235// class is not a metaclass
3236#define CLS_CLASS 0x1
3237// class is a metaclass
3238#define CLS_META 0x2
3239
3240struct objc_category_t {
3241 uint32_t category_name; /* char * (32-bit pointer) */
3242 uint32_t class_name; /* char * (32-bit pointer) */
3243 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3244 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3245 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3246};
3247
3248struct objc_ivar_t {
3249 uint32_t ivar_name; /* char * (32-bit pointer) */
3250 uint32_t ivar_type; /* char * (32-bit pointer) */
3251 int32_t ivar_offset;
3252};
3253
3254struct objc_ivar_list_t {
3255 int32_t ivar_count;
3256 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3257};
3258
3259struct objc_method_list_t {
3260 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3261 int32_t method_count;
3262 // struct objc_method_t method_list[1]; /* variable length structure */
3263};
3264
3265struct objc_method_t {
3266 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3267 uint32_t method_types; /* char * (32-bit pointer) */
3268 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3269 (32-bit pointer) */
3270};
3271
3272struct objc_protocol_list_t {
3273 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3274 int32_t count;
3275 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3276 // (32-bit pointer) */
3277};
3278
3279struct objc_protocol_t {
3280 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3281 uint32_t protocol_name; /* char * (32-bit pointer) */
3282 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3283 uint32_t instance_methods; /* struct objc_method_description_list *
3284 (32-bit pointer) */
3285 uint32_t class_methods; /* struct objc_method_description_list *
3286 (32-bit pointer) */
3287};
3288
3289struct objc_method_description_list_t {
3290 int32_t count;
3291 // struct objc_method_description_t list[1];
3292};
3293
3294struct objc_method_description_t {
3295 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3296 uint32_t types; /* char * (32-bit pointer) */
3297};
3298
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003299inline void swapStruct(struct cfstring64_t &cfs) {
3300 sys::swapByteOrder(cfs.isa);
3301 sys::swapByteOrder(cfs.flags);
3302 sys::swapByteOrder(cfs.characters);
3303 sys::swapByteOrder(cfs.length);
3304}
3305
3306inline void swapStruct(struct class64_t &c) {
3307 sys::swapByteOrder(c.isa);
3308 sys::swapByteOrder(c.superclass);
3309 sys::swapByteOrder(c.cache);
3310 sys::swapByteOrder(c.vtable);
3311 sys::swapByteOrder(c.data);
3312}
3313
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003314inline void swapStruct(struct class32_t &c) {
3315 sys::swapByteOrder(c.isa);
3316 sys::swapByteOrder(c.superclass);
3317 sys::swapByteOrder(c.cache);
3318 sys::swapByteOrder(c.vtable);
3319 sys::swapByteOrder(c.data);
3320}
3321
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003322inline void swapStruct(struct class_ro64_t &cro) {
3323 sys::swapByteOrder(cro.flags);
3324 sys::swapByteOrder(cro.instanceStart);
3325 sys::swapByteOrder(cro.instanceSize);
3326 sys::swapByteOrder(cro.reserved);
3327 sys::swapByteOrder(cro.ivarLayout);
3328 sys::swapByteOrder(cro.name);
3329 sys::swapByteOrder(cro.baseMethods);
3330 sys::swapByteOrder(cro.baseProtocols);
3331 sys::swapByteOrder(cro.ivars);
3332 sys::swapByteOrder(cro.weakIvarLayout);
3333 sys::swapByteOrder(cro.baseProperties);
3334}
3335
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003336inline void swapStruct(struct class_ro32_t &cro) {
3337 sys::swapByteOrder(cro.flags);
3338 sys::swapByteOrder(cro.instanceStart);
3339 sys::swapByteOrder(cro.instanceSize);
3340 sys::swapByteOrder(cro.ivarLayout);
3341 sys::swapByteOrder(cro.name);
3342 sys::swapByteOrder(cro.baseMethods);
3343 sys::swapByteOrder(cro.baseProtocols);
3344 sys::swapByteOrder(cro.ivars);
3345 sys::swapByteOrder(cro.weakIvarLayout);
3346 sys::swapByteOrder(cro.baseProperties);
3347}
3348
Kevin Enderby0fc11822015-04-01 20:57:01 +00003349inline void swapStruct(struct method_list64_t &ml) {
3350 sys::swapByteOrder(ml.entsize);
3351 sys::swapByteOrder(ml.count);
3352}
3353
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003354inline void swapStruct(struct method_list32_t &ml) {
3355 sys::swapByteOrder(ml.entsize);
3356 sys::swapByteOrder(ml.count);
3357}
3358
Kevin Enderby0fc11822015-04-01 20:57:01 +00003359inline void swapStruct(struct method64_t &m) {
3360 sys::swapByteOrder(m.name);
3361 sys::swapByteOrder(m.types);
3362 sys::swapByteOrder(m.imp);
3363}
3364
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003365inline void swapStruct(struct method32_t &m) {
3366 sys::swapByteOrder(m.name);
3367 sys::swapByteOrder(m.types);
3368 sys::swapByteOrder(m.imp);
3369}
3370
Kevin Enderby0fc11822015-04-01 20:57:01 +00003371inline void swapStruct(struct protocol_list64_t &pl) {
3372 sys::swapByteOrder(pl.count);
3373}
3374
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003375inline void swapStruct(struct protocol_list32_t &pl) {
3376 sys::swapByteOrder(pl.count);
3377}
3378
Kevin Enderby0fc11822015-04-01 20:57:01 +00003379inline void swapStruct(struct protocol64_t &p) {
3380 sys::swapByteOrder(p.isa);
3381 sys::swapByteOrder(p.name);
3382 sys::swapByteOrder(p.protocols);
3383 sys::swapByteOrder(p.instanceMethods);
3384 sys::swapByteOrder(p.classMethods);
3385 sys::swapByteOrder(p.optionalInstanceMethods);
3386 sys::swapByteOrder(p.optionalClassMethods);
3387 sys::swapByteOrder(p.instanceProperties);
3388}
3389
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003390inline void swapStruct(struct protocol32_t &p) {
3391 sys::swapByteOrder(p.isa);
3392 sys::swapByteOrder(p.name);
3393 sys::swapByteOrder(p.protocols);
3394 sys::swapByteOrder(p.instanceMethods);
3395 sys::swapByteOrder(p.classMethods);
3396 sys::swapByteOrder(p.optionalInstanceMethods);
3397 sys::swapByteOrder(p.optionalClassMethods);
3398 sys::swapByteOrder(p.instanceProperties);
3399}
3400
Kevin Enderby0fc11822015-04-01 20:57:01 +00003401inline void swapStruct(struct ivar_list64_t &il) {
3402 sys::swapByteOrder(il.entsize);
3403 sys::swapByteOrder(il.count);
3404}
3405
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003406inline void swapStruct(struct ivar_list32_t &il) {
3407 sys::swapByteOrder(il.entsize);
3408 sys::swapByteOrder(il.count);
3409}
3410
Kevin Enderby0fc11822015-04-01 20:57:01 +00003411inline void swapStruct(struct ivar64_t &i) {
3412 sys::swapByteOrder(i.offset);
3413 sys::swapByteOrder(i.name);
3414 sys::swapByteOrder(i.type);
3415 sys::swapByteOrder(i.alignment);
3416 sys::swapByteOrder(i.size);
3417}
3418
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003419inline void swapStruct(struct ivar32_t &i) {
3420 sys::swapByteOrder(i.offset);
3421 sys::swapByteOrder(i.name);
3422 sys::swapByteOrder(i.type);
3423 sys::swapByteOrder(i.alignment);
3424 sys::swapByteOrder(i.size);
3425}
3426
Kevin Enderby0fc11822015-04-01 20:57:01 +00003427inline void swapStruct(struct objc_property_list64 &pl) {
3428 sys::swapByteOrder(pl.entsize);
3429 sys::swapByteOrder(pl.count);
3430}
3431
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003432inline void swapStruct(struct objc_property_list32 &pl) {
3433 sys::swapByteOrder(pl.entsize);
3434 sys::swapByteOrder(pl.count);
3435}
3436
Kevin Enderby0fc11822015-04-01 20:57:01 +00003437inline void swapStruct(struct objc_property64 &op) {
3438 sys::swapByteOrder(op.name);
3439 sys::swapByteOrder(op.attributes);
3440}
3441
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003442inline void swapStruct(struct objc_property32 &op) {
3443 sys::swapByteOrder(op.name);
3444 sys::swapByteOrder(op.attributes);
3445}
3446
Kevin Enderby0fc11822015-04-01 20:57:01 +00003447inline void swapStruct(struct category64_t &c) {
3448 sys::swapByteOrder(c.name);
3449 sys::swapByteOrder(c.cls);
3450 sys::swapByteOrder(c.instanceMethods);
3451 sys::swapByteOrder(c.classMethods);
3452 sys::swapByteOrder(c.protocols);
3453 sys::swapByteOrder(c.instanceProperties);
3454}
3455
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003456inline void swapStruct(struct category32_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 Enderby0fc11822015-04-01 20:57:01 +00003465inline void swapStruct(struct objc_image_info64 &o) {
3466 sys::swapByteOrder(o.version);
3467 sys::swapByteOrder(o.flags);
3468}
3469
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003470inline void swapStruct(struct objc_image_info32 &o) {
3471 sys::swapByteOrder(o.version);
3472 sys::swapByteOrder(o.flags);
3473}
3474
Kevin Enderby846c0002015-04-16 17:19:59 +00003475inline void swapStruct(struct imageInfo_t &o) {
3476 sys::swapByteOrder(o.version);
3477 sys::swapByteOrder(o.flags);
3478}
3479
Kevin Enderby0fc11822015-04-01 20:57:01 +00003480inline void swapStruct(struct message_ref64 &mr) {
3481 sys::swapByteOrder(mr.imp);
3482 sys::swapByteOrder(mr.sel);
3483}
3484
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003485inline void swapStruct(struct message_ref32 &mr) {
3486 sys::swapByteOrder(mr.imp);
3487 sys::swapByteOrder(mr.sel);
3488}
3489
Kevin Enderby846c0002015-04-16 17:19:59 +00003490inline void swapStruct(struct objc_module_t &module) {
3491 sys::swapByteOrder(module.version);
3492 sys::swapByteOrder(module.size);
3493 sys::swapByteOrder(module.name);
3494 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003495}
Kevin Enderby846c0002015-04-16 17:19:59 +00003496
3497inline void swapStruct(struct objc_symtab_t &symtab) {
3498 sys::swapByteOrder(symtab.sel_ref_cnt);
3499 sys::swapByteOrder(symtab.refs);
3500 sys::swapByteOrder(symtab.cls_def_cnt);
3501 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003502}
Kevin Enderby846c0002015-04-16 17:19:59 +00003503
3504inline void swapStruct(struct objc_class_t &objc_class) {
3505 sys::swapByteOrder(objc_class.isa);
3506 sys::swapByteOrder(objc_class.super_class);
3507 sys::swapByteOrder(objc_class.name);
3508 sys::swapByteOrder(objc_class.version);
3509 sys::swapByteOrder(objc_class.info);
3510 sys::swapByteOrder(objc_class.instance_size);
3511 sys::swapByteOrder(objc_class.ivars);
3512 sys::swapByteOrder(objc_class.methodLists);
3513 sys::swapByteOrder(objc_class.cache);
3514 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003515}
Kevin Enderby846c0002015-04-16 17:19:59 +00003516
3517inline void swapStruct(struct objc_category_t &objc_category) {
3518 sys::swapByteOrder(objc_category.category_name);
3519 sys::swapByteOrder(objc_category.class_name);
3520 sys::swapByteOrder(objc_category.instance_methods);
3521 sys::swapByteOrder(objc_category.class_methods);
3522 sys::swapByteOrder(objc_category.protocols);
3523}
3524
3525inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3526 sys::swapByteOrder(objc_ivar_list.ivar_count);
3527}
3528
3529inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3530 sys::swapByteOrder(objc_ivar.ivar_name);
3531 sys::swapByteOrder(objc_ivar.ivar_type);
3532 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003533}
Kevin Enderby846c0002015-04-16 17:19:59 +00003534
3535inline void swapStruct(struct objc_method_list_t &method_list) {
3536 sys::swapByteOrder(method_list.obsolete);
3537 sys::swapByteOrder(method_list.method_count);
3538}
3539
3540inline void swapStruct(struct objc_method_t &method) {
3541 sys::swapByteOrder(method.method_name);
3542 sys::swapByteOrder(method.method_types);
3543 sys::swapByteOrder(method.method_imp);
3544}
3545
3546inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3547 sys::swapByteOrder(protocol_list.next);
3548 sys::swapByteOrder(protocol_list.count);
3549}
3550
3551inline void swapStruct(struct objc_protocol_t &protocol) {
3552 sys::swapByteOrder(protocol.isa);
3553 sys::swapByteOrder(protocol.protocol_name);
3554 sys::swapByteOrder(protocol.protocol_list);
3555 sys::swapByteOrder(protocol.instance_methods);
3556 sys::swapByteOrder(protocol.class_methods);
3557}
3558
3559inline void swapStruct(struct objc_method_description_list_t &mdl) {
3560 sys::swapByteOrder(mdl.count);
3561}
3562
3563inline void swapStruct(struct objc_method_description_t &md) {
3564 sys::swapByteOrder(md.name);
3565 sys::swapByteOrder(md.types);
3566}
3567
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003568static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3569 struct DisassembleInfo *info);
3570
3571// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3572// to an Objective-C class and returns the class name. It is also passed the
3573// address of the pointer, so when the pointer is zero as it can be in an .o
3574// file, that is used to look for an external relocation entry with a symbol
3575// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003576static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3577 uint64_t ReferenceValue,
3578 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003579 const char *r;
3580 uint32_t offset, left;
3581 SectionRef S;
3582
3583 // The pointer_value can be 0 in an object file and have a relocation
3584 // entry for the class symbol at the ReferenceValue (the address of the
3585 // pointer).
3586 if (pointer_value == 0) {
3587 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3588 if (r == nullptr || left < sizeof(uint64_t))
3589 return nullptr;
3590 uint64_t n_value;
3591 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3592 if (symbol_name == nullptr)
3593 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003594 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003595 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3596 return class_name + 2;
3597 else
3598 return nullptr;
3599 }
3600
3601 // The case were the pointer_value is non-zero and points to a class defined
3602 // in this Mach-O file.
3603 r = get_pointer_64(pointer_value, offset, left, S, info);
3604 if (r == nullptr || left < sizeof(struct class64_t))
3605 return nullptr;
3606 struct class64_t c;
3607 memcpy(&c, r, sizeof(struct class64_t));
3608 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3609 swapStruct(c);
3610 if (c.data == 0)
3611 return nullptr;
3612 r = get_pointer_64(c.data, offset, left, S, info);
3613 if (r == nullptr || left < sizeof(struct class_ro64_t))
3614 return nullptr;
3615 struct class_ro64_t cro;
3616 memcpy(&cro, r, sizeof(struct class_ro64_t));
3617 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3618 swapStruct(cro);
3619 if (cro.name == 0)
3620 return nullptr;
3621 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3622 return name;
3623}
3624
3625// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3626// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003627static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3628 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003629 const char *r, *name;
3630 uint32_t offset, left;
3631 SectionRef S;
3632 struct cfstring64_t cfs;
3633 uint64_t cfs_characters;
3634
3635 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3636 if (r == nullptr || left < sizeof(struct cfstring64_t))
3637 return nullptr;
3638 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3639 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3640 swapStruct(cfs);
3641 if (cfs.characters == 0) {
3642 uint64_t n_value;
3643 const char *symbol_name = get_symbol_64(
3644 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3645 if (symbol_name == nullptr)
3646 return nullptr;
3647 cfs_characters = n_value;
3648 } else
3649 cfs_characters = cfs.characters;
3650 name = get_pointer_64(cfs_characters, offset, left, S, info);
3651
3652 return name;
3653}
3654
3655// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3656// of a pointer to an Objective-C selector reference when the pointer value is
3657// zero as in a .o file and is likely to have a external relocation entry with
3658// who's symbol's n_value is the real pointer to the selector name. If that is
3659// the case the real pointer to the selector name is returned else 0 is
3660// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003661static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3662 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003663 uint32_t offset, left;
3664 SectionRef S;
3665
3666 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3667 if (r == nullptr || left < sizeof(uint64_t))
3668 return 0;
3669 uint64_t n_value;
3670 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3671 if (symbol_name == nullptr)
3672 return 0;
3673 return n_value;
3674}
3675
Kevin Enderby0fc11822015-04-01 20:57:01 +00003676static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3677 const char *sectname) {
3678 for (const SectionRef &Section : O->sections()) {
3679 StringRef SectName;
3680 Section.getName(SectName);
3681 DataRefImpl Ref = Section.getRawDataRefImpl();
3682 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3683 if (SegName == segname && SectName == sectname)
3684 return Section;
3685 }
3686 return SectionRef();
3687}
3688
3689static void
3690walk_pointer_list_64(const char *listname, const SectionRef S,
3691 MachOObjectFile *O, struct DisassembleInfo *info,
3692 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3693 if (S == SectionRef())
3694 return;
3695
3696 StringRef SectName;
3697 S.getName(SectName);
3698 DataRefImpl Ref = S.getRawDataRefImpl();
3699 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3700 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3701
3702 StringRef BytesStr;
3703 S.getContents(BytesStr);
3704 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3705
3706 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3707 uint32_t left = S.getSize() - i;
3708 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3709 uint64_t p = 0;
3710 memcpy(&p, Contents + i, size);
3711 if (i + sizeof(uint64_t) > S.getSize())
3712 outs() << listname << " list pointer extends past end of (" << SegName
3713 << "," << SectName << ") section\n";
3714 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3715
3716 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3717 sys::swapByteOrder(p);
3718
3719 uint64_t n_value = 0;
3720 const char *name = get_symbol_64(i, S, info, n_value, p);
3721 if (name == nullptr)
3722 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3723
3724 if (n_value != 0) {
3725 outs() << format("0x%" PRIx64, n_value);
3726 if (p != 0)
3727 outs() << " + " << format("0x%" PRIx64, p);
3728 } else
3729 outs() << format("0x%" PRIx64, p);
3730 if (name != nullptr)
3731 outs() << " " << name;
3732 outs() << "\n";
3733
3734 p += n_value;
3735 if (func)
3736 func(p, info);
3737 }
3738}
3739
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003740static void
3741walk_pointer_list_32(const char *listname, const SectionRef S,
3742 MachOObjectFile *O, struct DisassembleInfo *info,
3743 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3744 if (S == SectionRef())
3745 return;
3746
3747 StringRef SectName;
3748 S.getName(SectName);
3749 DataRefImpl Ref = S.getRawDataRefImpl();
3750 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3751 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3752
3753 StringRef BytesStr;
3754 S.getContents(BytesStr);
3755 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3756
3757 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3758 uint32_t left = S.getSize() - i;
3759 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3760 uint32_t p = 0;
3761 memcpy(&p, Contents + i, size);
3762 if (i + sizeof(uint32_t) > S.getSize())
3763 outs() << listname << " list pointer extends past end of (" << SegName
3764 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003765 uint32_t Address = S.getAddress() + i;
3766 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003767
3768 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3769 sys::swapByteOrder(p);
3770 outs() << format("0x%" PRIx32, p);
3771
3772 const char *name = get_symbol_32(i, S, info, p);
3773 if (name != nullptr)
3774 outs() << " " << name;
3775 outs() << "\n";
3776
3777 if (func)
3778 func(p, info);
3779 }
3780}
3781
3782static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003783 if (layout_map == nullptr)
3784 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003785 outs() << " layout map: ";
3786 do {
3787 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3788 left--;
3789 layout_map++;
3790 } while (*layout_map != '\0' && left != 0);
3791 outs() << "\n";
3792}
3793
Kevin Enderby0fc11822015-04-01 20:57:01 +00003794static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3795 uint32_t offset, left;
3796 SectionRef S;
3797 const char *layout_map;
3798
3799 if (p == 0)
3800 return;
3801 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003802 print_layout_map(layout_map, left);
3803}
3804
3805static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3806 uint32_t offset, left;
3807 SectionRef S;
3808 const char *layout_map;
3809
3810 if (p == 0)
3811 return;
3812 layout_map = get_pointer_32(p, offset, left, S, info);
3813 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003814}
3815
3816static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3817 const char *indent) {
3818 struct method_list64_t ml;
3819 struct method64_t m;
3820 const char *r;
3821 uint32_t offset, xoffset, left, i;
3822 SectionRef S, xS;
3823 const char *name, *sym_name;
3824 uint64_t n_value;
3825
3826 r = get_pointer_64(p, offset, left, S, info);
3827 if (r == nullptr)
3828 return;
3829 memset(&ml, '\0', sizeof(struct method_list64_t));
3830 if (left < sizeof(struct method_list64_t)) {
3831 memcpy(&ml, r, left);
3832 outs() << " (method_list_t entends past the end of the section)\n";
3833 } else
3834 memcpy(&ml, r, sizeof(struct method_list64_t));
3835 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3836 swapStruct(ml);
3837 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3838 outs() << indent << "\t\t count " << ml.count << "\n";
3839
3840 p += sizeof(struct method_list64_t);
3841 offset += sizeof(struct method_list64_t);
3842 for (i = 0; i < ml.count; i++) {
3843 r = get_pointer_64(p, offset, left, S, info);
3844 if (r == nullptr)
3845 return;
3846 memset(&m, '\0', sizeof(struct method64_t));
3847 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003848 memcpy(&m, r, left);
3849 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003850 } else
3851 memcpy(&m, r, sizeof(struct method64_t));
3852 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3853 swapStruct(m);
3854
3855 outs() << indent << "\t\t name ";
3856 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3857 info, n_value, m.name);
3858 if (n_value != 0) {
3859 if (info->verbose && sym_name != nullptr)
3860 outs() << sym_name;
3861 else
3862 outs() << format("0x%" PRIx64, n_value);
3863 if (m.name != 0)
3864 outs() << " + " << format("0x%" PRIx64, m.name);
3865 } else
3866 outs() << format("0x%" PRIx64, m.name);
3867 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3868 if (name != nullptr)
3869 outs() << format(" %.*s", left, name);
3870 outs() << "\n";
3871
3872 outs() << indent << "\t\t types ";
3873 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3874 info, n_value, m.types);
3875 if (n_value != 0) {
3876 if (info->verbose && sym_name != nullptr)
3877 outs() << sym_name;
3878 else
3879 outs() << format("0x%" PRIx64, n_value);
3880 if (m.types != 0)
3881 outs() << " + " << format("0x%" PRIx64, m.types);
3882 } else
3883 outs() << format("0x%" PRIx64, m.types);
3884 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3885 if (name != nullptr)
3886 outs() << format(" %.*s", left, name);
3887 outs() << "\n";
3888
3889 outs() << indent << "\t\t imp ";
3890 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3891 n_value, m.imp);
3892 if (info->verbose && name == nullptr) {
3893 if (n_value != 0) {
3894 outs() << format("0x%" PRIx64, n_value) << " ";
3895 if (m.imp != 0)
3896 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3897 } else
3898 outs() << format("0x%" PRIx64, m.imp) << " ";
3899 }
3900 if (name != nullptr)
3901 outs() << name;
3902 outs() << "\n";
3903
3904 p += sizeof(struct method64_t);
3905 offset += sizeof(struct method64_t);
3906 }
3907}
3908
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003909static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3910 const char *indent) {
3911 struct method_list32_t ml;
3912 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003913 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003914 uint32_t offset, xoffset, left, i;
3915 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003916
3917 r = get_pointer_32(p, offset, left, S, info);
3918 if (r == nullptr)
3919 return;
3920 memset(&ml, '\0', sizeof(struct method_list32_t));
3921 if (left < sizeof(struct method_list32_t)) {
3922 memcpy(&ml, r, left);
3923 outs() << " (method_list_t entends past the end of the section)\n";
3924 } else
3925 memcpy(&ml, r, sizeof(struct method_list32_t));
3926 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3927 swapStruct(ml);
3928 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3929 outs() << indent << "\t\t count " << ml.count << "\n";
3930
3931 p += sizeof(struct method_list32_t);
3932 offset += sizeof(struct method_list32_t);
3933 for (i = 0; i < ml.count; i++) {
3934 r = get_pointer_32(p, offset, left, S, info);
3935 if (r == nullptr)
3936 return;
3937 memset(&m, '\0', sizeof(struct method32_t));
3938 if (left < sizeof(struct method32_t)) {
3939 memcpy(&ml, r, left);
3940 outs() << indent << " (method_t entends past the end of the section)\n";
3941 } else
3942 memcpy(&m, r, sizeof(struct method32_t));
3943 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3944 swapStruct(m);
3945
3946 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3947 name = get_pointer_32(m.name, xoffset, left, xS, info);
3948 if (name != nullptr)
3949 outs() << format(" %.*s", left, name);
3950 outs() << "\n";
3951
3952 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3953 name = get_pointer_32(m.types, xoffset, left, xS, info);
3954 if (name != nullptr)
3955 outs() << format(" %.*s", left, name);
3956 outs() << "\n";
3957
3958 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3959 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3960 m.imp);
3961 if (name != nullptr)
3962 outs() << " " << name;
3963 outs() << "\n";
3964
3965 p += sizeof(struct method32_t);
3966 offset += sizeof(struct method32_t);
3967 }
3968}
3969
Kevin Enderby846c0002015-04-16 17:19:59 +00003970static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3971 uint32_t offset, left, xleft;
3972 SectionRef S;
3973 struct objc_method_list_t method_list;
3974 struct objc_method_t method;
3975 const char *r, *methods, *name, *SymbolName;
3976 int32_t i;
3977
3978 r = get_pointer_32(p, offset, left, S, info, true);
3979 if (r == nullptr)
3980 return true;
3981
3982 outs() << "\n";
3983 if (left > sizeof(struct objc_method_list_t)) {
3984 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3985 } else {
3986 outs() << "\t\t objc_method_list extends past end of the section\n";
3987 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3988 memcpy(&method_list, r, left);
3989 }
3990 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3991 swapStruct(method_list);
3992
3993 outs() << "\t\t obsolete "
3994 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3995 outs() << "\t\t method_count " << method_list.method_count << "\n";
3996
3997 methods = r + sizeof(struct objc_method_list_t);
3998 for (i = 0; i < method_list.method_count; i++) {
3999 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4000 outs() << "\t\t remaining method's extend past the of the section\n";
4001 break;
4002 }
4003 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4004 sizeof(struct objc_method_t));
4005 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4006 swapStruct(method);
4007
4008 outs() << "\t\t method_name "
4009 << format("0x%08" PRIx32, method.method_name);
4010 if (info->verbose) {
4011 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", xleft, name);
4014 else
4015 outs() << " (not in an __OBJC section)";
4016 }
4017 outs() << "\n";
4018
4019 outs() << "\t\t method_types "
4020 << format("0x%08" PRIx32, method.method_types);
4021 if (info->verbose) {
4022 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4023 if (name != nullptr)
4024 outs() << format(" %.*s", xleft, name);
4025 else
4026 outs() << " (not in an __OBJC section)";
4027 }
4028 outs() << "\n";
4029
4030 outs() << "\t\t method_imp "
4031 << format("0x%08" PRIx32, method.method_imp) << " ";
4032 if (info->verbose) {
4033 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4034 if (SymbolName != nullptr)
4035 outs() << SymbolName;
4036 }
4037 outs() << "\n";
4038 }
4039 return false;
4040}
4041
Kevin Enderby0fc11822015-04-01 20:57:01 +00004042static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4043 struct protocol_list64_t pl;
4044 uint64_t q, n_value;
4045 struct protocol64_t pc;
4046 const char *r;
4047 uint32_t offset, xoffset, left, i;
4048 SectionRef S, xS;
4049 const char *name, *sym_name;
4050
4051 r = get_pointer_64(p, offset, left, S, info);
4052 if (r == nullptr)
4053 return;
4054 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4055 if (left < sizeof(struct protocol_list64_t)) {
4056 memcpy(&pl, r, left);
4057 outs() << " (protocol_list_t entends past the end of the section)\n";
4058 } else
4059 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4061 swapStruct(pl);
4062 outs() << " count " << pl.count << "\n";
4063
4064 p += sizeof(struct protocol_list64_t);
4065 offset += sizeof(struct protocol_list64_t);
4066 for (i = 0; i < pl.count; i++) {
4067 r = get_pointer_64(p, offset, left, S, info);
4068 if (r == nullptr)
4069 return;
4070 q = 0;
4071 if (left < sizeof(uint64_t)) {
4072 memcpy(&q, r, left);
4073 outs() << " (protocol_t * entends past the end of the section)\n";
4074 } else
4075 memcpy(&q, r, sizeof(uint64_t));
4076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4077 sys::swapByteOrder(q);
4078
4079 outs() << "\t\t list[" << i << "] ";
4080 sym_name = get_symbol_64(offset, S, info, n_value, q);
4081 if (n_value != 0) {
4082 if (info->verbose && sym_name != nullptr)
4083 outs() << sym_name;
4084 else
4085 outs() << format("0x%" PRIx64, n_value);
4086 if (q != 0)
4087 outs() << " + " << format("0x%" PRIx64, q);
4088 } else
4089 outs() << format("0x%" PRIx64, q);
4090 outs() << " (struct protocol_t *)\n";
4091
4092 r = get_pointer_64(q + n_value, offset, left, S, info);
4093 if (r == nullptr)
4094 return;
4095 memset(&pc, '\0', sizeof(struct protocol64_t));
4096 if (left < sizeof(struct protocol64_t)) {
4097 memcpy(&pc, r, left);
4098 outs() << " (protocol_t entends past the end of the section)\n";
4099 } else
4100 memcpy(&pc, r, sizeof(struct protocol64_t));
4101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4102 swapStruct(pc);
4103
4104 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4105
4106 outs() << "\t\t\t name ";
4107 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4108 info, n_value, pc.name);
4109 if (n_value != 0) {
4110 if (info->verbose && sym_name != nullptr)
4111 outs() << sym_name;
4112 else
4113 outs() << format("0x%" PRIx64, n_value);
4114 if (pc.name != 0)
4115 outs() << " + " << format("0x%" PRIx64, pc.name);
4116 } else
4117 outs() << format("0x%" PRIx64, pc.name);
4118 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4119 if (name != nullptr)
4120 outs() << format(" %.*s", left, name);
4121 outs() << "\n";
4122
4123 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4124
4125 outs() << "\t\t instanceMethods ";
4126 sym_name =
4127 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4128 S, info, n_value, pc.instanceMethods);
4129 if (n_value != 0) {
4130 if (info->verbose && sym_name != nullptr)
4131 outs() << sym_name;
4132 else
4133 outs() << format("0x%" PRIx64, n_value);
4134 if (pc.instanceMethods != 0)
4135 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4136 } else
4137 outs() << format("0x%" PRIx64, pc.instanceMethods);
4138 outs() << " (struct method_list_t *)\n";
4139 if (pc.instanceMethods + n_value != 0)
4140 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4141
4142 outs() << "\t\t classMethods ";
4143 sym_name =
4144 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4145 info, n_value, pc.classMethods);
4146 if (n_value != 0) {
4147 if (info->verbose && sym_name != nullptr)
4148 outs() << sym_name;
4149 else
4150 outs() << format("0x%" PRIx64, n_value);
4151 if (pc.classMethods != 0)
4152 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4153 } else
4154 outs() << format("0x%" PRIx64, pc.classMethods);
4155 outs() << " (struct method_list_t *)\n";
4156 if (pc.classMethods + n_value != 0)
4157 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4158
4159 outs() << "\t optionalInstanceMethods "
4160 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4161 outs() << "\t optionalClassMethods "
4162 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4163 outs() << "\t instanceProperties "
4164 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4165
4166 p += sizeof(uint64_t);
4167 offset += sizeof(uint64_t);
4168 }
4169}
4170
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004171static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4172 struct protocol_list32_t pl;
4173 uint32_t q;
4174 struct protocol32_t pc;
4175 const char *r;
4176 uint32_t offset, xoffset, left, i;
4177 SectionRef S, xS;
4178 const char *name;
4179
4180 r = get_pointer_32(p, offset, left, S, info);
4181 if (r == nullptr)
4182 return;
4183 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4184 if (left < sizeof(struct protocol_list32_t)) {
4185 memcpy(&pl, r, left);
4186 outs() << " (protocol_list_t entends past the end of the section)\n";
4187 } else
4188 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4189 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4190 swapStruct(pl);
4191 outs() << " count " << pl.count << "\n";
4192
4193 p += sizeof(struct protocol_list32_t);
4194 offset += sizeof(struct protocol_list32_t);
4195 for (i = 0; i < pl.count; i++) {
4196 r = get_pointer_32(p, offset, left, S, info);
4197 if (r == nullptr)
4198 return;
4199 q = 0;
4200 if (left < sizeof(uint32_t)) {
4201 memcpy(&q, r, left);
4202 outs() << " (protocol_t * entends past the end of the section)\n";
4203 } else
4204 memcpy(&q, r, sizeof(uint32_t));
4205 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4206 sys::swapByteOrder(q);
4207 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4208 << " (struct protocol_t *)\n";
4209 r = get_pointer_32(q, offset, left, S, info);
4210 if (r == nullptr)
4211 return;
4212 memset(&pc, '\0', sizeof(struct protocol32_t));
4213 if (left < sizeof(struct protocol32_t)) {
4214 memcpy(&pc, r, left);
4215 outs() << " (protocol_t entends past the end of the section)\n";
4216 } else
4217 memcpy(&pc, r, sizeof(struct protocol32_t));
4218 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4219 swapStruct(pc);
4220 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4221 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4222 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4223 if (name != nullptr)
4224 outs() << format(" %.*s", left, name);
4225 outs() << "\n";
4226 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4227 outs() << "\t\t instanceMethods "
4228 << format("0x%" PRIx32, pc.instanceMethods)
4229 << " (struct method_list_t *)\n";
4230 if (pc.instanceMethods != 0)
4231 print_method_list32_t(pc.instanceMethods, info, "\t");
4232 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4233 << " (struct method_list_t *)\n";
4234 if (pc.classMethods != 0)
4235 print_method_list32_t(pc.classMethods, info, "\t");
4236 outs() << "\t optionalInstanceMethods "
4237 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4238 outs() << "\t optionalClassMethods "
4239 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4240 outs() << "\t instanceProperties "
4241 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4242 p += sizeof(uint32_t);
4243 offset += sizeof(uint32_t);
4244 }
4245}
4246
Kevin Enderby846c0002015-04-16 17:19:59 +00004247static void print_indent(uint32_t indent) {
4248 for (uint32_t i = 0; i < indent;) {
4249 if (indent - i >= 8) {
4250 outs() << "\t";
4251 i += 8;
4252 } else {
4253 for (uint32_t j = i; j < indent; j++)
4254 outs() << " ";
4255 return;
4256 }
4257 }
4258}
4259
4260static bool print_method_description_list(uint32_t p, uint32_t indent,
4261 struct DisassembleInfo *info) {
4262 uint32_t offset, left, xleft;
4263 SectionRef S;
4264 struct objc_method_description_list_t mdl;
4265 struct objc_method_description_t md;
4266 const char *r, *list, *name;
4267 int32_t i;
4268
4269 r = get_pointer_32(p, offset, left, S, info, true);
4270 if (r == nullptr)
4271 return true;
4272
4273 outs() << "\n";
4274 if (left > sizeof(struct objc_method_description_list_t)) {
4275 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4276 } else {
4277 print_indent(indent);
4278 outs() << " objc_method_description_list extends past end of the section\n";
4279 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4280 memcpy(&mdl, r, left);
4281 }
4282 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4283 swapStruct(mdl);
4284
4285 print_indent(indent);
4286 outs() << " count " << mdl.count << "\n";
4287
4288 list = r + sizeof(struct objc_method_description_list_t);
4289 for (i = 0; i < mdl.count; i++) {
4290 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4291 print_indent(indent);
4292 outs() << " remaining list entries extend past the of the section\n";
4293 break;
4294 }
4295 print_indent(indent);
4296 outs() << " list[" << i << "]\n";
4297 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4298 sizeof(struct objc_method_description_t));
4299 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4300 swapStruct(md);
4301
4302 print_indent(indent);
4303 outs() << " name " << format("0x%08" PRIx32, md.name);
4304 if (info->verbose) {
4305 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4306 if (name != nullptr)
4307 outs() << format(" %.*s", xleft, name);
4308 else
4309 outs() << " (not in an __OBJC section)";
4310 }
4311 outs() << "\n";
4312
4313 print_indent(indent);
4314 outs() << " types " << format("0x%08" PRIx32, md.types);
4315 if (info->verbose) {
4316 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4317 if (name != nullptr)
4318 outs() << format(" %.*s", xleft, name);
4319 else
4320 outs() << " (not in an __OBJC section)";
4321 }
4322 outs() << "\n";
4323 }
4324 return false;
4325}
4326
4327static bool print_protocol_list(uint32_t p, uint32_t indent,
4328 struct DisassembleInfo *info);
4329
4330static bool print_protocol(uint32_t p, uint32_t indent,
4331 struct DisassembleInfo *info) {
4332 uint32_t offset, left;
4333 SectionRef S;
4334 struct objc_protocol_t protocol;
4335 const char *r, *name;
4336
4337 r = get_pointer_32(p, offset, left, S, info, true);
4338 if (r == nullptr)
4339 return true;
4340
4341 outs() << "\n";
4342 if (left >= sizeof(struct objc_protocol_t)) {
4343 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4344 } else {
4345 print_indent(indent);
4346 outs() << " Protocol extends past end of the section\n";
4347 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4348 memcpy(&protocol, r, left);
4349 }
4350 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4351 swapStruct(protocol);
4352
4353 print_indent(indent);
4354 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4355 << "\n";
4356
4357 print_indent(indent);
4358 outs() << " protocol_name "
4359 << format("0x%08" PRIx32, protocol.protocol_name);
4360 if (info->verbose) {
4361 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4362 if (name != nullptr)
4363 outs() << format(" %.*s", left, name);
4364 else
4365 outs() << " (not in an __OBJC section)";
4366 }
4367 outs() << "\n";
4368
4369 print_indent(indent);
4370 outs() << " protocol_list "
4371 << format("0x%08" PRIx32, protocol.protocol_list);
4372 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4373 outs() << " (not in an __OBJC section)\n";
4374
4375 print_indent(indent);
4376 outs() << " instance_methods "
4377 << format("0x%08" PRIx32, protocol.instance_methods);
4378 if (print_method_description_list(protocol.instance_methods, indent, info))
4379 outs() << " (not in an __OBJC section)\n";
4380
4381 print_indent(indent);
4382 outs() << " class_methods "
4383 << format("0x%08" PRIx32, protocol.class_methods);
4384 if (print_method_description_list(protocol.class_methods, indent, info))
4385 outs() << " (not in an __OBJC section)\n";
4386
4387 return false;
4388}
4389
4390static bool print_protocol_list(uint32_t p, uint32_t indent,
4391 struct DisassembleInfo *info) {
4392 uint32_t offset, left, l;
4393 SectionRef S;
4394 struct objc_protocol_list_t protocol_list;
4395 const char *r, *list;
4396 int32_t i;
4397
4398 r = get_pointer_32(p, offset, left, S, info, true);
4399 if (r == nullptr)
4400 return true;
4401
4402 outs() << "\n";
4403 if (left > sizeof(struct objc_protocol_list_t)) {
4404 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4405 } else {
4406 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4407 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4408 memcpy(&protocol_list, r, left);
4409 }
4410 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4411 swapStruct(protocol_list);
4412
4413 print_indent(indent);
4414 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4415 << "\n";
4416 print_indent(indent);
4417 outs() << " count " << protocol_list.count << "\n";
4418
4419 list = r + sizeof(struct objc_protocol_list_t);
4420 for (i = 0; i < protocol_list.count; i++) {
4421 if ((i + 1) * sizeof(uint32_t) > left) {
4422 outs() << "\t\t remaining list entries extend past the of the section\n";
4423 break;
4424 }
4425 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4426 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4427 sys::swapByteOrder(l);
4428
4429 print_indent(indent);
4430 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4431 if (print_protocol(l, indent, info))
4432 outs() << "(not in an __OBJC section)\n";
4433 }
4434 return false;
4435}
4436
Kevin Enderby0fc11822015-04-01 20:57:01 +00004437static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4438 struct ivar_list64_t il;
4439 struct ivar64_t i;
4440 const char *r;
4441 uint32_t offset, xoffset, left, j;
4442 SectionRef S, xS;
4443 const char *name, *sym_name, *ivar_offset_p;
4444 uint64_t ivar_offset, n_value;
4445
4446 r = get_pointer_64(p, offset, left, S, info);
4447 if (r == nullptr)
4448 return;
4449 memset(&il, '\0', sizeof(struct ivar_list64_t));
4450 if (left < sizeof(struct ivar_list64_t)) {
4451 memcpy(&il, r, left);
4452 outs() << " (ivar_list_t entends past the end of the section)\n";
4453 } else
4454 memcpy(&il, r, sizeof(struct ivar_list64_t));
4455 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4456 swapStruct(il);
4457 outs() << " entsize " << il.entsize << "\n";
4458 outs() << " count " << il.count << "\n";
4459
4460 p += sizeof(struct ivar_list64_t);
4461 offset += sizeof(struct ivar_list64_t);
4462 for (j = 0; j < il.count; j++) {
4463 r = get_pointer_64(p, offset, left, S, info);
4464 if (r == nullptr)
4465 return;
4466 memset(&i, '\0', sizeof(struct ivar64_t));
4467 if (left < sizeof(struct ivar64_t)) {
4468 memcpy(&i, r, left);
4469 outs() << " (ivar_t entends past the end of the section)\n";
4470 } else
4471 memcpy(&i, r, sizeof(struct ivar64_t));
4472 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4473 swapStruct(i);
4474
4475 outs() << "\t\t\t offset ";
4476 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4477 info, n_value, i.offset);
4478 if (n_value != 0) {
4479 if (info->verbose && sym_name != nullptr)
4480 outs() << sym_name;
4481 else
4482 outs() << format("0x%" PRIx64, n_value);
4483 if (i.offset != 0)
4484 outs() << " + " << format("0x%" PRIx64, i.offset);
4485 } else
4486 outs() << format("0x%" PRIx64, i.offset);
4487 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4488 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4489 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4490 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4491 sys::swapByteOrder(ivar_offset);
4492 outs() << " " << ivar_offset << "\n";
4493 } else
4494 outs() << "\n";
4495
4496 outs() << "\t\t\t name ";
4497 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4498 n_value, i.name);
4499 if (n_value != 0) {
4500 if (info->verbose && sym_name != nullptr)
4501 outs() << sym_name;
4502 else
4503 outs() << format("0x%" PRIx64, n_value);
4504 if (i.name != 0)
4505 outs() << " + " << format("0x%" PRIx64, i.name);
4506 } else
4507 outs() << format("0x%" PRIx64, i.name);
4508 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4509 if (name != nullptr)
4510 outs() << format(" %.*s", left, name);
4511 outs() << "\n";
4512
4513 outs() << "\t\t\t type ";
4514 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4515 n_value, i.name);
4516 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4517 if (n_value != 0) {
4518 if (info->verbose && sym_name != nullptr)
4519 outs() << sym_name;
4520 else
4521 outs() << format("0x%" PRIx64, n_value);
4522 if (i.type != 0)
4523 outs() << " + " << format("0x%" PRIx64, i.type);
4524 } else
4525 outs() << format("0x%" PRIx64, i.type);
4526 if (name != nullptr)
4527 outs() << format(" %.*s", left, name);
4528 outs() << "\n";
4529
4530 outs() << "\t\t\talignment " << i.alignment << "\n";
4531 outs() << "\t\t\t size " << i.size << "\n";
4532
4533 p += sizeof(struct ivar64_t);
4534 offset += sizeof(struct ivar64_t);
4535 }
4536}
4537
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004538static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4539 struct ivar_list32_t il;
4540 struct ivar32_t i;
4541 const char *r;
4542 uint32_t offset, xoffset, left, j;
4543 SectionRef S, xS;
4544 const char *name, *ivar_offset_p;
4545 uint32_t ivar_offset;
4546
4547 r = get_pointer_32(p, offset, left, S, info);
4548 if (r == nullptr)
4549 return;
4550 memset(&il, '\0', sizeof(struct ivar_list32_t));
4551 if (left < sizeof(struct ivar_list32_t)) {
4552 memcpy(&il, r, left);
4553 outs() << " (ivar_list_t entends past the end of the section)\n";
4554 } else
4555 memcpy(&il, r, sizeof(struct ivar_list32_t));
4556 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4557 swapStruct(il);
4558 outs() << " entsize " << il.entsize << "\n";
4559 outs() << " count " << il.count << "\n";
4560
4561 p += sizeof(struct ivar_list32_t);
4562 offset += sizeof(struct ivar_list32_t);
4563 for (j = 0; j < il.count; j++) {
4564 r = get_pointer_32(p, offset, left, S, info);
4565 if (r == nullptr)
4566 return;
4567 memset(&i, '\0', sizeof(struct ivar32_t));
4568 if (left < sizeof(struct ivar32_t)) {
4569 memcpy(&i, r, left);
4570 outs() << " (ivar_t entends past the end of the section)\n";
4571 } else
4572 memcpy(&i, r, sizeof(struct ivar32_t));
4573 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4574 swapStruct(i);
4575
4576 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4577 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4578 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4579 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4580 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4581 sys::swapByteOrder(ivar_offset);
4582 outs() << " " << ivar_offset << "\n";
4583 } else
4584 outs() << "\n";
4585
4586 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4587 name = get_pointer_32(i.name, xoffset, left, xS, info);
4588 if (name != nullptr)
4589 outs() << format(" %.*s", left, name);
4590 outs() << "\n";
4591
4592 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4593 name = get_pointer_32(i.type, xoffset, left, xS, info);
4594 if (name != nullptr)
4595 outs() << format(" %.*s", left, name);
4596 outs() << "\n";
4597
4598 outs() << "\t\t\talignment " << i.alignment << "\n";
4599 outs() << "\t\t\t size " << i.size << "\n";
4600
4601 p += sizeof(struct ivar32_t);
4602 offset += sizeof(struct ivar32_t);
4603 }
4604}
4605
Kevin Enderby0fc11822015-04-01 20:57:01 +00004606static void print_objc_property_list64(uint64_t p,
4607 struct DisassembleInfo *info) {
4608 struct objc_property_list64 opl;
4609 struct objc_property64 op;
4610 const char *r;
4611 uint32_t offset, xoffset, left, j;
4612 SectionRef S, xS;
4613 const char *name, *sym_name;
4614 uint64_t n_value;
4615
4616 r = get_pointer_64(p, offset, left, S, info);
4617 if (r == nullptr)
4618 return;
4619 memset(&opl, '\0', sizeof(struct objc_property_list64));
4620 if (left < sizeof(struct objc_property_list64)) {
4621 memcpy(&opl, r, left);
4622 outs() << " (objc_property_list entends past the end of the section)\n";
4623 } else
4624 memcpy(&opl, r, sizeof(struct objc_property_list64));
4625 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4626 swapStruct(opl);
4627 outs() << " entsize " << opl.entsize << "\n";
4628 outs() << " count " << opl.count << "\n";
4629
4630 p += sizeof(struct objc_property_list64);
4631 offset += sizeof(struct objc_property_list64);
4632 for (j = 0; j < opl.count; j++) {
4633 r = get_pointer_64(p, offset, left, S, info);
4634 if (r == nullptr)
4635 return;
4636 memset(&op, '\0', sizeof(struct objc_property64));
4637 if (left < sizeof(struct objc_property64)) {
4638 memcpy(&op, r, left);
4639 outs() << " (objc_property entends past the end of the section)\n";
4640 } else
4641 memcpy(&op, r, sizeof(struct objc_property64));
4642 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4643 swapStruct(op);
4644
4645 outs() << "\t\t\t name ";
4646 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4647 info, n_value, op.name);
4648 if (n_value != 0) {
4649 if (info->verbose && sym_name != nullptr)
4650 outs() << sym_name;
4651 else
4652 outs() << format("0x%" PRIx64, n_value);
4653 if (op.name != 0)
4654 outs() << " + " << format("0x%" PRIx64, op.name);
4655 } else
4656 outs() << format("0x%" PRIx64, op.name);
4657 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4658 if (name != nullptr)
4659 outs() << format(" %.*s", left, name);
4660 outs() << "\n";
4661
4662 outs() << "\t\t\tattributes ";
4663 sym_name =
4664 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4665 info, n_value, op.attributes);
4666 if (n_value != 0) {
4667 if (info->verbose && sym_name != nullptr)
4668 outs() << sym_name;
4669 else
4670 outs() << format("0x%" PRIx64, n_value);
4671 if (op.attributes != 0)
4672 outs() << " + " << format("0x%" PRIx64, op.attributes);
4673 } else
4674 outs() << format("0x%" PRIx64, op.attributes);
4675 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4676 if (name != nullptr)
4677 outs() << format(" %.*s", left, name);
4678 outs() << "\n";
4679
4680 p += sizeof(struct objc_property64);
4681 offset += sizeof(struct objc_property64);
4682 }
4683}
4684
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004685static void print_objc_property_list32(uint32_t p,
4686 struct DisassembleInfo *info) {
4687 struct objc_property_list32 opl;
4688 struct objc_property32 op;
4689 const char *r;
4690 uint32_t offset, xoffset, left, j;
4691 SectionRef S, xS;
4692 const char *name;
4693
4694 r = get_pointer_32(p, offset, left, S, info);
4695 if (r == nullptr)
4696 return;
4697 memset(&opl, '\0', sizeof(struct objc_property_list32));
4698 if (left < sizeof(struct objc_property_list32)) {
4699 memcpy(&opl, r, left);
4700 outs() << " (objc_property_list entends past the end of the section)\n";
4701 } else
4702 memcpy(&opl, r, sizeof(struct objc_property_list32));
4703 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4704 swapStruct(opl);
4705 outs() << " entsize " << opl.entsize << "\n";
4706 outs() << " count " << opl.count << "\n";
4707
4708 p += sizeof(struct objc_property_list32);
4709 offset += sizeof(struct objc_property_list32);
4710 for (j = 0; j < opl.count; j++) {
4711 r = get_pointer_32(p, offset, left, S, info);
4712 if (r == nullptr)
4713 return;
4714 memset(&op, '\0', sizeof(struct objc_property32));
4715 if (left < sizeof(struct objc_property32)) {
4716 memcpy(&op, r, left);
4717 outs() << " (objc_property entends past the end of the section)\n";
4718 } else
4719 memcpy(&op, r, sizeof(struct objc_property32));
4720 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4721 swapStruct(op);
4722
4723 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4724 name = get_pointer_32(op.name, xoffset, left, xS, info);
4725 if (name != nullptr)
4726 outs() << format(" %.*s", left, name);
4727 outs() << "\n";
4728
4729 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4730 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4731 if (name != nullptr)
4732 outs() << format(" %.*s", left, name);
4733 outs() << "\n";
4734
4735 p += sizeof(struct objc_property32);
4736 offset += sizeof(struct objc_property32);
4737 }
4738}
4739
Richard Smith81ff44d2015-10-09 22:09:56 +00004740static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004741 bool &is_meta_class) {
4742 struct class_ro64_t cro;
4743 const char *r;
4744 uint32_t offset, xoffset, left;
4745 SectionRef S, xS;
4746 const char *name, *sym_name;
4747 uint64_t n_value;
4748
4749 r = get_pointer_64(p, offset, left, S, info);
4750 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004751 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004752 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004753 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4754 swapStruct(cro);
4755 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4756 if (cro.flags & RO_META)
4757 outs() << " RO_META";
4758 if (cro.flags & RO_ROOT)
4759 outs() << " RO_ROOT";
4760 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4761 outs() << " RO_HAS_CXX_STRUCTORS";
4762 outs() << "\n";
4763 outs() << " instanceStart " << cro.instanceStart << "\n";
4764 outs() << " instanceSize " << cro.instanceSize << "\n";
4765 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4766 << "\n";
4767 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4768 << "\n";
4769 print_layout_map64(cro.ivarLayout, info);
4770
4771 outs() << " name ";
4772 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4773 info, n_value, cro.name);
4774 if (n_value != 0) {
4775 if (info->verbose && sym_name != nullptr)
4776 outs() << sym_name;
4777 else
4778 outs() << format("0x%" PRIx64, n_value);
4779 if (cro.name != 0)
4780 outs() << " + " << format("0x%" PRIx64, cro.name);
4781 } else
4782 outs() << format("0x%" PRIx64, cro.name);
4783 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4784 if (name != nullptr)
4785 outs() << format(" %.*s", left, name);
4786 outs() << "\n";
4787
4788 outs() << " baseMethods ";
4789 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4790 S, info, n_value, cro.baseMethods);
4791 if (n_value != 0) {
4792 if (info->verbose && sym_name != nullptr)
4793 outs() << sym_name;
4794 else
4795 outs() << format("0x%" PRIx64, n_value);
4796 if (cro.baseMethods != 0)
4797 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4798 } else
4799 outs() << format("0x%" PRIx64, cro.baseMethods);
4800 outs() << " (struct method_list_t *)\n";
4801 if (cro.baseMethods + n_value != 0)
4802 print_method_list64_t(cro.baseMethods + n_value, info, "");
4803
4804 outs() << " baseProtocols ";
4805 sym_name =
4806 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4807 info, n_value, cro.baseProtocols);
4808 if (n_value != 0) {
4809 if (info->verbose && sym_name != nullptr)
4810 outs() << sym_name;
4811 else
4812 outs() << format("0x%" PRIx64, n_value);
4813 if (cro.baseProtocols != 0)
4814 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4815 } else
4816 outs() << format("0x%" PRIx64, cro.baseProtocols);
4817 outs() << "\n";
4818 if (cro.baseProtocols + n_value != 0)
4819 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4820
4821 outs() << " ivars ";
4822 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004823 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004824 if (n_value != 0) {
4825 if (info->verbose && sym_name != nullptr)
4826 outs() << sym_name;
4827 else
4828 outs() << format("0x%" PRIx64, n_value);
4829 if (cro.ivars != 0)
4830 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4831 } else
4832 outs() << format("0x%" PRIx64, cro.ivars);
4833 outs() << "\n";
4834 if (cro.ivars + n_value != 0)
4835 print_ivar_list64_t(cro.ivars + n_value, info);
4836
4837 outs() << " weakIvarLayout ";
4838 sym_name =
4839 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4840 info, n_value, cro.weakIvarLayout);
4841 if (n_value != 0) {
4842 if (info->verbose && sym_name != nullptr)
4843 outs() << sym_name;
4844 else
4845 outs() << format("0x%" PRIx64, n_value);
4846 if (cro.weakIvarLayout != 0)
4847 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4848 } else
4849 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4850 outs() << "\n";
4851 print_layout_map64(cro.weakIvarLayout + n_value, info);
4852
4853 outs() << " baseProperties ";
4854 sym_name =
4855 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4856 info, n_value, cro.baseProperties);
4857 if (n_value != 0) {
4858 if (info->verbose && sym_name != nullptr)
4859 outs() << sym_name;
4860 else
4861 outs() << format("0x%" PRIx64, n_value);
4862 if (cro.baseProperties != 0)
4863 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4864 } else
4865 outs() << format("0x%" PRIx64, cro.baseProperties);
4866 outs() << "\n";
4867 if (cro.baseProperties + n_value != 0)
4868 print_objc_property_list64(cro.baseProperties + n_value, info);
4869
Rafael Espindolab9091322015-10-24 23:19:10 +00004870 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004871 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004872}
4873
Richard Smith81ff44d2015-10-09 22:09:56 +00004874static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004875 bool &is_meta_class) {
4876 struct class_ro32_t cro;
4877 const char *r;
4878 uint32_t offset, xoffset, left;
4879 SectionRef S, xS;
4880 const char *name;
4881
4882 r = get_pointer_32(p, offset, left, S, info);
4883 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004884 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004885 memset(&cro, '\0', sizeof(struct class_ro32_t));
4886 if (left < sizeof(struct class_ro32_t)) {
4887 memcpy(&cro, r, left);
4888 outs() << " (class_ro_t entends past the end of the section)\n";
4889 } else
4890 memcpy(&cro, r, sizeof(struct class_ro32_t));
4891 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4892 swapStruct(cro);
4893 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4894 if (cro.flags & RO_META)
4895 outs() << " RO_META";
4896 if (cro.flags & RO_ROOT)
4897 outs() << " RO_ROOT";
4898 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4899 outs() << " RO_HAS_CXX_STRUCTORS";
4900 outs() << "\n";
4901 outs() << " instanceStart " << cro.instanceStart << "\n";
4902 outs() << " instanceSize " << cro.instanceSize << "\n";
4903 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4904 << "\n";
4905 print_layout_map32(cro.ivarLayout, info);
4906
4907 outs() << " name " << format("0x%" PRIx32, cro.name);
4908 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4909 if (name != nullptr)
4910 outs() << format(" %.*s", left, name);
4911 outs() << "\n";
4912
4913 outs() << " baseMethods "
4914 << format("0x%" PRIx32, cro.baseMethods)
4915 << " (struct method_list_t *)\n";
4916 if (cro.baseMethods != 0)
4917 print_method_list32_t(cro.baseMethods, info, "");
4918
4919 outs() << " baseProtocols "
4920 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4921 if (cro.baseProtocols != 0)
4922 print_protocol_list32_t(cro.baseProtocols, info);
4923 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4924 << "\n";
4925 if (cro.ivars != 0)
4926 print_ivar_list32_t(cro.ivars, info);
4927 outs() << " weakIvarLayout "
4928 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4929 print_layout_map32(cro.weakIvarLayout, info);
4930 outs() << " baseProperties "
4931 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4932 if (cro.baseProperties != 0)
4933 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004934 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004935 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004936}
4937
Kevin Enderby0fc11822015-04-01 20:57:01 +00004938static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4939 struct class64_t c;
4940 const char *r;
4941 uint32_t offset, left;
4942 SectionRef S;
4943 const char *name;
4944 uint64_t isa_n_value, n_value;
4945
4946 r = get_pointer_64(p, offset, left, S, info);
4947 if (r == nullptr || left < sizeof(struct class64_t))
4948 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004949 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004950 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4951 swapStruct(c);
4952
4953 outs() << " isa " << format("0x%" PRIx64, c.isa);
4954 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4955 isa_n_value, c.isa);
4956 if (name != nullptr)
4957 outs() << " " << name;
4958 outs() << "\n";
4959
4960 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4961 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4962 n_value, c.superclass);
4963 if (name != nullptr)
4964 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00004965 else {
4966 name = get_dyld_bind_info_symbolname(S.getAddress() +
4967 offset + offsetof(struct class64_t, superclass), info);
4968 if (name != nullptr)
4969 outs() << " " << name;
4970 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00004971 outs() << "\n";
4972
4973 outs() << " cache " << format("0x%" PRIx64, c.cache);
4974 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4975 n_value, c.cache);
4976 if (name != nullptr)
4977 outs() << " " << name;
4978 outs() << "\n";
4979
4980 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4981 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4982 n_value, c.vtable);
4983 if (name != nullptr)
4984 outs() << " " << name;
4985 outs() << "\n";
4986
4987 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4988 n_value, c.data);
4989 outs() << " data ";
4990 if (n_value != 0) {
4991 if (info->verbose && name != nullptr)
4992 outs() << name;
4993 else
4994 outs() << format("0x%" PRIx64, n_value);
4995 if (c.data != 0)
4996 outs() << " + " << format("0x%" PRIx64, c.data);
4997 } else
4998 outs() << format("0x%" PRIx64, c.data);
4999 outs() << " (struct class_ro_t *)";
5000
5001 // This is a Swift class if some of the low bits of the pointer are set.
5002 if ((c.data + n_value) & 0x7)
5003 outs() << " Swift class";
5004 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005005 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005006 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5007 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005008
Kevin Enderbyaac75382015-10-08 16:56:35 +00005009 if (!is_meta_class &&
5010 c.isa + isa_n_value != p &&
5011 c.isa + isa_n_value != 0 &&
5012 info->depth < 100) {
5013 info->depth++;
5014 outs() << "Meta Class\n";
5015 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005016 }
5017}
5018
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005019static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5020 struct class32_t c;
5021 const char *r;
5022 uint32_t offset, left;
5023 SectionRef S;
5024 const char *name;
5025
5026 r = get_pointer_32(p, offset, left, S, info);
5027 if (r == nullptr)
5028 return;
5029 memset(&c, '\0', sizeof(struct class32_t));
5030 if (left < sizeof(struct class32_t)) {
5031 memcpy(&c, r, left);
5032 outs() << " (class_t entends past the end of the section)\n";
5033 } else
5034 memcpy(&c, r, sizeof(struct class32_t));
5035 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5036 swapStruct(c);
5037
5038 outs() << " isa " << format("0x%" PRIx32, c.isa);
5039 name =
5040 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5041 if (name != nullptr)
5042 outs() << " " << name;
5043 outs() << "\n";
5044
5045 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5046 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5047 c.superclass);
5048 if (name != nullptr)
5049 outs() << " " << name;
5050 outs() << "\n";
5051
5052 outs() << " cache " << format("0x%" PRIx32, c.cache);
5053 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5054 c.cache);
5055 if (name != nullptr)
5056 outs() << " " << name;
5057 outs() << "\n";
5058
5059 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5060 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5061 c.vtable);
5062 if (name != nullptr)
5063 outs() << " " << name;
5064 outs() << "\n";
5065
5066 name =
5067 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5068 outs() << " data " << format("0x%" PRIx32, c.data)
5069 << " (struct class_ro_t *)";
5070
5071 // This is a Swift class if some of the low bits of the pointer are set.
5072 if (c.data & 0x3)
5073 outs() << " Swift class";
5074 outs() << "\n";
5075 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005076 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5077 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005078
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005079 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005080 outs() << "Meta Class\n";
5081 print_class32_t(c.isa, info);
5082 }
5083}
5084
Kevin Enderby846c0002015-04-16 17:19:59 +00005085static void print_objc_class_t(struct objc_class_t *objc_class,
5086 struct DisassembleInfo *info) {
5087 uint32_t offset, left, xleft;
5088 const char *name, *p, *ivar_list;
5089 SectionRef S;
5090 int32_t i;
5091 struct objc_ivar_list_t objc_ivar_list;
5092 struct objc_ivar_t ivar;
5093
5094 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5095 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5096 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5097 if (name != nullptr)
5098 outs() << format(" %.*s", left, name);
5099 else
5100 outs() << " (not in an __OBJC section)";
5101 }
5102 outs() << "\n";
5103
5104 outs() << "\t super_class "
5105 << format("0x%08" PRIx32, objc_class->super_class);
5106 if (info->verbose) {
5107 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5108 if (name != nullptr)
5109 outs() << format(" %.*s", left, name);
5110 else
5111 outs() << " (not in an __OBJC section)";
5112 }
5113 outs() << "\n";
5114
5115 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5116 if (info->verbose) {
5117 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5118 if (name != nullptr)
5119 outs() << format(" %.*s", left, name);
5120 else
5121 outs() << " (not in an __OBJC section)";
5122 }
5123 outs() << "\n";
5124
5125 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5126 << "\n";
5127
5128 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5129 if (info->verbose) {
5130 if (CLS_GETINFO(objc_class, CLS_CLASS))
5131 outs() << " CLS_CLASS";
5132 else if (CLS_GETINFO(objc_class, CLS_META))
5133 outs() << " CLS_META";
5134 }
5135 outs() << "\n";
5136
5137 outs() << "\t instance_size "
5138 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5139
5140 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5141 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5142 if (p != nullptr) {
5143 if (left > sizeof(struct objc_ivar_list_t)) {
5144 outs() << "\n";
5145 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5146 } else {
5147 outs() << " (entends past the end of the section)\n";
5148 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5149 memcpy(&objc_ivar_list, p, left);
5150 }
5151 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5152 swapStruct(objc_ivar_list);
5153 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5154 ivar_list = p + sizeof(struct objc_ivar_list_t);
5155 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5156 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5157 outs() << "\t\t remaining ivar's extend past the of the section\n";
5158 break;
5159 }
5160 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5161 sizeof(struct objc_ivar_t));
5162 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5163 swapStruct(ivar);
5164
5165 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5166 if (info->verbose) {
5167 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5168 if (name != nullptr)
5169 outs() << format(" %.*s", xleft, name);
5170 else
5171 outs() << " (not in an __OBJC section)";
5172 }
5173 outs() << "\n";
5174
5175 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5176 if (info->verbose) {
5177 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5178 if (name != nullptr)
5179 outs() << format(" %.*s", xleft, name);
5180 else
5181 outs() << " (not in an __OBJC section)";
5182 }
5183 outs() << "\n";
5184
5185 outs() << "\t\t ivar_offset "
5186 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5187 }
5188 } else {
5189 outs() << " (not in an __OBJC section)\n";
5190 }
5191
5192 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5193 if (print_method_list(objc_class->methodLists, info))
5194 outs() << " (not in an __OBJC section)\n";
5195
5196 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5197 << "\n";
5198
5199 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5200 if (print_protocol_list(objc_class->protocols, 16, info))
5201 outs() << " (not in an __OBJC section)\n";
5202}
5203
5204static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5205 struct DisassembleInfo *info) {
5206 uint32_t offset, left;
5207 const char *name;
5208 SectionRef S;
5209
5210 outs() << "\t category name "
5211 << format("0x%08" PRIx32, objc_category->category_name);
5212 if (info->verbose) {
5213 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5214 true);
5215 if (name != nullptr)
5216 outs() << format(" %.*s", left, name);
5217 else
5218 outs() << " (not in an __OBJC section)";
5219 }
5220 outs() << "\n";
5221
5222 outs() << "\t\t class name "
5223 << format("0x%08" PRIx32, objc_category->class_name);
5224 if (info->verbose) {
5225 name =
5226 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5227 if (name != nullptr)
5228 outs() << format(" %.*s", left, name);
5229 else
5230 outs() << " (not in an __OBJC section)";
5231 }
5232 outs() << "\n";
5233
5234 outs() << "\t instance methods "
5235 << format("0x%08" PRIx32, objc_category->instance_methods);
5236 if (print_method_list(objc_category->instance_methods, info))
5237 outs() << " (not in an __OBJC section)\n";
5238
5239 outs() << "\t class methods "
5240 << format("0x%08" PRIx32, objc_category->class_methods);
5241 if (print_method_list(objc_category->class_methods, info))
5242 outs() << " (not in an __OBJC section)\n";
5243}
5244
Kevin Enderby0fc11822015-04-01 20:57:01 +00005245static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5246 struct category64_t c;
5247 const char *r;
5248 uint32_t offset, xoffset, left;
5249 SectionRef S, xS;
5250 const char *name, *sym_name;
5251 uint64_t n_value;
5252
5253 r = get_pointer_64(p, offset, left, S, info);
5254 if (r == nullptr)
5255 return;
5256 memset(&c, '\0', sizeof(struct category64_t));
5257 if (left < sizeof(struct category64_t)) {
5258 memcpy(&c, r, left);
5259 outs() << " (category_t entends past the end of the section)\n";
5260 } else
5261 memcpy(&c, r, sizeof(struct category64_t));
5262 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5263 swapStruct(c);
5264
5265 outs() << " name ";
5266 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5267 info, n_value, c.name);
5268 if (n_value != 0) {
5269 if (info->verbose && sym_name != nullptr)
5270 outs() << sym_name;
5271 else
5272 outs() << format("0x%" PRIx64, n_value);
5273 if (c.name != 0)
5274 outs() << " + " << format("0x%" PRIx64, c.name);
5275 } else
5276 outs() << format("0x%" PRIx64, c.name);
5277 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5278 if (name != nullptr)
5279 outs() << format(" %.*s", left, name);
5280 outs() << "\n";
5281
5282 outs() << " cls ";
5283 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5284 n_value, c.cls);
5285 if (n_value != 0) {
5286 if (info->verbose && sym_name != nullptr)
5287 outs() << sym_name;
5288 else
5289 outs() << format("0x%" PRIx64, n_value);
5290 if (c.cls != 0)
5291 outs() << " + " << format("0x%" PRIx64, c.cls);
5292 } else
5293 outs() << format("0x%" PRIx64, c.cls);
5294 outs() << "\n";
5295 if (c.cls + n_value != 0)
5296 print_class64_t(c.cls + n_value, info);
5297
5298 outs() << " instanceMethods ";
5299 sym_name =
5300 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5301 info, n_value, c.instanceMethods);
5302 if (n_value != 0) {
5303 if (info->verbose && sym_name != nullptr)
5304 outs() << sym_name;
5305 else
5306 outs() << format("0x%" PRIx64, n_value);
5307 if (c.instanceMethods != 0)
5308 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5309 } else
5310 outs() << format("0x%" PRIx64, c.instanceMethods);
5311 outs() << "\n";
5312 if (c.instanceMethods + n_value != 0)
5313 print_method_list64_t(c.instanceMethods + n_value, info, "");
5314
5315 outs() << " classMethods ";
5316 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5317 S, info, n_value, c.classMethods);
5318 if (n_value != 0) {
5319 if (info->verbose && sym_name != nullptr)
5320 outs() << sym_name;
5321 else
5322 outs() << format("0x%" PRIx64, n_value);
5323 if (c.classMethods != 0)
5324 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5325 } else
5326 outs() << format("0x%" PRIx64, c.classMethods);
5327 outs() << "\n";
5328 if (c.classMethods + n_value != 0)
5329 print_method_list64_t(c.classMethods + n_value, info, "");
5330
5331 outs() << " protocols ";
5332 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5333 info, n_value, c.protocols);
5334 if (n_value != 0) {
5335 if (info->verbose && sym_name != nullptr)
5336 outs() << sym_name;
5337 else
5338 outs() << format("0x%" PRIx64, n_value);
5339 if (c.protocols != 0)
5340 outs() << " + " << format("0x%" PRIx64, c.protocols);
5341 } else
5342 outs() << format("0x%" PRIx64, c.protocols);
5343 outs() << "\n";
5344 if (c.protocols + n_value != 0)
5345 print_protocol_list64_t(c.protocols + n_value, info);
5346
5347 outs() << "instanceProperties ";
5348 sym_name =
5349 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5350 S, info, n_value, c.instanceProperties);
5351 if (n_value != 0) {
5352 if (info->verbose && sym_name != nullptr)
5353 outs() << sym_name;
5354 else
5355 outs() << format("0x%" PRIx64, n_value);
5356 if (c.instanceProperties != 0)
5357 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5358 } else
5359 outs() << format("0x%" PRIx64, c.instanceProperties);
5360 outs() << "\n";
5361 if (c.instanceProperties + n_value != 0)
5362 print_objc_property_list64(c.instanceProperties + n_value, info);
5363}
5364
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005365static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5366 struct category32_t c;
5367 const char *r;
5368 uint32_t offset, left;
5369 SectionRef S, xS;
5370 const char *name;
5371
5372 r = get_pointer_32(p, offset, left, S, info);
5373 if (r == nullptr)
5374 return;
5375 memset(&c, '\0', sizeof(struct category32_t));
5376 if (left < sizeof(struct category32_t)) {
5377 memcpy(&c, r, left);
5378 outs() << " (category_t entends past the end of the section)\n";
5379 } else
5380 memcpy(&c, r, sizeof(struct category32_t));
5381 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5382 swapStruct(c);
5383
5384 outs() << " name " << format("0x%" PRIx32, c.name);
5385 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5386 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005387 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005388 outs() << " " << name;
5389 outs() << "\n";
5390
5391 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5392 if (c.cls != 0)
5393 print_class32_t(c.cls, info);
5394 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5395 << "\n";
5396 if (c.instanceMethods != 0)
5397 print_method_list32_t(c.instanceMethods, info, "");
5398 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5399 << "\n";
5400 if (c.classMethods != 0)
5401 print_method_list32_t(c.classMethods, info, "");
5402 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5403 if (c.protocols != 0)
5404 print_protocol_list32_t(c.protocols, info);
5405 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5406 << "\n";
5407 if (c.instanceProperties != 0)
5408 print_objc_property_list32(c.instanceProperties, info);
5409}
5410
Kevin Enderby0fc11822015-04-01 20:57:01 +00005411static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5412 uint32_t i, left, offset, xoffset;
5413 uint64_t p, n_value;
5414 struct message_ref64 mr;
5415 const char *name, *sym_name;
5416 const char *r;
5417 SectionRef xS;
5418
5419 if (S == SectionRef())
5420 return;
5421
5422 StringRef SectName;
5423 S.getName(SectName);
5424 DataRefImpl Ref = S.getRawDataRefImpl();
5425 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5426 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5427 offset = 0;
5428 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5429 p = S.getAddress() + i;
5430 r = get_pointer_64(p, offset, left, S, info);
5431 if (r == nullptr)
5432 return;
5433 memset(&mr, '\0', sizeof(struct message_ref64));
5434 if (left < sizeof(struct message_ref64)) {
5435 memcpy(&mr, r, left);
5436 outs() << " (message_ref entends past the end of the section)\n";
5437 } else
5438 memcpy(&mr, r, sizeof(struct message_ref64));
5439 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5440 swapStruct(mr);
5441
5442 outs() << " imp ";
5443 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5444 n_value, mr.imp);
5445 if (n_value != 0) {
5446 outs() << format("0x%" PRIx64, n_value) << " ";
5447 if (mr.imp != 0)
5448 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5449 } else
5450 outs() << format("0x%" PRIx64, mr.imp) << " ";
5451 if (name != nullptr)
5452 outs() << " " << name;
5453 outs() << "\n";
5454
5455 outs() << " sel ";
5456 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5457 info, n_value, mr.sel);
5458 if (n_value != 0) {
5459 if (info->verbose && sym_name != nullptr)
5460 outs() << sym_name;
5461 else
5462 outs() << format("0x%" PRIx64, n_value);
5463 if (mr.sel != 0)
5464 outs() << " + " << format("0x%" PRIx64, mr.sel);
5465 } else
5466 outs() << format("0x%" PRIx64, mr.sel);
5467 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5468 if (name != nullptr)
5469 outs() << format(" %.*s", left, name);
5470 outs() << "\n";
5471
5472 offset += sizeof(struct message_ref64);
5473 }
5474}
5475
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005476static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5477 uint32_t i, left, offset, xoffset, p;
5478 struct message_ref32 mr;
5479 const char *name, *r;
5480 SectionRef xS;
5481
5482 if (S == SectionRef())
5483 return;
5484
5485 StringRef SectName;
5486 S.getName(SectName);
5487 DataRefImpl Ref = S.getRawDataRefImpl();
5488 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5489 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5490 offset = 0;
5491 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5492 p = S.getAddress() + i;
5493 r = get_pointer_32(p, offset, left, S, info);
5494 if (r == nullptr)
5495 return;
5496 memset(&mr, '\0', sizeof(struct message_ref32));
5497 if (left < sizeof(struct message_ref32)) {
5498 memcpy(&mr, r, left);
5499 outs() << " (message_ref entends past the end of the section)\n";
5500 } else
5501 memcpy(&mr, r, sizeof(struct message_ref32));
5502 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5503 swapStruct(mr);
5504
5505 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5506 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5507 mr.imp);
5508 if (name != nullptr)
5509 outs() << " " << name;
5510 outs() << "\n";
5511
5512 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5513 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5514 if (name != nullptr)
5515 outs() << " " << name;
5516 outs() << "\n";
5517
5518 offset += sizeof(struct message_ref32);
5519 }
5520}
5521
Kevin Enderby0fc11822015-04-01 20:57:01 +00005522static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5523 uint32_t left, offset, swift_version;
5524 uint64_t p;
5525 struct objc_image_info64 o;
5526 const char *r;
5527
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005528 if (S == SectionRef())
5529 return;
5530
Kevin Enderby0fc11822015-04-01 20:57:01 +00005531 StringRef SectName;
5532 S.getName(SectName);
5533 DataRefImpl Ref = S.getRawDataRefImpl();
5534 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5535 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5536 p = S.getAddress();
5537 r = get_pointer_64(p, offset, left, S, info);
5538 if (r == nullptr)
5539 return;
5540 memset(&o, '\0', sizeof(struct objc_image_info64));
5541 if (left < sizeof(struct objc_image_info64)) {
5542 memcpy(&o, r, left);
5543 outs() << " (objc_image_info entends past the end of the section)\n";
5544 } else
5545 memcpy(&o, r, sizeof(struct objc_image_info64));
5546 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5547 swapStruct(o);
5548 outs() << " version " << o.version << "\n";
5549 outs() << " flags " << format("0x%" PRIx32, o.flags);
5550 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5551 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5552 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5553 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5554 swift_version = (o.flags >> 8) & 0xff;
5555 if (swift_version != 0) {
5556 if (swift_version == 1)
5557 outs() << " Swift 1.0";
5558 else if (swift_version == 2)
5559 outs() << " Swift 1.1";
5560 else
5561 outs() << " unknown future Swift version (" << swift_version << ")";
5562 }
5563 outs() << "\n";
5564}
5565
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005566static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5567 uint32_t left, offset, swift_version, p;
5568 struct objc_image_info32 o;
5569 const char *r;
5570
Kevin Enderby19be2512016-04-21 19:49:29 +00005571 if (S == SectionRef())
5572 return;
5573
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005574 StringRef SectName;
5575 S.getName(SectName);
5576 DataRefImpl Ref = S.getRawDataRefImpl();
5577 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5578 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5579 p = S.getAddress();
5580 r = get_pointer_32(p, offset, left, S, info);
5581 if (r == nullptr)
5582 return;
5583 memset(&o, '\0', sizeof(struct objc_image_info32));
5584 if (left < sizeof(struct objc_image_info32)) {
5585 memcpy(&o, r, left);
5586 outs() << " (objc_image_info entends past the end of the section)\n";
5587 } else
5588 memcpy(&o, r, sizeof(struct objc_image_info32));
5589 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5590 swapStruct(o);
5591 outs() << " version " << o.version << "\n";
5592 outs() << " flags " << format("0x%" PRIx32, o.flags);
5593 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5594 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5595 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5596 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5597 swift_version = (o.flags >> 8) & 0xff;
5598 if (swift_version != 0) {
5599 if (swift_version == 1)
5600 outs() << " Swift 1.0";
5601 else if (swift_version == 2)
5602 outs() << " Swift 1.1";
5603 else
5604 outs() << " unknown future Swift version (" << swift_version << ")";
5605 }
5606 outs() << "\n";
5607}
5608
Kevin Enderby846c0002015-04-16 17:19:59 +00005609static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5610 uint32_t left, offset, p;
5611 struct imageInfo_t o;
5612 const char *r;
5613
5614 StringRef SectName;
5615 S.getName(SectName);
5616 DataRefImpl Ref = S.getRawDataRefImpl();
5617 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5618 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5619 p = S.getAddress();
5620 r = get_pointer_32(p, offset, left, S, info);
5621 if (r == nullptr)
5622 return;
5623 memset(&o, '\0', sizeof(struct imageInfo_t));
5624 if (left < sizeof(struct imageInfo_t)) {
5625 memcpy(&o, r, left);
5626 outs() << " (imageInfo entends past the end of the section)\n";
5627 } else
5628 memcpy(&o, r, sizeof(struct imageInfo_t));
5629 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5630 swapStruct(o);
5631 outs() << " version " << o.version << "\n";
5632 outs() << " flags " << format("0x%" PRIx32, o.flags);
5633 if (o.flags & 0x1)
5634 outs() << " F&C";
5635 if (o.flags & 0x2)
5636 outs() << " GC";
5637 if (o.flags & 0x4)
5638 outs() << " GC-only";
5639 else
5640 outs() << " RR";
5641 outs() << "\n";
5642}
5643
Kevin Enderby0fc11822015-04-01 20:57:01 +00005644static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5645 SymbolAddressMap AddrMap;
5646 if (verbose)
5647 CreateSymbolAddressMap(O, &AddrMap);
5648
5649 std::vector<SectionRef> Sections;
5650 for (const SectionRef &Section : O->sections()) {
5651 StringRef SectName;
5652 Section.getName(SectName);
5653 Sections.push_back(Section);
5654 }
5655
5656 struct DisassembleInfo info;
5657 // Set up the block of info used by the Symbolizer call backs.
5658 info.verbose = verbose;
5659 info.O = O;
5660 info.AddrMap = &AddrMap;
5661 info.Sections = &Sections;
5662 info.class_name = nullptr;
5663 info.selector_name = nullptr;
5664 info.method = nullptr;
5665 info.demangled_name = nullptr;
5666 info.bindtable = nullptr;
5667 info.adrp_addr = 0;
5668 info.adrp_inst = 0;
5669
Kevin Enderbyaac75382015-10-08 16:56:35 +00005670 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005671 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5672 if (CL == SectionRef())
5673 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005674 if (CL == SectionRef())
5675 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5676 if (CL == SectionRef())
5677 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005678 info.S = CL;
5679 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005680
Davide Italiano62507042015-12-11 22:27:59 +00005681 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5682 if (CR == SectionRef())
5683 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005684 if (CR == SectionRef())
5685 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5686 if (CR == SectionRef())
5687 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005688 info.S = CR;
5689 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005690
Davide Italiano62507042015-12-11 22:27:59 +00005691 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5692 if (SR == SectionRef())
5693 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005694 if (SR == SectionRef())
5695 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5696 if (SR == SectionRef())
5697 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005698 info.S = SR;
5699 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005700
Davide Italiano62507042015-12-11 22:27:59 +00005701 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5702 if (CA == SectionRef())
5703 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005704 if (CA == SectionRef())
5705 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5706 if (CA == SectionRef())
5707 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005708 info.S = CA;
5709 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005710
Davide Italiano62507042015-12-11 22:27:59 +00005711 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5712 if (PL == SectionRef())
5713 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005714 if (PL == SectionRef())
5715 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5716 if (PL == SectionRef())
5717 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005718 info.S = PL;
5719 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005720
Davide Italiano62507042015-12-11 22:27:59 +00005721 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5722 if (MR == SectionRef())
5723 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005724 if (MR == SectionRef())
5725 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5726 if (MR == SectionRef())
5727 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005728 info.S = MR;
5729 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005730
Davide Italiano62507042015-12-11 22:27:59 +00005731 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5732 if (II == SectionRef())
5733 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005734 if (II == SectionRef())
5735 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5736 if (II == SectionRef())
5737 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005738 info.S = II;
5739 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005740}
5741
5742static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005743 SymbolAddressMap AddrMap;
5744 if (verbose)
5745 CreateSymbolAddressMap(O, &AddrMap);
5746
5747 std::vector<SectionRef> Sections;
5748 for (const SectionRef &Section : O->sections()) {
5749 StringRef SectName;
5750 Section.getName(SectName);
5751 Sections.push_back(Section);
5752 }
5753
5754 struct DisassembleInfo info;
5755 // Set up the block of info used by the Symbolizer call backs.
5756 info.verbose = verbose;
5757 info.O = O;
5758 info.AddrMap = &AddrMap;
5759 info.Sections = &Sections;
5760 info.class_name = nullptr;
5761 info.selector_name = nullptr;
5762 info.method = nullptr;
5763 info.demangled_name = nullptr;
5764 info.bindtable = nullptr;
5765 info.adrp_addr = 0;
5766 info.adrp_inst = 0;
5767
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
5864 struct DisassembleInfo info;
5865 // Set up the block of info used by the Symbolizer call backs.
5866 info.verbose = verbose;
5867 info.O = O;
5868 info.AddrMap = &AddrMap;
5869 info.Sections = &Sections;
5870 info.class_name = nullptr;
5871 info.selector_name = nullptr;
5872 info.method = nullptr;
5873 info.demangled_name = nullptr;
5874 info.bindtable = nullptr;
5875 info.adrp_addr = 0;
5876 info.adrp_inst = 0;
5877
5878 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5879 p = S.getAddress() + i;
5880 r = get_pointer_32(p, offset, left, S, &info, true);
5881 if (r == nullptr)
5882 return true;
5883 memset(&module, '\0', sizeof(struct objc_module_t));
5884 if (left < sizeof(struct objc_module_t)) {
5885 memcpy(&module, r, left);
5886 outs() << " (module extends past end of __module_info section)\n";
5887 } else
5888 memcpy(&module, r, sizeof(struct objc_module_t));
5889 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5890 swapStruct(module);
5891
5892 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5893 outs() << " version " << module.version << "\n";
5894 outs() << " size " << module.size << "\n";
5895 outs() << " name ";
5896 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5897 if (name != nullptr)
5898 outs() << format("%.*s", left, name);
5899 else
5900 outs() << format("0x%08" PRIx32, module.name)
5901 << "(not in an __OBJC section)";
5902 outs() << "\n";
5903
5904 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5905 if (module.symtab == 0 || r == nullptr) {
5906 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5907 << " (not in an __OBJC section)\n";
5908 continue;
5909 }
5910 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5911 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5912 defs_left = 0;
5913 defs = nullptr;
5914 if (left < sizeof(struct objc_symtab_t)) {
5915 memcpy(&symtab, r, left);
5916 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5917 } else {
5918 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5919 if (left > sizeof(struct objc_symtab_t)) {
5920 defs_left = left - sizeof(struct objc_symtab_t);
5921 defs = r + sizeof(struct objc_symtab_t);
5922 }
5923 }
5924 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5925 swapStruct(symtab);
5926
5927 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5928 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5929 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5930 if (r == nullptr)
5931 outs() << " (not in an __OBJC section)";
5932 outs() << "\n";
5933 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5934 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5935 if (symtab.cls_def_cnt > 0)
5936 outs() << "\tClass Definitions\n";
5937 for (j = 0; j < symtab.cls_def_cnt; j++) {
5938 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5939 outs() << "\t(remaining class defs entries entends past the end of the "
5940 << "section)\n";
5941 break;
5942 }
5943 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5944 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5945 sys::swapByteOrder(def);
5946
5947 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5948 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5949 if (r != nullptr) {
5950 if (left > sizeof(struct objc_class_t)) {
5951 outs() << "\n";
5952 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5953 } else {
5954 outs() << " (entends past the end of the section)\n";
5955 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5956 memcpy(&objc_class, r, left);
5957 }
5958 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5959 swapStruct(objc_class);
5960 print_objc_class_t(&objc_class, &info);
5961 } else {
5962 outs() << "(not in an __OBJC section)\n";
5963 }
5964
5965 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5966 outs() << "\tMeta Class";
5967 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5968 if (r != nullptr) {
5969 if (left > sizeof(struct objc_class_t)) {
5970 outs() << "\n";
5971 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5972 } else {
5973 outs() << " (entends past the end of the section)\n";
5974 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5975 memcpy(&objc_class, r, left);
5976 }
5977 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5978 swapStruct(objc_class);
5979 print_objc_class_t(&objc_class, &info);
5980 } else {
5981 outs() << "(not in an __OBJC section)\n";
5982 }
5983 }
5984 }
5985 if (symtab.cat_def_cnt > 0)
5986 outs() << "\tCategory Definitions\n";
5987 for (j = 0; j < symtab.cat_def_cnt; j++) {
5988 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5989 outs() << "\t(remaining category defs entries entends past the end of "
5990 << "the section)\n";
5991 break;
5992 }
5993 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5994 sizeof(uint32_t));
5995 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5996 sys::swapByteOrder(def);
5997
5998 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5999 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6000 << format("0x%08" PRIx32, def);
6001 if (r != nullptr) {
6002 if (left > sizeof(struct objc_category_t)) {
6003 outs() << "\n";
6004 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6005 } else {
6006 outs() << " (entends past the end of the section)\n";
6007 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6008 memcpy(&objc_category, r, left);
6009 }
6010 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6011 swapStruct(objc_category);
6012 print_objc_objc_category_t(&objc_category, &info);
6013 } else {
6014 outs() << "(not in an __OBJC section)\n";
6015 }
6016 }
6017 }
6018 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6019 if (II != SectionRef())
6020 print_image_info(II, &info);
6021
6022 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006023}
6024
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006025static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6026 uint32_t size, uint32_t addr) {
6027 SymbolAddressMap AddrMap;
6028 CreateSymbolAddressMap(O, &AddrMap);
6029
6030 std::vector<SectionRef> Sections;
6031 for (const SectionRef &Section : O->sections()) {
6032 StringRef SectName;
6033 Section.getName(SectName);
6034 Sections.push_back(Section);
6035 }
6036
6037 struct DisassembleInfo info;
6038 // Set up the block of info used by the Symbolizer call backs.
6039 info.verbose = true;
6040 info.O = O;
6041 info.AddrMap = &AddrMap;
6042 info.Sections = &Sections;
6043 info.class_name = nullptr;
6044 info.selector_name = nullptr;
6045 info.method = nullptr;
6046 info.demangled_name = nullptr;
6047 info.bindtable = nullptr;
6048 info.adrp_addr = 0;
6049 info.adrp_inst = 0;
6050
6051 const char *p;
6052 struct objc_protocol_t protocol;
6053 uint32_t left, paddr;
6054 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6055 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6056 left = size - (p - sect);
6057 if (left < sizeof(struct objc_protocol_t)) {
6058 outs() << "Protocol extends past end of __protocol section\n";
6059 memcpy(&protocol, p, left);
6060 } else
6061 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6062 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6063 swapStruct(protocol);
6064 paddr = addr + (p - sect);
6065 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6066 if (print_protocol(paddr, 0, &info))
6067 outs() << "(not in an __OBJC section)\n";
6068 }
6069}
6070
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006071#ifdef HAVE_LIBXAR
6072inline void swapStruct(struct xar_header &xar) {
6073 sys::swapByteOrder(xar.magic);
6074 sys::swapByteOrder(xar.size);
6075 sys::swapByteOrder(xar.version);
6076 sys::swapByteOrder(xar.toc_length_compressed);
6077 sys::swapByteOrder(xar.toc_length_uncompressed);
6078 sys::swapByteOrder(xar.cksum_alg);
6079}
6080
6081static void PrintModeVerbose(uint32_t mode) {
6082 switch(mode & S_IFMT){
6083 case S_IFDIR:
6084 outs() << "d";
6085 break;
6086 case S_IFCHR:
6087 outs() << "c";
6088 break;
6089 case S_IFBLK:
6090 outs() << "b";
6091 break;
6092 case S_IFREG:
6093 outs() << "-";
6094 break;
6095 case S_IFLNK:
6096 outs() << "l";
6097 break;
6098 case S_IFSOCK:
6099 outs() << "s";
6100 break;
6101 default:
6102 outs() << "?";
6103 break;
6104 }
6105
6106 /* owner permissions */
6107 if(mode & S_IREAD)
6108 outs() << "r";
6109 else
6110 outs() << "-";
6111 if(mode & S_IWRITE)
6112 outs() << "w";
6113 else
6114 outs() << "-";
6115 if(mode & S_ISUID)
6116 outs() << "s";
6117 else if(mode & S_IEXEC)
6118 outs() << "x";
6119 else
6120 outs() << "-";
6121
6122 /* group permissions */
6123 if(mode & (S_IREAD >> 3))
6124 outs() << "r";
6125 else
6126 outs() << "-";
6127 if(mode & (S_IWRITE >> 3))
6128 outs() << "w";
6129 else
6130 outs() << "-";
6131 if(mode & S_ISGID)
6132 outs() << "s";
6133 else if(mode & (S_IEXEC >> 3))
6134 outs() << "x";
6135 else
6136 outs() << "-";
6137
6138 /* other permissions */
6139 if(mode & (S_IREAD >> 6))
6140 outs() << "r";
6141 else
6142 outs() << "-";
6143 if(mode & (S_IWRITE >> 6))
6144 outs() << "w";
6145 else
6146 outs() << "-";
6147 if(mode & S_ISVTX)
6148 outs() << "t";
6149 else if(mode & (S_IEXEC >> 6))
6150 outs() << "x";
6151 else
6152 outs() << "-";
6153}
6154
6155static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006156 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006157 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6158 char *endp;
6159 uint32_t mode_value;
6160
Francis Ricci6f942972017-10-06 15:33:28 +00006161 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006162 if (!xi) {
6163 errs() << "Can't obtain an xar iterator for xar archive "
6164 << XarFilename << "\n";
6165 return;
6166 }
6167
6168 // Go through the xar's files.
6169 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006170 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006171 if(!xp){
6172 errs() << "Can't obtain an xar iterator for xar archive "
6173 << XarFilename << "\n";
6174 return;
6175 }
6176 type = nullptr;
6177 mode = nullptr;
6178 user = nullptr;
6179 group = nullptr;
6180 size = nullptr;
6181 mtime = nullptr;
6182 name = nullptr;
6183 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006184 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006185 xar_prop_get(xf, key, &val);
6186#if 0 // Useful for debugging.
6187 outs() << "key: " << key << " value: " << val << "\n";
6188#endif
6189 if(strcmp(key, "type") == 0)
6190 type = val;
6191 if(strcmp(key, "mode") == 0)
6192 mode = val;
6193 if(strcmp(key, "user") == 0)
6194 user = val;
6195 if(strcmp(key, "group") == 0)
6196 group = val;
6197 if(strcmp(key, "data/size") == 0)
6198 size = val;
6199 if(strcmp(key, "mtime") == 0)
6200 mtime = val;
6201 if(strcmp(key, "name") == 0)
6202 name = val;
6203 }
6204 if(mode != nullptr){
6205 mode_value = strtoul(mode, &endp, 8);
6206 if(*endp != '\0')
6207 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6208 if(strcmp(type, "file") == 0)
6209 mode_value |= S_IFREG;
6210 PrintModeVerbose(mode_value);
6211 outs() << " ";
6212 }
6213 if(user != nullptr)
6214 outs() << format("%10s/", user);
6215 if(group != nullptr)
6216 outs() << format("%-10s ", group);
6217 if(size != nullptr)
6218 outs() << format("%7s ", size);
6219 if(mtime != nullptr){
6220 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6221 outs() << *m;
6222 if(*m == 'T')
6223 m++;
6224 outs() << " ";
6225 for( ; *m != 'Z' && *m != '\0'; m++)
6226 outs() << *m;
6227 outs() << " ";
6228 }
6229 if(name != nullptr)
6230 outs() << name;
6231 outs() << "\n";
6232 }
6233}
6234
6235static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6236 uint32_t size, bool verbose,
6237 bool PrintXarHeader, bool PrintXarFileHeaders,
6238 std::string XarMemberName) {
6239 if(size < sizeof(struct xar_header)) {
6240 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6241 "of struct xar_header)\n";
6242 return;
6243 }
6244 struct xar_header XarHeader;
6245 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6246 if (sys::IsLittleEndianHost)
6247 swapStruct(XarHeader);
6248 if (PrintXarHeader) {
6249 if (!XarMemberName.empty())
6250 outs() << "In xar member " << XarMemberName << ": ";
6251 else
6252 outs() << "For (__LLVM,__bundle) section: ";
6253 outs() << "xar header\n";
6254 if (XarHeader.magic == XAR_HEADER_MAGIC)
6255 outs() << " magic XAR_HEADER_MAGIC\n";
6256 else
6257 outs() << " magic "
6258 << format_hex(XarHeader.magic, 10, true)
6259 << " (not XAR_HEADER_MAGIC)\n";
6260 outs() << " size " << XarHeader.size << "\n";
6261 outs() << " version " << XarHeader.version << "\n";
6262 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6263 << "\n";
6264 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6265 << "\n";
6266 outs() << " cksum_alg ";
6267 switch (XarHeader.cksum_alg) {
6268 case XAR_CKSUM_NONE:
6269 outs() << "XAR_CKSUM_NONE\n";
6270 break;
6271 case XAR_CKSUM_SHA1:
6272 outs() << "XAR_CKSUM_SHA1\n";
6273 break;
6274 case XAR_CKSUM_MD5:
6275 outs() << "XAR_CKSUM_MD5\n";
6276 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006277#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006278 case XAR_CKSUM_SHA256:
6279 outs() << "XAR_CKSUM_SHA256\n";
6280 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006281#endif
6282#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006283 case XAR_CKSUM_SHA512:
6284 outs() << "XAR_CKSUM_SHA512\n";
6285 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006286#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006287 default:
6288 outs() << XarHeader.cksum_alg << "\n";
6289 }
6290 }
6291
6292 SmallString<128> XarFilename;
6293 int FD;
6294 std::error_code XarEC =
6295 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6296 if (XarEC) {
6297 errs() << XarEC.message() << "\n";
6298 return;
6299 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006300 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006301 raw_fd_ostream &XarOut = XarFile.os();
6302 StringRef XarContents(sect, size);
6303 XarOut << XarContents;
6304 XarOut.close();
6305 if (XarOut.has_error())
6306 return;
6307
Francis Ricci6f942972017-10-06 15:33:28 +00006308 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006309 if (!xar) {
6310 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
6311 return;
6312 }
6313
6314 SmallString<128> TocFilename;
6315 std::error_code TocEC =
6316 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6317 if (TocEC) {
6318 errs() << TocEC.message() << "\n";
6319 return;
6320 }
6321 xar_serialize(xar, TocFilename.c_str());
6322
6323 if (PrintXarFileHeaders) {
6324 if (!XarMemberName.empty())
6325 outs() << "In xar member " << XarMemberName << ": ";
6326 else
6327 outs() << "For (__LLVM,__bundle) section: ";
6328 outs() << "xar archive files:\n";
6329 PrintXarFilesSummary(XarFilename.c_str(), xar);
6330 }
6331
6332 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6333 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6334 if (std::error_code EC = FileOrErr.getError()) {
6335 errs() << EC.message() << "\n";
6336 return;
6337 }
6338 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6339
6340 if (!XarMemberName.empty())
6341 outs() << "In xar member " << XarMemberName << ": ";
6342 else
6343 outs() << "For (__LLVM,__bundle) section: ";
6344 outs() << "xar table of contents:\n";
6345 outs() << Buffer->getBuffer() << "\n";
6346
6347 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006348 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006349 if(!xi){
6350 errs() << "Can't obtain an xar iterator for xar archive "
6351 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006352 return;
6353 }
6354 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6355 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006356 const char *member_name, *member_type, *member_size_string;
6357 size_t member_size;
6358
Francis Ricci6f942972017-10-06 15:33:28 +00006359 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006360 if(!xp){
6361 errs() << "Can't obtain an xar iterator for xar archive "
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006362 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006363 return;
6364 }
6365 member_name = NULL;
6366 member_type = NULL;
6367 member_size_string = NULL;
6368 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006369 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006370 xar_prop_get(xf, key, &val);
6371#if 0 // Useful for debugging.
6372 outs() << "key: " << key << " value: " << val << "\n";
6373#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006374 if (strcmp(key, "name") == 0)
6375 member_name = val;
6376 if (strcmp(key, "type") == 0)
6377 member_type = val;
6378 if (strcmp(key, "data/size") == 0)
6379 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006380 }
6381 /*
6382 * If we find a file with a name, date/size and type properties
6383 * and with the type being "file" see if that is a xar file.
6384 */
6385 if (member_name != NULL && member_type != NULL &&
6386 strcmp(member_type, "file") == 0 &&
6387 member_size_string != NULL){
6388 // Extract the file into a buffer.
6389 char *endptr;
6390 member_size = strtoul(member_size_string, &endptr, 10);
6391 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006392 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006393 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006394#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006395 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006396#endif
6397 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006398 std::string OldXarMemberName;
6399 // If XarMemberName is already set this is nested. So
6400 // save the old name and create the nested name.
6401 if (!XarMemberName.empty()) {
6402 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006403 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006404 (Twine("[") + XarMemberName + "]" + member_name).str();
6405 } else {
6406 OldXarMemberName = "";
6407 XarMemberName = member_name;
6408 }
6409 // See if this is could be a xar file (nested).
6410 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006411#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006412 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006413#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006414 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006415 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006416 swapStruct(XarHeader);
6417 if (XarHeader.magic == XAR_HEADER_MAGIC)
6418 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006419 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006420 XarMemberName);
6421 }
6422 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006423 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006424 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006425 }
6426 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006427 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006428}
6429#endif // defined(HAVE_LIBXAR)
6430
Kevin Enderby0fc11822015-04-01 20:57:01 +00006431static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6432 if (O->is64Bit())
6433 printObjc2_64bit_MetaData(O, verbose);
6434 else {
6435 MachO::mach_header H;
6436 H = O->getHeader();
6437 if (H.cputype == MachO::CPU_TYPE_ARM)
6438 printObjc2_32bit_MetaData(O, verbose);
6439 else {
6440 // This is the 32-bit non-arm cputype case. Which is normally
6441 // the first Objective-C ABI. But it may be the case of a
6442 // binary for the iOS simulator which is the second Objective-C
6443 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6444 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006445 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006446 printObjc2_32bit_MetaData(O, verbose);
6447 }
6448 }
6449}
6450
Kevin Enderbybf246f52014-09-24 23:08:22 +00006451// GuessLiteralPointer returns a string which for the item in the Mach-O file
6452// for the address passed in as ReferenceValue for printing as a comment with
6453// the instruction and also returns the corresponding type of that item
6454// indirectly through ReferenceType.
6455//
6456// If ReferenceValue is an address of literal cstring then a pointer to the
6457// cstring is returned and ReferenceType is set to
6458// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6459//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006460// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6461// Class ref that name is returned and the ReferenceType is set accordingly.
6462//
6463// Lastly, literals which are Symbol address in a literal pool are looked for
6464// and if found the symbol name is returned and ReferenceType is set to
6465// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6466//
6467// If there is no item in the Mach-O file for the address passed in as
6468// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006469static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6470 uint64_t ReferencePC,
6471 uint64_t *ReferenceType,
6472 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006473 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006474 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6475 uint64_t sect_addr = info->S.getAddress();
6476 uint64_t sect_offset = ReferencePC - sect_addr;
6477 bool reloc_found = false;
6478 DataRefImpl Rel;
6479 MachO::any_relocation_info RE;
6480 bool isExtern = false;
6481 SymbolRef Symbol;
6482 for (const RelocationRef &Reloc : info->S.relocations()) {
6483 uint64_t RelocOffset = Reloc.getOffset();
6484 if (RelocOffset == sect_offset) {
6485 Rel = Reloc.getRawDataRefImpl();
6486 RE = info->O->getRelocation(Rel);
6487 if (info->O->isRelocationScattered(RE))
6488 continue;
6489 isExtern = info->O->getPlainRelocationExternal(RE);
6490 if (isExtern) {
6491 symbol_iterator RelocSym = Reloc.getSymbol();
6492 Symbol = *RelocSym;
6493 }
6494 reloc_found = true;
6495 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006496 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006497 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006498 // If there is an external relocation entry for a symbol in a section
6499 // then used that symbol's value for the value of the reference.
6500 if (reloc_found && isExtern) {
6501 if (info->O->getAnyRelocationPCRel(RE)) {
6502 unsigned Type = info->O->getAnyRelocationType(RE);
6503 if (Type == MachO::X86_64_RELOC_SIGNED) {
6504 ReferenceValue = Symbol.getValue();
6505 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006506 }
6507 }
6508 }
6509
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006510 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6511 // Message refs and Class refs.
6512 bool classref, selref, msgref, cfstring;
6513 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6514 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006515 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006516 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6517 // And the pointer_value in that section is typically zero as it will be
6518 // set by dyld as part of the "bind information".
6519 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6520 if (name != nullptr) {
6521 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006522 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006523 if (class_name != nullptr && class_name[1] == '_' &&
6524 class_name[2] != '\0') {
6525 info->class_name = class_name + 2;
6526 return name;
6527 }
6528 }
6529 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006530
David Blaikie33dd45d02015-03-23 18:39:02 +00006531 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006532 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6533 const char *name =
6534 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6535 if (name != nullptr)
6536 info->class_name = name;
6537 else
6538 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006539 return name;
6540 }
6541
David Blaikie33dd45d02015-03-23 18:39:02 +00006542 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006543 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6544 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6545 return name;
6546 }
6547
David Blaikie33dd45d02015-03-23 18:39:02 +00006548 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006549 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6550
6551 if (pointer_value != 0)
6552 ReferenceValue = pointer_value;
6553
6554 const char *name = GuessCstringPointer(ReferenceValue, info);
6555 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006556 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006557 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6558 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006559 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006560 info->class_name = nullptr;
6561 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6562 info->selector_name = name;
6563 } else
6564 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6565 return name;
6566 }
6567
6568 // Lastly look for an indirect symbol with this ReferenceValue which is in
6569 // a literal pool. If found return that symbol name.
6570 name = GuessIndirectSymbol(ReferenceValue, info);
6571 if (name) {
6572 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6573 return name;
6574 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006575
6576 return nullptr;
6577}
6578
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006579// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006580// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006581// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6582// is created and returns the symbol name that matches the ReferenceValue or
6583// nullptr if none. The ReferenceType is passed in for the IN type of
6584// reference the instruction is making from the values in defined in the header
6585// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6586// Out type and the ReferenceName will also be set which is added as a comment
6587// to the disassembled instruction.
6588//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006589// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006590// returned through ReferenceName and ReferenceType is set to
6591// LLVMDisassembler_ReferenceType_DeMangled_Name .
6592//
6593// When this is called to get a symbol name for a branch target then the
6594// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6595// SymbolValue will be looked for in the indirect symbol table to determine if
6596// it is an address for a symbol stub. If so then the symbol name for that
6597// stub is returned indirectly through ReferenceName and then ReferenceType is
6598// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6599//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006600// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006601// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6602// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6603// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006604// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006605static const char *SymbolizerSymbolLookUp(void *DisInfo,
6606 uint64_t ReferenceValue,
6607 uint64_t *ReferenceType,
6608 uint64_t ReferencePC,
6609 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006610 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006611 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006612 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006613 *ReferenceName = nullptr;
6614 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006615 return nullptr;
6616 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006617
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006618 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006619
Kevin Enderby85974882014-09-26 22:20:44 +00006620 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6621 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006622 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006623 method_reference(info, ReferenceType, ReferenceName);
6624 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6625 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006626 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006627 if (info->demangled_name != nullptr)
6628 free(info->demangled_name);
6629 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006630 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006631 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006632 if (info->demangled_name != nullptr) {
6633 *ReferenceName = info->demangled_name;
6634 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6635 } else
6636 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6637 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006638 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6639 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6640 *ReferenceName =
6641 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006642 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006643 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006644 else
6645 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006646 // If this is arm64 and the reference is an adrp instruction save the
6647 // instruction, passed in ReferenceValue and the address of the instruction
6648 // for use later if we see and add immediate instruction.
6649 } else if (info->O->getArch() == Triple::aarch64 &&
6650 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6651 info->adrp_inst = ReferenceValue;
6652 info->adrp_addr = ReferencePC;
6653 SymbolName = nullptr;
6654 *ReferenceName = nullptr;
6655 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6656 // If this is arm64 and reference is an add immediate instruction and we
6657 // have
6658 // seen an adrp instruction just before it and the adrp's Xd register
6659 // matches
6660 // this add's Xn register reconstruct the value being referenced and look to
6661 // see if it is a literal pointer. Note the add immediate instruction is
6662 // passed in ReferenceValue.
6663 } else if (info->O->getArch() == Triple::aarch64 &&
6664 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6665 ReferencePC - 4 == info->adrp_addr &&
6666 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6667 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6668 uint32_t addxri_inst;
6669 uint64_t adrp_imm, addxri_imm;
6670
6671 adrp_imm =
6672 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6673 if (info->adrp_inst & 0x0200000)
6674 adrp_imm |= 0xfffffffffc000000LL;
6675
6676 addxri_inst = ReferenceValue;
6677 addxri_imm = (addxri_inst >> 10) & 0xfff;
6678 if (((addxri_inst >> 22) & 0x3) == 1)
6679 addxri_imm <<= 12;
6680
6681 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6682 (adrp_imm << 12) + addxri_imm;
6683
6684 *ReferenceName =
6685 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6686 if (*ReferenceName == nullptr)
6687 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6688 // If this is arm64 and the reference is a load register instruction and we
6689 // have seen an adrp instruction just before it and the adrp's Xd register
6690 // matches this add's Xn register reconstruct the value being referenced and
6691 // look to see if it is a literal pointer. Note the load register
6692 // instruction is passed in ReferenceValue.
6693 } else if (info->O->getArch() == Triple::aarch64 &&
6694 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6695 ReferencePC - 4 == info->adrp_addr &&
6696 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6697 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6698 uint32_t ldrxui_inst;
6699 uint64_t adrp_imm, ldrxui_imm;
6700
6701 adrp_imm =
6702 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6703 if (info->adrp_inst & 0x0200000)
6704 adrp_imm |= 0xfffffffffc000000LL;
6705
6706 ldrxui_inst = ReferenceValue;
6707 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6708
6709 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6710 (adrp_imm << 12) + (ldrxui_imm << 3);
6711
6712 *ReferenceName =
6713 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6714 if (*ReferenceName == nullptr)
6715 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6716 }
6717 // If this arm64 and is an load register (PC-relative) instruction the
6718 // ReferenceValue is the PC plus the immediate value.
6719 else if (info->O->getArch() == Triple::aarch64 &&
6720 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6721 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6722 *ReferenceName =
6723 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6724 if (*ReferenceName == nullptr)
6725 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006726 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006727 if (info->demangled_name != nullptr)
6728 free(info->demangled_name);
6729 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006730 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006731 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006732 if (info->demangled_name != nullptr) {
6733 *ReferenceName = info->demangled_name;
6734 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6735 }
6736 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006737 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006738 *ReferenceName = nullptr;
6739 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6740 }
6741
6742 return SymbolName;
6743}
6744
Kevin Enderbybf246f52014-09-24 23:08:22 +00006745/// \brief Emits the comments that are stored in the CommentStream.
6746/// Each comment in the CommentStream must end with a newline.
6747static void emitComments(raw_svector_ostream &CommentStream,
6748 SmallString<128> &CommentsToEmit,
6749 formatted_raw_ostream &FormattedOS,
6750 const MCAsmInfo &MAI) {
6751 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006752 StringRef Comments = CommentsToEmit.str();
6753 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006754 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006755 unsigned CommentColumn = MAI.getCommentColumn();
6756 bool IsFirst = true;
6757 while (!Comments.empty()) {
6758 if (!IsFirst)
6759 FormattedOS << '\n';
6760 // Emit a line of comments.
6761 FormattedOS.PadToColumn(CommentColumn);
6762 size_t Position = Comments.find('\n');
6763 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6764 // Move after the newline character.
6765 Comments = Comments.substr(Position + 1);
6766 IsFirst = false;
6767 }
6768 FormattedOS.flush();
6769
6770 // Tell the comment stream that the vector changed underneath it.
6771 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006772}
6773
Kevin Enderby95df54c2015-02-04 01:01:38 +00006774static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6775 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006776 const char *McpuDefault = nullptr;
6777 const Target *ThumbTarget = nullptr;
6778 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006779 if (!TheTarget) {
6780 // GetTarget prints out stuff.
6781 return;
6782 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006783 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006784 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006785 MachOMCPU = McpuDefault;
6786 else
6787 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006788
Ahmed Charles56440fd2014-03-06 05:51:42 +00006789 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006790 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006791 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006792 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006793
Kevin Enderbyc9595622014-08-06 23:24:41 +00006794 // Package up features to be passed to target/subtarget
6795 std::string FeaturesStr;
6796 if (MAttrs.size()) {
6797 SubtargetFeatures Features;
6798 for (unsigned i = 0; i != MAttrs.size(); ++i)
6799 Features.AddFeature(MAttrs[i]);
6800 FeaturesStr = Features.getString();
6801 }
6802
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006803 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006804 std::unique_ptr<const MCRegisterInfo> MRI(
6805 TheTarget->createMCRegInfo(TripleName));
6806 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006807 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006808 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006809 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006810 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006811 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006812 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006813 std::unique_ptr<MCSymbolizer> Symbolizer;
6814 struct DisassembleInfo SymbolizerInfo;
6815 std::unique_ptr<MCRelocationInfo> RelInfo(
6816 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6817 if (RelInfo) {
6818 Symbolizer.reset(TheTarget->createMCSymbolizer(
6819 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006820 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006821 DisAsm->setSymbolizer(std::move(Symbolizer));
6822 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006823 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006824 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006825 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006826 // Set the display preference for hex vs. decimal immediates.
6827 IP->setPrintImmHex(PrintImmHex);
6828 // Comment stream and backing vector.
6829 SmallString<128> CommentsToEmit;
6830 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006831 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6832 // if it is done then arm64 comments for string literals don't get printed
6833 // and some constant get printed instead and not setting it causes intel
6834 // (32-bit and 64-bit) comments printed with different spacing before the
6835 // comment causing different diffs with the 'C' disassembler library API.
6836 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006837
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006838 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006839 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006840 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006841 return;
6842 }
6843
Tim Northover09ca33e2016-04-22 23:23:31 +00006844 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006845 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6846 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6847 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006848 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006849 std::unique_ptr<MCInstPrinter> ThumbIP;
6850 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006851 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6852 struct DisassembleInfo ThumbSymbolizerInfo;
6853 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006854 if (ThumbTarget) {
6855 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6856 ThumbAsmInfo.reset(
6857 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6858 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006859 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6860 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006861 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6862 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006863 MCContext *PtrThumbCtx = ThumbCtx.get();
6864 ThumbRelInfo.reset(
6865 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6866 if (ThumbRelInfo) {
6867 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6868 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006869 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006870 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6871 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006872 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6873 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006874 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6875 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006876 // Set the display preference for hex vs. decimal immediates.
6877 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006878 }
6879
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006880 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006881 errs() << "error: couldn't initialize disassembler for target "
6882 << ThumbTripleName << '\n';
6883 return;
6884 }
6885
Charles Davis8bdfafd2013-09-01 04:28:48 +00006886 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006887
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006888 // FIXME: Using the -cfg command line option, this code used to be able to
6889 // annotate relocations with the referenced symbol's name, and if this was
6890 // inside a __[cf]string section, the data it points to. This is now replaced
6891 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006892 std::vector<SectionRef> Sections;
6893 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006894 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006895 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006896
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006897 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006898 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006899
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006900 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006901 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006902
Kevin Enderby273ae012013-06-06 17:20:50 +00006903 // Build a data in code table that is sorted on by the address of each entry.
6904 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006905 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006906 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006907 else
6908 BaseAddress = BaseSegmentAddress;
6909 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006910 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006911 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006912 uint32_t Offset;
6913 DI->getOffset(Offset);
6914 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6915 }
6916 array_pod_sort(Dices.begin(), Dices.end());
6917
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006918#ifndef NDEBUG
6919 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6920#else
6921 raw_ostream &DebugOut = nulls();
6922#endif
6923
Ahmed Charles56440fd2014-03-06 05:51:42 +00006924 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006925 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006926 // Try to find debug info and set up the DIContext for it.
6927 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006928 // A separate DSym file path was specified, parse it as a macho file,
6929 // get the sections and supply it to the section name parsing machinery.
6930 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006931 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006932 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006933 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006934 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006935 return;
6936 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006937 DbgObj =
6938 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6939 .get()
6940 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006941 }
6942
Eric Christopher7370b552012-11-12 21:40:38 +00006943 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006944 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006945 }
6946
Colin LeMahieufcc32762015-07-29 19:08:10 +00006947 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006948 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006949
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006950 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006951 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006952 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6953 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006954
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006955 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006956
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006957 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006958 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006959 continue;
6960
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006961 StringRef BytesStr;
6962 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006963 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6964 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006965 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006966
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006967 bool symbolTableWorked = false;
6968
Kevin Enderbybf246f52014-09-24 23:08:22 +00006969 // Create a map of symbol addresses to symbol names for use by
6970 // the SymbolizerSymbolLookUp() routine.
6971 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006972 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006973 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006974 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006975 if (!STOrErr)
6976 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006977 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006978 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6979 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006980 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006981 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006982 if (!SymNameOrErr)
6983 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006984 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006985 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006986 if (!DisSymName.empty() && DisSymName == SymName)
6987 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006988 }
6989 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006990 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006991 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6992 return;
6993 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006994 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006995 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006996 SymbolizerInfo.O = MachOOF;
6997 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006998 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006999 SymbolizerInfo.Sections = &Sections;
7000 SymbolizerInfo.class_name = nullptr;
7001 SymbolizerInfo.selector_name = nullptr;
7002 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00007003 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00007004 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00007005 SymbolizerInfo.adrp_addr = 0;
7006 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007007 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007008 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007009 ThumbSymbolizerInfo.O = MachOOF;
7010 ThumbSymbolizerInfo.S = Sections[SectIdx];
7011 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7012 ThumbSymbolizerInfo.Sections = &Sections;
7013 ThumbSymbolizerInfo.class_name = nullptr;
7014 ThumbSymbolizerInfo.selector_name = nullptr;
7015 ThumbSymbolizerInfo.method = nullptr;
7016 ThumbSymbolizerInfo.demangled_name = nullptr;
7017 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00007018 ThumbSymbolizerInfo.adrp_addr = 0;
7019 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007020
Kevin Enderby4b627be2016-04-28 20:14:13 +00007021 unsigned int Arch = MachOOF->getArch();
7022
Tim Northoverf203ab52016-07-14 22:13:32 +00007023 // Skip all symbols if this is a stubs file.
7024 if (Bytes.size() == 0)
7025 return;
7026
Kevin Enderbyc138da32017-02-06 18:43:18 +00007027 // If the section has symbols but no symbol at the start of the section
7028 // these are used to make sure the bytes before the first symbol are
7029 // disassembled.
7030 bool FirstSymbol = true;
7031 bool FirstSymbolAtSectionStart = true;
7032
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007033 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007034 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007035 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007036 if (!SymNameOrErr)
7037 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007038 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007039
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007040 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007041 if (!STOrErr)
7042 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007043 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007044 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007045 continue;
7046
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007047 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007048 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007049 if (!containsSym) {
7050 if (!DisSymName.empty() && DisSymName == SymName) {
7051 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7052 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007053 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007054 continue;
7055 }
7056 // The __mh_execute_header is special and we need to deal with that fact
7057 // this symbol is before the start of the (__TEXT,__text) section and at the
7058 // address of the start of the __TEXT segment. This is because this symbol
7059 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7060 // start of the section in a standard MH_EXECUTE filetype.
7061 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7062 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7063 return;
7064 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007065 // When this code is trying to disassemble a symbol at a time and in the
7066 // case there is only the __mh_execute_header symbol left as in a stripped
7067 // executable, we need to deal with this by ignoring this symbol so the
7068 // whole section is disassembled and this symbol is then not displayed.
7069 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7070 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7071 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007072 continue;
7073
Kevin Enderby6a221752015-03-17 17:10:57 +00007074 // If we are only disassembling one symbol see if this is that symbol.
7075 if (!DisSymName.empty() && DisSymName != SymName)
7076 continue;
7077
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007078 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007079 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007080 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007081 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007082 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007083
Tim Northoverf203ab52016-07-14 22:13:32 +00007084 if (Start > SectSize) {
7085 outs() << "section data ends, " << SymName
7086 << " lies outside valid range\n";
7087 return;
7088 }
7089
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007090 // Stop disassembling either at the beginning of the next symbol or at
7091 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007092 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007093 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007094 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007095 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007096 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007097 if (!STOrErr)
7098 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007099 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007100 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007101 containsNextSym =
7102 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007103 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007104 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007105 break;
7106 }
7107 ++NextSymIdx;
7108 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007109
Tim Northoverf203ab52016-07-14 22:13:32 +00007110 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007111 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007112
7113 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007114
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007115 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007116 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7117
7118 // We only need the dedicated Thumb target if there's a real choice
7119 // (i.e. we're not targeting M-class) and the function is Thumb.
7120 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007121
Kevin Enderbyc138da32017-02-06 18:43:18 +00007122 // If we are not specifying a symbol to start disassembly with and this
7123 // is the first symbol in the section but not at the start of the section
7124 // then move the disassembly index to the start of the section and
7125 // don't print the symbol name just yet. This is so the bytes before the
7126 // first symbol are disassembled.
7127 uint64_t SymbolStart = Start;
7128 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7129 FirstSymbolAtSectionStart = false;
7130 Start = 0;
7131 }
7132 else
7133 outs() << SymName << ":\n";
7134
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007135 DILineInfo lastLine;
7136 for (uint64_t Index = Start; Index < End; Index += Size) {
7137 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007138
Kevin Enderbyc138da32017-02-06 18:43:18 +00007139 // If this is the first symbol in the section and it was not at the
7140 // start of the section, see if we are at its Index now and if so print
7141 // the symbol name.
7142 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7143 outs() << SymName << ":\n";
7144
Kevin Enderbybf246f52014-09-24 23:08:22 +00007145 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007146 if (!NoLeadingAddr) {
7147 if (FullLeadingAddr) {
7148 if (MachOOF->is64Bit())
7149 outs() << format("%016" PRIx64, PC);
7150 else
7151 outs() << format("%08" PRIx64, PC);
7152 } else {
7153 outs() << format("%8" PRIx64 ":", PC);
7154 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007155 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007156 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007157 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007158
7159 // Check the data in code table here to see if this is data not an
7160 // instruction to be disassembled.
7161 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007162 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007163 dice_table_iterator DTI =
7164 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7165 compareDiceTableEntries);
7166 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007167 uint16_t Length;
7168 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007169 uint16_t Kind;
7170 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007171 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007172 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7173 (PC == (DTI->first + Length - 1)) && (Length & 1))
7174 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007175 continue;
7176 }
7177
Kevin Enderbybf246f52014-09-24 23:08:22 +00007178 SmallVector<char, 64> AnnotationsBytes;
7179 raw_svector_ostream Annotations(AnnotationsBytes);
7180
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007181 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007182 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007183 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007184 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007185 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007186 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007187 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007188 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007189 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007190 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007191 }
7192 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007193 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007194 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007195 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007196 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007197 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007198 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007199
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007200 // Print debug info.
7201 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007202 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007203 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007204 if (dli != lastLine && dli.Line != 0)
7205 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7206 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007207 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007208 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007209 outs() << "\n";
7210 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007211 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007212 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007213 outs() << format("\t.byte 0x%02x #bad opcode\n",
7214 *(Bytes.data() + Index) & 0xff);
7215 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007216 } else if (Arch == Triple::aarch64 ||
7217 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007218 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7219 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7220 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7221 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7222 outs() << format("\t.long\t0x%08x\n", opcode);
7223 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007224 } else if (Arch == Triple::arm) {
7225 assert(IsThumb && "ARM mode should have been dealt with above");
7226 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7227 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7228 outs() << format("\t.short\t0x%04x\n", opcode);
7229 Size = 2;
7230 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007231 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7232 if (Size == 0)
7233 Size = 1; // skip illegible bytes
7234 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007235 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007236 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007237 // Now that we are done disassembled the first symbol set the bool that
7238 // were doing this to false.
7239 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007240 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007241 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007242 // Reading the symbol table didn't work, disassemble the whole section.
7243 uint64_t SectAddress = Sections[SectIdx].getAddress();
7244 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007245 uint64_t InstSize;
7246 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007247 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007248
Kevin Enderbybf246f52014-09-24 23:08:22 +00007249 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007250 SmallVector<char, 64> AnnotationsBytes;
7251 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007252 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007253 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007254 if (!NoLeadingAddr) {
7255 if (FullLeadingAddr) {
7256 if (MachOOF->is64Bit())
7257 outs() << format("%016" PRIx64, PC);
7258 else
7259 outs() << format("%08" PRIx64, PC);
7260 } else {
7261 outs() << format("%8" PRIx64 ":", PC);
7262 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007263 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007264 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007265 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007266 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007267 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007268 StringRef AnnotationsStr = Annotations.str();
7269 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007270 outs() << "\n";
7271 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007272 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007273 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007274 outs() << format("\t.byte 0x%02x #bad opcode\n",
7275 *(Bytes.data() + Index) & 0xff);
7276 InstSize = 1; // skip exactly one illegible byte and move on.
7277 } else {
7278 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
7279 if (InstSize == 0)
7280 InstSize = 1; // skip illegible bytes
7281 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007282 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007283 }
7284 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007285 // The TripleName's need to be reset if we are called again for a different
7286 // archtecture.
7287 TripleName = "";
7288 ThumbTripleName = "";
7289
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007290 if (SymbolizerInfo.method != nullptr)
7291 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007292 if (SymbolizerInfo.demangled_name != nullptr)
7293 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007294 if (ThumbSymbolizerInfo.method != nullptr)
7295 free(ThumbSymbolizerInfo.method);
7296 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7297 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007298 }
7299}
Tim Northover4bd286a2014-08-01 13:07:19 +00007300
Tim Northover39c70bb2014-08-12 11:52:59 +00007301//===----------------------------------------------------------------------===//
7302// __compact_unwind section dumping
7303//===----------------------------------------------------------------------===//
7304
Tim Northover4bd286a2014-08-01 13:07:19 +00007305namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007306
7307template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007308 using llvm::support::little;
7309 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007310
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007311 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
7312 Buf += sizeof(T);
7313 return Val;
7314}
Tim Northover39c70bb2014-08-12 11:52:59 +00007315
Tim Northover4bd286a2014-08-01 13:07:19 +00007316struct CompactUnwindEntry {
7317 uint32_t OffsetInSection;
7318
7319 uint64_t FunctionAddr;
7320 uint32_t Length;
7321 uint32_t CompactEncoding;
7322 uint64_t PersonalityAddr;
7323 uint64_t LSDAAddr;
7324
7325 RelocationRef FunctionReloc;
7326 RelocationRef PersonalityReloc;
7327 RelocationRef LSDAReloc;
7328
7329 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007330 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007331 if (Is64)
7332 read<uint64_t>(Contents.data() + Offset);
7333 else
7334 read<uint32_t>(Contents.data() + Offset);
7335 }
7336
7337private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007338 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007339 FunctionAddr = readNext<UIntPtr>(Buf);
7340 Length = readNext<uint32_t>(Buf);
7341 CompactEncoding = readNext<uint32_t>(Buf);
7342 PersonalityAddr = readNext<UIntPtr>(Buf);
7343 LSDAAddr = readNext<UIntPtr>(Buf);
7344 }
7345};
7346}
7347
7348/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7349/// and data being relocated, determine the best base Name and Addend to use for
7350/// display purposes.
7351///
7352/// 1. An Extern relocation will directly reference a symbol (and the data is
7353/// then already an addend), so use that.
7354/// 2. Otherwise the data is an offset in the object file's layout; try to find
7355// a symbol before it in the same section, and use the offset from there.
7356/// 3. Finally, if all that fails, fall back to an offset from the start of the
7357/// referenced section.
7358static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7359 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007360 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007361 StringRef &Name, uint64_t &Addend) {
7362 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007363 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007364 if (!NameOrErr)
7365 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007366 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007367 Addend = Addr;
7368 return;
7369 }
7370
7371 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007372 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007373
Rafael Espindola80291272014-10-08 15:28:58 +00007374 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007375
7376 auto Sym = Symbols.upper_bound(Addr);
7377 if (Sym == Symbols.begin()) {
7378 // The first symbol in the object is after this reference, the best we can
7379 // do is section-relative notation.
7380 RelocSection.getName(Name);
7381 Addend = Addr - SectionAddr;
7382 return;
7383 }
7384
7385 // Go back one so that SymbolAddress <= Addr.
7386 --Sym;
7387
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007388 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007389 if (!SectOrErr)
7390 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007391 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007392 if (RelocSection == *SymSection) {
7393 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007394 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007395 if (!NameOrErr)
7396 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007397 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007398 Addend = Addr - Sym->first;
7399 return;
7400 }
7401
7402 // There is a symbol before this reference, but it's in a different
7403 // section. Probably not helpful to mention it, so use the section name.
7404 RelocSection.getName(Name);
7405 Addend = Addr - SectionAddr;
7406}
7407
7408static void printUnwindRelocDest(const MachOObjectFile *Obj,
7409 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007410 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007411 StringRef Name;
7412 uint64_t Addend;
7413
Rafael Espindola854038e2015-06-26 14:51:16 +00007414 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007415 return;
7416
Tim Northover4bd286a2014-08-01 13:07:19 +00007417 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7418
7419 outs() << Name;
7420 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007421 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007422}
7423
7424static void
7425printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7426 std::map<uint64_t, SymbolRef> &Symbols,
7427 const SectionRef &CompactUnwind) {
7428
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007429 if (!Obj->isLittleEndian()) {
7430 outs() << "Skipping big-endian __compact_unwind section\n";
7431 return;
7432 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007433
7434 bool Is64 = Obj->is64Bit();
7435 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7436 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7437
7438 StringRef Contents;
7439 CompactUnwind.getContents(Contents);
7440
7441 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7442
7443 // First populate the initial raw offsets, encodings and so on from the entry.
7444 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7445 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7446 CompactUnwinds.push_back(Entry);
7447 }
7448
7449 // Next we need to look at the relocations to find out what objects are
7450 // actually being referred to.
7451 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007452 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007453
7454 uint32_t EntryIdx = RelocAddress / EntrySize;
7455 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7456 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7457
7458 if (OffsetInEntry == 0)
7459 Entry.FunctionReloc = Reloc;
7460 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7461 Entry.PersonalityReloc = Reloc;
7462 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7463 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007464 else {
7465 outs() << "Invalid relocation in __compact_unwind section\n";
7466 return;
7467 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007468 }
7469
7470 // Finally, we're ready to print the data we've gathered.
7471 outs() << "Contents of __compact_unwind section:\n";
7472 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007473 outs() << " Entry at offset "
7474 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007475
7476 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007477 outs() << " start: " << format("0x%" PRIx64,
7478 Entry.FunctionAddr) << ' ';
7479 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007480 outs() << '\n';
7481
7482 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007483 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7484 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007485 // 3. The 32-bit compact encoding.
7486 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007487 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007488
7489 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007490 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007491 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007492 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007493 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7494 Entry.PersonalityAddr);
7495 outs() << '\n';
7496 }
7497
7498 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007499 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007500 outs() << " LSDA: " << format("0x%" PRIx64,
7501 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007502 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7503 outs() << '\n';
7504 }
7505 }
7506}
7507
Tim Northover39c70bb2014-08-12 11:52:59 +00007508//===----------------------------------------------------------------------===//
7509// __unwind_info section dumping
7510//===----------------------------------------------------------------------===//
7511
7512static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7513 const char *Pos = PageStart;
7514 uint32_t Kind = readNext<uint32_t>(Pos);
7515 (void)Kind;
7516 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7517
7518 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7519 uint16_t NumEntries = readNext<uint16_t>(Pos);
7520
7521 Pos = PageStart + EntriesStart;
7522 for (unsigned i = 0; i < NumEntries; ++i) {
7523 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7524 uint32_t Encoding = readNext<uint32_t>(Pos);
7525
7526 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007527 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7528 << ", "
7529 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007530 }
7531}
7532
7533static void printCompressedSecondLevelUnwindPage(
7534 const char *PageStart, uint32_t FunctionBase,
7535 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7536 const char *Pos = PageStart;
7537 uint32_t Kind = readNext<uint32_t>(Pos);
7538 (void)Kind;
7539 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7540
7541 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7542 uint16_t NumEntries = readNext<uint16_t>(Pos);
7543
7544 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7545 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007546 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7547 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007548
7549 Pos = PageStart + EntriesStart;
7550 for (unsigned i = 0; i < NumEntries; ++i) {
7551 uint32_t Entry = readNext<uint32_t>(Pos);
7552 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7553 uint32_t EncodingIdx = Entry >> 24;
7554
7555 uint32_t Encoding;
7556 if (EncodingIdx < CommonEncodings.size())
7557 Encoding = CommonEncodings[EncodingIdx];
7558 else
7559 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7560
7561 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007562 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7563 << ", "
7564 << "encoding[" << EncodingIdx
7565 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007566 }
7567}
7568
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007569static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7570 std::map<uint64_t, SymbolRef> &Symbols,
7571 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007572
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007573 if (!Obj->isLittleEndian()) {
7574 outs() << "Skipping big-endian __unwind_info section\n";
7575 return;
7576 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007577
7578 outs() << "Contents of __unwind_info section:\n";
7579
7580 StringRef Contents;
7581 UnwindInfo.getContents(Contents);
7582 const char *Pos = Contents.data();
7583
7584 //===----------------------------------
7585 // Section header
7586 //===----------------------------------
7587
7588 uint32_t Version = readNext<uint32_t>(Pos);
7589 outs() << " Version: "
7590 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007591 if (Version != 1) {
7592 outs() << " Skipping section with unknown version\n";
7593 return;
7594 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007595
7596 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7597 outs() << " Common encodings array section offset: "
7598 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7599 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7600 outs() << " Number of common encodings in array: "
7601 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7602
7603 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7604 outs() << " Personality function array section offset: "
7605 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7606 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7607 outs() << " Number of personality functions in array: "
7608 << format("0x%" PRIx32, NumPersonalities) << '\n';
7609
7610 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7611 outs() << " Index array section offset: "
7612 << format("0x%" PRIx32, IndicesStart) << '\n';
7613 uint32_t NumIndices = readNext<uint32_t>(Pos);
7614 outs() << " Number of indices in array: "
7615 << format("0x%" PRIx32, NumIndices) << '\n';
7616
7617 //===----------------------------------
7618 // A shared list of common encodings
7619 //===----------------------------------
7620
7621 // These occupy indices in the range [0, N] whenever an encoding is referenced
7622 // from a compressed 2nd level index table. In practice the linker only
7623 // creates ~128 of these, so that indices are available to embed encodings in
7624 // the 2nd level index.
7625
7626 SmallVector<uint32_t, 64> CommonEncodings;
7627 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7628 Pos = Contents.data() + CommonEncodingsStart;
7629 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7630 uint32_t Encoding = readNext<uint32_t>(Pos);
7631 CommonEncodings.push_back(Encoding);
7632
7633 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7634 << '\n';
7635 }
7636
Tim Northover39c70bb2014-08-12 11:52:59 +00007637 //===----------------------------------
7638 // Personality functions used in this executable
7639 //===----------------------------------
7640
7641 // There should be only a handful of these (one per source language,
7642 // roughly). Particularly since they only get 2 bits in the compact encoding.
7643
7644 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7645 Pos = Contents.data() + PersonalitiesStart;
7646 for (unsigned i = 0; i < NumPersonalities; ++i) {
7647 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7648 outs() << " personality[" << i + 1
7649 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7650 }
7651
7652 //===----------------------------------
7653 // The level 1 index entries
7654 //===----------------------------------
7655
7656 // These specify an approximate place to start searching for the more detailed
7657 // information, sorted by PC.
7658
7659 struct IndexEntry {
7660 uint32_t FunctionOffset;
7661 uint32_t SecondLevelPageStart;
7662 uint32_t LSDAStart;
7663 };
7664
7665 SmallVector<IndexEntry, 4> IndexEntries;
7666
7667 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7668 Pos = Contents.data() + IndicesStart;
7669 for (unsigned i = 0; i < NumIndices; ++i) {
7670 IndexEntry Entry;
7671
7672 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7673 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7674 Entry.LSDAStart = readNext<uint32_t>(Pos);
7675 IndexEntries.push_back(Entry);
7676
7677 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007678 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7679 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007680 << "2nd level page offset="
7681 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007682 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007683 }
7684
Tim Northover39c70bb2014-08-12 11:52:59 +00007685 //===----------------------------------
7686 // Next come the LSDA tables
7687 //===----------------------------------
7688
7689 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7690 // the first top-level index's LSDAOffset to the last (sentinel).
7691
7692 outs() << " LSDA descriptors:\n";
7693 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7694 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7695 (2 * sizeof(uint32_t));
7696 for (int i = 0; i < NumLSDAs; ++i) {
7697 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7698 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7699 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007700 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7701 << ", "
7702 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007703 }
7704
7705 //===----------------------------------
7706 // Finally, the 2nd level indices
7707 //===----------------------------------
7708
7709 // Generally these are 4K in size, and have 2 possible forms:
7710 // + Regular stores up to 511 entries with disparate encodings
7711 // + Compressed stores up to 1021 entries if few enough compact encoding
7712 // values are used.
7713 outs() << " Second level indices:\n";
7714 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7715 // The final sentinel top-level index has no associated 2nd level page
7716 if (IndexEntries[i].SecondLevelPageStart == 0)
7717 break;
7718
7719 outs() << " Second level index[" << i << "]: "
7720 << "offset in section="
7721 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7722 << ", "
7723 << "base function offset="
7724 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7725
7726 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007727 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007728 if (Kind == 2)
7729 printRegularSecondLevelUnwindPage(Pos);
7730 else if (Kind == 3)
7731 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7732 CommonEncodings);
7733 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007734 outs() << " Skipping 2nd level page with unknown kind " << Kind
7735 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007736 }
7737}
7738
Tim Northover4bd286a2014-08-01 13:07:19 +00007739void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7740 std::map<uint64_t, SymbolRef> Symbols;
7741 for (const SymbolRef &SymRef : Obj->symbols()) {
7742 // Discard any undefined or absolute symbols. They're not going to take part
7743 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007744 auto SectOrErr = SymRef.getSection();
7745 if (!SectOrErr) {
7746 // TODO: Actually report errors helpfully.
7747 consumeError(SectOrErr.takeError());
7748 continue;
7749 }
7750 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007751 if (Section == Obj->section_end())
7752 continue;
7753
Rafael Espindoladea00162015-07-03 17:44:18 +00007754 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007755 Symbols.insert(std::make_pair(Addr, SymRef));
7756 }
7757
7758 for (const SectionRef &Section : Obj->sections()) {
7759 StringRef SectName;
7760 Section.getName(SectName);
7761 if (SectName == "__compact_unwind")
7762 printMachOCompactUnwindSection(Obj, Symbols, Section);
7763 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007764 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007765 }
7766}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007767
7768static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7769 uint32_t cpusubtype, uint32_t filetype,
7770 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7771 bool verbose) {
7772 outs() << "Mach header\n";
7773 outs() << " magic cputype cpusubtype caps filetype ncmds "
7774 "sizeofcmds flags\n";
7775 if (verbose) {
7776 if (magic == MachO::MH_MAGIC)
7777 outs() << " MH_MAGIC";
7778 else if (magic == MachO::MH_MAGIC_64)
7779 outs() << "MH_MAGIC_64";
7780 else
7781 outs() << format(" 0x%08" PRIx32, magic);
7782 switch (cputype) {
7783 case MachO::CPU_TYPE_I386:
7784 outs() << " I386";
7785 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7786 case MachO::CPU_SUBTYPE_I386_ALL:
7787 outs() << " ALL";
7788 break;
7789 default:
7790 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7791 break;
7792 }
7793 break;
7794 case MachO::CPU_TYPE_X86_64:
7795 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007796 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7797 case MachO::CPU_SUBTYPE_X86_64_ALL:
7798 outs() << " ALL";
7799 break;
7800 case MachO::CPU_SUBTYPE_X86_64_H:
7801 outs() << " Haswell";
7802 break;
7803 default:
7804 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7805 break;
7806 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007807 break;
7808 case MachO::CPU_TYPE_ARM:
7809 outs() << " ARM";
7810 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7811 case MachO::CPU_SUBTYPE_ARM_ALL:
7812 outs() << " ALL";
7813 break;
7814 case MachO::CPU_SUBTYPE_ARM_V4T:
7815 outs() << " V4T";
7816 break;
7817 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7818 outs() << " V5TEJ";
7819 break;
7820 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7821 outs() << " XSCALE";
7822 break;
7823 case MachO::CPU_SUBTYPE_ARM_V6:
7824 outs() << " V6";
7825 break;
7826 case MachO::CPU_SUBTYPE_ARM_V6M:
7827 outs() << " V6M";
7828 break;
7829 case MachO::CPU_SUBTYPE_ARM_V7:
7830 outs() << " V7";
7831 break;
7832 case MachO::CPU_SUBTYPE_ARM_V7EM:
7833 outs() << " V7EM";
7834 break;
7835 case MachO::CPU_SUBTYPE_ARM_V7K:
7836 outs() << " V7K";
7837 break;
7838 case MachO::CPU_SUBTYPE_ARM_V7M:
7839 outs() << " V7M";
7840 break;
7841 case MachO::CPU_SUBTYPE_ARM_V7S:
7842 outs() << " V7S";
7843 break;
7844 default:
7845 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7846 break;
7847 }
7848 break;
7849 case MachO::CPU_TYPE_ARM64:
7850 outs() << " ARM64";
7851 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7852 case MachO::CPU_SUBTYPE_ARM64_ALL:
7853 outs() << " ALL";
7854 break;
7855 default:
7856 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7857 break;
7858 }
7859 break;
7860 case MachO::CPU_TYPE_POWERPC:
7861 outs() << " PPC";
7862 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7863 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7864 outs() << " ALL";
7865 break;
7866 default:
7867 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7868 break;
7869 }
7870 break;
7871 case MachO::CPU_TYPE_POWERPC64:
7872 outs() << " PPC64";
7873 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7874 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7875 outs() << " ALL";
7876 break;
7877 default:
7878 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7879 break;
7880 }
7881 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007882 default:
7883 outs() << format(" %7d", cputype);
7884 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7885 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007886 }
7887 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007888 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007889 } else {
7890 outs() << format(" 0x%02" PRIx32,
7891 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7892 }
7893 switch (filetype) {
7894 case MachO::MH_OBJECT:
7895 outs() << " OBJECT";
7896 break;
7897 case MachO::MH_EXECUTE:
7898 outs() << " EXECUTE";
7899 break;
7900 case MachO::MH_FVMLIB:
7901 outs() << " FVMLIB";
7902 break;
7903 case MachO::MH_CORE:
7904 outs() << " CORE";
7905 break;
7906 case MachO::MH_PRELOAD:
7907 outs() << " PRELOAD";
7908 break;
7909 case MachO::MH_DYLIB:
7910 outs() << " DYLIB";
7911 break;
7912 case MachO::MH_DYLIB_STUB:
7913 outs() << " DYLIB_STUB";
7914 break;
7915 case MachO::MH_DYLINKER:
7916 outs() << " DYLINKER";
7917 break;
7918 case MachO::MH_BUNDLE:
7919 outs() << " BUNDLE";
7920 break;
7921 case MachO::MH_DSYM:
7922 outs() << " DSYM";
7923 break;
7924 case MachO::MH_KEXT_BUNDLE:
7925 outs() << " KEXTBUNDLE";
7926 break;
7927 default:
7928 outs() << format(" %10u", filetype);
7929 break;
7930 }
7931 outs() << format(" %5u", ncmds);
7932 outs() << format(" %10u", sizeofcmds);
7933 uint32_t f = flags;
7934 if (f & MachO::MH_NOUNDEFS) {
7935 outs() << " NOUNDEFS";
7936 f &= ~MachO::MH_NOUNDEFS;
7937 }
7938 if (f & MachO::MH_INCRLINK) {
7939 outs() << " INCRLINK";
7940 f &= ~MachO::MH_INCRLINK;
7941 }
7942 if (f & MachO::MH_DYLDLINK) {
7943 outs() << " DYLDLINK";
7944 f &= ~MachO::MH_DYLDLINK;
7945 }
7946 if (f & MachO::MH_BINDATLOAD) {
7947 outs() << " BINDATLOAD";
7948 f &= ~MachO::MH_BINDATLOAD;
7949 }
7950 if (f & MachO::MH_PREBOUND) {
7951 outs() << " PREBOUND";
7952 f &= ~MachO::MH_PREBOUND;
7953 }
7954 if (f & MachO::MH_SPLIT_SEGS) {
7955 outs() << " SPLIT_SEGS";
7956 f &= ~MachO::MH_SPLIT_SEGS;
7957 }
7958 if (f & MachO::MH_LAZY_INIT) {
7959 outs() << " LAZY_INIT";
7960 f &= ~MachO::MH_LAZY_INIT;
7961 }
7962 if (f & MachO::MH_TWOLEVEL) {
7963 outs() << " TWOLEVEL";
7964 f &= ~MachO::MH_TWOLEVEL;
7965 }
7966 if (f & MachO::MH_FORCE_FLAT) {
7967 outs() << " FORCE_FLAT";
7968 f &= ~MachO::MH_FORCE_FLAT;
7969 }
7970 if (f & MachO::MH_NOMULTIDEFS) {
7971 outs() << " NOMULTIDEFS";
7972 f &= ~MachO::MH_NOMULTIDEFS;
7973 }
7974 if (f & MachO::MH_NOFIXPREBINDING) {
7975 outs() << " NOFIXPREBINDING";
7976 f &= ~MachO::MH_NOFIXPREBINDING;
7977 }
7978 if (f & MachO::MH_PREBINDABLE) {
7979 outs() << " PREBINDABLE";
7980 f &= ~MachO::MH_PREBINDABLE;
7981 }
7982 if (f & MachO::MH_ALLMODSBOUND) {
7983 outs() << " ALLMODSBOUND";
7984 f &= ~MachO::MH_ALLMODSBOUND;
7985 }
7986 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7987 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7988 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7989 }
7990 if (f & MachO::MH_CANONICAL) {
7991 outs() << " CANONICAL";
7992 f &= ~MachO::MH_CANONICAL;
7993 }
7994 if (f & MachO::MH_WEAK_DEFINES) {
7995 outs() << " WEAK_DEFINES";
7996 f &= ~MachO::MH_WEAK_DEFINES;
7997 }
7998 if (f & MachO::MH_BINDS_TO_WEAK) {
7999 outs() << " BINDS_TO_WEAK";
8000 f &= ~MachO::MH_BINDS_TO_WEAK;
8001 }
8002 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8003 outs() << " ALLOW_STACK_EXECUTION";
8004 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8005 }
8006 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8007 outs() << " DEAD_STRIPPABLE_DYLIB";
8008 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8009 }
8010 if (f & MachO::MH_PIE) {
8011 outs() << " PIE";
8012 f &= ~MachO::MH_PIE;
8013 }
8014 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8015 outs() << " NO_REEXPORTED_DYLIBS";
8016 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8017 }
8018 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8019 outs() << " MH_HAS_TLV_DESCRIPTORS";
8020 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8021 }
8022 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8023 outs() << " MH_NO_HEAP_EXECUTION";
8024 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8025 }
8026 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8027 outs() << " APP_EXTENSION_SAFE";
8028 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8029 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008030 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8031 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8032 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8033 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008034 if (f != 0 || flags == 0)
8035 outs() << format(" 0x%08" PRIx32, f);
8036 } else {
8037 outs() << format(" 0x%08" PRIx32, magic);
8038 outs() << format(" %7d", cputype);
8039 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8040 outs() << format(" 0x%02" PRIx32,
8041 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8042 outs() << format(" %10u", filetype);
8043 outs() << format(" %5u", ncmds);
8044 outs() << format(" %10u", sizeofcmds);
8045 outs() << format(" 0x%08" PRIx32, flags);
8046 }
8047 outs() << "\n";
8048}
8049
Kevin Enderby956366c2014-08-29 22:30:52 +00008050static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8051 StringRef SegName, uint64_t vmaddr,
8052 uint64_t vmsize, uint64_t fileoff,
8053 uint64_t filesize, uint32_t maxprot,
8054 uint32_t initprot, uint32_t nsects,
8055 uint32_t flags, uint32_t object_size,
8056 bool verbose) {
8057 uint64_t expected_cmdsize;
8058 if (cmd == MachO::LC_SEGMENT) {
8059 outs() << " cmd LC_SEGMENT\n";
8060 expected_cmdsize = nsects;
8061 expected_cmdsize *= sizeof(struct MachO::section);
8062 expected_cmdsize += sizeof(struct MachO::segment_command);
8063 } else {
8064 outs() << " cmd LC_SEGMENT_64\n";
8065 expected_cmdsize = nsects;
8066 expected_cmdsize *= sizeof(struct MachO::section_64);
8067 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8068 }
8069 outs() << " cmdsize " << cmdsize;
8070 if (cmdsize != expected_cmdsize)
8071 outs() << " Inconsistent size\n";
8072 else
8073 outs() << "\n";
8074 outs() << " segname " << SegName << "\n";
8075 if (cmd == MachO::LC_SEGMENT_64) {
8076 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8077 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8078 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008079 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8080 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008081 }
8082 outs() << " fileoff " << fileoff;
8083 if (fileoff > object_size)
8084 outs() << " (past end of file)\n";
8085 else
8086 outs() << "\n";
8087 outs() << " filesize " << filesize;
8088 if (fileoff + filesize > object_size)
8089 outs() << " (past end of file)\n";
8090 else
8091 outs() << "\n";
8092 if (verbose) {
8093 if ((maxprot &
8094 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8095 MachO::VM_PROT_EXECUTE)) != 0)
8096 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8097 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008098 outs() << " maxprot ";
8099 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8100 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8101 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008102 }
8103 if ((initprot &
8104 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8105 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008106 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008107 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008108 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008109 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8110 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8111 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008112 }
8113 } else {
8114 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8115 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8116 }
8117 outs() << " nsects " << nsects << "\n";
8118 if (verbose) {
8119 outs() << " flags";
8120 if (flags == 0)
8121 outs() << " (none)\n";
8122 else {
8123 if (flags & MachO::SG_HIGHVM) {
8124 outs() << " HIGHVM";
8125 flags &= ~MachO::SG_HIGHVM;
8126 }
8127 if (flags & MachO::SG_FVMLIB) {
8128 outs() << " FVMLIB";
8129 flags &= ~MachO::SG_FVMLIB;
8130 }
8131 if (flags & MachO::SG_NORELOC) {
8132 outs() << " NORELOC";
8133 flags &= ~MachO::SG_NORELOC;
8134 }
8135 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8136 outs() << " PROTECTED_VERSION_1";
8137 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8138 }
8139 if (flags)
8140 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8141 else
8142 outs() << "\n";
8143 }
8144 } else {
8145 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8146 }
8147}
8148
8149static void PrintSection(const char *sectname, const char *segname,
8150 uint64_t addr, uint64_t size, uint32_t offset,
8151 uint32_t align, uint32_t reloff, uint32_t nreloc,
8152 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8153 uint32_t cmd, const char *sg_segname,
8154 uint32_t filetype, uint32_t object_size,
8155 bool verbose) {
8156 outs() << "Section\n";
8157 outs() << " sectname " << format("%.16s\n", sectname);
8158 outs() << " segname " << format("%.16s", segname);
8159 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8160 outs() << " (does not match segment)\n";
8161 else
8162 outs() << "\n";
8163 if (cmd == MachO::LC_SEGMENT_64) {
8164 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8165 outs() << " size " << format("0x%016" PRIx64, size);
8166 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008167 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8168 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008169 }
8170 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8171 outs() << " (past end of file)\n";
8172 else
8173 outs() << "\n";
8174 outs() << " offset " << offset;
8175 if (offset > object_size)
8176 outs() << " (past end of file)\n";
8177 else
8178 outs() << "\n";
8179 uint32_t align_shifted = 1 << align;
8180 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8181 outs() << " reloff " << reloff;
8182 if (reloff > object_size)
8183 outs() << " (past end of file)\n";
8184 else
8185 outs() << "\n";
8186 outs() << " nreloc " << nreloc;
8187 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8188 outs() << " (past end of file)\n";
8189 else
8190 outs() << "\n";
8191 uint32_t section_type = flags & MachO::SECTION_TYPE;
8192 if (verbose) {
8193 outs() << " type";
8194 if (section_type == MachO::S_REGULAR)
8195 outs() << " S_REGULAR\n";
8196 else if (section_type == MachO::S_ZEROFILL)
8197 outs() << " S_ZEROFILL\n";
8198 else if (section_type == MachO::S_CSTRING_LITERALS)
8199 outs() << " S_CSTRING_LITERALS\n";
8200 else if (section_type == MachO::S_4BYTE_LITERALS)
8201 outs() << " S_4BYTE_LITERALS\n";
8202 else if (section_type == MachO::S_8BYTE_LITERALS)
8203 outs() << " S_8BYTE_LITERALS\n";
8204 else if (section_type == MachO::S_16BYTE_LITERALS)
8205 outs() << " S_16BYTE_LITERALS\n";
8206 else if (section_type == MachO::S_LITERAL_POINTERS)
8207 outs() << " S_LITERAL_POINTERS\n";
8208 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8209 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8210 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8211 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8212 else if (section_type == MachO::S_SYMBOL_STUBS)
8213 outs() << " S_SYMBOL_STUBS\n";
8214 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8215 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8216 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8217 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8218 else if (section_type == MachO::S_COALESCED)
8219 outs() << " S_COALESCED\n";
8220 else if (section_type == MachO::S_INTERPOSING)
8221 outs() << " S_INTERPOSING\n";
8222 else if (section_type == MachO::S_DTRACE_DOF)
8223 outs() << " S_DTRACE_DOF\n";
8224 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8225 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8226 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8227 outs() << " S_THREAD_LOCAL_REGULAR\n";
8228 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8229 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8230 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8231 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8232 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8233 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8234 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8235 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8236 else
8237 outs() << format("0x%08" PRIx32, section_type) << "\n";
8238 outs() << "attributes";
8239 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8240 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8241 outs() << " PURE_INSTRUCTIONS";
8242 if (section_attributes & MachO::S_ATTR_NO_TOC)
8243 outs() << " NO_TOC";
8244 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8245 outs() << " STRIP_STATIC_SYMS";
8246 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8247 outs() << " NO_DEAD_STRIP";
8248 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8249 outs() << " LIVE_SUPPORT";
8250 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8251 outs() << " SELF_MODIFYING_CODE";
8252 if (section_attributes & MachO::S_ATTR_DEBUG)
8253 outs() << " DEBUG";
8254 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8255 outs() << " SOME_INSTRUCTIONS";
8256 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8257 outs() << " EXT_RELOC";
8258 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8259 outs() << " LOC_RELOC";
8260 if (section_attributes == 0)
8261 outs() << " (none)";
8262 outs() << "\n";
8263 } else
8264 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8265 outs() << " reserved1 " << reserved1;
8266 if (section_type == MachO::S_SYMBOL_STUBS ||
8267 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8268 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8269 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8270 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8271 outs() << " (index into indirect symbol table)\n";
8272 else
8273 outs() << "\n";
8274 outs() << " reserved2 " << reserved2;
8275 if (section_type == MachO::S_SYMBOL_STUBS)
8276 outs() << " (size of stubs)\n";
8277 else
8278 outs() << "\n";
8279}
8280
David Majnemer73cc6ff2014-11-13 19:48:56 +00008281static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008282 uint32_t object_size) {
8283 outs() << " cmd LC_SYMTAB\n";
8284 outs() << " cmdsize " << st.cmdsize;
8285 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8286 outs() << " Incorrect size\n";
8287 else
8288 outs() << "\n";
8289 outs() << " symoff " << st.symoff;
8290 if (st.symoff > object_size)
8291 outs() << " (past end of file)\n";
8292 else
8293 outs() << "\n";
8294 outs() << " nsyms " << st.nsyms;
8295 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008296 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008297 big_size = st.nsyms;
8298 big_size *= sizeof(struct MachO::nlist_64);
8299 big_size += st.symoff;
8300 if (big_size > object_size)
8301 outs() << " (past end of file)\n";
8302 else
8303 outs() << "\n";
8304 } else {
8305 big_size = st.nsyms;
8306 big_size *= sizeof(struct MachO::nlist);
8307 big_size += st.symoff;
8308 if (big_size > object_size)
8309 outs() << " (past end of file)\n";
8310 else
8311 outs() << "\n";
8312 }
8313 outs() << " stroff " << st.stroff;
8314 if (st.stroff > object_size)
8315 outs() << " (past end of file)\n";
8316 else
8317 outs() << "\n";
8318 outs() << " strsize " << st.strsize;
8319 big_size = st.stroff;
8320 big_size += st.strsize;
8321 if (big_size > object_size)
8322 outs() << " (past end of file)\n";
8323 else
8324 outs() << "\n";
8325}
8326
8327static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8328 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008329 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008330 outs() << " cmd LC_DYSYMTAB\n";
8331 outs() << " cmdsize " << dyst.cmdsize;
8332 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8333 outs() << " Incorrect size\n";
8334 else
8335 outs() << "\n";
8336 outs() << " ilocalsym " << dyst.ilocalsym;
8337 if (dyst.ilocalsym > nsyms)
8338 outs() << " (greater than the number of symbols)\n";
8339 else
8340 outs() << "\n";
8341 outs() << " nlocalsym " << dyst.nlocalsym;
8342 uint64_t big_size;
8343 big_size = dyst.ilocalsym;
8344 big_size += dyst.nlocalsym;
8345 if (big_size > nsyms)
8346 outs() << " (past the end of the symbol table)\n";
8347 else
8348 outs() << "\n";
8349 outs() << " iextdefsym " << dyst.iextdefsym;
8350 if (dyst.iextdefsym > nsyms)
8351 outs() << " (greater than the number of symbols)\n";
8352 else
8353 outs() << "\n";
8354 outs() << " nextdefsym " << dyst.nextdefsym;
8355 big_size = dyst.iextdefsym;
8356 big_size += dyst.nextdefsym;
8357 if (big_size > nsyms)
8358 outs() << " (past the end of the symbol table)\n";
8359 else
8360 outs() << "\n";
8361 outs() << " iundefsym " << dyst.iundefsym;
8362 if (dyst.iundefsym > nsyms)
8363 outs() << " (greater than the number of symbols)\n";
8364 else
8365 outs() << "\n";
8366 outs() << " nundefsym " << dyst.nundefsym;
8367 big_size = dyst.iundefsym;
8368 big_size += dyst.nundefsym;
8369 if (big_size > nsyms)
8370 outs() << " (past the end of the symbol table)\n";
8371 else
8372 outs() << "\n";
8373 outs() << " tocoff " << dyst.tocoff;
8374 if (dyst.tocoff > object_size)
8375 outs() << " (past end of file)\n";
8376 else
8377 outs() << "\n";
8378 outs() << " ntoc " << dyst.ntoc;
8379 big_size = dyst.ntoc;
8380 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8381 big_size += dyst.tocoff;
8382 if (big_size > object_size)
8383 outs() << " (past end of file)\n";
8384 else
8385 outs() << "\n";
8386 outs() << " modtaboff " << dyst.modtaboff;
8387 if (dyst.modtaboff > object_size)
8388 outs() << " (past end of file)\n";
8389 else
8390 outs() << "\n";
8391 outs() << " nmodtab " << dyst.nmodtab;
8392 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008393 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008394 modtabend = dyst.nmodtab;
8395 modtabend *= sizeof(struct MachO::dylib_module_64);
8396 modtabend += dyst.modtaboff;
8397 } else {
8398 modtabend = dyst.nmodtab;
8399 modtabend *= sizeof(struct MachO::dylib_module);
8400 modtabend += dyst.modtaboff;
8401 }
8402 if (modtabend > object_size)
8403 outs() << " (past end of file)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " extrefsymoff " << dyst.extrefsymoff;
8407 if (dyst.extrefsymoff > object_size)
8408 outs() << " (past end of file)\n";
8409 else
8410 outs() << "\n";
8411 outs() << " nextrefsyms " << dyst.nextrefsyms;
8412 big_size = dyst.nextrefsyms;
8413 big_size *= sizeof(struct MachO::dylib_reference);
8414 big_size += dyst.extrefsymoff;
8415 if (big_size > object_size)
8416 outs() << " (past end of file)\n";
8417 else
8418 outs() << "\n";
8419 outs() << " indirectsymoff " << dyst.indirectsymoff;
8420 if (dyst.indirectsymoff > object_size)
8421 outs() << " (past end of file)\n";
8422 else
8423 outs() << "\n";
8424 outs() << " nindirectsyms " << dyst.nindirectsyms;
8425 big_size = dyst.nindirectsyms;
8426 big_size *= sizeof(uint32_t);
8427 big_size += dyst.indirectsymoff;
8428 if (big_size > object_size)
8429 outs() << " (past end of file)\n";
8430 else
8431 outs() << "\n";
8432 outs() << " extreloff " << dyst.extreloff;
8433 if (dyst.extreloff > object_size)
8434 outs() << " (past end of file)\n";
8435 else
8436 outs() << "\n";
8437 outs() << " nextrel " << dyst.nextrel;
8438 big_size = dyst.nextrel;
8439 big_size *= sizeof(struct MachO::relocation_info);
8440 big_size += dyst.extreloff;
8441 if (big_size > object_size)
8442 outs() << " (past end of file)\n";
8443 else
8444 outs() << "\n";
8445 outs() << " locreloff " << dyst.locreloff;
8446 if (dyst.locreloff > object_size)
8447 outs() << " (past end of file)\n";
8448 else
8449 outs() << "\n";
8450 outs() << " nlocrel " << dyst.nlocrel;
8451 big_size = dyst.nlocrel;
8452 big_size *= sizeof(struct MachO::relocation_info);
8453 big_size += dyst.locreloff;
8454 if (big_size > object_size)
8455 outs() << " (past end of file)\n";
8456 else
8457 outs() << "\n";
8458}
8459
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008460static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8461 uint32_t object_size) {
8462 if (dc.cmd == MachO::LC_DYLD_INFO)
8463 outs() << " cmd LC_DYLD_INFO\n";
8464 else
8465 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8466 outs() << " cmdsize " << dc.cmdsize;
8467 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8468 outs() << " Incorrect size\n";
8469 else
8470 outs() << "\n";
8471 outs() << " rebase_off " << dc.rebase_off;
8472 if (dc.rebase_off > object_size)
8473 outs() << " (past end of file)\n";
8474 else
8475 outs() << "\n";
8476 outs() << " rebase_size " << dc.rebase_size;
8477 uint64_t big_size;
8478 big_size = dc.rebase_off;
8479 big_size += dc.rebase_size;
8480 if (big_size > object_size)
8481 outs() << " (past end of file)\n";
8482 else
8483 outs() << "\n";
8484 outs() << " bind_off " << dc.bind_off;
8485 if (dc.bind_off > object_size)
8486 outs() << " (past end of file)\n";
8487 else
8488 outs() << "\n";
8489 outs() << " bind_size " << dc.bind_size;
8490 big_size = dc.bind_off;
8491 big_size += dc.bind_size;
8492 if (big_size > object_size)
8493 outs() << " (past end of file)\n";
8494 else
8495 outs() << "\n";
8496 outs() << " weak_bind_off " << dc.weak_bind_off;
8497 if (dc.weak_bind_off > object_size)
8498 outs() << " (past end of file)\n";
8499 else
8500 outs() << "\n";
8501 outs() << " weak_bind_size " << dc.weak_bind_size;
8502 big_size = dc.weak_bind_off;
8503 big_size += dc.weak_bind_size;
8504 if (big_size > object_size)
8505 outs() << " (past end of file)\n";
8506 else
8507 outs() << "\n";
8508 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8509 if (dc.lazy_bind_off > object_size)
8510 outs() << " (past end of file)\n";
8511 else
8512 outs() << "\n";
8513 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8514 big_size = dc.lazy_bind_off;
8515 big_size += dc.lazy_bind_size;
8516 if (big_size > object_size)
8517 outs() << " (past end of file)\n";
8518 else
8519 outs() << "\n";
8520 outs() << " export_off " << dc.export_off;
8521 if (dc.export_off > object_size)
8522 outs() << " (past end of file)\n";
8523 else
8524 outs() << "\n";
8525 outs() << " export_size " << dc.export_size;
8526 big_size = dc.export_off;
8527 big_size += dc.export_size;
8528 if (big_size > object_size)
8529 outs() << " (past end of file)\n";
8530 else
8531 outs() << "\n";
8532}
8533
8534static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8535 const char *Ptr) {
8536 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8537 outs() << " cmd LC_ID_DYLINKER\n";
8538 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8539 outs() << " cmd LC_LOAD_DYLINKER\n";
8540 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8541 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8542 else
8543 outs() << " cmd ?(" << dyld.cmd << ")\n";
8544 outs() << " cmdsize " << dyld.cmdsize;
8545 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8546 outs() << " Incorrect size\n";
8547 else
8548 outs() << "\n";
8549 if (dyld.name >= dyld.cmdsize)
8550 outs() << " name ?(bad offset " << dyld.name << ")\n";
8551 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008552 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008553 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8554 }
8555}
8556
8557static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8558 outs() << " cmd LC_UUID\n";
8559 outs() << " cmdsize " << uuid.cmdsize;
8560 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8561 outs() << " Incorrect size\n";
8562 else
8563 outs() << "\n";
8564 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008565 for (int i = 0; i < 16; ++i) {
8566 outs() << format("%02" PRIX32, uuid.uuid[i]);
8567 if (i == 3 || i == 5 || i == 7 || i == 9)
8568 outs() << "-";
8569 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008570 outs() << "\n";
8571}
8572
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008573static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008574 outs() << " cmd LC_RPATH\n";
8575 outs() << " cmdsize " << rpath.cmdsize;
8576 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8577 outs() << " Incorrect size\n";
8578 else
8579 outs() << "\n";
8580 if (rpath.path >= rpath.cmdsize)
8581 outs() << " path ?(bad offset " << rpath.path << ")\n";
8582 else {
8583 const char *P = (const char *)(Ptr) + rpath.path;
8584 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8585 }
8586}
8587
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008588static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008589 StringRef LoadCmdName;
8590 switch (vd.cmd) {
8591 case MachO::LC_VERSION_MIN_MACOSX:
8592 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8593 break;
8594 case MachO::LC_VERSION_MIN_IPHONEOS:
8595 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8596 break;
8597 case MachO::LC_VERSION_MIN_TVOS:
8598 LoadCmdName = "LC_VERSION_MIN_TVOS";
8599 break;
8600 case MachO::LC_VERSION_MIN_WATCHOS:
8601 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8602 break;
8603 default:
8604 llvm_unreachable("Unknown version min load command");
8605 }
8606
8607 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008608 outs() << " cmdsize " << vd.cmdsize;
8609 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8610 outs() << " Incorrect size\n";
8611 else
8612 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008613 outs() << " version "
8614 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8615 << MachOObjectFile::getVersionMinMinor(vd, false);
8616 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8617 if (Update != 0)
8618 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008619 outs() << "\n";
8620 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008621 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008622 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008623 outs() << " sdk "
8624 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8625 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008626 }
Davide Italiano56baef32015-08-26 12:26:11 +00008627 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8628 if (Update != 0)
8629 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008630 outs() << "\n";
8631}
8632
Kevin Enderbya4579c42017-01-19 17:36:31 +00008633static void PrintNoteLoadCommand(MachO::note_command Nt) {
8634 outs() << " cmd LC_NOTE\n";
8635 outs() << " cmdsize " << Nt.cmdsize;
8636 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8637 outs() << " Incorrect size\n";
8638 else
8639 outs() << "\n";
8640 const char *d = Nt.data_owner;
8641 outs() << "data_owner " << format("%.16s\n", d);
8642 outs() << " offset " << Nt.offset << "\n";
8643 outs() << " size " << Nt.size << "\n";
8644}
8645
Steven Wu5b54a422017-01-23 20:07:55 +00008646static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8647 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8648 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8649 << "\n";
8650}
8651
8652static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8653 MachO::build_version_command bd) {
8654 outs() << " cmd LC_BUILD_VERSION\n";
8655 outs() << " cmdsize " << bd.cmdsize;
8656 if (bd.cmdsize !=
8657 sizeof(struct MachO::build_version_command) +
8658 bd.ntools * sizeof(struct MachO::build_tool_version))
8659 outs() << " Incorrect size\n";
8660 else
8661 outs() << "\n";
8662 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8663 << "\n";
8664 if (bd.sdk)
8665 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8666 << "\n";
8667 else
8668 outs() << " sdk n/a\n";
8669 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8670 << "\n";
8671 outs() << " ntools " << bd.ntools << "\n";
8672 for (unsigned i = 0; i < bd.ntools; ++i) {
8673 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8674 PrintBuildToolVersion(bv);
8675 }
8676}
8677
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008678static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8679 outs() << " cmd LC_SOURCE_VERSION\n";
8680 outs() << " cmdsize " << sd.cmdsize;
8681 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8682 outs() << " Incorrect size\n";
8683 else
8684 outs() << "\n";
8685 uint64_t a = (sd.version >> 40) & 0xffffff;
8686 uint64_t b = (sd.version >> 30) & 0x3ff;
8687 uint64_t c = (sd.version >> 20) & 0x3ff;
8688 uint64_t d = (sd.version >> 10) & 0x3ff;
8689 uint64_t e = sd.version & 0x3ff;
8690 outs() << " version " << a << "." << b;
8691 if (e != 0)
8692 outs() << "." << c << "." << d << "." << e;
8693 else if (d != 0)
8694 outs() << "." << c << "." << d;
8695 else if (c != 0)
8696 outs() << "." << c;
8697 outs() << "\n";
8698}
8699
8700static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8701 outs() << " cmd LC_MAIN\n";
8702 outs() << " cmdsize " << ep.cmdsize;
8703 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8704 outs() << " Incorrect size\n";
8705 else
8706 outs() << "\n";
8707 outs() << " entryoff " << ep.entryoff << "\n";
8708 outs() << " stacksize " << ep.stacksize << "\n";
8709}
8710
Kevin Enderby0804f4672014-12-16 23:25:52 +00008711static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8712 uint32_t object_size) {
8713 outs() << " cmd LC_ENCRYPTION_INFO\n";
8714 outs() << " cmdsize " << ec.cmdsize;
8715 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8716 outs() << " Incorrect size\n";
8717 else
8718 outs() << "\n";
8719 outs() << " cryptoff " << ec.cryptoff;
8720 if (ec.cryptoff > object_size)
8721 outs() << " (past end of file)\n";
8722 else
8723 outs() << "\n";
8724 outs() << " cryptsize " << ec.cryptsize;
8725 if (ec.cryptsize > object_size)
8726 outs() << " (past end of file)\n";
8727 else
8728 outs() << "\n";
8729 outs() << " cryptid " << ec.cryptid << "\n";
8730}
8731
Kevin Enderby57538292014-12-17 01:01:30 +00008732static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008733 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008734 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8735 outs() << " cmdsize " << ec.cmdsize;
8736 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8737 outs() << " Incorrect size\n";
8738 else
8739 outs() << "\n";
8740 outs() << " cryptoff " << ec.cryptoff;
8741 if (ec.cryptoff > object_size)
8742 outs() << " (past end of file)\n";
8743 else
8744 outs() << "\n";
8745 outs() << " cryptsize " << ec.cryptsize;
8746 if (ec.cryptsize > object_size)
8747 outs() << " (past end of file)\n";
8748 else
8749 outs() << "\n";
8750 outs() << " cryptid " << ec.cryptid << "\n";
8751 outs() << " pad " << ec.pad << "\n";
8752}
8753
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008754static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8755 const char *Ptr) {
8756 outs() << " cmd LC_LINKER_OPTION\n";
8757 outs() << " cmdsize " << lo.cmdsize;
8758 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8759 outs() << " Incorrect size\n";
8760 else
8761 outs() << "\n";
8762 outs() << " count " << lo.count << "\n";
8763 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8764 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8765 uint32_t i = 0;
8766 while (left > 0) {
8767 while (*string == '\0' && left > 0) {
8768 string++;
8769 left--;
8770 }
8771 if (left > 0) {
8772 i++;
8773 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008774 uint32_t NullPos = StringRef(string, left).find('\0');
8775 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008776 string += len;
8777 left -= len;
8778 }
8779 }
8780 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008781 outs() << " count " << lo.count << " does not match number of strings "
8782 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008783}
8784
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008785static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8786 const char *Ptr) {
8787 outs() << " cmd LC_SUB_FRAMEWORK\n";
8788 outs() << " cmdsize " << sub.cmdsize;
8789 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8790 outs() << " Incorrect size\n";
8791 else
8792 outs() << "\n";
8793 if (sub.umbrella < sub.cmdsize) {
8794 const char *P = Ptr + sub.umbrella;
8795 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8796 } else {
8797 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8798 }
8799}
8800
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008801static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8802 const char *Ptr) {
8803 outs() << " cmd LC_SUB_UMBRELLA\n";
8804 outs() << " cmdsize " << sub.cmdsize;
8805 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8806 outs() << " Incorrect size\n";
8807 else
8808 outs() << "\n";
8809 if (sub.sub_umbrella < sub.cmdsize) {
8810 const char *P = Ptr + sub.sub_umbrella;
8811 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8812 } else {
8813 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8814 }
8815}
8816
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008817static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008818 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008819 outs() << " cmd LC_SUB_LIBRARY\n";
8820 outs() << " cmdsize " << sub.cmdsize;
8821 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8822 outs() << " Incorrect size\n";
8823 else
8824 outs() << "\n";
8825 if (sub.sub_library < sub.cmdsize) {
8826 const char *P = Ptr + sub.sub_library;
8827 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8828 } else {
8829 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8830 }
8831}
8832
Kevin Enderby186eac32014-12-19 21:06:24 +00008833static void PrintSubClientCommand(MachO::sub_client_command sub,
8834 const char *Ptr) {
8835 outs() << " cmd LC_SUB_CLIENT\n";
8836 outs() << " cmdsize " << sub.cmdsize;
8837 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8838 outs() << " Incorrect size\n";
8839 else
8840 outs() << "\n";
8841 if (sub.client < sub.cmdsize) {
8842 const char *P = Ptr + sub.client;
8843 outs() << " client " << P << " (offset " << sub.client << ")\n";
8844 } else {
8845 outs() << " client ?(bad offset " << sub.client << ")\n";
8846 }
8847}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008848
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008849static void PrintRoutinesCommand(MachO::routines_command r) {
8850 outs() << " cmd LC_ROUTINES\n";
8851 outs() << " cmdsize " << r.cmdsize;
8852 if (r.cmdsize != sizeof(struct MachO::routines_command))
8853 outs() << " Incorrect size\n";
8854 else
8855 outs() << "\n";
8856 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8857 outs() << " init_module " << r.init_module << "\n";
8858 outs() << " reserved1 " << r.reserved1 << "\n";
8859 outs() << " reserved2 " << r.reserved2 << "\n";
8860 outs() << " reserved3 " << r.reserved3 << "\n";
8861 outs() << " reserved4 " << r.reserved4 << "\n";
8862 outs() << " reserved5 " << r.reserved5 << "\n";
8863 outs() << " reserved6 " << r.reserved6 << "\n";
8864}
8865
8866static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8867 outs() << " cmd LC_ROUTINES_64\n";
8868 outs() << " cmdsize " << r.cmdsize;
8869 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8870 outs() << " Incorrect size\n";
8871 else
8872 outs() << "\n";
8873 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8874 outs() << " init_module " << r.init_module << "\n";
8875 outs() << " reserved1 " << r.reserved1 << "\n";
8876 outs() << " reserved2 " << r.reserved2 << "\n";
8877 outs() << " reserved3 " << r.reserved3 << "\n";
8878 outs() << " reserved4 " << r.reserved4 << "\n";
8879 outs() << " reserved5 " << r.reserved5 << "\n";
8880 outs() << " reserved6 " << r.reserved6 << "\n";
8881}
8882
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008883static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8884 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8885 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8886 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8887 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8888 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8889 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8890 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8891 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8892 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8893 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8894 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8895 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8896 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8897 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8898 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8899 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8900}
8901
Kevin Enderby48ef5342014-12-23 22:56:39 +00008902static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8903 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8904 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8905 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8906 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8907 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8908 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8909 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8910 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8911 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8912 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8913 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8914 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8915 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8916 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8917 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8918 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8919 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8920 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8921 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8922 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8923 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8924}
8925
Kevin Enderby227df342014-12-23 23:43:59 +00008926static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008927 uint32_t f;
8928 outs() << "\t mmst_reg ";
8929 for (f = 0; f < 10; f++)
8930 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8931 outs() << "\n";
8932 outs() << "\t mmst_rsrv ";
8933 for (f = 0; f < 6; f++)
8934 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8935 outs() << "\n";
8936}
8937
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008938static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008939 uint32_t f;
8940 outs() << "\t xmm_reg ";
8941 for (f = 0; f < 16; f++)
8942 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8943 outs() << "\n";
8944}
8945
8946static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8947 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8948 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8949 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8950 outs() << " denorm " << fpu.fpu_fcw.denorm;
8951 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8952 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8953 outs() << " undfl " << fpu.fpu_fcw.undfl;
8954 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8955 outs() << "\t\t pc ";
8956 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8957 outs() << "FP_PREC_24B ";
8958 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8959 outs() << "FP_PREC_53B ";
8960 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8961 outs() << "FP_PREC_64B ";
8962 else
8963 outs() << fpu.fpu_fcw.pc << " ";
8964 outs() << "rc ";
8965 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8966 outs() << "FP_RND_NEAR ";
8967 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8968 outs() << "FP_RND_DOWN ";
8969 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8970 outs() << "FP_RND_UP ";
8971 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008972 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008973 outs() << "\n";
8974 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8975 outs() << " denorm " << fpu.fpu_fsw.denorm;
8976 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8977 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8978 outs() << " undfl " << fpu.fpu_fsw.undfl;
8979 outs() << " precis " << fpu.fpu_fsw.precis;
8980 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8981 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8982 outs() << " c0 " << fpu.fpu_fsw.c0;
8983 outs() << " c1 " << fpu.fpu_fsw.c1;
8984 outs() << " c2 " << fpu.fpu_fsw.c2;
8985 outs() << " tos " << fpu.fpu_fsw.tos;
8986 outs() << " c3 " << fpu.fpu_fsw.c3;
8987 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8988 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8989 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8990 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8991 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8992 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8993 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8994 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8995 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8996 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8997 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8998 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8999 outs() << "\n";
9000 outs() << "\t fpu_stmm0:\n";
9001 Print_mmst_reg(fpu.fpu_stmm0);
9002 outs() << "\t fpu_stmm1:\n";
9003 Print_mmst_reg(fpu.fpu_stmm1);
9004 outs() << "\t fpu_stmm2:\n";
9005 Print_mmst_reg(fpu.fpu_stmm2);
9006 outs() << "\t fpu_stmm3:\n";
9007 Print_mmst_reg(fpu.fpu_stmm3);
9008 outs() << "\t fpu_stmm4:\n";
9009 Print_mmst_reg(fpu.fpu_stmm4);
9010 outs() << "\t fpu_stmm5:\n";
9011 Print_mmst_reg(fpu.fpu_stmm5);
9012 outs() << "\t fpu_stmm6:\n";
9013 Print_mmst_reg(fpu.fpu_stmm6);
9014 outs() << "\t fpu_stmm7:\n";
9015 Print_mmst_reg(fpu.fpu_stmm7);
9016 outs() << "\t fpu_xmm0:\n";
9017 Print_xmm_reg(fpu.fpu_xmm0);
9018 outs() << "\t fpu_xmm1:\n";
9019 Print_xmm_reg(fpu.fpu_xmm1);
9020 outs() << "\t fpu_xmm2:\n";
9021 Print_xmm_reg(fpu.fpu_xmm2);
9022 outs() << "\t fpu_xmm3:\n";
9023 Print_xmm_reg(fpu.fpu_xmm3);
9024 outs() << "\t fpu_xmm4:\n";
9025 Print_xmm_reg(fpu.fpu_xmm4);
9026 outs() << "\t fpu_xmm5:\n";
9027 Print_xmm_reg(fpu.fpu_xmm5);
9028 outs() << "\t fpu_xmm6:\n";
9029 Print_xmm_reg(fpu.fpu_xmm6);
9030 outs() << "\t fpu_xmm7:\n";
9031 Print_xmm_reg(fpu.fpu_xmm7);
9032 outs() << "\t fpu_xmm8:\n";
9033 Print_xmm_reg(fpu.fpu_xmm8);
9034 outs() << "\t fpu_xmm9:\n";
9035 Print_xmm_reg(fpu.fpu_xmm9);
9036 outs() << "\t fpu_xmm10:\n";
9037 Print_xmm_reg(fpu.fpu_xmm10);
9038 outs() << "\t fpu_xmm11:\n";
9039 Print_xmm_reg(fpu.fpu_xmm11);
9040 outs() << "\t fpu_xmm12:\n";
9041 Print_xmm_reg(fpu.fpu_xmm12);
9042 outs() << "\t fpu_xmm13:\n";
9043 Print_xmm_reg(fpu.fpu_xmm13);
9044 outs() << "\t fpu_xmm14:\n";
9045 Print_xmm_reg(fpu.fpu_xmm14);
9046 outs() << "\t fpu_xmm15:\n";
9047 Print_xmm_reg(fpu.fpu_xmm15);
9048 outs() << "\t fpu_rsrv4:\n";
9049 for (uint32_t f = 0; f < 6; f++) {
9050 outs() << "\t ";
9051 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009052 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009053 outs() << "\n";
9054 }
9055 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9056 outs() << "\n";
9057}
9058
9059static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9060 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9061 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9062 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9063}
9064
Kevin Enderby41c9c002016-10-21 18:22:35 +00009065static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9066 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9067 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9068 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9069 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9070 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9071 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9072 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9073 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9074 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9075 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9076 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9077 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9078 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9079 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9080 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9081 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9082 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9083}
9084
Kevin Enderby7747cb52016-11-03 20:51:28 +00009085static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9086 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9087 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9088 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9089 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9090 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9091 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9092 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9093 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9094 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9095 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9096 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9097 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9098 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9099 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9100 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9101 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9102 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9103 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9104 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9105 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9106 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9107 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9108 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9109 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9110 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9111 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9112 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9113 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9114 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9115 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9116 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9117 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9118 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9119 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9120}
9121
Kevin Enderby48ef5342014-12-23 22:56:39 +00009122static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9123 bool isLittleEndian, uint32_t cputype) {
9124 if (t.cmd == MachO::LC_THREAD)
9125 outs() << " cmd LC_THREAD\n";
9126 else if (t.cmd == MachO::LC_UNIXTHREAD)
9127 outs() << " cmd LC_UNIXTHREAD\n";
9128 else
9129 outs() << " cmd " << t.cmd << " (unknown)\n";
9130 outs() << " cmdsize " << t.cmdsize;
9131 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9132 outs() << " Incorrect size\n";
9133 else
9134 outs() << "\n";
9135
9136 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9137 const char *end = Ptr + t.cmdsize;
9138 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009139 if (cputype == MachO::CPU_TYPE_I386) {
9140 while (begin < end) {
9141 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9142 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9143 begin += sizeof(uint32_t);
9144 } else {
9145 flavor = 0;
9146 begin = end;
9147 }
9148 if (isLittleEndian != sys::IsLittleEndianHost)
9149 sys::swapByteOrder(flavor);
9150 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9151 memcpy((char *)&count, begin, sizeof(uint32_t));
9152 begin += sizeof(uint32_t);
9153 } else {
9154 count = 0;
9155 begin = end;
9156 }
9157 if (isLittleEndian != sys::IsLittleEndianHost)
9158 sys::swapByteOrder(count);
9159 if (flavor == MachO::x86_THREAD_STATE32) {
9160 outs() << " flavor i386_THREAD_STATE\n";
9161 if (count == MachO::x86_THREAD_STATE32_COUNT)
9162 outs() << " count i386_THREAD_STATE_COUNT\n";
9163 else
9164 outs() << " count " << count
9165 << " (not x86_THREAD_STATE32_COUNT)\n";
9166 MachO::x86_thread_state32_t cpu32;
9167 left = end - begin;
9168 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9169 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9170 begin += sizeof(MachO::x86_thread_state32_t);
9171 } else {
9172 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9173 memcpy(&cpu32, begin, left);
9174 begin += left;
9175 }
9176 if (isLittleEndian != sys::IsLittleEndianHost)
9177 swapStruct(cpu32);
9178 Print_x86_thread_state32_t(cpu32);
9179 } else if (flavor == MachO::x86_THREAD_STATE) {
9180 outs() << " flavor x86_THREAD_STATE\n";
9181 if (count == MachO::x86_THREAD_STATE_COUNT)
9182 outs() << " count x86_THREAD_STATE_COUNT\n";
9183 else
9184 outs() << " count " << count
9185 << " (not x86_THREAD_STATE_COUNT)\n";
9186 struct MachO::x86_thread_state_t ts;
9187 left = end - begin;
9188 if (left >= sizeof(MachO::x86_thread_state_t)) {
9189 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9190 begin += sizeof(MachO::x86_thread_state_t);
9191 } else {
9192 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9193 memcpy(&ts, begin, left);
9194 begin += left;
9195 }
9196 if (isLittleEndian != sys::IsLittleEndianHost)
9197 swapStruct(ts);
9198 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9199 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9200 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9201 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9202 else
9203 outs() << "tsh.count " << ts.tsh.count
9204 << " (not x86_THREAD_STATE32_COUNT\n";
9205 Print_x86_thread_state32_t(ts.uts.ts32);
9206 } else {
9207 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9208 << ts.tsh.count << "\n";
9209 }
9210 } else {
9211 outs() << " flavor " << flavor << " (unknown)\n";
9212 outs() << " count " << count << "\n";
9213 outs() << " state (unknown)\n";
9214 begin += count * sizeof(uint32_t);
9215 }
9216 }
9217 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009218 while (begin < end) {
9219 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9220 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9221 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009222 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009223 flavor = 0;
9224 begin = end;
9225 }
9226 if (isLittleEndian != sys::IsLittleEndianHost)
9227 sys::swapByteOrder(flavor);
9228 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9229 memcpy((char *)&count, begin, sizeof(uint32_t));
9230 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009231 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009232 count = 0;
9233 begin = end;
9234 }
9235 if (isLittleEndian != sys::IsLittleEndianHost)
9236 sys::swapByteOrder(count);
9237 if (flavor == MachO::x86_THREAD_STATE64) {
9238 outs() << " flavor x86_THREAD_STATE64\n";
9239 if (count == MachO::x86_THREAD_STATE64_COUNT)
9240 outs() << " count x86_THREAD_STATE64_COUNT\n";
9241 else
9242 outs() << " count " << count
9243 << " (not x86_THREAD_STATE64_COUNT)\n";
9244 MachO::x86_thread_state64_t cpu64;
9245 left = end - begin;
9246 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9247 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9248 begin += sizeof(MachO::x86_thread_state64_t);
9249 } else {
9250 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9251 memcpy(&cpu64, begin, left);
9252 begin += left;
9253 }
9254 if (isLittleEndian != sys::IsLittleEndianHost)
9255 swapStruct(cpu64);
9256 Print_x86_thread_state64_t(cpu64);
9257 } else if (flavor == MachO::x86_THREAD_STATE) {
9258 outs() << " flavor x86_THREAD_STATE\n";
9259 if (count == MachO::x86_THREAD_STATE_COUNT)
9260 outs() << " count x86_THREAD_STATE_COUNT\n";
9261 else
9262 outs() << " count " << count
9263 << " (not x86_THREAD_STATE_COUNT)\n";
9264 struct MachO::x86_thread_state_t ts;
9265 left = end - begin;
9266 if (left >= sizeof(MachO::x86_thread_state_t)) {
9267 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9268 begin += sizeof(MachO::x86_thread_state_t);
9269 } else {
9270 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9271 memcpy(&ts, begin, left);
9272 begin += left;
9273 }
9274 if (isLittleEndian != sys::IsLittleEndianHost)
9275 swapStruct(ts);
9276 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9277 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9278 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9279 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9280 else
9281 outs() << "tsh.count " << ts.tsh.count
9282 << " (not x86_THREAD_STATE64_COUNT\n";
9283 Print_x86_thread_state64_t(ts.uts.ts64);
9284 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009285 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9286 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009287 }
9288 } else if (flavor == MachO::x86_FLOAT_STATE) {
9289 outs() << " flavor x86_FLOAT_STATE\n";
9290 if (count == MachO::x86_FLOAT_STATE_COUNT)
9291 outs() << " count x86_FLOAT_STATE_COUNT\n";
9292 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009293 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009294 struct MachO::x86_float_state_t fs;
9295 left = end - begin;
9296 if (left >= sizeof(MachO::x86_float_state_t)) {
9297 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9298 begin += sizeof(MachO::x86_float_state_t);
9299 } else {
9300 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9301 memcpy(&fs, begin, left);
9302 begin += left;
9303 }
9304 if (isLittleEndian != sys::IsLittleEndianHost)
9305 swapStruct(fs);
9306 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9307 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009308 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009309 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9310 else
9311 outs() << "fsh.count " << fs.fsh.count
9312 << " (not x86_FLOAT_STATE64_COUNT\n";
9313 Print_x86_float_state_t(fs.ufs.fs64);
9314 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009315 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9316 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009317 }
9318 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9319 outs() << " flavor x86_EXCEPTION_STATE\n";
9320 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9321 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9322 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009323 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009324 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9325 struct MachO::x86_exception_state_t es;
9326 left = end - begin;
9327 if (left >= sizeof(MachO::x86_exception_state_t)) {
9328 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9329 begin += sizeof(MachO::x86_exception_state_t);
9330 } else {
9331 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9332 memcpy(&es, begin, left);
9333 begin += left;
9334 }
9335 if (isLittleEndian != sys::IsLittleEndianHost)
9336 swapStruct(es);
9337 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9338 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009339 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009340 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9341 else
9342 outs() << "\t esh.count " << es.esh.count
9343 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9344 Print_x86_exception_state_t(es.ues.es64);
9345 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009346 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9347 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009348 }
9349 } else {
9350 outs() << " flavor " << flavor << " (unknown)\n";
9351 outs() << " count " << count << "\n";
9352 outs() << " state (unknown)\n";
9353 begin += count * sizeof(uint32_t);
9354 }
9355 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009356 } else if (cputype == MachO::CPU_TYPE_ARM) {
9357 while (begin < end) {
9358 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9359 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9360 begin += sizeof(uint32_t);
9361 } else {
9362 flavor = 0;
9363 begin = end;
9364 }
9365 if (isLittleEndian != sys::IsLittleEndianHost)
9366 sys::swapByteOrder(flavor);
9367 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9368 memcpy((char *)&count, begin, sizeof(uint32_t));
9369 begin += sizeof(uint32_t);
9370 } else {
9371 count = 0;
9372 begin = end;
9373 }
9374 if (isLittleEndian != sys::IsLittleEndianHost)
9375 sys::swapByteOrder(count);
9376 if (flavor == MachO::ARM_THREAD_STATE) {
9377 outs() << " flavor ARM_THREAD_STATE\n";
9378 if (count == MachO::ARM_THREAD_STATE_COUNT)
9379 outs() << " count ARM_THREAD_STATE_COUNT\n";
9380 else
9381 outs() << " count " << count
9382 << " (not ARM_THREAD_STATE_COUNT)\n";
9383 MachO::arm_thread_state32_t cpu32;
9384 left = end - begin;
9385 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9386 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9387 begin += sizeof(MachO::arm_thread_state32_t);
9388 } else {
9389 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9390 memcpy(&cpu32, begin, left);
9391 begin += left;
9392 }
9393 if (isLittleEndian != sys::IsLittleEndianHost)
9394 swapStruct(cpu32);
9395 Print_arm_thread_state32_t(cpu32);
9396 } else {
9397 outs() << " flavor " << flavor << " (unknown)\n";
9398 outs() << " count " << count << "\n";
9399 outs() << " state (unknown)\n";
9400 begin += count * sizeof(uint32_t);
9401 }
9402 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009403 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9404 while (begin < end) {
9405 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9406 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9407 begin += sizeof(uint32_t);
9408 } else {
9409 flavor = 0;
9410 begin = end;
9411 }
9412 if (isLittleEndian != sys::IsLittleEndianHost)
9413 sys::swapByteOrder(flavor);
9414 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9415 memcpy((char *)&count, begin, sizeof(uint32_t));
9416 begin += sizeof(uint32_t);
9417 } else {
9418 count = 0;
9419 begin = end;
9420 }
9421 if (isLittleEndian != sys::IsLittleEndianHost)
9422 sys::swapByteOrder(count);
9423 if (flavor == MachO::ARM_THREAD_STATE64) {
9424 outs() << " flavor ARM_THREAD_STATE64\n";
9425 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9426 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9427 else
9428 outs() << " count " << count
9429 << " (not ARM_THREAD_STATE64_COUNT)\n";
9430 MachO::arm_thread_state64_t cpu64;
9431 left = end - begin;
9432 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9433 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9434 begin += sizeof(MachO::arm_thread_state64_t);
9435 } else {
9436 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9437 memcpy(&cpu64, begin, left);
9438 begin += left;
9439 }
9440 if (isLittleEndian != sys::IsLittleEndianHost)
9441 swapStruct(cpu64);
9442 Print_arm_thread_state64_t(cpu64);
9443 } else {
9444 outs() << " flavor " << flavor << " (unknown)\n";
9445 outs() << " count " << count << "\n";
9446 outs() << " state (unknown)\n";
9447 begin += count * sizeof(uint32_t);
9448 }
9449 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009450 } else {
9451 while (begin < end) {
9452 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9453 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9454 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009455 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009456 flavor = 0;
9457 begin = end;
9458 }
9459 if (isLittleEndian != sys::IsLittleEndianHost)
9460 sys::swapByteOrder(flavor);
9461 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9462 memcpy((char *)&count, begin, sizeof(uint32_t));
9463 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009464 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009465 count = 0;
9466 begin = end;
9467 }
9468 if (isLittleEndian != sys::IsLittleEndianHost)
9469 sys::swapByteOrder(count);
9470 outs() << " flavor " << flavor << "\n";
9471 outs() << " count " << count << "\n";
9472 outs() << " state (Unknown cputype/cpusubtype)\n";
9473 begin += count * sizeof(uint32_t);
9474 }
9475 }
9476}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009477
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009478static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9479 if (dl.cmd == MachO::LC_ID_DYLIB)
9480 outs() << " cmd LC_ID_DYLIB\n";
9481 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9482 outs() << " cmd LC_LOAD_DYLIB\n";
9483 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9484 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9485 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9486 outs() << " cmd LC_REEXPORT_DYLIB\n";
9487 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9488 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9489 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9490 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9491 else
9492 outs() << " cmd " << dl.cmd << " (unknown)\n";
9493 outs() << " cmdsize " << dl.cmdsize;
9494 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9495 outs() << " Incorrect size\n";
9496 else
9497 outs() << "\n";
9498 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009499 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009500 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9501 } else {
9502 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9503 }
9504 outs() << " time stamp " << dl.dylib.timestamp << " ";
9505 time_t t = dl.dylib.timestamp;
9506 outs() << ctime(&t);
9507 outs() << " current version ";
9508 if (dl.dylib.current_version == 0xffffffff)
9509 outs() << "n/a\n";
9510 else
9511 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9512 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9513 << (dl.dylib.current_version & 0xff) << "\n";
9514 outs() << "compatibility version ";
9515 if (dl.dylib.compatibility_version == 0xffffffff)
9516 outs() << "n/a\n";
9517 else
9518 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9519 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9520 << (dl.dylib.compatibility_version & 0xff) << "\n";
9521}
9522
9523static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9524 uint32_t object_size) {
9525 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009526 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009527 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9528 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9529 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9530 outs() << " cmd LC_FUNCTION_STARTS\n";
9531 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9532 outs() << " cmd LC_DATA_IN_CODE\n";
9533 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9534 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9535 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9536 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9537 else
9538 outs() << " cmd " << ld.cmd << " (?)\n";
9539 outs() << " cmdsize " << ld.cmdsize;
9540 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9541 outs() << " Incorrect size\n";
9542 else
9543 outs() << "\n";
9544 outs() << " dataoff " << ld.dataoff;
9545 if (ld.dataoff > object_size)
9546 outs() << " (past end of file)\n";
9547 else
9548 outs() << "\n";
9549 outs() << " datasize " << ld.datasize;
9550 uint64_t big_size = ld.dataoff;
9551 big_size += ld.datasize;
9552 if (big_size > object_size)
9553 outs() << " (past end of file)\n";
9554 else
9555 outs() << "\n";
9556}
9557
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009558static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9559 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009560 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009561 unsigned Index = 0;
9562 for (const auto &Command : Obj->load_commands()) {
9563 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009564 if (Command.C.cmd == MachO::LC_SEGMENT) {
9565 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9566 const char *sg_segname = SLC.segname;
9567 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9568 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9569 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9570 verbose);
9571 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009572 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009573 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9574 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9575 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9576 }
9577 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9578 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9579 const char *sg_segname = SLC_64.segname;
9580 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9581 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9582 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9583 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9584 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9585 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9586 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9587 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9588 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9589 sg_segname, filetype, Buf.size(), verbose);
9590 }
9591 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9592 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009593 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009594 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9595 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9596 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009597 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9598 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009599 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9600 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9601 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9602 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9603 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9604 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9605 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9606 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9607 PrintDyldLoadCommand(Dyld, Command.Ptr);
9608 } else if (Command.C.cmd == MachO::LC_UUID) {
9609 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9610 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009611 } else if (Command.C.cmd == MachO::LC_RPATH) {
9612 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9613 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009614 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009615 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9616 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9617 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009618 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9619 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009620 } else if (Command.C.cmd == MachO::LC_NOTE) {
9621 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9622 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009623 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9624 MachO::build_version_command Bv =
9625 Obj->getBuildVersionLoadCommand(Command);
9626 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009627 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9628 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9629 PrintSourceVersionCommand(Sd);
9630 } else if (Command.C.cmd == MachO::LC_MAIN) {
9631 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9632 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009633 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009634 MachO::encryption_info_command Ei =
9635 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009636 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009637 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009638 MachO::encryption_info_command_64 Ei =
9639 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009640 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009641 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009642 MachO::linker_option_command Lo =
9643 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009644 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009645 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9646 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9647 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009648 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9649 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9650 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009651 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9652 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9653 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009654 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9655 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9656 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009657 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9658 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9659 PrintRoutinesCommand(Rc);
9660 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9661 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9662 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009663 } else if (Command.C.cmd == MachO::LC_THREAD ||
9664 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9665 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9666 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009667 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9668 Command.C.cmd == MachO::LC_ID_DYLIB ||
9669 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9670 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9671 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9672 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009673 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9674 PrintDylibCommand(Dl, Command.Ptr);
9675 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9676 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9677 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9678 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9679 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9680 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9681 MachO::linkedit_data_command Ld =
9682 Obj->getLinkeditDataLoadCommand(Command);
9683 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009684 } else {
9685 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9686 << ")\n";
9687 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9688 // TODO: get and print the raw bytes of the load command.
9689 }
9690 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009691 }
9692}
9693
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009694static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009695 if (Obj->is64Bit()) {
9696 MachO::mach_header_64 H_64;
9697 H_64 = Obj->getHeader64();
9698 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9699 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9700 } else {
9701 MachO::mach_header H;
9702 H = Obj->getHeader();
9703 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9704 H.sizeofcmds, H.flags, verbose);
9705 }
9706}
9707
9708void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9709 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009710 PrintMachHeader(file, !NonVerbose);
9711}
9712
9713void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9714 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009715 uint32_t filetype = 0;
9716 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009717 if (file->is64Bit()) {
9718 MachO::mach_header_64 H_64;
9719 H_64 = file->getHeader64();
9720 filetype = H_64.filetype;
9721 cputype = H_64.cputype;
9722 } else {
9723 MachO::mach_header H;
9724 H = file->getHeader();
9725 filetype = H.filetype;
9726 cputype = H.cputype;
9727 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009728 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009729}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009730
9731//===----------------------------------------------------------------------===//
9732// export trie dumping
9733//===----------------------------------------------------------------------===//
9734
9735void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009736 uint64_t BaseSegmentAddress = 0;
9737 for (const auto &Command : Obj->load_commands()) {
9738 if (Command.C.cmd == MachO::LC_SEGMENT) {
9739 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9740 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9741 BaseSegmentAddress = Seg.vmaddr;
9742 break;
9743 }
9744 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9745 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9746 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9747 BaseSegmentAddress = Seg.vmaddr;
9748 break;
9749 }
9750 }
9751 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009752 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009753 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009754 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009755 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9756 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9757 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9758 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9759 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9760 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9761 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9762 if (ReExport)
9763 outs() << "[re-export] ";
9764 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009765 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009766 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009767 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009768 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009769 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009770 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009771 if (WeakDef) {
9772 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009773 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009774 }
9775 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009776 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009777 outs() << ", ";
9778 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009779 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009780 }
9781 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009782 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009783 outs() << ", ";
9784 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009785 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009786 }
9787 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009788 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009789 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009790 outs() << format("resolver=0x%08llX", Entry.other());
9791 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009792 }
9793 outs() << "]";
9794 }
9795 if (ReExport) {
9796 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009797 int Ordinal = Entry.other() - 1;
9798 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9799 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009800 outs() << " (from " << DylibName << ")";
9801 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009802 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009803 }
9804 outs() << "\n";
9805 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009806 if (Err)
9807 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009808}
Nick Kledzikac431442014-09-12 21:34:15 +00009809
Nick Kledzikac431442014-09-12 21:34:15 +00009810//===----------------------------------------------------------------------===//
9811// rebase table dumping
9812//===----------------------------------------------------------------------===//
9813
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009814void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009815 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009816 Error Err = Error::success();
9817 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9818 StringRef SegmentName = Entry.segmentName();
9819 StringRef SectionName = Entry.sectionName();
9820 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009821
9822 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009823 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9824 SegmentName.str().c_str(), SectionName.str().c_str(),
9825 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009826 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009827 if (Err)
9828 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009829}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009830
9831static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9832 StringRef DylibName;
9833 switch (Ordinal) {
9834 case MachO::BIND_SPECIAL_DYLIB_SELF:
9835 return "this-image";
9836 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9837 return "main-executable";
9838 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9839 return "flat-namespace";
9840 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009841 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009842 std::error_code EC =
9843 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009844 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009845 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009846 return DylibName;
9847 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009848 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009849 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009850}
9851
9852//===----------------------------------------------------------------------===//
9853// bind table dumping
9854//===----------------------------------------------------------------------===//
9855
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009856void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009857 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009858 outs() << "segment section address type "
9859 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009860 Error Err = Error::success();
9861 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009862 StringRef SegmentName = Entry.segmentName();
9863 StringRef SectionName = Entry.sectionName();
9864 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009865
9866 // Table lines look like:
9867 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009868 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009869 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009870 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009871 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009872 << left_justify(SectionName, 18) << " "
9873 << format_hex(Address, 10, true) << " "
9874 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009875 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009876 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009877 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009878 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009879 if (Err)
9880 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009881}
9882
9883//===----------------------------------------------------------------------===//
9884// lazy bind table dumping
9885//===----------------------------------------------------------------------===//
9886
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009887void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009888 outs() << "segment section address "
9889 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009890 Error Err = Error::success();
9891 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009892 StringRef SegmentName = Entry.segmentName();
9893 StringRef SectionName = Entry.sectionName();
9894 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009895
9896 // Table lines look like:
9897 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009898 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009899 << left_justify(SectionName, 18) << " "
9900 << format_hex(Address, 10, true) << " "
9901 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009902 << Entry.symbolName() << "\n";
9903 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009904 if (Err)
9905 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009906}
9907
Nick Kledzik56ebef42014-09-16 01:41:51 +00009908//===----------------------------------------------------------------------===//
9909// weak bind table dumping
9910//===----------------------------------------------------------------------===//
9911
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009912void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009913 outs() << "segment section address "
9914 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009915 Error Err = Error::success();
9916 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009917 // Strong symbols don't have a location to update.
9918 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009919 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009920 << Entry.symbolName() << "\n";
9921 continue;
9922 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009923 StringRef SegmentName = Entry.segmentName();
9924 StringRef SectionName = Entry.sectionName();
9925 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009926
9927 // Table lines look like:
9928 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009929 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009930 << left_justify(SectionName, 18) << " "
9931 << format_hex(Address, 10, true) << " "
9932 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009933 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9934 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009935 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009936 if (Err)
9937 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009938}
9939
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009940// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9941// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9942// information for that address. If the address is found its binding symbol
9943// name is returned. If not nullptr is returned.
9944static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9945 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009946 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009947 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009948 Error Err = Error::success();
9949 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009950 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009951 StringRef name = Entry.symbolName();
9952 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009953 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009954 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009955 if (Err)
9956 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009957 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009958 auto name = info->bindtable->lookup(ReferenceValue);
9959 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009960}
Michael Trent1854ecc2017-12-05 07:50:00 +00009961