blob: ffa0ff050680339e90e224cb45597af98844fb3f [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"
Pete Cooper23bfa7e2015-12-14 21:39:27 +000016#include "llvm/ADT/Optional.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/Triple.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"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000032#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MachO.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"
46#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include <algorithm>
48#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000049#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000050
51#if HAVE_CXXABI_H
52#include <cxxabi.h>
53#endif
54
Benjamin Kramer43a772e2011-09-19 17:56:04 +000055using namespace llvm;
56using namespace object;
57
58static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000059 UseDbg("g",
60 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000061
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062static cl::opt<std::string> DSYMFile("dsym",
63 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<bool> FullLeadingAddr("full-leading-addr",
66 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000067
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000068static cl::opt<bool> NoLeadingAddr("no-leading-addr",
69 cl::desc("Print no leading address"));
70
Kevin Enderby13023a12015-01-15 23:19:11 +000071cl::opt<bool> llvm::UniversalHeaders("universal-headers",
72 cl::desc("Print Mach-O universal headers "
73 "(requires -macho)"));
74
Kevin Enderby131d1772015-01-09 19:22:37 +000075cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000076 llvm::ArchiveHeaders("archive-headers",
77 cl::desc("Print archive headers for Mach-O archives "
78 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000079
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000080cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000081 ArchiveMemberOffsets("archive-member-offsets",
82 cl::desc("Print the offset to each archive member for "
83 "Mach-O archives (requires -macho and "
84 "-archive-headers)"));
85
86cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000087 llvm::IndirectSymbols("indirect-symbols",
88 cl::desc("Print indirect symbol table for Mach-O "
89 "objects (requires -macho)"));
90
Kevin Enderby69fe98d2015-01-23 18:52:17 +000091cl::opt<bool>
92 llvm::DataInCode("data-in-code",
93 cl::desc("Print the data in code table for Mach-O objects "
94 "(requires -macho)"));
95
Kevin Enderby9a509442015-01-27 21:28:24 +000096cl::opt<bool>
97 llvm::LinkOptHints("link-opt-hints",
98 cl::desc("Print the linker optimization hints for "
99 "Mach-O objects (requires -macho)"));
100
Kevin Enderbycd66be52015-03-11 22:06:32 +0000101cl::opt<bool>
102 llvm::InfoPlist("info-plist",
103 cl::desc("Print the info plist section as strings for "
104 "Mach-O objects (requires -macho)"));
105
Kevin Enderbyf0640752015-03-13 17:56:32 +0000106cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000107 llvm::DylibsUsed("dylibs-used",
108 cl::desc("Print the shared libraries used for linked "
109 "Mach-O files (requires -macho)"));
110
111cl::opt<bool>
112 llvm::DylibId("dylib-id",
113 cl::desc("Print the shared library's id for the dylib Mach-O "
114 "file (requires -macho)"));
115
116cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000117 llvm::NonVerbose("non-verbose",
118 cl::desc("Print the info for Mach-O objects in "
119 "non-verbose or numeric form (requires -macho)"));
120
Kevin Enderby0fc11822015-04-01 20:57:01 +0000121cl::opt<bool>
122 llvm::ObjcMetaData("objc-meta-data",
123 cl::desc("Print the Objective-C runtime meta data for "
124 "Mach-O files (requires -macho)"));
125
Kevin Enderby6a221752015-03-17 17:10:57 +0000126cl::opt<std::string> llvm::DisSymName(
127 "dis-symname",
128 cl::desc("disassemble just this symbol's instructions (requires -macho"));
129
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000130static cl::opt<bool> NoSymbolicOperands(
131 "no-symbolic-operands",
132 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
133
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000134static cl::list<std::string>
135 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
136 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000137
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000138bool ArchAll = false;
139
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000140static std::string ThumbTripleName;
141
142static const Target *GetTarget(const MachOObjectFile *MachOObj,
143 const char **McpuDefault,
144 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000145 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000146 if (TripleName.empty()) {
147 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000148 llvm::Triple ThumbTriple = Triple();
149 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000151 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000152 }
153
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000154 // Get the target specific parser.
155 std::string Error;
156 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000157 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 return TheTarget;
159
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000160 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
161 if (*ThumbTarget)
162 return TheTarget;
163
164 errs() << "llvm-objdump: error: unable to get target for '";
165 if (!TheTarget)
166 errs() << TripleName;
167 else
168 errs() << ThumbTripleName;
169 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000170 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171}
172
Owen Andersond9243c42011-10-17 21:37:35 +0000173struct SymbolSorter {
174 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000175 ErrorOr<SymbolRef::Type> ATypeOrErr = A.getType();
176 if (std::error_code EC = ATypeOrErr.getError())
177 report_fatal_error(EC.message());
178 SymbolRef::Type AType = *ATypeOrErr;
179 ErrorOr<SymbolRef::Type> BTypeOrErr = B.getType();
180 if (std::error_code EC = BTypeOrErr.getError())
181 report_fatal_error(EC.message());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000182 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000183 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
184 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000185 return AAddr < BAddr;
186 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000187};
188
Kevin Enderby273ae012013-06-06 17:20:50 +0000189// Types for the storted data in code table that is built before disassembly
190// and the predicate function to sort them.
191typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
192typedef std::vector<DiceTableEntry> DiceTable;
193typedef DiceTable::iterator dice_table_iterator;
194
Kevin Enderby930fdc72014-11-06 19:00:13 +0000195// This is used to search for a data in code table entry for the PC being
196// disassembled. The j parameter has the PC in j.first. A single data in code
197// table entry can cover many bytes for each of its Kind's. So if the offset,
198// aka the i.first value, of the data in code table entry plus its Length
199// covers the PC being searched for this will return true. If not it will
200// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000201static bool compareDiceTableEntries(const DiceTableEntry &i,
202 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000203 uint16_t Length;
204 i.second.getLength(Length);
205
206 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000207}
208
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000209static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000210 unsigned short Kind) {
211 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000212
213 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000214 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000215 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000216 if (Length >= 4) {
217 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000218 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000219 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000220 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000221 Size = 4;
222 } else if (Length >= 2) {
223 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000224 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000225 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000226 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000227 Size = 2;
228 } else {
229 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000230 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000231 Value = bytes[0];
232 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000234 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000235 if (Kind == MachO::DICE_KIND_DATA)
236 outs() << "\t@ KIND_DATA\n";
237 else
238 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000239 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000240 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000241 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000242 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000243 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
245 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000247 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000249 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000250 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 outs() << "\t.short " << format("%5u", Value & 0xffff)
252 << "\t@ KIND_JUMP_TABLE16\n";
253 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000255 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000256 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
257 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000258 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000259 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000260 outs() << "\t.long " << Value;
261 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
262 outs() << "\t@ KIND_JUMP_TABLE32\n";
263 else
264 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
265 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000266 break;
267 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000268 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000269}
270
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000271static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000272 std::vector<SectionRef> &Sections,
273 std::vector<SymbolRef> &Symbols,
274 SmallVectorImpl<uint64_t> &FoundFns,
275 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000276 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000277 ErrorOr<StringRef> SymName = Symbol.getName();
278 if (std::error_code EC = SymName.getError())
279 report_fatal_error(EC.message());
280 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000281 Symbols.push_back(Symbol);
282 }
Owen Andersond9243c42011-10-17 21:37:35 +0000283
Alexey Samsonov48803e52014-03-13 14:37:36 +0000284 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000285 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000286 Section.getName(SectName);
287 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000288 }
289
Kevin Enderby273ae012013-06-06 17:20:50 +0000290 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000291 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000292 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000293 // We found a function starts segment, parse the addresses for later
294 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000295 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000296 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000297
Charles Davis8bdfafd2013-09-01 04:28:48 +0000298 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000299 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
300 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000301 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000302 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000303 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000304 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000305 }
306 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000307 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000308}
309
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000310static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
311 uint32_t n, uint32_t count,
312 uint32_t stride, uint64_t addr) {
313 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
314 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
315 if (n > nindirectsyms)
316 outs() << " (entries start past the end of the indirect symbol "
317 "table) (reserved1 field greater than the table size)";
318 else if (n + count > nindirectsyms)
319 outs() << " (entries extends past the end of the indirect symbol "
320 "table)";
321 outs() << "\n";
322 uint32_t cputype = O->getHeader().cputype;
323 if (cputype & MachO::CPU_ARCH_ABI64)
324 outs() << "address index";
325 else
326 outs() << "address index";
327 if (verbose)
328 outs() << " name\n";
329 else
330 outs() << "\n";
331 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
332 if (cputype & MachO::CPU_ARCH_ABI64)
333 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
334 else
335 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
336 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
337 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
338 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
339 outs() << "LOCAL\n";
340 continue;
341 }
342 if (indirect_symbol ==
343 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
344 outs() << "LOCAL ABSOLUTE\n";
345 continue;
346 }
347 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
348 outs() << "ABSOLUTE\n";
349 continue;
350 }
351 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000352 if (verbose) {
353 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
354 if (indirect_symbol < Symtab.nsyms) {
355 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
356 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000357 ErrorOr<StringRef> SymName = Symbol.getName();
358 if (std::error_code EC = SymName.getError())
359 report_fatal_error(EC.message());
360 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000361 } else {
362 outs() << "?";
363 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000364 }
365 outs() << "\n";
366 }
367}
368
369static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000370 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000371 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
372 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
373 for (unsigned J = 0; J < Seg.nsects; ++J) {
374 MachO::section_64 Sec = O->getSection64(Load, J);
375 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
376 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
377 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
378 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
379 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
380 section_type == MachO::S_SYMBOL_STUBS) {
381 uint32_t stride;
382 if (section_type == MachO::S_SYMBOL_STUBS)
383 stride = Sec.reserved2;
384 else
385 stride = 8;
386 if (stride == 0) {
387 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
388 << Sec.sectname << ") "
389 << "(size of stubs in reserved2 field is zero)\n";
390 continue;
391 }
392 uint32_t count = Sec.size / stride;
393 outs() << "Indirect symbols for (" << Sec.segname << ","
394 << Sec.sectname << ") " << count << " entries";
395 uint32_t n = Sec.reserved1;
396 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
397 }
398 }
399 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
400 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
401 for (unsigned J = 0; J < Seg.nsects; ++J) {
402 MachO::section Sec = O->getSection(Load, J);
403 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
404 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
405 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
406 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
407 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
408 section_type == MachO::S_SYMBOL_STUBS) {
409 uint32_t stride;
410 if (section_type == MachO::S_SYMBOL_STUBS)
411 stride = Sec.reserved2;
412 else
413 stride = 4;
414 if (stride == 0) {
415 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
416 << Sec.sectname << ") "
417 << "(size of stubs in reserved2 field is zero)\n";
418 continue;
419 }
420 uint32_t count = Sec.size / stride;
421 outs() << "Indirect symbols for (" << Sec.segname << ","
422 << Sec.sectname << ") " << count << " entries";
423 uint32_t n = Sec.reserved1;
424 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
425 }
426 }
427 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000428 }
429}
430
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000431static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
432 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
433 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
434 outs() << "Data in code table (" << nentries << " entries)\n";
435 outs() << "offset length kind\n";
436 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
437 ++DI) {
438 uint32_t Offset;
439 DI->getOffset(Offset);
440 outs() << format("0x%08" PRIx32, Offset) << " ";
441 uint16_t Length;
442 DI->getLength(Length);
443 outs() << format("%6u", Length) << " ";
444 uint16_t Kind;
445 DI->getKind(Kind);
446 if (verbose) {
447 switch (Kind) {
448 case MachO::DICE_KIND_DATA:
449 outs() << "DATA";
450 break;
451 case MachO::DICE_KIND_JUMP_TABLE8:
452 outs() << "JUMP_TABLE8";
453 break;
454 case MachO::DICE_KIND_JUMP_TABLE16:
455 outs() << "JUMP_TABLE16";
456 break;
457 case MachO::DICE_KIND_JUMP_TABLE32:
458 outs() << "JUMP_TABLE32";
459 break;
460 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
461 outs() << "ABS_JUMP_TABLE32";
462 break;
463 default:
464 outs() << format("0x%04" PRIx32, Kind);
465 break;
466 }
467 } else
468 outs() << format("0x%04" PRIx32, Kind);
469 outs() << "\n";
470 }
471}
472
Kevin Enderby9a509442015-01-27 21:28:24 +0000473static void PrintLinkOptHints(MachOObjectFile *O) {
474 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
475 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
476 uint32_t nloh = LohLC.datasize;
477 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
478 for (uint32_t i = 0; i < nloh;) {
479 unsigned n;
480 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
481 i += n;
482 outs() << " identifier " << identifier << " ";
483 if (i >= nloh)
484 return;
485 switch (identifier) {
486 case 1:
487 outs() << "AdrpAdrp\n";
488 break;
489 case 2:
490 outs() << "AdrpLdr\n";
491 break;
492 case 3:
493 outs() << "AdrpAddLdr\n";
494 break;
495 case 4:
496 outs() << "AdrpLdrGotLdr\n";
497 break;
498 case 5:
499 outs() << "AdrpAddStr\n";
500 break;
501 case 6:
502 outs() << "AdrpLdrGotStr\n";
503 break;
504 case 7:
505 outs() << "AdrpAdd\n";
506 break;
507 case 8:
508 outs() << "AdrpLdrGot\n";
509 break;
510 default:
511 outs() << "Unknown identifier value\n";
512 break;
513 }
514 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
515 i += n;
516 outs() << " narguments " << narguments << "\n";
517 if (i >= nloh)
518 return;
519
520 for (uint32_t j = 0; j < narguments; j++) {
521 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
522 i += n;
523 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
524 if (i >= nloh)
525 return;
526 }
527 }
528}
529
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000530static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000531 unsigned Index = 0;
532 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000533 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
534 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
535 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
536 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
537 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
538 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
539 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
540 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
541 if (dl.dylib.name < dl.cmdsize) {
542 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
543 if (JustId)
544 outs() << p << "\n";
545 else {
546 outs() << "\t" << p;
547 outs() << " (compatibility version "
548 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
549 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
550 << (dl.dylib.compatibility_version & 0xff) << ",";
551 outs() << " current version "
552 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
553 << ((dl.dylib.current_version >> 8) & 0xff) << "."
554 << (dl.dylib.current_version & 0xff) << ")\n";
555 }
556 } else {
557 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
558 if (Load.C.cmd == MachO::LC_ID_DYLIB)
559 outs() << "LC_ID_DYLIB ";
560 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
561 outs() << "LC_LOAD_DYLIB ";
562 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
563 outs() << "LC_LOAD_WEAK_DYLIB ";
564 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
565 outs() << "LC_LAZY_LOAD_DYLIB ";
566 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
567 outs() << "LC_REEXPORT_DYLIB ";
568 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
569 outs() << "LC_LOAD_UPWARD_DYLIB ";
570 else
571 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000572 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000573 }
574 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000575 }
576}
577
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000578typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
579
580static void CreateSymbolAddressMap(MachOObjectFile *O,
581 SymbolAddressMap *AddrMap) {
582 // Create a map of symbol addresses to symbol names.
583 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000584 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
585 if (std::error_code EC = STOrErr.getError())
586 report_fatal_error(EC.message());
587 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000588 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
589 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000590 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000591 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
592 if (std::error_code EC = SymNameOrErr.getError())
593 report_fatal_error(EC.message());
594 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000595 if (!SymName.startswith(".objc"))
596 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000597 }
598 }
599}
600
601// GuessSymbolName is passed the address of what might be a symbol and a
602// pointer to the SymbolAddressMap. It returns the name of a symbol
603// with that address or nullptr if no symbol is found with that address.
604static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
605 const char *SymbolName = nullptr;
606 // A DenseMap can't lookup up some values.
607 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
608 StringRef name = AddrMap->lookup(value);
609 if (!name.empty())
610 SymbolName = name.data();
611 }
612 return SymbolName;
613}
614
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000615static void DumpCstringChar(const char c) {
616 char p[2];
617 p[0] = c;
618 p[1] = '\0';
619 outs().write_escaped(p);
620}
621
Kevin Enderby10ba0412015-02-04 21:38:42 +0000622static void DumpCstringSection(MachOObjectFile *O, const char *sect,
623 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000624 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000625 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000626 if (print_addresses) {
627 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000628 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000629 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000630 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000631 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000632 for (; i < sect_size && sect[i] != '\0'; i++)
633 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000634 if (i < sect_size && sect[i] == '\0')
635 outs() << "\n";
636 }
637}
638
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000639static void DumpLiteral4(uint32_t l, float f) {
640 outs() << format("0x%08" PRIx32, l);
641 if ((l & 0x7f800000) != 0x7f800000)
642 outs() << format(" (%.16e)\n", f);
643 else {
644 if (l == 0x7f800000)
645 outs() << " (+Infinity)\n";
646 else if (l == 0xff800000)
647 outs() << " (-Infinity)\n";
648 else if ((l & 0x00400000) == 0x00400000)
649 outs() << " (non-signaling Not-a-Number)\n";
650 else
651 outs() << " (signaling Not-a-Number)\n";
652 }
653}
654
655static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
656 uint32_t sect_size, uint64_t sect_addr,
657 bool print_addresses) {
658 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
659 if (print_addresses) {
660 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000661 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000662 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000663 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000664 }
665 float f;
666 memcpy(&f, sect + i, sizeof(float));
667 if (O->isLittleEndian() != sys::IsLittleEndianHost)
668 sys::swapByteOrder(f);
669 uint32_t l;
670 memcpy(&l, sect + i, sizeof(uint32_t));
671 if (O->isLittleEndian() != sys::IsLittleEndianHost)
672 sys::swapByteOrder(l);
673 DumpLiteral4(l, f);
674 }
675}
676
677static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
678 double d) {
679 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
680 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000681 Hi = (O->isLittleEndian()) ? l1 : l0;
682 Lo = (O->isLittleEndian()) ? l0 : l1;
683
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000684 // Hi is the high word, so this is equivalent to if(isfinite(d))
685 if ((Hi & 0x7ff00000) != 0x7ff00000)
686 outs() << format(" (%.16e)\n", d);
687 else {
688 if (Hi == 0x7ff00000 && Lo == 0)
689 outs() << " (+Infinity)\n";
690 else if (Hi == 0xfff00000 && Lo == 0)
691 outs() << " (-Infinity)\n";
692 else if ((Hi & 0x00080000) == 0x00080000)
693 outs() << " (non-signaling Not-a-Number)\n";
694 else
695 outs() << " (signaling Not-a-Number)\n";
696 }
697}
698
699static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
700 uint32_t sect_size, uint64_t sect_addr,
701 bool print_addresses) {
702 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
703 if (print_addresses) {
704 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000705 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000706 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000707 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000708 }
709 double d;
710 memcpy(&d, sect + i, sizeof(double));
711 if (O->isLittleEndian() != sys::IsLittleEndianHost)
712 sys::swapByteOrder(d);
713 uint32_t l0, l1;
714 memcpy(&l0, sect + i, sizeof(uint32_t));
715 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
716 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
717 sys::swapByteOrder(l0);
718 sys::swapByteOrder(l1);
719 }
720 DumpLiteral8(O, l0, l1, d);
721 }
722}
723
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000724static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
725 outs() << format("0x%08" PRIx32, l0) << " ";
726 outs() << format("0x%08" PRIx32, l1) << " ";
727 outs() << format("0x%08" PRIx32, l2) << " ";
728 outs() << format("0x%08" PRIx32, l3) << "\n";
729}
730
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000731static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
732 uint32_t sect_size, uint64_t sect_addr,
733 bool print_addresses) {
734 for (uint32_t i = 0; i < sect_size; i += 16) {
735 if (print_addresses) {
736 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000737 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000738 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000739 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000740 }
741 uint32_t l0, l1, l2, l3;
742 memcpy(&l0, sect + i, sizeof(uint32_t));
743 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
744 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
745 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
746 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
747 sys::swapByteOrder(l0);
748 sys::swapByteOrder(l1);
749 sys::swapByteOrder(l2);
750 sys::swapByteOrder(l3);
751 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000752 DumpLiteral16(l0, l1, l2, l3);
753 }
754}
755
756static void DumpLiteralPointerSection(MachOObjectFile *O,
757 const SectionRef &Section,
758 const char *sect, uint32_t sect_size,
759 uint64_t sect_addr,
760 bool print_addresses) {
761 // Collect the literal sections in this Mach-O file.
762 std::vector<SectionRef> LiteralSections;
763 for (const SectionRef &Section : O->sections()) {
764 DataRefImpl Ref = Section.getRawDataRefImpl();
765 uint32_t section_type;
766 if (O->is64Bit()) {
767 const MachO::section_64 Sec = O->getSection64(Ref);
768 section_type = Sec.flags & MachO::SECTION_TYPE;
769 } else {
770 const MachO::section Sec = O->getSection(Ref);
771 section_type = Sec.flags & MachO::SECTION_TYPE;
772 }
773 if (section_type == MachO::S_CSTRING_LITERALS ||
774 section_type == MachO::S_4BYTE_LITERALS ||
775 section_type == MachO::S_8BYTE_LITERALS ||
776 section_type == MachO::S_16BYTE_LITERALS)
777 LiteralSections.push_back(Section);
778 }
779
780 // Set the size of the literal pointer.
781 uint32_t lp_size = O->is64Bit() ? 8 : 4;
782
Eric Christopher572e03a2015-06-19 01:53:21 +0000783 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000784 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
785 for (const RelocationRef &Reloc : Section.relocations()) {
786 DataRefImpl Rel;
787 MachO::any_relocation_info RE;
788 bool isExtern = false;
789 Rel = Reloc.getRawDataRefImpl();
790 RE = O->getRelocation(Rel);
791 isExtern = O->getPlainRelocationExternal(RE);
792 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000793 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000794 symbol_iterator RelocSym = Reloc.getSymbol();
795 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
796 }
797 }
798 array_pod_sort(Relocs.begin(), Relocs.end());
799
800 // Dump each literal pointer.
801 for (uint32_t i = 0; i < sect_size; i += lp_size) {
802 if (print_addresses) {
803 if (O->is64Bit())
804 outs() << format("%016" PRIx64, sect_addr + i) << " ";
805 else
806 outs() << format("%08" PRIx64, sect_addr + i) << " ";
807 }
808 uint64_t lp;
809 if (O->is64Bit()) {
810 memcpy(&lp, sect + i, sizeof(uint64_t));
811 if (O->isLittleEndian() != sys::IsLittleEndianHost)
812 sys::swapByteOrder(lp);
813 } else {
814 uint32_t li;
815 memcpy(&li, sect + i, sizeof(uint32_t));
816 if (O->isLittleEndian() != sys::IsLittleEndianHost)
817 sys::swapByteOrder(li);
818 lp = li;
819 }
820
821 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000822 auto Reloc = std::find_if(
823 Relocs.begin(), Relocs.end(),
824 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
825 if (Reloc != Relocs.end()) {
826 symbol_iterator RelocSym = Reloc->second;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000827 ErrorOr<StringRef> SymName = RelocSym->getName();
828 if (std::error_code EC = SymName.getError())
829 report_fatal_error(EC.message());
830 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000831 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000832 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000833
834 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000835 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
836 [&](const SectionRef &R) {
837 return lp >= R.getAddress() &&
838 lp < R.getAddress() + R.getSize();
839 });
840 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000841 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000842 continue;
843 }
844
845 uint64_t SectAddress = Sect->getAddress();
846 uint64_t SectSize = Sect->getSize();
847
848 StringRef SectName;
849 Sect->getName(SectName);
850 DataRefImpl Ref = Sect->getRawDataRefImpl();
851 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
852 outs() << SegmentName << ":" << SectName << ":";
853
854 uint32_t section_type;
855 if (O->is64Bit()) {
856 const MachO::section_64 Sec = O->getSection64(Ref);
857 section_type = Sec.flags & MachO::SECTION_TYPE;
858 } else {
859 const MachO::section Sec = O->getSection(Ref);
860 section_type = Sec.flags & MachO::SECTION_TYPE;
861 }
862
863 StringRef BytesStr;
864 Sect->getContents(BytesStr);
865 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
866
867 switch (section_type) {
868 case MachO::S_CSTRING_LITERALS:
869 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
870 i++) {
871 DumpCstringChar(Contents[i]);
872 }
873 outs() << "\n";
874 break;
875 case MachO::S_4BYTE_LITERALS:
876 float f;
877 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
878 uint32_t l;
879 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
880 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
881 sys::swapByteOrder(f);
882 sys::swapByteOrder(l);
883 }
884 DumpLiteral4(l, f);
885 break;
886 case MachO::S_8BYTE_LITERALS: {
887 double d;
888 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
889 uint32_t l0, l1;
890 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
891 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
892 sizeof(uint32_t));
893 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
894 sys::swapByteOrder(f);
895 sys::swapByteOrder(l0);
896 sys::swapByteOrder(l1);
897 }
898 DumpLiteral8(O, l0, l1, d);
899 break;
900 }
901 case MachO::S_16BYTE_LITERALS: {
902 uint32_t l0, l1, l2, l3;
903 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
904 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
905 sizeof(uint32_t));
906 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
907 sizeof(uint32_t));
908 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
909 sizeof(uint32_t));
910 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
911 sys::swapByteOrder(l0);
912 sys::swapByteOrder(l1);
913 sys::swapByteOrder(l2);
914 sys::swapByteOrder(l3);
915 }
916 DumpLiteral16(l0, l1, l2, l3);
917 break;
918 }
919 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000920 }
921}
922
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000923static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
924 uint32_t sect_size, uint64_t sect_addr,
925 SymbolAddressMap *AddrMap,
926 bool verbose) {
927 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000928 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000929 for (uint32_t i = 0; i < sect_size; i += stride) {
930 const char *SymbolName = nullptr;
931 if (O->is64Bit()) {
932 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
933 uint64_t pointer_value;
934 memcpy(&pointer_value, sect + i, stride);
935 if (O->isLittleEndian() != sys::IsLittleEndianHost)
936 sys::swapByteOrder(pointer_value);
937 outs() << format("0x%016" PRIx64, pointer_value);
938 if (verbose)
939 SymbolName = GuessSymbolName(pointer_value, AddrMap);
940 } else {
941 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
942 uint32_t pointer_value;
943 memcpy(&pointer_value, sect + i, stride);
944 if (O->isLittleEndian() != sys::IsLittleEndianHost)
945 sys::swapByteOrder(pointer_value);
946 outs() << format("0x%08" PRIx32, pointer_value);
947 if (verbose)
948 SymbolName = GuessSymbolName(pointer_value, AddrMap);
949 }
950 if (SymbolName)
951 outs() << " " << SymbolName;
952 outs() << "\n";
953 }
954}
955
956static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
957 uint32_t size, uint64_t addr) {
958 uint32_t cputype = O->getHeader().cputype;
959 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
960 uint32_t j;
961 for (uint32_t i = 0; i < size; i += j, addr += j) {
962 if (O->is64Bit())
963 outs() << format("%016" PRIx64, addr) << "\t";
964 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000965 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000966 for (j = 0; j < 16 && i + j < size; j++) {
967 uint8_t byte_word = *(sect + i + j);
968 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
969 }
970 outs() << "\n";
971 }
972 } else {
973 uint32_t j;
974 for (uint32_t i = 0; i < size; i += j, addr += j) {
975 if (O->is64Bit())
976 outs() << format("%016" PRIx64, addr) << "\t";
977 else
978 outs() << format("%08" PRIx64, sect) << "\t";
979 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
980 j += sizeof(int32_t)) {
981 if (i + j + sizeof(int32_t) < size) {
982 uint32_t long_word;
983 memcpy(&long_word, sect + i + j, sizeof(int32_t));
984 if (O->isLittleEndian() != sys::IsLittleEndianHost)
985 sys::swapByteOrder(long_word);
986 outs() << format("%08" PRIx32, long_word) << " ";
987 } else {
988 for (uint32_t k = 0; i + j + k < size; k++) {
989 uint8_t byte_word = *(sect + i + j);
990 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
991 }
992 }
993 }
994 outs() << "\n";
995 }
996 }
997}
998
Kevin Enderby95df54c2015-02-04 01:01:38 +0000999static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1000 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001001static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1002 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001003
1004static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1005 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001006 SymbolAddressMap AddrMap;
1007 if (verbose)
1008 CreateSymbolAddressMap(O, &AddrMap);
1009
Colin LeMahieufcc32762015-07-29 19:08:10 +00001010 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1011 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001012 std::pair<StringRef, StringRef> DumpSegSectName;
1013 DumpSegSectName = DumpSection.split(',');
1014 StringRef DumpSegName, DumpSectName;
1015 if (DumpSegSectName.second.size()) {
1016 DumpSegName = DumpSegSectName.first;
1017 DumpSectName = DumpSegSectName.second;
1018 } else {
1019 DumpSegName = "";
1020 DumpSectName = DumpSegSectName.first;
1021 }
1022 for (const SectionRef &Section : O->sections()) {
1023 StringRef SectName;
1024 Section.getName(SectName);
1025 DataRefImpl Ref = Section.getRawDataRefImpl();
1026 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1027 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1028 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001029
Kevin Enderby95df54c2015-02-04 01:01:38 +00001030 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001031 if (O->is64Bit()) {
1032 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001033 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001034
1035 } else {
1036 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001037 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001038 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001039 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001040
1041 StringRef BytesStr;
1042 Section.getContents(BytesStr);
1043 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1044 uint32_t sect_size = BytesStr.size();
1045 uint64_t sect_addr = Section.getAddress();
1046
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001047 outs() << "Contents of (" << SegName << "," << SectName
1048 << ") section\n";
1049
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001050 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001051 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1052 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1053 DisassembleMachO(Filename, O, SegName, SectName);
1054 continue;
1055 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001056 if (SegName == "__TEXT" && SectName == "__info_plist") {
1057 outs() << sect;
1058 continue;
1059 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001060 if (SegName == "__OBJC" && SectName == "__protocol") {
1061 DumpProtocolSection(O, sect, sect_size, sect_addr);
1062 continue;
1063 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001064 switch (section_type) {
1065 case MachO::S_REGULAR:
1066 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1067 break;
1068 case MachO::S_ZEROFILL:
1069 outs() << "zerofill section and has no contents in the file\n";
1070 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001071 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001072 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001073 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001074 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001075 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001076 break;
1077 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001078 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001079 break;
1080 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001081 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1082 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001083 case MachO::S_LITERAL_POINTERS:
1084 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001085 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001086 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001087 case MachO::S_MOD_INIT_FUNC_POINTERS:
1088 case MachO::S_MOD_TERM_FUNC_POINTERS:
1089 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1090 verbose);
1091 break;
1092 default:
1093 outs() << "Unknown section type ("
1094 << format("0x%08" PRIx32, section_type) << ")\n";
1095 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1096 break;
1097 }
1098 } else {
1099 if (section_type == MachO::S_ZEROFILL)
1100 outs() << "zerofill section and has no contents in the file\n";
1101 else
1102 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1103 }
1104 }
1105 }
1106 }
1107}
1108
Kevin Enderbycd66be52015-03-11 22:06:32 +00001109static void DumpInfoPlistSectionContents(StringRef Filename,
1110 MachOObjectFile *O) {
1111 for (const SectionRef &Section : O->sections()) {
1112 StringRef SectName;
1113 Section.getName(SectName);
1114 DataRefImpl Ref = Section.getRawDataRefImpl();
1115 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1116 if (SegName == "__TEXT" && SectName == "__info_plist") {
1117 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1118 StringRef BytesStr;
1119 Section.getContents(BytesStr);
1120 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1121 outs() << sect;
1122 return;
1123 }
1124 }
1125}
1126
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001127// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1128// and if it is and there is a list of architecture flags is specified then
1129// check to make sure this Mach-O file is one of those architectures or all
1130// architectures were specified. If not then an error is generated and this
1131// routine returns false. Else it returns true.
1132static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1133 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1134 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1135 bool ArchFound = false;
1136 MachO::mach_header H;
1137 MachO::mach_header_64 H_64;
1138 Triple T;
1139 if (MachO->is64Bit()) {
1140 H_64 = MachO->MachOObjectFile::getHeader64();
1141 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1142 } else {
1143 H = MachO->MachOObjectFile::getHeader();
1144 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1145 }
1146 unsigned i;
1147 for (i = 0; i < ArchFlags.size(); ++i) {
1148 if (ArchFlags[i] == T.getArchName())
1149 ArchFound = true;
1150 break;
1151 }
1152 if (!ArchFound) {
1153 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1154 << "architecture: " + ArchFlags[i] + "\n";
1155 return false;
1156 }
1157 }
1158 return true;
1159}
1160
Kevin Enderby0fc11822015-04-01 20:57:01 +00001161static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1162
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001163// ProcessMachO() is passed a single opened Mach-O file, which may be an
1164// archive member and or in a slice of a universal file. It prints the
1165// the file name and header info and then processes it according to the
1166// command line options.
1167static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1168 StringRef ArchiveMemberName = StringRef(),
1169 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001170 // If we are doing some processing here on the Mach-O file print the header
1171 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001172 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001173 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001174 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001175 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001176 outs() << Filename;
1177 if (!ArchiveMemberName.empty())
1178 outs() << '(' << ArchiveMemberName << ')';
1179 if (!ArchitectureName.empty())
1180 outs() << " (architecture " << ArchitectureName << ")";
1181 outs() << ":\n";
1182 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001183
1184 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001185 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001186 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001187 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001188 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001189 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001190 if (LinkOptHints)
1191 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001192 if (Relocations)
1193 PrintRelocations(MachOOF);
1194 if (SectionHeaders)
1195 PrintSectionHeaders(MachOOF);
1196 if (SectionContents)
1197 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001198 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001199 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001200 if (InfoPlist)
1201 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001202 if (DylibsUsed)
1203 PrintDylibs(MachOOF, false);
1204 if (DylibId)
1205 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001206 if (SymbolTable)
1207 PrintSymbolTable(MachOOF);
1208 if (UnwindInfo)
1209 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001210 if (PrivateHeaders) {
1211 printMachOFileHeader(MachOOF);
1212 printMachOLoadCommands(MachOOF);
1213 }
1214 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001215 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001216 if (ObjcMetaData)
1217 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001218 if (ExportsTrie)
1219 printExportsTrie(MachOOF);
1220 if (Rebase)
1221 printRebaseTable(MachOOF);
1222 if (Bind)
1223 printBindTable(MachOOF);
1224 if (LazyBind)
1225 printLazyBindTable(MachOOF);
1226 if (WeakBind)
1227 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001228
1229 if (DwarfDumpType != DIDT_Null) {
1230 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1231 // Dump the complete DWARF structure.
1232 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1233 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001234}
1235
Kevin Enderby131d1772015-01-09 19:22:37 +00001236// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1237static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1238 outs() << " cputype (" << cputype << ")\n";
1239 outs() << " cpusubtype (" << cpusubtype << ")\n";
1240}
1241
1242// printCPUType() helps print_fat_headers by printing the cputype and
1243// pusubtype (symbolically for the one's it knows about).
1244static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1245 switch (cputype) {
1246 case MachO::CPU_TYPE_I386:
1247 switch (cpusubtype) {
1248 case MachO::CPU_SUBTYPE_I386_ALL:
1249 outs() << " cputype CPU_TYPE_I386\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1251 break;
1252 default:
1253 printUnknownCPUType(cputype, cpusubtype);
1254 break;
1255 }
1256 break;
1257 case MachO::CPU_TYPE_X86_64:
1258 switch (cpusubtype) {
1259 case MachO::CPU_SUBTYPE_X86_64_ALL:
1260 outs() << " cputype CPU_TYPE_X86_64\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1262 break;
1263 case MachO::CPU_SUBTYPE_X86_64_H:
1264 outs() << " cputype CPU_TYPE_X86_64\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1266 break;
1267 default:
1268 printUnknownCPUType(cputype, cpusubtype);
1269 break;
1270 }
1271 break;
1272 case MachO::CPU_TYPE_ARM:
1273 switch (cpusubtype) {
1274 case MachO::CPU_SUBTYPE_ARM_ALL:
1275 outs() << " cputype CPU_TYPE_ARM\n";
1276 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1277 break;
1278 case MachO::CPU_SUBTYPE_ARM_V4T:
1279 outs() << " cputype CPU_TYPE_ARM\n";
1280 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1281 break;
1282 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1283 outs() << " cputype CPU_TYPE_ARM\n";
1284 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1285 break;
1286 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1287 outs() << " cputype CPU_TYPE_ARM\n";
1288 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1289 break;
1290 case MachO::CPU_SUBTYPE_ARM_V6:
1291 outs() << " cputype CPU_TYPE_ARM\n";
1292 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1293 break;
1294 case MachO::CPU_SUBTYPE_ARM_V6M:
1295 outs() << " cputype CPU_TYPE_ARM\n";
1296 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1297 break;
1298 case MachO::CPU_SUBTYPE_ARM_V7:
1299 outs() << " cputype CPU_TYPE_ARM\n";
1300 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1301 break;
1302 case MachO::CPU_SUBTYPE_ARM_V7EM:
1303 outs() << " cputype CPU_TYPE_ARM\n";
1304 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1305 break;
1306 case MachO::CPU_SUBTYPE_ARM_V7K:
1307 outs() << " cputype CPU_TYPE_ARM\n";
1308 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1309 break;
1310 case MachO::CPU_SUBTYPE_ARM_V7M:
1311 outs() << " cputype CPU_TYPE_ARM\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1313 break;
1314 case MachO::CPU_SUBTYPE_ARM_V7S:
1315 outs() << " cputype CPU_TYPE_ARM\n";
1316 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1317 break;
1318 default:
1319 printUnknownCPUType(cputype, cpusubtype);
1320 break;
1321 }
1322 break;
1323 case MachO::CPU_TYPE_ARM64:
1324 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1325 case MachO::CPU_SUBTYPE_ARM64_ALL:
1326 outs() << " cputype CPU_TYPE_ARM64\n";
1327 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1328 break;
1329 default:
1330 printUnknownCPUType(cputype, cpusubtype);
1331 break;
1332 }
1333 break;
1334 default:
1335 printUnknownCPUType(cputype, cpusubtype);
1336 break;
1337 }
1338}
1339
1340static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1341 bool verbose) {
1342 outs() << "Fat headers\n";
1343 if (verbose)
1344 outs() << "fat_magic FAT_MAGIC\n";
1345 else
1346 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1347
1348 uint32_t nfat_arch = UB->getNumberOfObjects();
1349 StringRef Buf = UB->getData();
1350 uint64_t size = Buf.size();
1351 uint64_t big_size = sizeof(struct MachO::fat_header) +
1352 nfat_arch * sizeof(struct MachO::fat_arch);
1353 outs() << "nfat_arch " << UB->getNumberOfObjects();
1354 if (nfat_arch == 0)
1355 outs() << " (malformed, contains zero architecture types)\n";
1356 else if (big_size > size)
1357 outs() << " (malformed, architectures past end of file)\n";
1358 else
1359 outs() << "\n";
1360
1361 for (uint32_t i = 0; i < nfat_arch; ++i) {
1362 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1363 uint32_t cputype = OFA.getCPUType();
1364 uint32_t cpusubtype = OFA.getCPUSubType();
1365 outs() << "architecture ";
1366 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1367 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1368 uint32_t other_cputype = other_OFA.getCPUType();
1369 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001370 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001371 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001372 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001373 outs() << "(illegal duplicate architecture) ";
1374 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001375 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001376 }
1377 if (verbose) {
1378 outs() << OFA.getArchTypeName() << "\n";
1379 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1380 } else {
1381 outs() << i << "\n";
1382 outs() << " cputype " << cputype << "\n";
1383 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1384 << "\n";
1385 }
1386 if (verbose &&
1387 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1388 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1389 else
1390 outs() << " capabilities "
1391 << format("0x%" PRIx32,
1392 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1393 outs() << " offset " << OFA.getOffset();
1394 if (OFA.getOffset() > size)
1395 outs() << " (past end of file)";
1396 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1397 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1398 outs() << "\n";
1399 outs() << " size " << OFA.getSize();
1400 big_size = OFA.getOffset() + OFA.getSize();
1401 if (big_size > size)
1402 outs() << " (past end of file)";
1403 outs() << "\n";
1404 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1405 << ")\n";
1406 }
1407}
1408
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001409static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001410 bool print_offset) {
1411 if (print_offset)
1412 outs() << C.getChildOffset() << "\t";
1413 sys::fs::perms Mode = C.getAccessMode();
1414 if (verbose) {
1415 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1416 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1417 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001418 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1419 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1420 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1421 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1422 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1423 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1424 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1425 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1426 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001427 } else {
1428 outs() << format("0%o ", Mode);
1429 }
1430
1431 unsigned UID = C.getUID();
1432 outs() << format("%3d/", UID);
1433 unsigned GID = C.getGID();
1434 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001435 ErrorOr<uint64_t> Size = C.getRawSize();
1436 if (std::error_code EC = Size.getError())
1437 report_fatal_error(EC.message());
1438 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001439
1440 StringRef RawLastModified = C.getRawLastModified();
1441 if (verbose) {
1442 unsigned Seconds;
1443 if (RawLastModified.getAsInteger(10, Seconds))
1444 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1445 else {
1446 // Since cime(3) returns a 26 character string of the form:
1447 // "Sun Sep 16 01:03:52 1973\n\0"
1448 // just print 24 characters.
1449 time_t t = Seconds;
1450 outs() << format("%.24s ", ctime(&t));
1451 }
1452 } else {
1453 outs() << RawLastModified << " ";
1454 }
1455
1456 if (verbose) {
1457 ErrorOr<StringRef> NameOrErr = C.getName();
1458 if (NameOrErr.getError()) {
1459 StringRef RawName = C.getRawName();
1460 outs() << RawName << "\n";
1461 } else {
1462 StringRef Name = NameOrErr.get();
1463 outs() << Name << "\n";
1464 }
1465 } else {
1466 StringRef RawName = C.getRawName();
1467 outs() << RawName << "\n";
1468 }
1469}
1470
1471static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001472 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1473 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001474 if (std::error_code EC = I->getError())
1475 report_fatal_error(EC.message());
1476 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001477 printArchiveChild(C, verbose, print_offset);
1478 }
1479}
1480
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001481// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1482// -arch flags selecting just those slices as specified by them and also parses
1483// archive files. Then for each individual Mach-O file ProcessMachO() is
1484// called to process the file based on the command line options.
1485void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001486 // Check for -arch all and verifiy the -arch flags are valid.
1487 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1488 if (ArchFlags[i] == "all") {
1489 ArchAll = true;
1490 } else {
1491 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1492 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1493 "'for the -arch option\n";
1494 return;
1495 }
1496 }
1497 }
1498
1499 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001500 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1501 if (!BinaryOrErr)
1502 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001503 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001504
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001505 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1506 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001507 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001508 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001509 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1510 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001511 if (std::error_code EC = I->getError())
1512 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001513 auto &C = I->get();
1514 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001515 if (ChildOrErr.getError())
1516 continue;
1517 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1518 if (!checkMachOAndArchFlags(O, Filename))
1519 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001520 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001521 }
1522 }
1523 return;
1524 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001525 if (UniversalHeaders) {
1526 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001527 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001528 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001529 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1530 // If we have a list of architecture flags specified dump only those.
1531 if (!ArchAll && ArchFlags.size() != 0) {
1532 // Look for a slice in the universal binary that matches each ArchFlag.
1533 bool ArchFound;
1534 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1535 ArchFound = false;
1536 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1537 E = UB->end_objects();
1538 I != E; ++I) {
1539 if (ArchFlags[i] == I->getArchTypeName()) {
1540 ArchFound = true;
1541 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1542 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001543 std::string ArchitectureName = "";
1544 if (ArchFlags.size() > 1)
1545 ArchitectureName = I->getArchTypeName();
1546 if (ObjOrErr) {
1547 ObjectFile &O = *ObjOrErr.get();
1548 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001549 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001550 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1551 I->getAsArchive()) {
1552 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001553 outs() << "Archive : " << Filename;
1554 if (!ArchitectureName.empty())
1555 outs() << " (architecture " << ArchitectureName << ")";
1556 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001557 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001558 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001559 for (Archive::child_iterator AI = A->child_begin(),
1560 AE = A->child_end();
1561 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001562 if (std::error_code EC = AI->getError())
1563 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001564 auto &C = AI->get();
1565 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001566 if (ChildOrErr.getError())
1567 continue;
1568 if (MachOObjectFile *O =
1569 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001570 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001571 }
1572 }
1573 }
1574 }
1575 if (!ArchFound) {
1576 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1577 << "architecture: " + ArchFlags[i] + "\n";
1578 return;
1579 }
1580 }
1581 return;
1582 }
1583 // No architecture flags were specified so if this contains a slice that
1584 // matches the host architecture dump only that.
1585 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001586 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1587 E = UB->end_objects();
1588 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001589 if (MachOObjectFile::getHostArch().getArchName() ==
1590 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001591 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001592 std::string ArchiveName;
1593 ArchiveName.clear();
1594 if (ObjOrErr) {
1595 ObjectFile &O = *ObjOrErr.get();
1596 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001597 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001598 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1599 I->getAsArchive()) {
1600 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001601 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001602 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001603 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001604 for (Archive::child_iterator AI = A->child_begin(),
1605 AE = A->child_end();
1606 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001607 if (std::error_code EC = AI->getError())
1608 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001609 auto &C = AI->get();
1610 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001611 if (ChildOrErr.getError())
1612 continue;
1613 if (MachOObjectFile *O =
1614 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001615 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001616 }
1617 }
1618 return;
1619 }
1620 }
1621 }
1622 // Either all architectures have been specified or none have been specified
1623 // and this does not contain the host architecture so dump all the slices.
1624 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1625 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1626 E = UB->end_objects();
1627 I != E; ++I) {
1628 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001629 std::string ArchitectureName = "";
1630 if (moreThanOneArch)
1631 ArchitectureName = I->getArchTypeName();
1632 if (ObjOrErr) {
1633 ObjectFile &Obj = *ObjOrErr.get();
1634 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001635 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001636 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1637 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001638 outs() << "Archive : " << Filename;
1639 if (!ArchitectureName.empty())
1640 outs() << " (architecture " << ArchitectureName << ")";
1641 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001642 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001643 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001644 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1645 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001646 if (std::error_code EC = AI->getError())
1647 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001648 auto &C = AI->get();
1649 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001650 if (ChildOrErr.getError())
1651 continue;
1652 if (MachOObjectFile *O =
1653 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1654 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001655 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1656 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001657 }
1658 }
1659 }
1660 }
1661 return;
1662 }
1663 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1664 if (!checkMachOAndArchFlags(O, Filename))
1665 return;
1666 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001667 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001668 } else
1669 errs() << "llvm-objdump: '" << Filename << "': "
1670 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001671 return;
1672 }
1673 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001674}
1675
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001676typedef std::pair<uint64_t, const char *> BindInfoEntry;
1677typedef std::vector<BindInfoEntry> BindTable;
1678typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001679
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001680// The block of info used by the Symbolizer call backs.
1681struct DisassembleInfo {
1682 bool verbose;
1683 MachOObjectFile *O;
1684 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001685 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001686 std::vector<SectionRef> *Sections;
1687 const char *class_name;
1688 const char *selector_name;
1689 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001690 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001691 uint64_t adrp_addr;
1692 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001693 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001694 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001695};
1696
1697// SymbolizerGetOpInfo() is the operand information call back function.
1698// This is called to get the symbolic information for operand(s) of an
1699// instruction when it is being done. This routine does this from
1700// the relocation information, symbol table, etc. That block of information
1701// is a pointer to the struct DisassembleInfo that was passed when the
1702// disassembler context was created and passed to back to here when
1703// called back by the disassembler for instruction operands that could have
1704// relocation information. The address of the instruction containing operand is
1705// at the Pc parameter. The immediate value the operand has is passed in
1706// op_info->Value and is at Offset past the start of the instruction and has a
1707// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1708// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1709// names and addends of the symbolic expression to add for the operand. The
1710// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1711// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001712static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1713 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001714 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1715 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001716 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001717
1718 // Make sure all fields returned are zero if we don't set them.
1719 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1720 op_info->Value = value;
1721
1722 // If the TagType is not the value 1 which it code knows about or if no
1723 // verbose symbolic information is wanted then just return 0, indicating no
1724 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001725 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001726 return 0;
1727
1728 unsigned int Arch = info->O->getArch();
1729 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001730 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1731 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001732 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1733 // TODO:
1734 // Search the external relocation entries of a fully linked image
1735 // (if any) for an entry that matches this segment offset.
1736 // uint32_t seg_offset = (Pc + Offset);
1737 return 0;
1738 }
1739 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1740 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001741 uint32_t sect_addr = info->S.getAddress();
1742 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1743 bool reloc_found = false;
1744 DataRefImpl Rel;
1745 MachO::any_relocation_info RE;
1746 bool isExtern = false;
1747 SymbolRef Symbol;
1748 bool r_scattered = false;
1749 uint32_t r_value, pair_r_value, r_type;
1750 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001751 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001752 if (RelocOffset == sect_offset) {
1753 Rel = Reloc.getRawDataRefImpl();
1754 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001755 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001756 r_scattered = info->O->isRelocationScattered(RE);
1757 if (r_scattered) {
1758 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001759 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1760 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1761 DataRefImpl RelNext = Rel;
1762 info->O->moveRelocationNext(RelNext);
1763 MachO::any_relocation_info RENext;
1764 RENext = info->O->getRelocation(RelNext);
1765 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001766 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001767 else
1768 return 0;
1769 }
1770 } else {
1771 isExtern = info->O->getPlainRelocationExternal(RE);
1772 if (isExtern) {
1773 symbol_iterator RelocSym = Reloc.getSymbol();
1774 Symbol = *RelocSym;
1775 }
1776 }
1777 reloc_found = true;
1778 break;
1779 }
1780 }
1781 if (reloc_found && isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001782 ErrorOr<StringRef> SymName = Symbol.getName();
1783 if (std::error_code EC = SymName.getError())
1784 report_fatal_error(EC.message());
1785 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001786 op_info->AddSymbol.Present = 1;
1787 op_info->AddSymbol.Name = name;
1788 // For i386 extern relocation entries the value in the instruction is
1789 // the offset from the symbol, and value is already set in op_info->Value.
1790 return 1;
1791 }
1792 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1793 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001794 const char *add = GuessSymbolName(r_value, info->AddrMap);
1795 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001796 uint32_t offset = value - (r_value - pair_r_value);
1797 op_info->AddSymbol.Present = 1;
1798 if (add != nullptr)
1799 op_info->AddSymbol.Name = add;
1800 else
1801 op_info->AddSymbol.Value = r_value;
1802 op_info->SubtractSymbol.Present = 1;
1803 if (sub != nullptr)
1804 op_info->SubtractSymbol.Name = sub;
1805 else
1806 op_info->SubtractSymbol.Value = pair_r_value;
1807 op_info->Value = offset;
1808 return 1;
1809 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001810 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001811 }
1812 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001813 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1814 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001815 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1816 // TODO:
1817 // Search the external relocation entries of a fully linked image
1818 // (if any) for an entry that matches this segment offset.
1819 // uint64_t seg_offset = (Pc + Offset);
1820 return 0;
1821 }
1822 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1823 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001824 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001825 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1826 bool reloc_found = false;
1827 DataRefImpl Rel;
1828 MachO::any_relocation_info RE;
1829 bool isExtern = false;
1830 SymbolRef Symbol;
1831 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001832 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001833 if (RelocOffset == sect_offset) {
1834 Rel = Reloc.getRawDataRefImpl();
1835 RE = info->O->getRelocation(Rel);
1836 // NOTE: Scattered relocations don't exist on x86_64.
1837 isExtern = info->O->getPlainRelocationExternal(RE);
1838 if (isExtern) {
1839 symbol_iterator RelocSym = Reloc.getSymbol();
1840 Symbol = *RelocSym;
1841 }
1842 reloc_found = true;
1843 break;
1844 }
1845 }
1846 if (reloc_found && isExtern) {
1847 // The Value passed in will be adjusted by the Pc if the instruction
1848 // adds the Pc. But for x86_64 external relocation entries the Value
1849 // is the offset from the external symbol.
1850 if (info->O->getAnyRelocationPCRel(RE))
1851 op_info->Value -= Pc + Offset + Size;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001852 ErrorOr<StringRef> SymName = Symbol.getName();
1853 if (std::error_code EC = SymName.getError())
1854 report_fatal_error(EC.message());
1855 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001856 unsigned Type = info->O->getAnyRelocationType(RE);
1857 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1858 DataRefImpl RelNext = Rel;
1859 info->O->moveRelocationNext(RelNext);
1860 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1861 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1862 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1863 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1864 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1865 op_info->SubtractSymbol.Present = 1;
1866 op_info->SubtractSymbol.Name = name;
1867 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1868 Symbol = *RelocSymNext;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001869 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1870 if (std::error_code EC = SymNameNext.getError())
1871 report_fatal_error(EC.message());
1872 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001873 }
1874 }
1875 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1876 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1877 op_info->AddSymbol.Present = 1;
1878 op_info->AddSymbol.Name = name;
1879 return 1;
1880 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001881 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001882 }
1883 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001884 if (Offset != 0 || (Size != 4 && Size != 2))
1885 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001886 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1887 // TODO:
1888 // Search the external relocation entries of a fully linked image
1889 // (if any) for an entry that matches this segment offset.
1890 // uint32_t seg_offset = (Pc + Offset);
1891 return 0;
1892 }
1893 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1894 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001895 uint32_t sect_addr = info->S.getAddress();
1896 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001897 DataRefImpl Rel;
1898 MachO::any_relocation_info RE;
1899 bool isExtern = false;
1900 SymbolRef Symbol;
1901 bool r_scattered = false;
1902 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001903 auto Reloc =
1904 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1905 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001906 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001907 return RelocOffset == sect_offset;
1908 });
1909
1910 if (Reloc == info->S.relocations().end())
1911 return 0;
1912
1913 Rel = Reloc->getRawDataRefImpl();
1914 RE = info->O->getRelocation(Rel);
1915 r_length = info->O->getAnyRelocationLength(RE);
1916 r_scattered = info->O->isRelocationScattered(RE);
1917 if (r_scattered) {
1918 r_value = info->O->getScatteredRelocationValue(RE);
1919 r_type = info->O->getScatteredRelocationType(RE);
1920 } else {
1921 r_type = info->O->getAnyRelocationType(RE);
1922 isExtern = info->O->getPlainRelocationExternal(RE);
1923 if (isExtern) {
1924 symbol_iterator RelocSym = Reloc->getSymbol();
1925 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001926 }
1927 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001928 if (r_type == MachO::ARM_RELOC_HALF ||
1929 r_type == MachO::ARM_RELOC_SECTDIFF ||
1930 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1931 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1932 DataRefImpl RelNext = Rel;
1933 info->O->moveRelocationNext(RelNext);
1934 MachO::any_relocation_info RENext;
1935 RENext = info->O->getRelocation(RelNext);
1936 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1937 if (info->O->isRelocationScattered(RENext))
1938 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1939 }
1940
1941 if (isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001942 ErrorOr<StringRef> SymName = Symbol.getName();
1943 if (std::error_code EC = SymName.getError())
1944 report_fatal_error(EC.message());
1945 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001946 op_info->AddSymbol.Present = 1;
1947 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001948 switch (r_type) {
1949 case MachO::ARM_RELOC_HALF:
1950 if ((r_length & 0x1) == 1) {
1951 op_info->Value = value << 16 | other_half;
1952 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1953 } else {
1954 op_info->Value = other_half << 16 | value;
1955 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001956 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001957 break;
1958 default:
1959 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001960 }
1961 return 1;
1962 }
1963 // If we have a branch that is not an external relocation entry then
1964 // return 0 so the code in tryAddingSymbolicOperand() can use the
1965 // SymbolLookUp call back with the branch target address to look up the
1966 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001967 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1968 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001969 return 0;
1970
1971 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001972 if (r_type == MachO::ARM_RELOC_HALF ||
1973 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1974 if ((r_length & 0x1) == 1)
1975 value = value << 16 | other_half;
1976 else
1977 value = other_half << 16 | value;
1978 }
1979 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1980 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1981 offset = value - r_value;
1982 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001983 }
1984
David Blaikie33dd45d02015-03-23 18:39:02 +00001985 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001986 if ((r_length & 0x1) == 1)
1987 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1988 else
1989 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001990 const char *add = GuessSymbolName(r_value, info->AddrMap);
1991 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001992 int32_t offset = value - (r_value - pair_r_value);
1993 op_info->AddSymbol.Present = 1;
1994 if (add != nullptr)
1995 op_info->AddSymbol.Name = add;
1996 else
1997 op_info->AddSymbol.Value = r_value;
1998 op_info->SubtractSymbol.Present = 1;
1999 if (sub != nullptr)
2000 op_info->SubtractSymbol.Name = sub;
2001 else
2002 op_info->SubtractSymbol.Value = pair_r_value;
2003 op_info->Value = offset;
2004 return 1;
2005 }
2006
Kevin Enderby930fdc72014-11-06 19:00:13 +00002007 op_info->AddSymbol.Present = 1;
2008 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002009 if (r_type == MachO::ARM_RELOC_HALF) {
2010 if ((r_length & 0x1) == 1)
2011 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2012 else
2013 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002014 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002015 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002016 if (add != nullptr) {
2017 op_info->AddSymbol.Name = add;
2018 return 1;
2019 }
2020 op_info->AddSymbol.Value = value;
2021 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002022 }
2023 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002024 if (Offset != 0 || Size != 4)
2025 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002026 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2027 // TODO:
2028 // Search the external relocation entries of a fully linked image
2029 // (if any) for an entry that matches this segment offset.
2030 // uint64_t seg_offset = (Pc + Offset);
2031 return 0;
2032 }
2033 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2034 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002035 uint64_t sect_addr = info->S.getAddress();
2036 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002037 auto Reloc =
2038 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2039 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002040 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002041 return RelocOffset == sect_offset;
2042 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002043
David Blaikie33dd45d02015-03-23 18:39:02 +00002044 if (Reloc == info->S.relocations().end())
2045 return 0;
2046
2047 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2048 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2049 uint32_t r_type = info->O->getAnyRelocationType(RE);
2050 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2051 DataRefImpl RelNext = Rel;
2052 info->O->moveRelocationNext(RelNext);
2053 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2054 if (value == 0) {
2055 value = info->O->getPlainRelocationSymbolNum(RENext);
2056 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002057 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002058 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002059 // NOTE: Scattered relocations don't exist on arm64.
2060 if (!info->O->getPlainRelocationExternal(RE))
2061 return 0;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002062 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2063 if (std::error_code EC = SymName.getError())
2064 report_fatal_error(EC.message());
2065 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002066 op_info->AddSymbol.Present = 1;
2067 op_info->AddSymbol.Name = name;
2068
2069 switch (r_type) {
2070 case MachO::ARM64_RELOC_PAGE21:
2071 /* @page */
2072 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2073 break;
2074 case MachO::ARM64_RELOC_PAGEOFF12:
2075 /* @pageoff */
2076 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2077 break;
2078 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2079 /* @gotpage */
2080 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2081 break;
2082 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2083 /* @gotpageoff */
2084 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2085 break;
2086 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2087 /* @tvlppage is not implemented in llvm-mc */
2088 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2089 break;
2090 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2091 /* @tvlppageoff is not implemented in llvm-mc */
2092 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2093 break;
2094 default:
2095 case MachO::ARM64_RELOC_BRANCH26:
2096 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2097 break;
2098 }
2099 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002100 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002101 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002102}
2103
Kevin Enderbybf246f52014-09-24 23:08:22 +00002104// GuessCstringPointer is passed the address of what might be a pointer to a
2105// literal string in a cstring section. If that address is in a cstring section
2106// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002107static const char *GuessCstringPointer(uint64_t ReferenceValue,
2108 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002109 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002110 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2111 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2112 for (unsigned J = 0; J < Seg.nsects; ++J) {
2113 MachO::section_64 Sec = info->O->getSection64(Load, J);
2114 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2115 if (section_type == MachO::S_CSTRING_LITERALS &&
2116 ReferenceValue >= Sec.addr &&
2117 ReferenceValue < Sec.addr + Sec.size) {
2118 uint64_t sect_offset = ReferenceValue - Sec.addr;
2119 uint64_t object_offset = Sec.offset + sect_offset;
2120 StringRef MachOContents = info->O->getData();
2121 uint64_t object_size = MachOContents.size();
2122 const char *object_addr = (const char *)MachOContents.data();
2123 if (object_offset < object_size) {
2124 const char *name = object_addr + object_offset;
2125 return name;
2126 } else {
2127 return nullptr;
2128 }
2129 }
2130 }
2131 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2132 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2133 for (unsigned J = 0; J < Seg.nsects; ++J) {
2134 MachO::section Sec = info->O->getSection(Load, J);
2135 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2136 if (section_type == MachO::S_CSTRING_LITERALS &&
2137 ReferenceValue >= Sec.addr &&
2138 ReferenceValue < Sec.addr + Sec.size) {
2139 uint64_t sect_offset = ReferenceValue - Sec.addr;
2140 uint64_t object_offset = Sec.offset + sect_offset;
2141 StringRef MachOContents = info->O->getData();
2142 uint64_t object_size = MachOContents.size();
2143 const char *object_addr = (const char *)MachOContents.data();
2144 if (object_offset < object_size) {
2145 const char *name = object_addr + object_offset;
2146 return name;
2147 } else {
2148 return nullptr;
2149 }
2150 }
2151 }
2152 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002153 }
2154 return nullptr;
2155}
2156
Kevin Enderby85974882014-09-26 22:20:44 +00002157// GuessIndirectSymbol returns the name of the indirect symbol for the
2158// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2159// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2160// symbol name being referenced by the stub or pointer.
2161static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2162 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002163 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2164 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002165 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002166 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2167 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2168 for (unsigned J = 0; J < Seg.nsects; ++J) {
2169 MachO::section_64 Sec = info->O->getSection64(Load, J);
2170 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2171 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2172 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2173 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2174 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2175 section_type == MachO::S_SYMBOL_STUBS) &&
2176 ReferenceValue >= Sec.addr &&
2177 ReferenceValue < Sec.addr + Sec.size) {
2178 uint32_t stride;
2179 if (section_type == MachO::S_SYMBOL_STUBS)
2180 stride = Sec.reserved2;
2181 else
2182 stride = 8;
2183 if (stride == 0)
2184 return nullptr;
2185 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2186 if (index < Dysymtab.nindirectsyms) {
2187 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002188 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002189 if (indirect_symbol < Symtab.nsyms) {
2190 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2191 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002192 ErrorOr<StringRef> SymName = Symbol.getName();
2193 if (std::error_code EC = SymName.getError())
2194 report_fatal_error(EC.message());
2195 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002196 return name;
2197 }
2198 }
2199 }
2200 }
2201 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2202 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2203 for (unsigned J = 0; J < Seg.nsects; ++J) {
2204 MachO::section Sec = info->O->getSection(Load, J);
2205 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2206 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2207 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2208 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2209 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2210 section_type == MachO::S_SYMBOL_STUBS) &&
2211 ReferenceValue >= Sec.addr &&
2212 ReferenceValue < Sec.addr + Sec.size) {
2213 uint32_t stride;
2214 if (section_type == MachO::S_SYMBOL_STUBS)
2215 stride = Sec.reserved2;
2216 else
2217 stride = 4;
2218 if (stride == 0)
2219 return nullptr;
2220 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2221 if (index < Dysymtab.nindirectsyms) {
2222 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002223 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002224 if (indirect_symbol < Symtab.nsyms) {
2225 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2226 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002227 ErrorOr<StringRef> SymName = Symbol.getName();
2228 if (std::error_code EC = SymName.getError())
2229 report_fatal_error(EC.message());
2230 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002231 return name;
2232 }
2233 }
2234 }
2235 }
2236 }
Kevin Enderby85974882014-09-26 22:20:44 +00002237 }
2238 return nullptr;
2239}
2240
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002241// method_reference() is called passing it the ReferenceName that might be
2242// a reference it to an Objective-C method call. If so then it allocates and
2243// assembles a method call string with the values last seen and saved in
2244// the DisassembleInfo's class_name and selector_name fields. This is saved
2245// into the method field of the info and any previous string is free'ed.
2246// Then the class_name field in the info is set to nullptr. The method call
2247// string is set into ReferenceName and ReferenceType is set to
2248// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2249// then both ReferenceType and ReferenceName are left unchanged.
2250static void method_reference(struct DisassembleInfo *info,
2251 uint64_t *ReferenceType,
2252 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002253 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002254 if (*ReferenceName != nullptr) {
2255 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002256 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002257 if (info->method != nullptr)
2258 free(info->method);
2259 if (info->class_name != nullptr) {
2260 info->method = (char *)malloc(5 + strlen(info->class_name) +
2261 strlen(info->selector_name));
2262 if (info->method != nullptr) {
2263 strcpy(info->method, "+[");
2264 strcat(info->method, info->class_name);
2265 strcat(info->method, " ");
2266 strcat(info->method, info->selector_name);
2267 strcat(info->method, "]");
2268 *ReferenceName = info->method;
2269 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2270 }
2271 } else {
2272 info->method = (char *)malloc(9 + strlen(info->selector_name));
2273 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002274 if (Arch == Triple::x86_64)
2275 strcpy(info->method, "-[%rdi ");
2276 else if (Arch == Triple::aarch64)
2277 strcpy(info->method, "-[x0 ");
2278 else
2279 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002280 strcat(info->method, info->selector_name);
2281 strcat(info->method, "]");
2282 *ReferenceName = info->method;
2283 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2284 }
2285 }
2286 info->class_name = nullptr;
2287 }
2288 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002289 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002290 if (info->method != nullptr)
2291 free(info->method);
2292 info->method = (char *)malloc(17 + strlen(info->selector_name));
2293 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002294 if (Arch == Triple::x86_64)
2295 strcpy(info->method, "-[[%rdi super] ");
2296 else if (Arch == Triple::aarch64)
2297 strcpy(info->method, "-[[x0 super] ");
2298 else
2299 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002300 strcat(info->method, info->selector_name);
2301 strcat(info->method, "]");
2302 *ReferenceName = info->method;
2303 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2304 }
2305 info->class_name = nullptr;
2306 }
2307 }
2308 }
2309}
2310
2311// GuessPointerPointer() is passed the address of what might be a pointer to
2312// a reference to an Objective-C class, selector, message ref or cfstring.
2313// If so the value of the pointer is returned and one of the booleans are set
2314// to true. If not zero is returned and all the booleans are set to false.
2315static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2316 struct DisassembleInfo *info,
2317 bool &classref, bool &selref, bool &msgref,
2318 bool &cfstring) {
2319 classref = false;
2320 selref = false;
2321 msgref = false;
2322 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002323 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002324 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2325 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2326 for (unsigned J = 0; J < Seg.nsects; ++J) {
2327 MachO::section_64 Sec = info->O->getSection64(Load, J);
2328 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2329 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2330 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2331 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2332 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2333 ReferenceValue >= Sec.addr &&
2334 ReferenceValue < Sec.addr + Sec.size) {
2335 uint64_t sect_offset = ReferenceValue - Sec.addr;
2336 uint64_t object_offset = Sec.offset + sect_offset;
2337 StringRef MachOContents = info->O->getData();
2338 uint64_t object_size = MachOContents.size();
2339 const char *object_addr = (const char *)MachOContents.data();
2340 if (object_offset < object_size) {
2341 uint64_t pointer_value;
2342 memcpy(&pointer_value, object_addr + object_offset,
2343 sizeof(uint64_t));
2344 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2345 sys::swapByteOrder(pointer_value);
2346 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2347 selref = true;
2348 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2349 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2350 classref = true;
2351 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2352 ReferenceValue + 8 < Sec.addr + Sec.size) {
2353 msgref = true;
2354 memcpy(&pointer_value, object_addr + object_offset + 8,
2355 sizeof(uint64_t));
2356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2357 sys::swapByteOrder(pointer_value);
2358 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2359 cfstring = true;
2360 return pointer_value;
2361 } else {
2362 return 0;
2363 }
2364 }
2365 }
2366 }
2367 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002368 }
2369 return 0;
2370}
2371
2372// get_pointer_64 returns a pointer to the bytes in the object file at the
2373// Address from a section in the Mach-O file. And indirectly returns the
2374// offset into the section, number of bytes left in the section past the offset
2375// and which section is was being referenced. If the Address is not in a
2376// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002377static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2378 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002379 DisassembleInfo *info,
2380 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002381 offset = 0;
2382 left = 0;
2383 S = SectionRef();
2384 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2385 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2386 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002387 if (SectSize == 0)
2388 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002389 if (objc_only) {
2390 StringRef SectName;
2391 ((*(info->Sections))[SectIdx]).getName(SectName);
2392 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2393 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2394 if (SegName != "__OBJC" && SectName != "__cstring")
2395 continue;
2396 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002397 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2398 S = (*(info->Sections))[SectIdx];
2399 offset = Address - SectAddress;
2400 left = SectSize - offset;
2401 StringRef SectContents;
2402 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2403 return SectContents.data() + offset;
2404 }
2405 }
2406 return nullptr;
2407}
2408
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002409static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2410 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002411 DisassembleInfo *info,
2412 bool objc_only = false) {
2413 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002414}
2415
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002416// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2417// the symbol indirectly through n_value. Based on the relocation information
2418// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002419// If no relocation information is found and a non-zero ReferenceValue for the
2420// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002421static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2422 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002423 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002424 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002425 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002426 return nullptr;
2427
2428 // See if there is an external relocation entry at the sect_offset.
2429 bool reloc_found = false;
2430 DataRefImpl Rel;
2431 MachO::any_relocation_info RE;
2432 bool isExtern = false;
2433 SymbolRef Symbol;
2434 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002435 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002436 if (RelocOffset == sect_offset) {
2437 Rel = Reloc.getRawDataRefImpl();
2438 RE = info->O->getRelocation(Rel);
2439 if (info->O->isRelocationScattered(RE))
2440 continue;
2441 isExtern = info->O->getPlainRelocationExternal(RE);
2442 if (isExtern) {
2443 symbol_iterator RelocSym = Reloc.getSymbol();
2444 Symbol = *RelocSym;
2445 }
2446 reloc_found = true;
2447 break;
2448 }
2449 }
2450 // If there is an external relocation entry for a symbol in this section
2451 // at this section_offset then use that symbol's value for the n_value
2452 // and return its name.
2453 const char *SymbolName = nullptr;
2454 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002455 n_value = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002456 ErrorOr<StringRef> NameOrError = Symbol.getName();
2457 if (std::error_code EC = NameOrError.getError())
2458 report_fatal_error(EC.message());
2459 StringRef Name = *NameOrError;
2460 if (!Name.empty()) {
2461 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002462 return SymbolName;
2463 }
2464 }
2465
2466 // TODO: For fully linked images, look through the external relocation
2467 // entries off the dynamic symtab command. For these the r_offset is from the
2468 // start of the first writeable segment in the Mach-O file. So the offset
2469 // to this section from that segment is passed to this routine by the caller,
2470 // as the database_offset. Which is the difference of the section's starting
2471 // address and the first writable segment.
2472 //
2473 // NOTE: need add passing the database_offset to this routine.
2474
Kevin Enderby0fc11822015-04-01 20:57:01 +00002475 // We did not find an external relocation entry so look up the ReferenceValue
2476 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002477 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002478
2479 return SymbolName;
2480}
2481
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002482static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2483 DisassembleInfo *info,
2484 uint32_t ReferenceValue) {
2485 uint64_t n_value64;
2486 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2487}
2488
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002489// These are structs in the Objective-C meta data and read to produce the
2490// comments for disassembly. While these are part of the ABI they are no
2491// public defintions. So the are here not in include/llvm/Support/MachO.h .
2492
2493// The cfstring object in a 64-bit Mach-O file.
2494struct cfstring64_t {
2495 uint64_t isa; // class64_t * (64-bit pointer)
2496 uint64_t flags; // flag bits
2497 uint64_t characters; // char * (64-bit pointer)
2498 uint64_t length; // number of non-NULL characters in above
2499};
2500
2501// The class object in a 64-bit Mach-O file.
2502struct class64_t {
2503 uint64_t isa; // class64_t * (64-bit pointer)
2504 uint64_t superclass; // class64_t * (64-bit pointer)
2505 uint64_t cache; // Cache (64-bit pointer)
2506 uint64_t vtable; // IMP * (64-bit pointer)
2507 uint64_t data; // class_ro64_t * (64-bit pointer)
2508};
2509
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002510struct class32_t {
2511 uint32_t isa; /* class32_t * (32-bit pointer) */
2512 uint32_t superclass; /* class32_t * (32-bit pointer) */
2513 uint32_t cache; /* Cache (32-bit pointer) */
2514 uint32_t vtable; /* IMP * (32-bit pointer) */
2515 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2516};
2517
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002518struct class_ro64_t {
2519 uint32_t flags;
2520 uint32_t instanceStart;
2521 uint32_t instanceSize;
2522 uint32_t reserved;
2523 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2524 uint64_t name; // const char * (64-bit pointer)
2525 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2526 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2527 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2528 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2529 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2530};
2531
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002532struct class_ro32_t {
2533 uint32_t flags;
2534 uint32_t instanceStart;
2535 uint32_t instanceSize;
2536 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2537 uint32_t name; /* const char * (32-bit pointer) */
2538 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2539 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2540 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2541 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2542 uint32_t baseProperties; /* const struct objc_property_list *
2543 (32-bit pointer) */
2544};
2545
2546/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002547#define RO_META (1 << 0)
2548#define RO_ROOT (1 << 1)
2549#define RO_HAS_CXX_STRUCTORS (1 << 2)
2550
2551struct method_list64_t {
2552 uint32_t entsize;
2553 uint32_t count;
2554 /* struct method64_t first; These structures follow inline */
2555};
2556
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002557struct method_list32_t {
2558 uint32_t entsize;
2559 uint32_t count;
2560 /* struct method32_t first; These structures follow inline */
2561};
2562
Kevin Enderby0fc11822015-04-01 20:57:01 +00002563struct method64_t {
2564 uint64_t name; /* SEL (64-bit pointer) */
2565 uint64_t types; /* const char * (64-bit pointer) */
2566 uint64_t imp; /* IMP (64-bit pointer) */
2567};
2568
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002569struct method32_t {
2570 uint32_t name; /* SEL (32-bit pointer) */
2571 uint32_t types; /* const char * (32-bit pointer) */
2572 uint32_t imp; /* IMP (32-bit pointer) */
2573};
2574
Kevin Enderby0fc11822015-04-01 20:57:01 +00002575struct protocol_list64_t {
2576 uint64_t count; /* uintptr_t (a 64-bit value) */
2577 /* struct protocol64_t * list[0]; These pointers follow inline */
2578};
2579
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002580struct protocol_list32_t {
2581 uint32_t count; /* uintptr_t (a 32-bit value) */
2582 /* struct protocol32_t * list[0]; These pointers follow inline */
2583};
2584
Kevin Enderby0fc11822015-04-01 20:57:01 +00002585struct protocol64_t {
2586 uint64_t isa; /* id * (64-bit pointer) */
2587 uint64_t name; /* const char * (64-bit pointer) */
2588 uint64_t protocols; /* struct protocol_list64_t *
2589 (64-bit pointer) */
2590 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2591 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2592 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2593 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2594 uint64_t instanceProperties; /* struct objc_property_list *
2595 (64-bit pointer) */
2596};
2597
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002598struct protocol32_t {
2599 uint32_t isa; /* id * (32-bit pointer) */
2600 uint32_t name; /* const char * (32-bit pointer) */
2601 uint32_t protocols; /* struct protocol_list_t *
2602 (32-bit pointer) */
2603 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2604 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2605 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2606 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2607 uint32_t instanceProperties; /* struct objc_property_list *
2608 (32-bit pointer) */
2609};
2610
Kevin Enderby0fc11822015-04-01 20:57:01 +00002611struct ivar_list64_t {
2612 uint32_t entsize;
2613 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002614 /* struct ivar64_t first; These structures follow inline */
2615};
2616
2617struct ivar_list32_t {
2618 uint32_t entsize;
2619 uint32_t count;
2620 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002621};
2622
2623struct ivar64_t {
2624 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2625 uint64_t name; /* const char * (64-bit pointer) */
2626 uint64_t type; /* const char * (64-bit pointer) */
2627 uint32_t alignment;
2628 uint32_t size;
2629};
2630
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002631struct ivar32_t {
2632 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2633 uint32_t name; /* const char * (32-bit pointer) */
2634 uint32_t type; /* const char * (32-bit pointer) */
2635 uint32_t alignment;
2636 uint32_t size;
2637};
2638
Kevin Enderby0fc11822015-04-01 20:57:01 +00002639struct objc_property_list64 {
2640 uint32_t entsize;
2641 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002642 /* struct objc_property64 first; These structures follow inline */
2643};
2644
2645struct objc_property_list32 {
2646 uint32_t entsize;
2647 uint32_t count;
2648 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002649};
2650
2651struct objc_property64 {
2652 uint64_t name; /* const char * (64-bit pointer) */
2653 uint64_t attributes; /* const char * (64-bit pointer) */
2654};
2655
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002656struct objc_property32 {
2657 uint32_t name; /* const char * (32-bit pointer) */
2658 uint32_t attributes; /* const char * (32-bit pointer) */
2659};
2660
Kevin Enderby0fc11822015-04-01 20:57:01 +00002661struct category64_t {
2662 uint64_t name; /* const char * (64-bit pointer) */
2663 uint64_t cls; /* struct class_t * (64-bit pointer) */
2664 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2665 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2666 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2667 uint64_t instanceProperties; /* struct objc_property_list *
2668 (64-bit pointer) */
2669};
2670
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002671struct category32_t {
2672 uint32_t name; /* const char * (32-bit pointer) */
2673 uint32_t cls; /* struct class_t * (32-bit pointer) */
2674 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2675 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2676 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2677 uint32_t instanceProperties; /* struct objc_property_list *
2678 (32-bit pointer) */
2679};
2680
Kevin Enderby0fc11822015-04-01 20:57:01 +00002681struct objc_image_info64 {
2682 uint32_t version;
2683 uint32_t flags;
2684};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002685struct objc_image_info32 {
2686 uint32_t version;
2687 uint32_t flags;
2688};
Kevin Enderby846c0002015-04-16 17:19:59 +00002689struct imageInfo_t {
2690 uint32_t version;
2691 uint32_t flags;
2692};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002693/* masks for objc_image_info.flags */
2694#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2695#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2696
2697struct message_ref64 {
2698 uint64_t imp; /* IMP (64-bit pointer) */
2699 uint64_t sel; /* SEL (64-bit pointer) */
2700};
2701
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002702struct message_ref32 {
2703 uint32_t imp; /* IMP (32-bit pointer) */
2704 uint32_t sel; /* SEL (32-bit pointer) */
2705};
2706
Kevin Enderby846c0002015-04-16 17:19:59 +00002707// Objective-C 1 (32-bit only) meta data structs.
2708
2709struct objc_module_t {
2710 uint32_t version;
2711 uint32_t size;
2712 uint32_t name; /* char * (32-bit pointer) */
2713 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2714};
2715
2716struct objc_symtab_t {
2717 uint32_t sel_ref_cnt;
2718 uint32_t refs; /* SEL * (32-bit pointer) */
2719 uint16_t cls_def_cnt;
2720 uint16_t cat_def_cnt;
2721 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2722};
2723
2724struct objc_class_t {
2725 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2726 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2727 uint32_t name; /* const char * (32-bit pointer) */
2728 int32_t version;
2729 int32_t info;
2730 int32_t instance_size;
2731 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2732 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2733 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2734 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2735};
2736
2737#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2738// class is not a metaclass
2739#define CLS_CLASS 0x1
2740// class is a metaclass
2741#define CLS_META 0x2
2742
2743struct objc_category_t {
2744 uint32_t category_name; /* char * (32-bit pointer) */
2745 uint32_t class_name; /* char * (32-bit pointer) */
2746 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2747 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2748 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2749};
2750
2751struct objc_ivar_t {
2752 uint32_t ivar_name; /* char * (32-bit pointer) */
2753 uint32_t ivar_type; /* char * (32-bit pointer) */
2754 int32_t ivar_offset;
2755};
2756
2757struct objc_ivar_list_t {
2758 int32_t ivar_count;
2759 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2760};
2761
2762struct objc_method_list_t {
2763 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2764 int32_t method_count;
2765 // struct objc_method_t method_list[1]; /* variable length structure */
2766};
2767
2768struct objc_method_t {
2769 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2770 uint32_t method_types; /* char * (32-bit pointer) */
2771 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2772 (32-bit pointer) */
2773};
2774
2775struct objc_protocol_list_t {
2776 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2777 int32_t count;
2778 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2779 // (32-bit pointer) */
2780};
2781
2782struct objc_protocol_t {
2783 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2784 uint32_t protocol_name; /* char * (32-bit pointer) */
2785 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2786 uint32_t instance_methods; /* struct objc_method_description_list *
2787 (32-bit pointer) */
2788 uint32_t class_methods; /* struct objc_method_description_list *
2789 (32-bit pointer) */
2790};
2791
2792struct objc_method_description_list_t {
2793 int32_t count;
2794 // struct objc_method_description_t list[1];
2795};
2796
2797struct objc_method_description_t {
2798 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2799 uint32_t types; /* char * (32-bit pointer) */
2800};
2801
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002802inline void swapStruct(struct cfstring64_t &cfs) {
2803 sys::swapByteOrder(cfs.isa);
2804 sys::swapByteOrder(cfs.flags);
2805 sys::swapByteOrder(cfs.characters);
2806 sys::swapByteOrder(cfs.length);
2807}
2808
2809inline void swapStruct(struct class64_t &c) {
2810 sys::swapByteOrder(c.isa);
2811 sys::swapByteOrder(c.superclass);
2812 sys::swapByteOrder(c.cache);
2813 sys::swapByteOrder(c.vtable);
2814 sys::swapByteOrder(c.data);
2815}
2816
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002817inline void swapStruct(struct class32_t &c) {
2818 sys::swapByteOrder(c.isa);
2819 sys::swapByteOrder(c.superclass);
2820 sys::swapByteOrder(c.cache);
2821 sys::swapByteOrder(c.vtable);
2822 sys::swapByteOrder(c.data);
2823}
2824
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002825inline void swapStruct(struct class_ro64_t &cro) {
2826 sys::swapByteOrder(cro.flags);
2827 sys::swapByteOrder(cro.instanceStart);
2828 sys::swapByteOrder(cro.instanceSize);
2829 sys::swapByteOrder(cro.reserved);
2830 sys::swapByteOrder(cro.ivarLayout);
2831 sys::swapByteOrder(cro.name);
2832 sys::swapByteOrder(cro.baseMethods);
2833 sys::swapByteOrder(cro.baseProtocols);
2834 sys::swapByteOrder(cro.ivars);
2835 sys::swapByteOrder(cro.weakIvarLayout);
2836 sys::swapByteOrder(cro.baseProperties);
2837}
2838
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002839inline void swapStruct(struct class_ro32_t &cro) {
2840 sys::swapByteOrder(cro.flags);
2841 sys::swapByteOrder(cro.instanceStart);
2842 sys::swapByteOrder(cro.instanceSize);
2843 sys::swapByteOrder(cro.ivarLayout);
2844 sys::swapByteOrder(cro.name);
2845 sys::swapByteOrder(cro.baseMethods);
2846 sys::swapByteOrder(cro.baseProtocols);
2847 sys::swapByteOrder(cro.ivars);
2848 sys::swapByteOrder(cro.weakIvarLayout);
2849 sys::swapByteOrder(cro.baseProperties);
2850}
2851
Kevin Enderby0fc11822015-04-01 20:57:01 +00002852inline void swapStruct(struct method_list64_t &ml) {
2853 sys::swapByteOrder(ml.entsize);
2854 sys::swapByteOrder(ml.count);
2855}
2856
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002857inline void swapStruct(struct method_list32_t &ml) {
2858 sys::swapByteOrder(ml.entsize);
2859 sys::swapByteOrder(ml.count);
2860}
2861
Kevin Enderby0fc11822015-04-01 20:57:01 +00002862inline void swapStruct(struct method64_t &m) {
2863 sys::swapByteOrder(m.name);
2864 sys::swapByteOrder(m.types);
2865 sys::swapByteOrder(m.imp);
2866}
2867
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002868inline void swapStruct(struct method32_t &m) {
2869 sys::swapByteOrder(m.name);
2870 sys::swapByteOrder(m.types);
2871 sys::swapByteOrder(m.imp);
2872}
2873
Kevin Enderby0fc11822015-04-01 20:57:01 +00002874inline void swapStruct(struct protocol_list64_t &pl) {
2875 sys::swapByteOrder(pl.count);
2876}
2877
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002878inline void swapStruct(struct protocol_list32_t &pl) {
2879 sys::swapByteOrder(pl.count);
2880}
2881
Kevin Enderby0fc11822015-04-01 20:57:01 +00002882inline void swapStruct(struct protocol64_t &p) {
2883 sys::swapByteOrder(p.isa);
2884 sys::swapByteOrder(p.name);
2885 sys::swapByteOrder(p.protocols);
2886 sys::swapByteOrder(p.instanceMethods);
2887 sys::swapByteOrder(p.classMethods);
2888 sys::swapByteOrder(p.optionalInstanceMethods);
2889 sys::swapByteOrder(p.optionalClassMethods);
2890 sys::swapByteOrder(p.instanceProperties);
2891}
2892
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002893inline void swapStruct(struct protocol32_t &p) {
2894 sys::swapByteOrder(p.isa);
2895 sys::swapByteOrder(p.name);
2896 sys::swapByteOrder(p.protocols);
2897 sys::swapByteOrder(p.instanceMethods);
2898 sys::swapByteOrder(p.classMethods);
2899 sys::swapByteOrder(p.optionalInstanceMethods);
2900 sys::swapByteOrder(p.optionalClassMethods);
2901 sys::swapByteOrder(p.instanceProperties);
2902}
2903
Kevin Enderby0fc11822015-04-01 20:57:01 +00002904inline void swapStruct(struct ivar_list64_t &il) {
2905 sys::swapByteOrder(il.entsize);
2906 sys::swapByteOrder(il.count);
2907}
2908
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002909inline void swapStruct(struct ivar_list32_t &il) {
2910 sys::swapByteOrder(il.entsize);
2911 sys::swapByteOrder(il.count);
2912}
2913
Kevin Enderby0fc11822015-04-01 20:57:01 +00002914inline void swapStruct(struct ivar64_t &i) {
2915 sys::swapByteOrder(i.offset);
2916 sys::swapByteOrder(i.name);
2917 sys::swapByteOrder(i.type);
2918 sys::swapByteOrder(i.alignment);
2919 sys::swapByteOrder(i.size);
2920}
2921
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002922inline void swapStruct(struct ivar32_t &i) {
2923 sys::swapByteOrder(i.offset);
2924 sys::swapByteOrder(i.name);
2925 sys::swapByteOrder(i.type);
2926 sys::swapByteOrder(i.alignment);
2927 sys::swapByteOrder(i.size);
2928}
2929
Kevin Enderby0fc11822015-04-01 20:57:01 +00002930inline void swapStruct(struct objc_property_list64 &pl) {
2931 sys::swapByteOrder(pl.entsize);
2932 sys::swapByteOrder(pl.count);
2933}
2934
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002935inline void swapStruct(struct objc_property_list32 &pl) {
2936 sys::swapByteOrder(pl.entsize);
2937 sys::swapByteOrder(pl.count);
2938}
2939
Kevin Enderby0fc11822015-04-01 20:57:01 +00002940inline void swapStruct(struct objc_property64 &op) {
2941 sys::swapByteOrder(op.name);
2942 sys::swapByteOrder(op.attributes);
2943}
2944
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002945inline void swapStruct(struct objc_property32 &op) {
2946 sys::swapByteOrder(op.name);
2947 sys::swapByteOrder(op.attributes);
2948}
2949
Kevin Enderby0fc11822015-04-01 20:57:01 +00002950inline void swapStruct(struct category64_t &c) {
2951 sys::swapByteOrder(c.name);
2952 sys::swapByteOrder(c.cls);
2953 sys::swapByteOrder(c.instanceMethods);
2954 sys::swapByteOrder(c.classMethods);
2955 sys::swapByteOrder(c.protocols);
2956 sys::swapByteOrder(c.instanceProperties);
2957}
2958
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002959inline void swapStruct(struct category32_t &c) {
2960 sys::swapByteOrder(c.name);
2961 sys::swapByteOrder(c.cls);
2962 sys::swapByteOrder(c.instanceMethods);
2963 sys::swapByteOrder(c.classMethods);
2964 sys::swapByteOrder(c.protocols);
2965 sys::swapByteOrder(c.instanceProperties);
2966}
2967
Kevin Enderby0fc11822015-04-01 20:57:01 +00002968inline void swapStruct(struct objc_image_info64 &o) {
2969 sys::swapByteOrder(o.version);
2970 sys::swapByteOrder(o.flags);
2971}
2972
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002973inline void swapStruct(struct objc_image_info32 &o) {
2974 sys::swapByteOrder(o.version);
2975 sys::swapByteOrder(o.flags);
2976}
2977
Kevin Enderby846c0002015-04-16 17:19:59 +00002978inline void swapStruct(struct imageInfo_t &o) {
2979 sys::swapByteOrder(o.version);
2980 sys::swapByteOrder(o.flags);
2981}
2982
Kevin Enderby0fc11822015-04-01 20:57:01 +00002983inline void swapStruct(struct message_ref64 &mr) {
2984 sys::swapByteOrder(mr.imp);
2985 sys::swapByteOrder(mr.sel);
2986}
2987
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002988inline void swapStruct(struct message_ref32 &mr) {
2989 sys::swapByteOrder(mr.imp);
2990 sys::swapByteOrder(mr.sel);
2991}
2992
Kevin Enderby846c0002015-04-16 17:19:59 +00002993inline void swapStruct(struct objc_module_t &module) {
2994 sys::swapByteOrder(module.version);
2995 sys::swapByteOrder(module.size);
2996 sys::swapByteOrder(module.name);
2997 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00002998}
Kevin Enderby846c0002015-04-16 17:19:59 +00002999
3000inline void swapStruct(struct objc_symtab_t &symtab) {
3001 sys::swapByteOrder(symtab.sel_ref_cnt);
3002 sys::swapByteOrder(symtab.refs);
3003 sys::swapByteOrder(symtab.cls_def_cnt);
3004 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003005}
Kevin Enderby846c0002015-04-16 17:19:59 +00003006
3007inline void swapStruct(struct objc_class_t &objc_class) {
3008 sys::swapByteOrder(objc_class.isa);
3009 sys::swapByteOrder(objc_class.super_class);
3010 sys::swapByteOrder(objc_class.name);
3011 sys::swapByteOrder(objc_class.version);
3012 sys::swapByteOrder(objc_class.info);
3013 sys::swapByteOrder(objc_class.instance_size);
3014 sys::swapByteOrder(objc_class.ivars);
3015 sys::swapByteOrder(objc_class.methodLists);
3016 sys::swapByteOrder(objc_class.cache);
3017 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003018}
Kevin Enderby846c0002015-04-16 17:19:59 +00003019
3020inline void swapStruct(struct objc_category_t &objc_category) {
3021 sys::swapByteOrder(objc_category.category_name);
3022 sys::swapByteOrder(objc_category.class_name);
3023 sys::swapByteOrder(objc_category.instance_methods);
3024 sys::swapByteOrder(objc_category.class_methods);
3025 sys::swapByteOrder(objc_category.protocols);
3026}
3027
3028inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3029 sys::swapByteOrder(objc_ivar_list.ivar_count);
3030}
3031
3032inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3033 sys::swapByteOrder(objc_ivar.ivar_name);
3034 sys::swapByteOrder(objc_ivar.ivar_type);
3035 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003036}
Kevin Enderby846c0002015-04-16 17:19:59 +00003037
3038inline void swapStruct(struct objc_method_list_t &method_list) {
3039 sys::swapByteOrder(method_list.obsolete);
3040 sys::swapByteOrder(method_list.method_count);
3041}
3042
3043inline void swapStruct(struct objc_method_t &method) {
3044 sys::swapByteOrder(method.method_name);
3045 sys::swapByteOrder(method.method_types);
3046 sys::swapByteOrder(method.method_imp);
3047}
3048
3049inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3050 sys::swapByteOrder(protocol_list.next);
3051 sys::swapByteOrder(protocol_list.count);
3052}
3053
3054inline void swapStruct(struct objc_protocol_t &protocol) {
3055 sys::swapByteOrder(protocol.isa);
3056 sys::swapByteOrder(protocol.protocol_name);
3057 sys::swapByteOrder(protocol.protocol_list);
3058 sys::swapByteOrder(protocol.instance_methods);
3059 sys::swapByteOrder(protocol.class_methods);
3060}
3061
3062inline void swapStruct(struct objc_method_description_list_t &mdl) {
3063 sys::swapByteOrder(mdl.count);
3064}
3065
3066inline void swapStruct(struct objc_method_description_t &md) {
3067 sys::swapByteOrder(md.name);
3068 sys::swapByteOrder(md.types);
3069}
3070
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003071static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3072 struct DisassembleInfo *info);
3073
3074// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3075// to an Objective-C class and returns the class name. It is also passed the
3076// address of the pointer, so when the pointer is zero as it can be in an .o
3077// file, that is used to look for an external relocation entry with a symbol
3078// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003079static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3080 uint64_t ReferenceValue,
3081 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003082 const char *r;
3083 uint32_t offset, left;
3084 SectionRef S;
3085
3086 // The pointer_value can be 0 in an object file and have a relocation
3087 // entry for the class symbol at the ReferenceValue (the address of the
3088 // pointer).
3089 if (pointer_value == 0) {
3090 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3091 if (r == nullptr || left < sizeof(uint64_t))
3092 return nullptr;
3093 uint64_t n_value;
3094 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3095 if (symbol_name == nullptr)
3096 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003097 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003098 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3099 return class_name + 2;
3100 else
3101 return nullptr;
3102 }
3103
3104 // The case were the pointer_value is non-zero and points to a class defined
3105 // in this Mach-O file.
3106 r = get_pointer_64(pointer_value, offset, left, S, info);
3107 if (r == nullptr || left < sizeof(struct class64_t))
3108 return nullptr;
3109 struct class64_t c;
3110 memcpy(&c, r, sizeof(struct class64_t));
3111 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3112 swapStruct(c);
3113 if (c.data == 0)
3114 return nullptr;
3115 r = get_pointer_64(c.data, offset, left, S, info);
3116 if (r == nullptr || left < sizeof(struct class_ro64_t))
3117 return nullptr;
3118 struct class_ro64_t cro;
3119 memcpy(&cro, r, sizeof(struct class_ro64_t));
3120 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3121 swapStruct(cro);
3122 if (cro.name == 0)
3123 return nullptr;
3124 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3125 return name;
3126}
3127
3128// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3129// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003130static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3131 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003132 const char *r, *name;
3133 uint32_t offset, left;
3134 SectionRef S;
3135 struct cfstring64_t cfs;
3136 uint64_t cfs_characters;
3137
3138 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3139 if (r == nullptr || left < sizeof(struct cfstring64_t))
3140 return nullptr;
3141 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3142 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3143 swapStruct(cfs);
3144 if (cfs.characters == 0) {
3145 uint64_t n_value;
3146 const char *symbol_name = get_symbol_64(
3147 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3148 if (symbol_name == nullptr)
3149 return nullptr;
3150 cfs_characters = n_value;
3151 } else
3152 cfs_characters = cfs.characters;
3153 name = get_pointer_64(cfs_characters, offset, left, S, info);
3154
3155 return name;
3156}
3157
3158// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3159// of a pointer to an Objective-C selector reference when the pointer value is
3160// zero as in a .o file and is likely to have a external relocation entry with
3161// who's symbol's n_value is the real pointer to the selector name. If that is
3162// the case the real pointer to the selector name is returned else 0 is
3163// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003164static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3165 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003166 uint32_t offset, left;
3167 SectionRef S;
3168
3169 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3170 if (r == nullptr || left < sizeof(uint64_t))
3171 return 0;
3172 uint64_t n_value;
3173 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3174 if (symbol_name == nullptr)
3175 return 0;
3176 return n_value;
3177}
3178
Kevin Enderby0fc11822015-04-01 20:57:01 +00003179static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3180 const char *sectname) {
3181 for (const SectionRef &Section : O->sections()) {
3182 StringRef SectName;
3183 Section.getName(SectName);
3184 DataRefImpl Ref = Section.getRawDataRefImpl();
3185 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3186 if (SegName == segname && SectName == sectname)
3187 return Section;
3188 }
3189 return SectionRef();
3190}
3191
3192static void
3193walk_pointer_list_64(const char *listname, const SectionRef S,
3194 MachOObjectFile *O, struct DisassembleInfo *info,
3195 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3196 if (S == SectionRef())
3197 return;
3198
3199 StringRef SectName;
3200 S.getName(SectName);
3201 DataRefImpl Ref = S.getRawDataRefImpl();
3202 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3203 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3204
3205 StringRef BytesStr;
3206 S.getContents(BytesStr);
3207 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3208
3209 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3210 uint32_t left = S.getSize() - i;
3211 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3212 uint64_t p = 0;
3213 memcpy(&p, Contents + i, size);
3214 if (i + sizeof(uint64_t) > S.getSize())
3215 outs() << listname << " list pointer extends past end of (" << SegName
3216 << "," << SectName << ") section\n";
3217 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3218
3219 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3220 sys::swapByteOrder(p);
3221
3222 uint64_t n_value = 0;
3223 const char *name = get_symbol_64(i, S, info, n_value, p);
3224 if (name == nullptr)
3225 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3226
3227 if (n_value != 0) {
3228 outs() << format("0x%" PRIx64, n_value);
3229 if (p != 0)
3230 outs() << " + " << format("0x%" PRIx64, p);
3231 } else
3232 outs() << format("0x%" PRIx64, p);
3233 if (name != nullptr)
3234 outs() << " " << name;
3235 outs() << "\n";
3236
3237 p += n_value;
3238 if (func)
3239 func(p, info);
3240 }
3241}
3242
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003243static void
3244walk_pointer_list_32(const char *listname, const SectionRef S,
3245 MachOObjectFile *O, struct DisassembleInfo *info,
3246 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3247 if (S == SectionRef())
3248 return;
3249
3250 StringRef SectName;
3251 S.getName(SectName);
3252 DataRefImpl Ref = S.getRawDataRefImpl();
3253 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3254 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3255
3256 StringRef BytesStr;
3257 S.getContents(BytesStr);
3258 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3259
3260 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3261 uint32_t left = S.getSize() - i;
3262 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3263 uint32_t p = 0;
3264 memcpy(&p, Contents + i, size);
3265 if (i + sizeof(uint32_t) > S.getSize())
3266 outs() << listname << " list pointer extends past end of (" << SegName
3267 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003268 uint32_t Address = S.getAddress() + i;
3269 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003270
3271 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3272 sys::swapByteOrder(p);
3273 outs() << format("0x%" PRIx32, p);
3274
3275 const char *name = get_symbol_32(i, S, info, p);
3276 if (name != nullptr)
3277 outs() << " " << name;
3278 outs() << "\n";
3279
3280 if (func)
3281 func(p, info);
3282 }
3283}
3284
3285static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003286 if (layout_map == nullptr)
3287 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003288 outs() << " layout map: ";
3289 do {
3290 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3291 left--;
3292 layout_map++;
3293 } while (*layout_map != '\0' && left != 0);
3294 outs() << "\n";
3295}
3296
Kevin Enderby0fc11822015-04-01 20:57:01 +00003297static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3298 uint32_t offset, left;
3299 SectionRef S;
3300 const char *layout_map;
3301
3302 if (p == 0)
3303 return;
3304 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003305 print_layout_map(layout_map, left);
3306}
3307
3308static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3309 uint32_t offset, left;
3310 SectionRef S;
3311 const char *layout_map;
3312
3313 if (p == 0)
3314 return;
3315 layout_map = get_pointer_32(p, offset, left, S, info);
3316 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003317}
3318
3319static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3320 const char *indent) {
3321 struct method_list64_t ml;
3322 struct method64_t m;
3323 const char *r;
3324 uint32_t offset, xoffset, left, i;
3325 SectionRef S, xS;
3326 const char *name, *sym_name;
3327 uint64_t n_value;
3328
3329 r = get_pointer_64(p, offset, left, S, info);
3330 if (r == nullptr)
3331 return;
3332 memset(&ml, '\0', sizeof(struct method_list64_t));
3333 if (left < sizeof(struct method_list64_t)) {
3334 memcpy(&ml, r, left);
3335 outs() << " (method_list_t entends past the end of the section)\n";
3336 } else
3337 memcpy(&ml, r, sizeof(struct method_list64_t));
3338 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3339 swapStruct(ml);
3340 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3341 outs() << indent << "\t\t count " << ml.count << "\n";
3342
3343 p += sizeof(struct method_list64_t);
3344 offset += sizeof(struct method_list64_t);
3345 for (i = 0; i < ml.count; i++) {
3346 r = get_pointer_64(p, offset, left, S, info);
3347 if (r == nullptr)
3348 return;
3349 memset(&m, '\0', sizeof(struct method64_t));
3350 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003351 memcpy(&m, r, left);
3352 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003353 } else
3354 memcpy(&m, r, sizeof(struct method64_t));
3355 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3356 swapStruct(m);
3357
3358 outs() << indent << "\t\t name ";
3359 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3360 info, n_value, m.name);
3361 if (n_value != 0) {
3362 if (info->verbose && sym_name != nullptr)
3363 outs() << sym_name;
3364 else
3365 outs() << format("0x%" PRIx64, n_value);
3366 if (m.name != 0)
3367 outs() << " + " << format("0x%" PRIx64, m.name);
3368 } else
3369 outs() << format("0x%" PRIx64, m.name);
3370 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3371 if (name != nullptr)
3372 outs() << format(" %.*s", left, name);
3373 outs() << "\n";
3374
3375 outs() << indent << "\t\t types ";
3376 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3377 info, n_value, m.types);
3378 if (n_value != 0) {
3379 if (info->verbose && sym_name != nullptr)
3380 outs() << sym_name;
3381 else
3382 outs() << format("0x%" PRIx64, n_value);
3383 if (m.types != 0)
3384 outs() << " + " << format("0x%" PRIx64, m.types);
3385 } else
3386 outs() << format("0x%" PRIx64, m.types);
3387 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3388 if (name != nullptr)
3389 outs() << format(" %.*s", left, name);
3390 outs() << "\n";
3391
3392 outs() << indent << "\t\t imp ";
3393 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3394 n_value, m.imp);
3395 if (info->verbose && name == nullptr) {
3396 if (n_value != 0) {
3397 outs() << format("0x%" PRIx64, n_value) << " ";
3398 if (m.imp != 0)
3399 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3400 } else
3401 outs() << format("0x%" PRIx64, m.imp) << " ";
3402 }
3403 if (name != nullptr)
3404 outs() << name;
3405 outs() << "\n";
3406
3407 p += sizeof(struct method64_t);
3408 offset += sizeof(struct method64_t);
3409 }
3410}
3411
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003412static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3413 const char *indent) {
3414 struct method_list32_t ml;
3415 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003416 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003417 uint32_t offset, xoffset, left, i;
3418 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003419
3420 r = get_pointer_32(p, offset, left, S, info);
3421 if (r == nullptr)
3422 return;
3423 memset(&ml, '\0', sizeof(struct method_list32_t));
3424 if (left < sizeof(struct method_list32_t)) {
3425 memcpy(&ml, r, left);
3426 outs() << " (method_list_t entends past the end of the section)\n";
3427 } else
3428 memcpy(&ml, r, sizeof(struct method_list32_t));
3429 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3430 swapStruct(ml);
3431 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3432 outs() << indent << "\t\t count " << ml.count << "\n";
3433
3434 p += sizeof(struct method_list32_t);
3435 offset += sizeof(struct method_list32_t);
3436 for (i = 0; i < ml.count; i++) {
3437 r = get_pointer_32(p, offset, left, S, info);
3438 if (r == nullptr)
3439 return;
3440 memset(&m, '\0', sizeof(struct method32_t));
3441 if (left < sizeof(struct method32_t)) {
3442 memcpy(&ml, r, left);
3443 outs() << indent << " (method_t entends past the end of the section)\n";
3444 } else
3445 memcpy(&m, r, sizeof(struct method32_t));
3446 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3447 swapStruct(m);
3448
3449 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3450 name = get_pointer_32(m.name, xoffset, left, xS, info);
3451 if (name != nullptr)
3452 outs() << format(" %.*s", left, name);
3453 outs() << "\n";
3454
3455 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3456 name = get_pointer_32(m.types, xoffset, left, xS, info);
3457 if (name != nullptr)
3458 outs() << format(" %.*s", left, name);
3459 outs() << "\n";
3460
3461 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3462 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3463 m.imp);
3464 if (name != nullptr)
3465 outs() << " " << name;
3466 outs() << "\n";
3467
3468 p += sizeof(struct method32_t);
3469 offset += sizeof(struct method32_t);
3470 }
3471}
3472
Kevin Enderby846c0002015-04-16 17:19:59 +00003473static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3474 uint32_t offset, left, xleft;
3475 SectionRef S;
3476 struct objc_method_list_t method_list;
3477 struct objc_method_t method;
3478 const char *r, *methods, *name, *SymbolName;
3479 int32_t i;
3480
3481 r = get_pointer_32(p, offset, left, S, info, true);
3482 if (r == nullptr)
3483 return true;
3484
3485 outs() << "\n";
3486 if (left > sizeof(struct objc_method_list_t)) {
3487 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3488 } else {
3489 outs() << "\t\t objc_method_list extends past end of the section\n";
3490 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3491 memcpy(&method_list, r, left);
3492 }
3493 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3494 swapStruct(method_list);
3495
3496 outs() << "\t\t obsolete "
3497 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3498 outs() << "\t\t method_count " << method_list.method_count << "\n";
3499
3500 methods = r + sizeof(struct objc_method_list_t);
3501 for (i = 0; i < method_list.method_count; i++) {
3502 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3503 outs() << "\t\t remaining method's extend past the of the section\n";
3504 break;
3505 }
3506 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3507 sizeof(struct objc_method_t));
3508 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3509 swapStruct(method);
3510
3511 outs() << "\t\t method_name "
3512 << format("0x%08" PRIx32, method.method_name);
3513 if (info->verbose) {
3514 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3515 if (name != nullptr)
3516 outs() << format(" %.*s", xleft, name);
3517 else
3518 outs() << " (not in an __OBJC section)";
3519 }
3520 outs() << "\n";
3521
3522 outs() << "\t\t method_types "
3523 << format("0x%08" PRIx32, method.method_types);
3524 if (info->verbose) {
3525 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3526 if (name != nullptr)
3527 outs() << format(" %.*s", xleft, name);
3528 else
3529 outs() << " (not in an __OBJC section)";
3530 }
3531 outs() << "\n";
3532
3533 outs() << "\t\t method_imp "
3534 << format("0x%08" PRIx32, method.method_imp) << " ";
3535 if (info->verbose) {
3536 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3537 if (SymbolName != nullptr)
3538 outs() << SymbolName;
3539 }
3540 outs() << "\n";
3541 }
3542 return false;
3543}
3544
Kevin Enderby0fc11822015-04-01 20:57:01 +00003545static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3546 struct protocol_list64_t pl;
3547 uint64_t q, n_value;
3548 struct protocol64_t pc;
3549 const char *r;
3550 uint32_t offset, xoffset, left, i;
3551 SectionRef S, xS;
3552 const char *name, *sym_name;
3553
3554 r = get_pointer_64(p, offset, left, S, info);
3555 if (r == nullptr)
3556 return;
3557 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3558 if (left < sizeof(struct protocol_list64_t)) {
3559 memcpy(&pl, r, left);
3560 outs() << " (protocol_list_t entends past the end of the section)\n";
3561 } else
3562 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3563 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3564 swapStruct(pl);
3565 outs() << " count " << pl.count << "\n";
3566
3567 p += sizeof(struct protocol_list64_t);
3568 offset += sizeof(struct protocol_list64_t);
3569 for (i = 0; i < pl.count; i++) {
3570 r = get_pointer_64(p, offset, left, S, info);
3571 if (r == nullptr)
3572 return;
3573 q = 0;
3574 if (left < sizeof(uint64_t)) {
3575 memcpy(&q, r, left);
3576 outs() << " (protocol_t * entends past the end of the section)\n";
3577 } else
3578 memcpy(&q, r, sizeof(uint64_t));
3579 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3580 sys::swapByteOrder(q);
3581
3582 outs() << "\t\t list[" << i << "] ";
3583 sym_name = get_symbol_64(offset, S, info, n_value, q);
3584 if (n_value != 0) {
3585 if (info->verbose && sym_name != nullptr)
3586 outs() << sym_name;
3587 else
3588 outs() << format("0x%" PRIx64, n_value);
3589 if (q != 0)
3590 outs() << " + " << format("0x%" PRIx64, q);
3591 } else
3592 outs() << format("0x%" PRIx64, q);
3593 outs() << " (struct protocol_t *)\n";
3594
3595 r = get_pointer_64(q + n_value, offset, left, S, info);
3596 if (r == nullptr)
3597 return;
3598 memset(&pc, '\0', sizeof(struct protocol64_t));
3599 if (left < sizeof(struct protocol64_t)) {
3600 memcpy(&pc, r, left);
3601 outs() << " (protocol_t entends past the end of the section)\n";
3602 } else
3603 memcpy(&pc, r, sizeof(struct protocol64_t));
3604 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3605 swapStruct(pc);
3606
3607 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3608
3609 outs() << "\t\t\t name ";
3610 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3611 info, n_value, pc.name);
3612 if (n_value != 0) {
3613 if (info->verbose && sym_name != nullptr)
3614 outs() << sym_name;
3615 else
3616 outs() << format("0x%" PRIx64, n_value);
3617 if (pc.name != 0)
3618 outs() << " + " << format("0x%" PRIx64, pc.name);
3619 } else
3620 outs() << format("0x%" PRIx64, pc.name);
3621 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3622 if (name != nullptr)
3623 outs() << format(" %.*s", left, name);
3624 outs() << "\n";
3625
3626 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3627
3628 outs() << "\t\t instanceMethods ";
3629 sym_name =
3630 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3631 S, info, n_value, pc.instanceMethods);
3632 if (n_value != 0) {
3633 if (info->verbose && sym_name != nullptr)
3634 outs() << sym_name;
3635 else
3636 outs() << format("0x%" PRIx64, n_value);
3637 if (pc.instanceMethods != 0)
3638 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3639 } else
3640 outs() << format("0x%" PRIx64, pc.instanceMethods);
3641 outs() << " (struct method_list_t *)\n";
3642 if (pc.instanceMethods + n_value != 0)
3643 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3644
3645 outs() << "\t\t classMethods ";
3646 sym_name =
3647 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3648 info, n_value, pc.classMethods);
3649 if (n_value != 0) {
3650 if (info->verbose && sym_name != nullptr)
3651 outs() << sym_name;
3652 else
3653 outs() << format("0x%" PRIx64, n_value);
3654 if (pc.classMethods != 0)
3655 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3656 } else
3657 outs() << format("0x%" PRIx64, pc.classMethods);
3658 outs() << " (struct method_list_t *)\n";
3659 if (pc.classMethods + n_value != 0)
3660 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3661
3662 outs() << "\t optionalInstanceMethods "
3663 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3664 outs() << "\t optionalClassMethods "
3665 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3666 outs() << "\t instanceProperties "
3667 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3668
3669 p += sizeof(uint64_t);
3670 offset += sizeof(uint64_t);
3671 }
3672}
3673
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003674static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3675 struct protocol_list32_t pl;
3676 uint32_t q;
3677 struct protocol32_t pc;
3678 const char *r;
3679 uint32_t offset, xoffset, left, i;
3680 SectionRef S, xS;
3681 const char *name;
3682
3683 r = get_pointer_32(p, offset, left, S, info);
3684 if (r == nullptr)
3685 return;
3686 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3687 if (left < sizeof(struct protocol_list32_t)) {
3688 memcpy(&pl, r, left);
3689 outs() << " (protocol_list_t entends past the end of the section)\n";
3690 } else
3691 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3692 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3693 swapStruct(pl);
3694 outs() << " count " << pl.count << "\n";
3695
3696 p += sizeof(struct protocol_list32_t);
3697 offset += sizeof(struct protocol_list32_t);
3698 for (i = 0; i < pl.count; i++) {
3699 r = get_pointer_32(p, offset, left, S, info);
3700 if (r == nullptr)
3701 return;
3702 q = 0;
3703 if (left < sizeof(uint32_t)) {
3704 memcpy(&q, r, left);
3705 outs() << " (protocol_t * entends past the end of the section)\n";
3706 } else
3707 memcpy(&q, r, sizeof(uint32_t));
3708 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3709 sys::swapByteOrder(q);
3710 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3711 << " (struct protocol_t *)\n";
3712 r = get_pointer_32(q, offset, left, S, info);
3713 if (r == nullptr)
3714 return;
3715 memset(&pc, '\0', sizeof(struct protocol32_t));
3716 if (left < sizeof(struct protocol32_t)) {
3717 memcpy(&pc, r, left);
3718 outs() << " (protocol_t entends past the end of the section)\n";
3719 } else
3720 memcpy(&pc, r, sizeof(struct protocol32_t));
3721 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3722 swapStruct(pc);
3723 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3724 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3725 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3726 if (name != nullptr)
3727 outs() << format(" %.*s", left, name);
3728 outs() << "\n";
3729 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3730 outs() << "\t\t instanceMethods "
3731 << format("0x%" PRIx32, pc.instanceMethods)
3732 << " (struct method_list_t *)\n";
3733 if (pc.instanceMethods != 0)
3734 print_method_list32_t(pc.instanceMethods, info, "\t");
3735 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3736 << " (struct method_list_t *)\n";
3737 if (pc.classMethods != 0)
3738 print_method_list32_t(pc.classMethods, info, "\t");
3739 outs() << "\t optionalInstanceMethods "
3740 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3741 outs() << "\t optionalClassMethods "
3742 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3743 outs() << "\t instanceProperties "
3744 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3745 p += sizeof(uint32_t);
3746 offset += sizeof(uint32_t);
3747 }
3748}
3749
Kevin Enderby846c0002015-04-16 17:19:59 +00003750static void print_indent(uint32_t indent) {
3751 for (uint32_t i = 0; i < indent;) {
3752 if (indent - i >= 8) {
3753 outs() << "\t";
3754 i += 8;
3755 } else {
3756 for (uint32_t j = i; j < indent; j++)
3757 outs() << " ";
3758 return;
3759 }
3760 }
3761}
3762
3763static bool print_method_description_list(uint32_t p, uint32_t indent,
3764 struct DisassembleInfo *info) {
3765 uint32_t offset, left, xleft;
3766 SectionRef S;
3767 struct objc_method_description_list_t mdl;
3768 struct objc_method_description_t md;
3769 const char *r, *list, *name;
3770 int32_t i;
3771
3772 r = get_pointer_32(p, offset, left, S, info, true);
3773 if (r == nullptr)
3774 return true;
3775
3776 outs() << "\n";
3777 if (left > sizeof(struct objc_method_description_list_t)) {
3778 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3779 } else {
3780 print_indent(indent);
3781 outs() << " objc_method_description_list extends past end of the section\n";
3782 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3783 memcpy(&mdl, r, left);
3784 }
3785 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3786 swapStruct(mdl);
3787
3788 print_indent(indent);
3789 outs() << " count " << mdl.count << "\n";
3790
3791 list = r + sizeof(struct objc_method_description_list_t);
3792 for (i = 0; i < mdl.count; i++) {
3793 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3794 print_indent(indent);
3795 outs() << " remaining list entries extend past the of the section\n";
3796 break;
3797 }
3798 print_indent(indent);
3799 outs() << " list[" << i << "]\n";
3800 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3801 sizeof(struct objc_method_description_t));
3802 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3803 swapStruct(md);
3804
3805 print_indent(indent);
3806 outs() << " name " << format("0x%08" PRIx32, md.name);
3807 if (info->verbose) {
3808 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3809 if (name != nullptr)
3810 outs() << format(" %.*s", xleft, name);
3811 else
3812 outs() << " (not in an __OBJC section)";
3813 }
3814 outs() << "\n";
3815
3816 print_indent(indent);
3817 outs() << " types " << format("0x%08" PRIx32, md.types);
3818 if (info->verbose) {
3819 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3820 if (name != nullptr)
3821 outs() << format(" %.*s", xleft, name);
3822 else
3823 outs() << " (not in an __OBJC section)";
3824 }
3825 outs() << "\n";
3826 }
3827 return false;
3828}
3829
3830static bool print_protocol_list(uint32_t p, uint32_t indent,
3831 struct DisassembleInfo *info);
3832
3833static bool print_protocol(uint32_t p, uint32_t indent,
3834 struct DisassembleInfo *info) {
3835 uint32_t offset, left;
3836 SectionRef S;
3837 struct objc_protocol_t protocol;
3838 const char *r, *name;
3839
3840 r = get_pointer_32(p, offset, left, S, info, true);
3841 if (r == nullptr)
3842 return true;
3843
3844 outs() << "\n";
3845 if (left >= sizeof(struct objc_protocol_t)) {
3846 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3847 } else {
3848 print_indent(indent);
3849 outs() << " Protocol extends past end of the section\n";
3850 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3851 memcpy(&protocol, r, left);
3852 }
3853 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3854 swapStruct(protocol);
3855
3856 print_indent(indent);
3857 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3858 << "\n";
3859
3860 print_indent(indent);
3861 outs() << " protocol_name "
3862 << format("0x%08" PRIx32, protocol.protocol_name);
3863 if (info->verbose) {
3864 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3865 if (name != nullptr)
3866 outs() << format(" %.*s", left, name);
3867 else
3868 outs() << " (not in an __OBJC section)";
3869 }
3870 outs() << "\n";
3871
3872 print_indent(indent);
3873 outs() << " protocol_list "
3874 << format("0x%08" PRIx32, protocol.protocol_list);
3875 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3876 outs() << " (not in an __OBJC section)\n";
3877
3878 print_indent(indent);
3879 outs() << " instance_methods "
3880 << format("0x%08" PRIx32, protocol.instance_methods);
3881 if (print_method_description_list(protocol.instance_methods, indent, info))
3882 outs() << " (not in an __OBJC section)\n";
3883
3884 print_indent(indent);
3885 outs() << " class_methods "
3886 << format("0x%08" PRIx32, protocol.class_methods);
3887 if (print_method_description_list(protocol.class_methods, indent, info))
3888 outs() << " (not in an __OBJC section)\n";
3889
3890 return false;
3891}
3892
3893static bool print_protocol_list(uint32_t p, uint32_t indent,
3894 struct DisassembleInfo *info) {
3895 uint32_t offset, left, l;
3896 SectionRef S;
3897 struct objc_protocol_list_t protocol_list;
3898 const char *r, *list;
3899 int32_t i;
3900
3901 r = get_pointer_32(p, offset, left, S, info, true);
3902 if (r == nullptr)
3903 return true;
3904
3905 outs() << "\n";
3906 if (left > sizeof(struct objc_protocol_list_t)) {
3907 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3908 } else {
3909 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3910 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3911 memcpy(&protocol_list, r, left);
3912 }
3913 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3914 swapStruct(protocol_list);
3915
3916 print_indent(indent);
3917 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3918 << "\n";
3919 print_indent(indent);
3920 outs() << " count " << protocol_list.count << "\n";
3921
3922 list = r + sizeof(struct objc_protocol_list_t);
3923 for (i = 0; i < protocol_list.count; i++) {
3924 if ((i + 1) * sizeof(uint32_t) > left) {
3925 outs() << "\t\t remaining list entries extend past the of the section\n";
3926 break;
3927 }
3928 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3930 sys::swapByteOrder(l);
3931
3932 print_indent(indent);
3933 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3934 if (print_protocol(l, indent, info))
3935 outs() << "(not in an __OBJC section)\n";
3936 }
3937 return false;
3938}
3939
Kevin Enderby0fc11822015-04-01 20:57:01 +00003940static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3941 struct ivar_list64_t il;
3942 struct ivar64_t i;
3943 const char *r;
3944 uint32_t offset, xoffset, left, j;
3945 SectionRef S, xS;
3946 const char *name, *sym_name, *ivar_offset_p;
3947 uint64_t ivar_offset, n_value;
3948
3949 r = get_pointer_64(p, offset, left, S, info);
3950 if (r == nullptr)
3951 return;
3952 memset(&il, '\0', sizeof(struct ivar_list64_t));
3953 if (left < sizeof(struct ivar_list64_t)) {
3954 memcpy(&il, r, left);
3955 outs() << " (ivar_list_t entends past the end of the section)\n";
3956 } else
3957 memcpy(&il, r, sizeof(struct ivar_list64_t));
3958 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3959 swapStruct(il);
3960 outs() << " entsize " << il.entsize << "\n";
3961 outs() << " count " << il.count << "\n";
3962
3963 p += sizeof(struct ivar_list64_t);
3964 offset += sizeof(struct ivar_list64_t);
3965 for (j = 0; j < il.count; j++) {
3966 r = get_pointer_64(p, offset, left, S, info);
3967 if (r == nullptr)
3968 return;
3969 memset(&i, '\0', sizeof(struct ivar64_t));
3970 if (left < sizeof(struct ivar64_t)) {
3971 memcpy(&i, r, left);
3972 outs() << " (ivar_t entends past the end of the section)\n";
3973 } else
3974 memcpy(&i, r, sizeof(struct ivar64_t));
3975 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3976 swapStruct(i);
3977
3978 outs() << "\t\t\t offset ";
3979 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3980 info, n_value, i.offset);
3981 if (n_value != 0) {
3982 if (info->verbose && sym_name != nullptr)
3983 outs() << sym_name;
3984 else
3985 outs() << format("0x%" PRIx64, n_value);
3986 if (i.offset != 0)
3987 outs() << " + " << format("0x%" PRIx64, i.offset);
3988 } else
3989 outs() << format("0x%" PRIx64, i.offset);
3990 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3991 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3992 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3993 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3994 sys::swapByteOrder(ivar_offset);
3995 outs() << " " << ivar_offset << "\n";
3996 } else
3997 outs() << "\n";
3998
3999 outs() << "\t\t\t name ";
4000 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4001 n_value, i.name);
4002 if (n_value != 0) {
4003 if (info->verbose && sym_name != nullptr)
4004 outs() << sym_name;
4005 else
4006 outs() << format("0x%" PRIx64, n_value);
4007 if (i.name != 0)
4008 outs() << " + " << format("0x%" PRIx64, i.name);
4009 } else
4010 outs() << format("0x%" PRIx64, i.name);
4011 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", left, name);
4014 outs() << "\n";
4015
4016 outs() << "\t\t\t type ";
4017 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4018 n_value, i.name);
4019 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4020 if (n_value != 0) {
4021 if (info->verbose && sym_name != nullptr)
4022 outs() << sym_name;
4023 else
4024 outs() << format("0x%" PRIx64, n_value);
4025 if (i.type != 0)
4026 outs() << " + " << format("0x%" PRIx64, i.type);
4027 } else
4028 outs() << format("0x%" PRIx64, i.type);
4029 if (name != nullptr)
4030 outs() << format(" %.*s", left, name);
4031 outs() << "\n";
4032
4033 outs() << "\t\t\talignment " << i.alignment << "\n";
4034 outs() << "\t\t\t size " << i.size << "\n";
4035
4036 p += sizeof(struct ivar64_t);
4037 offset += sizeof(struct ivar64_t);
4038 }
4039}
4040
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004041static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4042 struct ivar_list32_t il;
4043 struct ivar32_t i;
4044 const char *r;
4045 uint32_t offset, xoffset, left, j;
4046 SectionRef S, xS;
4047 const char *name, *ivar_offset_p;
4048 uint32_t ivar_offset;
4049
4050 r = get_pointer_32(p, offset, left, S, info);
4051 if (r == nullptr)
4052 return;
4053 memset(&il, '\0', sizeof(struct ivar_list32_t));
4054 if (left < sizeof(struct ivar_list32_t)) {
4055 memcpy(&il, r, left);
4056 outs() << " (ivar_list_t entends past the end of the section)\n";
4057 } else
4058 memcpy(&il, r, sizeof(struct ivar_list32_t));
4059 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4060 swapStruct(il);
4061 outs() << " entsize " << il.entsize << "\n";
4062 outs() << " count " << il.count << "\n";
4063
4064 p += sizeof(struct ivar_list32_t);
4065 offset += sizeof(struct ivar_list32_t);
4066 for (j = 0; j < il.count; j++) {
4067 r = get_pointer_32(p, offset, left, S, info);
4068 if (r == nullptr)
4069 return;
4070 memset(&i, '\0', sizeof(struct ivar32_t));
4071 if (left < sizeof(struct ivar32_t)) {
4072 memcpy(&i, r, left);
4073 outs() << " (ivar_t entends past the end of the section)\n";
4074 } else
4075 memcpy(&i, r, sizeof(struct ivar32_t));
4076 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4077 swapStruct(i);
4078
4079 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4080 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4081 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4082 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4083 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4084 sys::swapByteOrder(ivar_offset);
4085 outs() << " " << ivar_offset << "\n";
4086 } else
4087 outs() << "\n";
4088
4089 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4090 name = get_pointer_32(i.name, xoffset, left, xS, info);
4091 if (name != nullptr)
4092 outs() << format(" %.*s", left, name);
4093 outs() << "\n";
4094
4095 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4096 name = get_pointer_32(i.type, xoffset, left, xS, info);
4097 if (name != nullptr)
4098 outs() << format(" %.*s", left, name);
4099 outs() << "\n";
4100
4101 outs() << "\t\t\talignment " << i.alignment << "\n";
4102 outs() << "\t\t\t size " << i.size << "\n";
4103
4104 p += sizeof(struct ivar32_t);
4105 offset += sizeof(struct ivar32_t);
4106 }
4107}
4108
Kevin Enderby0fc11822015-04-01 20:57:01 +00004109static void print_objc_property_list64(uint64_t p,
4110 struct DisassembleInfo *info) {
4111 struct objc_property_list64 opl;
4112 struct objc_property64 op;
4113 const char *r;
4114 uint32_t offset, xoffset, left, j;
4115 SectionRef S, xS;
4116 const char *name, *sym_name;
4117 uint64_t n_value;
4118
4119 r = get_pointer_64(p, offset, left, S, info);
4120 if (r == nullptr)
4121 return;
4122 memset(&opl, '\0', sizeof(struct objc_property_list64));
4123 if (left < sizeof(struct objc_property_list64)) {
4124 memcpy(&opl, r, left);
4125 outs() << " (objc_property_list entends past the end of the section)\n";
4126 } else
4127 memcpy(&opl, r, sizeof(struct objc_property_list64));
4128 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4129 swapStruct(opl);
4130 outs() << " entsize " << opl.entsize << "\n";
4131 outs() << " count " << opl.count << "\n";
4132
4133 p += sizeof(struct objc_property_list64);
4134 offset += sizeof(struct objc_property_list64);
4135 for (j = 0; j < opl.count; j++) {
4136 r = get_pointer_64(p, offset, left, S, info);
4137 if (r == nullptr)
4138 return;
4139 memset(&op, '\0', sizeof(struct objc_property64));
4140 if (left < sizeof(struct objc_property64)) {
4141 memcpy(&op, r, left);
4142 outs() << " (objc_property entends past the end of the section)\n";
4143 } else
4144 memcpy(&op, r, sizeof(struct objc_property64));
4145 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4146 swapStruct(op);
4147
4148 outs() << "\t\t\t name ";
4149 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4150 info, n_value, op.name);
4151 if (n_value != 0) {
4152 if (info->verbose && sym_name != nullptr)
4153 outs() << sym_name;
4154 else
4155 outs() << format("0x%" PRIx64, n_value);
4156 if (op.name != 0)
4157 outs() << " + " << format("0x%" PRIx64, op.name);
4158 } else
4159 outs() << format("0x%" PRIx64, op.name);
4160 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4161 if (name != nullptr)
4162 outs() << format(" %.*s", left, name);
4163 outs() << "\n";
4164
4165 outs() << "\t\t\tattributes ";
4166 sym_name =
4167 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4168 info, n_value, op.attributes);
4169 if (n_value != 0) {
4170 if (info->verbose && sym_name != nullptr)
4171 outs() << sym_name;
4172 else
4173 outs() << format("0x%" PRIx64, n_value);
4174 if (op.attributes != 0)
4175 outs() << " + " << format("0x%" PRIx64, op.attributes);
4176 } else
4177 outs() << format("0x%" PRIx64, op.attributes);
4178 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4179 if (name != nullptr)
4180 outs() << format(" %.*s", left, name);
4181 outs() << "\n";
4182
4183 p += sizeof(struct objc_property64);
4184 offset += sizeof(struct objc_property64);
4185 }
4186}
4187
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004188static void print_objc_property_list32(uint32_t p,
4189 struct DisassembleInfo *info) {
4190 struct objc_property_list32 opl;
4191 struct objc_property32 op;
4192 const char *r;
4193 uint32_t offset, xoffset, left, j;
4194 SectionRef S, xS;
4195 const char *name;
4196
4197 r = get_pointer_32(p, offset, left, S, info);
4198 if (r == nullptr)
4199 return;
4200 memset(&opl, '\0', sizeof(struct objc_property_list32));
4201 if (left < sizeof(struct objc_property_list32)) {
4202 memcpy(&opl, r, left);
4203 outs() << " (objc_property_list entends past the end of the section)\n";
4204 } else
4205 memcpy(&opl, r, sizeof(struct objc_property_list32));
4206 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4207 swapStruct(opl);
4208 outs() << " entsize " << opl.entsize << "\n";
4209 outs() << " count " << opl.count << "\n";
4210
4211 p += sizeof(struct objc_property_list32);
4212 offset += sizeof(struct objc_property_list32);
4213 for (j = 0; j < opl.count; j++) {
4214 r = get_pointer_32(p, offset, left, S, info);
4215 if (r == nullptr)
4216 return;
4217 memset(&op, '\0', sizeof(struct objc_property32));
4218 if (left < sizeof(struct objc_property32)) {
4219 memcpy(&op, r, left);
4220 outs() << " (objc_property entends past the end of the section)\n";
4221 } else
4222 memcpy(&op, r, sizeof(struct objc_property32));
4223 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4224 swapStruct(op);
4225
4226 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4227 name = get_pointer_32(op.name, xoffset, left, xS, info);
4228 if (name != nullptr)
4229 outs() << format(" %.*s", left, name);
4230 outs() << "\n";
4231
4232 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4233 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4234 if (name != nullptr)
4235 outs() << format(" %.*s", left, name);
4236 outs() << "\n";
4237
4238 p += sizeof(struct objc_property32);
4239 offset += sizeof(struct objc_property32);
4240 }
4241}
4242
Richard Smith81ff44d2015-10-09 22:09:56 +00004243static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004244 bool &is_meta_class) {
4245 struct class_ro64_t cro;
4246 const char *r;
4247 uint32_t offset, xoffset, left;
4248 SectionRef S, xS;
4249 const char *name, *sym_name;
4250 uint64_t n_value;
4251
4252 r = get_pointer_64(p, offset, left, S, info);
4253 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004254 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004255 memset(&cro, '\0', sizeof(struct class_ro64_t));
4256 if (left < sizeof(struct class_ro64_t)) {
4257 memcpy(&cro, r, left);
4258 outs() << " (class_ro_t entends past the end of the section)\n";
4259 } else
4260 memcpy(&cro, r, sizeof(struct class_ro64_t));
4261 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4262 swapStruct(cro);
4263 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4264 if (cro.flags & RO_META)
4265 outs() << " RO_META";
4266 if (cro.flags & RO_ROOT)
4267 outs() << " RO_ROOT";
4268 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4269 outs() << " RO_HAS_CXX_STRUCTORS";
4270 outs() << "\n";
4271 outs() << " instanceStart " << cro.instanceStart << "\n";
4272 outs() << " instanceSize " << cro.instanceSize << "\n";
4273 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4274 << "\n";
4275 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4276 << "\n";
4277 print_layout_map64(cro.ivarLayout, info);
4278
4279 outs() << " name ";
4280 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4281 info, n_value, cro.name);
4282 if (n_value != 0) {
4283 if (info->verbose && sym_name != nullptr)
4284 outs() << sym_name;
4285 else
4286 outs() << format("0x%" PRIx64, n_value);
4287 if (cro.name != 0)
4288 outs() << " + " << format("0x%" PRIx64, cro.name);
4289 } else
4290 outs() << format("0x%" PRIx64, cro.name);
4291 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4292 if (name != nullptr)
4293 outs() << format(" %.*s", left, name);
4294 outs() << "\n";
4295
4296 outs() << " baseMethods ";
4297 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4298 S, info, n_value, cro.baseMethods);
4299 if (n_value != 0) {
4300 if (info->verbose && sym_name != nullptr)
4301 outs() << sym_name;
4302 else
4303 outs() << format("0x%" PRIx64, n_value);
4304 if (cro.baseMethods != 0)
4305 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4306 } else
4307 outs() << format("0x%" PRIx64, cro.baseMethods);
4308 outs() << " (struct method_list_t *)\n";
4309 if (cro.baseMethods + n_value != 0)
4310 print_method_list64_t(cro.baseMethods + n_value, info, "");
4311
4312 outs() << " baseProtocols ";
4313 sym_name =
4314 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4315 info, n_value, cro.baseProtocols);
4316 if (n_value != 0) {
4317 if (info->verbose && sym_name != nullptr)
4318 outs() << sym_name;
4319 else
4320 outs() << format("0x%" PRIx64, n_value);
4321 if (cro.baseProtocols != 0)
4322 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4323 } else
4324 outs() << format("0x%" PRIx64, cro.baseProtocols);
4325 outs() << "\n";
4326 if (cro.baseProtocols + n_value != 0)
4327 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4328
4329 outs() << " ivars ";
4330 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004331 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004332 if (n_value != 0) {
4333 if (info->verbose && sym_name != nullptr)
4334 outs() << sym_name;
4335 else
4336 outs() << format("0x%" PRIx64, n_value);
4337 if (cro.ivars != 0)
4338 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4339 } else
4340 outs() << format("0x%" PRIx64, cro.ivars);
4341 outs() << "\n";
4342 if (cro.ivars + n_value != 0)
4343 print_ivar_list64_t(cro.ivars + n_value, info);
4344
4345 outs() << " weakIvarLayout ";
4346 sym_name =
4347 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4348 info, n_value, cro.weakIvarLayout);
4349 if (n_value != 0) {
4350 if (info->verbose && sym_name != nullptr)
4351 outs() << sym_name;
4352 else
4353 outs() << format("0x%" PRIx64, n_value);
4354 if (cro.weakIvarLayout != 0)
4355 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4356 } else
4357 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4358 outs() << "\n";
4359 print_layout_map64(cro.weakIvarLayout + n_value, info);
4360
4361 outs() << " baseProperties ";
4362 sym_name =
4363 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4364 info, n_value, cro.baseProperties);
4365 if (n_value != 0) {
4366 if (info->verbose && sym_name != nullptr)
4367 outs() << sym_name;
4368 else
4369 outs() << format("0x%" PRIx64, n_value);
4370 if (cro.baseProperties != 0)
4371 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4372 } else
4373 outs() << format("0x%" PRIx64, cro.baseProperties);
4374 outs() << "\n";
4375 if (cro.baseProperties + n_value != 0)
4376 print_objc_property_list64(cro.baseProperties + n_value, info);
4377
Rafael Espindolab9091322015-10-24 23:19:10 +00004378 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004379 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004380}
4381
Richard Smith81ff44d2015-10-09 22:09:56 +00004382static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004383 bool &is_meta_class) {
4384 struct class_ro32_t cro;
4385 const char *r;
4386 uint32_t offset, xoffset, left;
4387 SectionRef S, xS;
4388 const char *name;
4389
4390 r = get_pointer_32(p, offset, left, S, info);
4391 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004392 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004393 memset(&cro, '\0', sizeof(struct class_ro32_t));
4394 if (left < sizeof(struct class_ro32_t)) {
4395 memcpy(&cro, r, left);
4396 outs() << " (class_ro_t entends past the end of the section)\n";
4397 } else
4398 memcpy(&cro, r, sizeof(struct class_ro32_t));
4399 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4400 swapStruct(cro);
4401 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4402 if (cro.flags & RO_META)
4403 outs() << " RO_META";
4404 if (cro.flags & RO_ROOT)
4405 outs() << " RO_ROOT";
4406 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4407 outs() << " RO_HAS_CXX_STRUCTORS";
4408 outs() << "\n";
4409 outs() << " instanceStart " << cro.instanceStart << "\n";
4410 outs() << " instanceSize " << cro.instanceSize << "\n";
4411 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4412 << "\n";
4413 print_layout_map32(cro.ivarLayout, info);
4414
4415 outs() << " name " << format("0x%" PRIx32, cro.name);
4416 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4417 if (name != nullptr)
4418 outs() << format(" %.*s", left, name);
4419 outs() << "\n";
4420
4421 outs() << " baseMethods "
4422 << format("0x%" PRIx32, cro.baseMethods)
4423 << " (struct method_list_t *)\n";
4424 if (cro.baseMethods != 0)
4425 print_method_list32_t(cro.baseMethods, info, "");
4426
4427 outs() << " baseProtocols "
4428 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4429 if (cro.baseProtocols != 0)
4430 print_protocol_list32_t(cro.baseProtocols, info);
4431 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4432 << "\n";
4433 if (cro.ivars != 0)
4434 print_ivar_list32_t(cro.ivars, info);
4435 outs() << " weakIvarLayout "
4436 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4437 print_layout_map32(cro.weakIvarLayout, info);
4438 outs() << " baseProperties "
4439 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4440 if (cro.baseProperties != 0)
4441 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004442 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004443 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004444}
4445
Kevin Enderby0fc11822015-04-01 20:57:01 +00004446static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4447 struct class64_t c;
4448 const char *r;
4449 uint32_t offset, left;
4450 SectionRef S;
4451 const char *name;
4452 uint64_t isa_n_value, n_value;
4453
4454 r = get_pointer_64(p, offset, left, S, info);
4455 if (r == nullptr || left < sizeof(struct class64_t))
4456 return;
4457 memset(&c, '\0', sizeof(struct class64_t));
4458 if (left < sizeof(struct class64_t)) {
4459 memcpy(&c, r, left);
4460 outs() << " (class_t entends past the end of the section)\n";
4461 } else
4462 memcpy(&c, r, sizeof(struct class64_t));
4463 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4464 swapStruct(c);
4465
4466 outs() << " isa " << format("0x%" PRIx64, c.isa);
4467 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4468 isa_n_value, c.isa);
4469 if (name != nullptr)
4470 outs() << " " << name;
4471 outs() << "\n";
4472
4473 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4474 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4475 n_value, c.superclass);
4476 if (name != nullptr)
4477 outs() << " " << name;
4478 outs() << "\n";
4479
4480 outs() << " cache " << format("0x%" PRIx64, c.cache);
4481 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4482 n_value, c.cache);
4483 if (name != nullptr)
4484 outs() << " " << name;
4485 outs() << "\n";
4486
4487 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4488 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4489 n_value, c.vtable);
4490 if (name != nullptr)
4491 outs() << " " << name;
4492 outs() << "\n";
4493
4494 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4495 n_value, c.data);
4496 outs() << " data ";
4497 if (n_value != 0) {
4498 if (info->verbose && name != nullptr)
4499 outs() << name;
4500 else
4501 outs() << format("0x%" PRIx64, n_value);
4502 if (c.data != 0)
4503 outs() << " + " << format("0x%" PRIx64, c.data);
4504 } else
4505 outs() << format("0x%" PRIx64, c.data);
4506 outs() << " (struct class_ro_t *)";
4507
4508 // This is a Swift class if some of the low bits of the pointer are set.
4509 if ((c.data + n_value) & 0x7)
4510 outs() << " Swift class";
4511 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004512 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004513 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4514 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004515
Kevin Enderbyaac75382015-10-08 16:56:35 +00004516 if (!is_meta_class &&
4517 c.isa + isa_n_value != p &&
4518 c.isa + isa_n_value != 0 &&
4519 info->depth < 100) {
4520 info->depth++;
4521 outs() << "Meta Class\n";
4522 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004523 }
4524}
4525
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004526static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4527 struct class32_t c;
4528 const char *r;
4529 uint32_t offset, left;
4530 SectionRef S;
4531 const char *name;
4532
4533 r = get_pointer_32(p, offset, left, S, info);
4534 if (r == nullptr)
4535 return;
4536 memset(&c, '\0', sizeof(struct class32_t));
4537 if (left < sizeof(struct class32_t)) {
4538 memcpy(&c, r, left);
4539 outs() << " (class_t entends past the end of the section)\n";
4540 } else
4541 memcpy(&c, r, sizeof(struct class32_t));
4542 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4543 swapStruct(c);
4544
4545 outs() << " isa " << format("0x%" PRIx32, c.isa);
4546 name =
4547 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4548 if (name != nullptr)
4549 outs() << " " << name;
4550 outs() << "\n";
4551
4552 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4553 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4554 c.superclass);
4555 if (name != nullptr)
4556 outs() << " " << name;
4557 outs() << "\n";
4558
4559 outs() << " cache " << format("0x%" PRIx32, c.cache);
4560 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4561 c.cache);
4562 if (name != nullptr)
4563 outs() << " " << name;
4564 outs() << "\n";
4565
4566 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4567 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4568 c.vtable);
4569 if (name != nullptr)
4570 outs() << " " << name;
4571 outs() << "\n";
4572
4573 name =
4574 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4575 outs() << " data " << format("0x%" PRIx32, c.data)
4576 << " (struct class_ro_t *)";
4577
4578 // This is a Swift class if some of the low bits of the pointer are set.
4579 if (c.data & 0x3)
4580 outs() << " Swift class";
4581 outs() << "\n";
4582 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004583 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4584 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004585
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004586 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004587 outs() << "Meta Class\n";
4588 print_class32_t(c.isa, info);
4589 }
4590}
4591
Kevin Enderby846c0002015-04-16 17:19:59 +00004592static void print_objc_class_t(struct objc_class_t *objc_class,
4593 struct DisassembleInfo *info) {
4594 uint32_t offset, left, xleft;
4595 const char *name, *p, *ivar_list;
4596 SectionRef S;
4597 int32_t i;
4598 struct objc_ivar_list_t objc_ivar_list;
4599 struct objc_ivar_t ivar;
4600
4601 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4602 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4603 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4604 if (name != nullptr)
4605 outs() << format(" %.*s", left, name);
4606 else
4607 outs() << " (not in an __OBJC section)";
4608 }
4609 outs() << "\n";
4610
4611 outs() << "\t super_class "
4612 << format("0x%08" PRIx32, objc_class->super_class);
4613 if (info->verbose) {
4614 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4615 if (name != nullptr)
4616 outs() << format(" %.*s", left, name);
4617 else
4618 outs() << " (not in an __OBJC section)";
4619 }
4620 outs() << "\n";
4621
4622 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4623 if (info->verbose) {
4624 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4625 if (name != nullptr)
4626 outs() << format(" %.*s", left, name);
4627 else
4628 outs() << " (not in an __OBJC section)";
4629 }
4630 outs() << "\n";
4631
4632 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4633 << "\n";
4634
4635 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4636 if (info->verbose) {
4637 if (CLS_GETINFO(objc_class, CLS_CLASS))
4638 outs() << " CLS_CLASS";
4639 else if (CLS_GETINFO(objc_class, CLS_META))
4640 outs() << " CLS_META";
4641 }
4642 outs() << "\n";
4643
4644 outs() << "\t instance_size "
4645 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4646
4647 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4648 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4649 if (p != nullptr) {
4650 if (left > sizeof(struct objc_ivar_list_t)) {
4651 outs() << "\n";
4652 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4653 } else {
4654 outs() << " (entends past the end of the section)\n";
4655 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4656 memcpy(&objc_ivar_list, p, left);
4657 }
4658 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4659 swapStruct(objc_ivar_list);
4660 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4661 ivar_list = p + sizeof(struct objc_ivar_list_t);
4662 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4663 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4664 outs() << "\t\t remaining ivar's extend past the of the section\n";
4665 break;
4666 }
4667 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4668 sizeof(struct objc_ivar_t));
4669 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4670 swapStruct(ivar);
4671
4672 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4673 if (info->verbose) {
4674 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4675 if (name != nullptr)
4676 outs() << format(" %.*s", xleft, name);
4677 else
4678 outs() << " (not in an __OBJC section)";
4679 }
4680 outs() << "\n";
4681
4682 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4683 if (info->verbose) {
4684 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4685 if (name != nullptr)
4686 outs() << format(" %.*s", xleft, name);
4687 else
4688 outs() << " (not in an __OBJC section)";
4689 }
4690 outs() << "\n";
4691
4692 outs() << "\t\t ivar_offset "
4693 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4694 }
4695 } else {
4696 outs() << " (not in an __OBJC section)\n";
4697 }
4698
4699 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4700 if (print_method_list(objc_class->methodLists, info))
4701 outs() << " (not in an __OBJC section)\n";
4702
4703 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4704 << "\n";
4705
4706 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4707 if (print_protocol_list(objc_class->protocols, 16, info))
4708 outs() << " (not in an __OBJC section)\n";
4709}
4710
4711static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4712 struct DisassembleInfo *info) {
4713 uint32_t offset, left;
4714 const char *name;
4715 SectionRef S;
4716
4717 outs() << "\t category name "
4718 << format("0x%08" PRIx32, objc_category->category_name);
4719 if (info->verbose) {
4720 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4721 true);
4722 if (name != nullptr)
4723 outs() << format(" %.*s", left, name);
4724 else
4725 outs() << " (not in an __OBJC section)";
4726 }
4727 outs() << "\n";
4728
4729 outs() << "\t\t class name "
4730 << format("0x%08" PRIx32, objc_category->class_name);
4731 if (info->verbose) {
4732 name =
4733 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", left, name);
4736 else
4737 outs() << " (not in an __OBJC section)";
4738 }
4739 outs() << "\n";
4740
4741 outs() << "\t instance methods "
4742 << format("0x%08" PRIx32, objc_category->instance_methods);
4743 if (print_method_list(objc_category->instance_methods, info))
4744 outs() << " (not in an __OBJC section)\n";
4745
4746 outs() << "\t class methods "
4747 << format("0x%08" PRIx32, objc_category->class_methods);
4748 if (print_method_list(objc_category->class_methods, info))
4749 outs() << " (not in an __OBJC section)\n";
4750}
4751
Kevin Enderby0fc11822015-04-01 20:57:01 +00004752static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4753 struct category64_t c;
4754 const char *r;
4755 uint32_t offset, xoffset, left;
4756 SectionRef S, xS;
4757 const char *name, *sym_name;
4758 uint64_t n_value;
4759
4760 r = get_pointer_64(p, offset, left, S, info);
4761 if (r == nullptr)
4762 return;
4763 memset(&c, '\0', sizeof(struct category64_t));
4764 if (left < sizeof(struct category64_t)) {
4765 memcpy(&c, r, left);
4766 outs() << " (category_t entends past the end of the section)\n";
4767 } else
4768 memcpy(&c, r, sizeof(struct category64_t));
4769 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4770 swapStruct(c);
4771
4772 outs() << " name ";
4773 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4774 info, n_value, c.name);
4775 if (n_value != 0) {
4776 if (info->verbose && sym_name != nullptr)
4777 outs() << sym_name;
4778 else
4779 outs() << format("0x%" PRIx64, n_value);
4780 if (c.name != 0)
4781 outs() << " + " << format("0x%" PRIx64, c.name);
4782 } else
4783 outs() << format("0x%" PRIx64, c.name);
4784 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4785 if (name != nullptr)
4786 outs() << format(" %.*s", left, name);
4787 outs() << "\n";
4788
4789 outs() << " cls ";
4790 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4791 n_value, c.cls);
4792 if (n_value != 0) {
4793 if (info->verbose && sym_name != nullptr)
4794 outs() << sym_name;
4795 else
4796 outs() << format("0x%" PRIx64, n_value);
4797 if (c.cls != 0)
4798 outs() << " + " << format("0x%" PRIx64, c.cls);
4799 } else
4800 outs() << format("0x%" PRIx64, c.cls);
4801 outs() << "\n";
4802 if (c.cls + n_value != 0)
4803 print_class64_t(c.cls + n_value, info);
4804
4805 outs() << " instanceMethods ";
4806 sym_name =
4807 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4808 info, n_value, c.instanceMethods);
4809 if (n_value != 0) {
4810 if (info->verbose && sym_name != nullptr)
4811 outs() << sym_name;
4812 else
4813 outs() << format("0x%" PRIx64, n_value);
4814 if (c.instanceMethods != 0)
4815 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4816 } else
4817 outs() << format("0x%" PRIx64, c.instanceMethods);
4818 outs() << "\n";
4819 if (c.instanceMethods + n_value != 0)
4820 print_method_list64_t(c.instanceMethods + n_value, info, "");
4821
4822 outs() << " classMethods ";
4823 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4824 S, info, n_value, c.classMethods);
4825 if (n_value != 0) {
4826 if (info->verbose && sym_name != nullptr)
4827 outs() << sym_name;
4828 else
4829 outs() << format("0x%" PRIx64, n_value);
4830 if (c.classMethods != 0)
4831 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4832 } else
4833 outs() << format("0x%" PRIx64, c.classMethods);
4834 outs() << "\n";
4835 if (c.classMethods + n_value != 0)
4836 print_method_list64_t(c.classMethods + n_value, info, "");
4837
4838 outs() << " protocols ";
4839 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4840 info, n_value, c.protocols);
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 (c.protocols != 0)
4847 outs() << " + " << format("0x%" PRIx64, c.protocols);
4848 } else
4849 outs() << format("0x%" PRIx64, c.protocols);
4850 outs() << "\n";
4851 if (c.protocols + n_value != 0)
4852 print_protocol_list64_t(c.protocols + n_value, info);
4853
4854 outs() << "instanceProperties ";
4855 sym_name =
4856 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4857 S, info, n_value, c.instanceProperties);
4858 if (n_value != 0) {
4859 if (info->verbose && sym_name != nullptr)
4860 outs() << sym_name;
4861 else
4862 outs() << format("0x%" PRIx64, n_value);
4863 if (c.instanceProperties != 0)
4864 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4865 } else
4866 outs() << format("0x%" PRIx64, c.instanceProperties);
4867 outs() << "\n";
4868 if (c.instanceProperties + n_value != 0)
4869 print_objc_property_list64(c.instanceProperties + n_value, info);
4870}
4871
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004872static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4873 struct category32_t c;
4874 const char *r;
4875 uint32_t offset, left;
4876 SectionRef S, xS;
4877 const char *name;
4878
4879 r = get_pointer_32(p, offset, left, S, info);
4880 if (r == nullptr)
4881 return;
4882 memset(&c, '\0', sizeof(struct category32_t));
4883 if (left < sizeof(struct category32_t)) {
4884 memcpy(&c, r, left);
4885 outs() << " (category_t entends past the end of the section)\n";
4886 } else
4887 memcpy(&c, r, sizeof(struct category32_t));
4888 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4889 swapStruct(c);
4890
4891 outs() << " name " << format("0x%" PRIx32, c.name);
4892 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4893 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004894 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004895 outs() << " " << name;
4896 outs() << "\n";
4897
4898 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4899 if (c.cls != 0)
4900 print_class32_t(c.cls, info);
4901 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4902 << "\n";
4903 if (c.instanceMethods != 0)
4904 print_method_list32_t(c.instanceMethods, info, "");
4905 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4906 << "\n";
4907 if (c.classMethods != 0)
4908 print_method_list32_t(c.classMethods, info, "");
4909 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4910 if (c.protocols != 0)
4911 print_protocol_list32_t(c.protocols, info);
4912 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4913 << "\n";
4914 if (c.instanceProperties != 0)
4915 print_objc_property_list32(c.instanceProperties, info);
4916}
4917
Kevin Enderby0fc11822015-04-01 20:57:01 +00004918static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4919 uint32_t i, left, offset, xoffset;
4920 uint64_t p, n_value;
4921 struct message_ref64 mr;
4922 const char *name, *sym_name;
4923 const char *r;
4924 SectionRef xS;
4925
4926 if (S == SectionRef())
4927 return;
4928
4929 StringRef SectName;
4930 S.getName(SectName);
4931 DataRefImpl Ref = S.getRawDataRefImpl();
4932 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4933 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4934 offset = 0;
4935 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4936 p = S.getAddress() + i;
4937 r = get_pointer_64(p, offset, left, S, info);
4938 if (r == nullptr)
4939 return;
4940 memset(&mr, '\0', sizeof(struct message_ref64));
4941 if (left < sizeof(struct message_ref64)) {
4942 memcpy(&mr, r, left);
4943 outs() << " (message_ref entends past the end of the section)\n";
4944 } else
4945 memcpy(&mr, r, sizeof(struct message_ref64));
4946 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4947 swapStruct(mr);
4948
4949 outs() << " imp ";
4950 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4951 n_value, mr.imp);
4952 if (n_value != 0) {
4953 outs() << format("0x%" PRIx64, n_value) << " ";
4954 if (mr.imp != 0)
4955 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4956 } else
4957 outs() << format("0x%" PRIx64, mr.imp) << " ";
4958 if (name != nullptr)
4959 outs() << " " << name;
4960 outs() << "\n";
4961
4962 outs() << " sel ";
4963 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4964 info, n_value, mr.sel);
4965 if (n_value != 0) {
4966 if (info->verbose && sym_name != nullptr)
4967 outs() << sym_name;
4968 else
4969 outs() << format("0x%" PRIx64, n_value);
4970 if (mr.sel != 0)
4971 outs() << " + " << format("0x%" PRIx64, mr.sel);
4972 } else
4973 outs() << format("0x%" PRIx64, mr.sel);
4974 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4975 if (name != nullptr)
4976 outs() << format(" %.*s", left, name);
4977 outs() << "\n";
4978
4979 offset += sizeof(struct message_ref64);
4980 }
4981}
4982
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004983static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4984 uint32_t i, left, offset, xoffset, p;
4985 struct message_ref32 mr;
4986 const char *name, *r;
4987 SectionRef xS;
4988
4989 if (S == SectionRef())
4990 return;
4991
4992 StringRef SectName;
4993 S.getName(SectName);
4994 DataRefImpl Ref = S.getRawDataRefImpl();
4995 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4996 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4997 offset = 0;
4998 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4999 p = S.getAddress() + i;
5000 r = get_pointer_32(p, offset, left, S, info);
5001 if (r == nullptr)
5002 return;
5003 memset(&mr, '\0', sizeof(struct message_ref32));
5004 if (left < sizeof(struct message_ref32)) {
5005 memcpy(&mr, r, left);
5006 outs() << " (message_ref entends past the end of the section)\n";
5007 } else
5008 memcpy(&mr, r, sizeof(struct message_ref32));
5009 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5010 swapStruct(mr);
5011
5012 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5013 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5014 mr.imp);
5015 if (name != nullptr)
5016 outs() << " " << name;
5017 outs() << "\n";
5018
5019 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5020 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5021 if (name != nullptr)
5022 outs() << " " << name;
5023 outs() << "\n";
5024
5025 offset += sizeof(struct message_ref32);
5026 }
5027}
5028
Kevin Enderby0fc11822015-04-01 20:57:01 +00005029static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5030 uint32_t left, offset, swift_version;
5031 uint64_t p;
5032 struct objc_image_info64 o;
5033 const char *r;
5034
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005035 if (S == SectionRef())
5036 return;
5037
Kevin Enderby0fc11822015-04-01 20:57:01 +00005038 StringRef SectName;
5039 S.getName(SectName);
5040 DataRefImpl Ref = S.getRawDataRefImpl();
5041 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5042 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5043 p = S.getAddress();
5044 r = get_pointer_64(p, offset, left, S, info);
5045 if (r == nullptr)
5046 return;
5047 memset(&o, '\0', sizeof(struct objc_image_info64));
5048 if (left < sizeof(struct objc_image_info64)) {
5049 memcpy(&o, r, left);
5050 outs() << " (objc_image_info entends past the end of the section)\n";
5051 } else
5052 memcpy(&o, r, sizeof(struct objc_image_info64));
5053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5054 swapStruct(o);
5055 outs() << " version " << o.version << "\n";
5056 outs() << " flags " << format("0x%" PRIx32, o.flags);
5057 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5058 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5059 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5060 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5061 swift_version = (o.flags >> 8) & 0xff;
5062 if (swift_version != 0) {
5063 if (swift_version == 1)
5064 outs() << " Swift 1.0";
5065 else if (swift_version == 2)
5066 outs() << " Swift 1.1";
5067 else
5068 outs() << " unknown future Swift version (" << swift_version << ")";
5069 }
5070 outs() << "\n";
5071}
5072
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005073static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5074 uint32_t left, offset, swift_version, p;
5075 struct objc_image_info32 o;
5076 const char *r;
5077
5078 StringRef SectName;
5079 S.getName(SectName);
5080 DataRefImpl Ref = S.getRawDataRefImpl();
5081 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5082 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5083 p = S.getAddress();
5084 r = get_pointer_32(p, offset, left, S, info);
5085 if (r == nullptr)
5086 return;
5087 memset(&o, '\0', sizeof(struct objc_image_info32));
5088 if (left < sizeof(struct objc_image_info32)) {
5089 memcpy(&o, r, left);
5090 outs() << " (objc_image_info entends past the end of the section)\n";
5091 } else
5092 memcpy(&o, r, sizeof(struct objc_image_info32));
5093 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5094 swapStruct(o);
5095 outs() << " version " << o.version << "\n";
5096 outs() << " flags " << format("0x%" PRIx32, o.flags);
5097 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5098 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5099 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5100 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5101 swift_version = (o.flags >> 8) & 0xff;
5102 if (swift_version != 0) {
5103 if (swift_version == 1)
5104 outs() << " Swift 1.0";
5105 else if (swift_version == 2)
5106 outs() << " Swift 1.1";
5107 else
5108 outs() << " unknown future Swift version (" << swift_version << ")";
5109 }
5110 outs() << "\n";
5111}
5112
Kevin Enderby846c0002015-04-16 17:19:59 +00005113static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5114 uint32_t left, offset, p;
5115 struct imageInfo_t o;
5116 const char *r;
5117
5118 StringRef SectName;
5119 S.getName(SectName);
5120 DataRefImpl Ref = S.getRawDataRefImpl();
5121 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5122 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5123 p = S.getAddress();
5124 r = get_pointer_32(p, offset, left, S, info);
5125 if (r == nullptr)
5126 return;
5127 memset(&o, '\0', sizeof(struct imageInfo_t));
5128 if (left < sizeof(struct imageInfo_t)) {
5129 memcpy(&o, r, left);
5130 outs() << " (imageInfo entends past the end of the section)\n";
5131 } else
5132 memcpy(&o, r, sizeof(struct imageInfo_t));
5133 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5134 swapStruct(o);
5135 outs() << " version " << o.version << "\n";
5136 outs() << " flags " << format("0x%" PRIx32, o.flags);
5137 if (o.flags & 0x1)
5138 outs() << " F&C";
5139 if (o.flags & 0x2)
5140 outs() << " GC";
5141 if (o.flags & 0x4)
5142 outs() << " GC-only";
5143 else
5144 outs() << " RR";
5145 outs() << "\n";
5146}
5147
Kevin Enderby0fc11822015-04-01 20:57:01 +00005148static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5149 SymbolAddressMap AddrMap;
5150 if (verbose)
5151 CreateSymbolAddressMap(O, &AddrMap);
5152
5153 std::vector<SectionRef> Sections;
5154 for (const SectionRef &Section : O->sections()) {
5155 StringRef SectName;
5156 Section.getName(SectName);
5157 Sections.push_back(Section);
5158 }
5159
5160 struct DisassembleInfo info;
5161 // Set up the block of info used by the Symbolizer call backs.
5162 info.verbose = verbose;
5163 info.O = O;
5164 info.AddrMap = &AddrMap;
5165 info.Sections = &Sections;
5166 info.class_name = nullptr;
5167 info.selector_name = nullptr;
5168 info.method = nullptr;
5169 info.demangled_name = nullptr;
5170 info.bindtable = nullptr;
5171 info.adrp_addr = 0;
5172 info.adrp_inst = 0;
5173
Kevin Enderbyaac75382015-10-08 16:56:35 +00005174 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005175 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5176 if (CL == SectionRef())
5177 CL = get_section(O, "__DATA", "__objc_classlist");
5178 info.S = CL;
5179 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005180
Davide Italiano62507042015-12-11 22:27:59 +00005181 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5182 if (CR == SectionRef())
5183 CR = get_section(O, "__DATA", "__objc_classrefs");
5184 info.S = CR;
5185 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005186
Davide Italiano62507042015-12-11 22:27:59 +00005187 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5188 if (SR == SectionRef())
5189 SR = get_section(O, "__DATA", "__objc_superrefs");
5190 info.S = SR;
5191 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005192
Davide Italiano62507042015-12-11 22:27:59 +00005193 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5194 if (CA == SectionRef())
5195 CA = get_section(O, "__DATA", "__objc_catlist");
5196 info.S = CA;
5197 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005198
Davide Italiano62507042015-12-11 22:27:59 +00005199 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5200 if (PL == SectionRef())
5201 PL = get_section(O, "__DATA", "__objc_protolist");
5202 info.S = PL;
5203 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005204
Davide Italiano62507042015-12-11 22:27:59 +00005205 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5206 if (MR == SectionRef())
5207 MR = get_section(O, "__DATA", "__objc_msgrefs");
5208 info.S = MR;
5209 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005210
Davide Italiano62507042015-12-11 22:27:59 +00005211 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5212 if (II == SectionRef())
5213 II = get_section(O, "__DATA", "__objc_imageinfo");
5214 info.S = II;
5215 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005216
5217 if (info.bindtable != nullptr)
5218 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005219}
5220
5221static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005222 SymbolAddressMap AddrMap;
5223 if (verbose)
5224 CreateSymbolAddressMap(O, &AddrMap);
5225
5226 std::vector<SectionRef> Sections;
5227 for (const SectionRef &Section : O->sections()) {
5228 StringRef SectName;
5229 Section.getName(SectName);
5230 Sections.push_back(Section);
5231 }
5232
5233 struct DisassembleInfo info;
5234 // Set up the block of info used by the Symbolizer call backs.
5235 info.verbose = verbose;
5236 info.O = O;
5237 info.AddrMap = &AddrMap;
5238 info.Sections = &Sections;
5239 info.class_name = nullptr;
5240 info.selector_name = nullptr;
5241 info.method = nullptr;
5242 info.demangled_name = nullptr;
5243 info.bindtable = nullptr;
5244 info.adrp_addr = 0;
5245 info.adrp_inst = 0;
5246
5247 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5248 if (CL != SectionRef()) {
5249 info.S = CL;
5250 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5251 } else {
5252 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5253 info.S = CL;
5254 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5255 }
5256
5257 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5258 if (CR != SectionRef()) {
5259 info.S = CR;
5260 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5261 } else {
5262 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5263 info.S = CR;
5264 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5265 }
5266
5267 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5268 if (SR != SectionRef()) {
5269 info.S = SR;
5270 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5271 } else {
5272 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5273 info.S = SR;
5274 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5275 }
5276
5277 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5278 if (CA != SectionRef()) {
5279 info.S = CA;
5280 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5281 } else {
5282 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5283 info.S = CA;
5284 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5285 }
5286
5287 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5288 if (PL != SectionRef()) {
5289 info.S = PL;
5290 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5291 } else {
5292 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5293 info.S = PL;
5294 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5295 }
5296
5297 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5298 if (MR != SectionRef()) {
5299 info.S = MR;
5300 print_message_refs32(MR, &info);
5301 } else {
5302 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5303 info.S = MR;
5304 print_message_refs32(MR, &info);
5305 }
5306
5307 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5308 if (II != SectionRef()) {
5309 info.S = II;
5310 print_image_info32(II, &info);
5311 } else {
5312 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5313 info.S = II;
5314 print_image_info32(II, &info);
5315 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005316}
5317
5318static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005319 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5320 const char *r, *name, *defs;
5321 struct objc_module_t module;
5322 SectionRef S, xS;
5323 struct objc_symtab_t symtab;
5324 struct objc_class_t objc_class;
5325 struct objc_category_t objc_category;
5326
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005327 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005328 S = get_section(O, "__OBJC", "__module_info");
5329 if (S == SectionRef())
5330 return false;
5331
5332 SymbolAddressMap AddrMap;
5333 if (verbose)
5334 CreateSymbolAddressMap(O, &AddrMap);
5335
5336 std::vector<SectionRef> Sections;
5337 for (const SectionRef &Section : O->sections()) {
5338 StringRef SectName;
5339 Section.getName(SectName);
5340 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005341 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005342
5343 struct DisassembleInfo info;
5344 // Set up the block of info used by the Symbolizer call backs.
5345 info.verbose = verbose;
5346 info.O = O;
5347 info.AddrMap = &AddrMap;
5348 info.Sections = &Sections;
5349 info.class_name = nullptr;
5350 info.selector_name = nullptr;
5351 info.method = nullptr;
5352 info.demangled_name = nullptr;
5353 info.bindtable = nullptr;
5354 info.adrp_addr = 0;
5355 info.adrp_inst = 0;
5356
5357 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5358 p = S.getAddress() + i;
5359 r = get_pointer_32(p, offset, left, S, &info, true);
5360 if (r == nullptr)
5361 return true;
5362 memset(&module, '\0', sizeof(struct objc_module_t));
5363 if (left < sizeof(struct objc_module_t)) {
5364 memcpy(&module, r, left);
5365 outs() << " (module extends past end of __module_info section)\n";
5366 } else
5367 memcpy(&module, r, sizeof(struct objc_module_t));
5368 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5369 swapStruct(module);
5370
5371 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5372 outs() << " version " << module.version << "\n";
5373 outs() << " size " << module.size << "\n";
5374 outs() << " name ";
5375 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5376 if (name != nullptr)
5377 outs() << format("%.*s", left, name);
5378 else
5379 outs() << format("0x%08" PRIx32, module.name)
5380 << "(not in an __OBJC section)";
5381 outs() << "\n";
5382
5383 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5384 if (module.symtab == 0 || r == nullptr) {
5385 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5386 << " (not in an __OBJC section)\n";
5387 continue;
5388 }
5389 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5390 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5391 defs_left = 0;
5392 defs = nullptr;
5393 if (left < sizeof(struct objc_symtab_t)) {
5394 memcpy(&symtab, r, left);
5395 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5396 } else {
5397 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5398 if (left > sizeof(struct objc_symtab_t)) {
5399 defs_left = left - sizeof(struct objc_symtab_t);
5400 defs = r + sizeof(struct objc_symtab_t);
5401 }
5402 }
5403 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5404 swapStruct(symtab);
5405
5406 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5407 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5408 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5409 if (r == nullptr)
5410 outs() << " (not in an __OBJC section)";
5411 outs() << "\n";
5412 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5413 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5414 if (symtab.cls_def_cnt > 0)
5415 outs() << "\tClass Definitions\n";
5416 for (j = 0; j < symtab.cls_def_cnt; j++) {
5417 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5418 outs() << "\t(remaining class defs entries entends past the end of the "
5419 << "section)\n";
5420 break;
5421 }
5422 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5423 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5424 sys::swapByteOrder(def);
5425
5426 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5427 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5428 if (r != nullptr) {
5429 if (left > sizeof(struct objc_class_t)) {
5430 outs() << "\n";
5431 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5432 } else {
5433 outs() << " (entends past the end of the section)\n";
5434 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5435 memcpy(&objc_class, r, left);
5436 }
5437 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5438 swapStruct(objc_class);
5439 print_objc_class_t(&objc_class, &info);
5440 } else {
5441 outs() << "(not in an __OBJC section)\n";
5442 }
5443
5444 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5445 outs() << "\tMeta Class";
5446 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5447 if (r != nullptr) {
5448 if (left > sizeof(struct objc_class_t)) {
5449 outs() << "\n";
5450 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5451 } else {
5452 outs() << " (entends past the end of the section)\n";
5453 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5454 memcpy(&objc_class, r, left);
5455 }
5456 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5457 swapStruct(objc_class);
5458 print_objc_class_t(&objc_class, &info);
5459 } else {
5460 outs() << "(not in an __OBJC section)\n";
5461 }
5462 }
5463 }
5464 if (symtab.cat_def_cnt > 0)
5465 outs() << "\tCategory Definitions\n";
5466 for (j = 0; j < symtab.cat_def_cnt; j++) {
5467 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5468 outs() << "\t(remaining category defs entries entends past the end of "
5469 << "the section)\n";
5470 break;
5471 }
5472 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5473 sizeof(uint32_t));
5474 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5475 sys::swapByteOrder(def);
5476
5477 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5478 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5479 << format("0x%08" PRIx32, def);
5480 if (r != nullptr) {
5481 if (left > sizeof(struct objc_category_t)) {
5482 outs() << "\n";
5483 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5484 } else {
5485 outs() << " (entends past the end of the section)\n";
5486 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5487 memcpy(&objc_category, r, left);
5488 }
5489 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5490 swapStruct(objc_category);
5491 print_objc_objc_category_t(&objc_category, &info);
5492 } else {
5493 outs() << "(not in an __OBJC section)\n";
5494 }
5495 }
5496 }
5497 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5498 if (II != SectionRef())
5499 print_image_info(II, &info);
5500
5501 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005502}
5503
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005504static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5505 uint32_t size, uint32_t addr) {
5506 SymbolAddressMap AddrMap;
5507 CreateSymbolAddressMap(O, &AddrMap);
5508
5509 std::vector<SectionRef> Sections;
5510 for (const SectionRef &Section : O->sections()) {
5511 StringRef SectName;
5512 Section.getName(SectName);
5513 Sections.push_back(Section);
5514 }
5515
5516 struct DisassembleInfo info;
5517 // Set up the block of info used by the Symbolizer call backs.
5518 info.verbose = true;
5519 info.O = O;
5520 info.AddrMap = &AddrMap;
5521 info.Sections = &Sections;
5522 info.class_name = nullptr;
5523 info.selector_name = nullptr;
5524 info.method = nullptr;
5525 info.demangled_name = nullptr;
5526 info.bindtable = nullptr;
5527 info.adrp_addr = 0;
5528 info.adrp_inst = 0;
5529
5530 const char *p;
5531 struct objc_protocol_t protocol;
5532 uint32_t left, paddr;
5533 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5534 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5535 left = size - (p - sect);
5536 if (left < sizeof(struct objc_protocol_t)) {
5537 outs() << "Protocol extends past end of __protocol section\n";
5538 memcpy(&protocol, p, left);
5539 } else
5540 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5541 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5542 swapStruct(protocol);
5543 paddr = addr + (p - sect);
5544 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5545 if (print_protocol(paddr, 0, &info))
5546 outs() << "(not in an __OBJC section)\n";
5547 }
5548}
5549
Kevin Enderby0fc11822015-04-01 20:57:01 +00005550static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5551 if (O->is64Bit())
5552 printObjc2_64bit_MetaData(O, verbose);
5553 else {
5554 MachO::mach_header H;
5555 H = O->getHeader();
5556 if (H.cputype == MachO::CPU_TYPE_ARM)
5557 printObjc2_32bit_MetaData(O, verbose);
5558 else {
5559 // This is the 32-bit non-arm cputype case. Which is normally
5560 // the first Objective-C ABI. But it may be the case of a
5561 // binary for the iOS simulator which is the second Objective-C
5562 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5563 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005564 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005565 printObjc2_32bit_MetaData(O, verbose);
5566 }
5567 }
5568}
5569
Kevin Enderbybf246f52014-09-24 23:08:22 +00005570// GuessLiteralPointer returns a string which for the item in the Mach-O file
5571// for the address passed in as ReferenceValue for printing as a comment with
5572// the instruction and also returns the corresponding type of that item
5573// indirectly through ReferenceType.
5574//
5575// If ReferenceValue is an address of literal cstring then a pointer to the
5576// cstring is returned and ReferenceType is set to
5577// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5578//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005579// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5580// Class ref that name is returned and the ReferenceType is set accordingly.
5581//
5582// Lastly, literals which are Symbol address in a literal pool are looked for
5583// and if found the symbol name is returned and ReferenceType is set to
5584// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5585//
5586// If there is no item in the Mach-O file for the address passed in as
5587// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005588static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5589 uint64_t ReferencePC,
5590 uint64_t *ReferenceType,
5591 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005592 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005593 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5594 uint64_t sect_addr = info->S.getAddress();
5595 uint64_t sect_offset = ReferencePC - sect_addr;
5596 bool reloc_found = false;
5597 DataRefImpl Rel;
5598 MachO::any_relocation_info RE;
5599 bool isExtern = false;
5600 SymbolRef Symbol;
5601 for (const RelocationRef &Reloc : info->S.relocations()) {
5602 uint64_t RelocOffset = Reloc.getOffset();
5603 if (RelocOffset == sect_offset) {
5604 Rel = Reloc.getRawDataRefImpl();
5605 RE = info->O->getRelocation(Rel);
5606 if (info->O->isRelocationScattered(RE))
5607 continue;
5608 isExtern = info->O->getPlainRelocationExternal(RE);
5609 if (isExtern) {
5610 symbol_iterator RelocSym = Reloc.getSymbol();
5611 Symbol = *RelocSym;
5612 }
5613 reloc_found = true;
5614 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005615 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005616 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005617 // If there is an external relocation entry for a symbol in a section
5618 // then used that symbol's value for the value of the reference.
5619 if (reloc_found && isExtern) {
5620 if (info->O->getAnyRelocationPCRel(RE)) {
5621 unsigned Type = info->O->getAnyRelocationType(RE);
5622 if (Type == MachO::X86_64_RELOC_SIGNED) {
5623 ReferenceValue = Symbol.getValue();
5624 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005625 }
5626 }
5627 }
5628
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005629 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5630 // Message refs and Class refs.
5631 bool classref, selref, msgref, cfstring;
5632 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5633 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005634 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005635 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5636 // And the pointer_value in that section is typically zero as it will be
5637 // set by dyld as part of the "bind information".
5638 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5639 if (name != nullptr) {
5640 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005641 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005642 if (class_name != nullptr && class_name[1] == '_' &&
5643 class_name[2] != '\0') {
5644 info->class_name = class_name + 2;
5645 return name;
5646 }
5647 }
5648 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005649
David Blaikie33dd45d02015-03-23 18:39:02 +00005650 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005651 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5652 const char *name =
5653 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5654 if (name != nullptr)
5655 info->class_name = name;
5656 else
5657 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005658 return name;
5659 }
5660
David Blaikie33dd45d02015-03-23 18:39:02 +00005661 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005662 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5663 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5664 return name;
5665 }
5666
David Blaikie33dd45d02015-03-23 18:39:02 +00005667 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005668 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5669
5670 if (pointer_value != 0)
5671 ReferenceValue = pointer_value;
5672
5673 const char *name = GuessCstringPointer(ReferenceValue, info);
5674 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005675 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005676 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5677 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005678 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005679 info->class_name = nullptr;
5680 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5681 info->selector_name = name;
5682 } else
5683 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5684 return name;
5685 }
5686
5687 // Lastly look for an indirect symbol with this ReferenceValue which is in
5688 // a literal pool. If found return that symbol name.
5689 name = GuessIndirectSymbol(ReferenceValue, info);
5690 if (name) {
5691 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5692 return name;
5693 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005694
5695 return nullptr;
5696}
5697
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005698// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005699// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005700// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5701// is created and returns the symbol name that matches the ReferenceValue or
5702// nullptr if none. The ReferenceType is passed in for the IN type of
5703// reference the instruction is making from the values in defined in the header
5704// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5705// Out type and the ReferenceName will also be set which is added as a comment
5706// to the disassembled instruction.
5707//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005708#if HAVE_CXXABI_H
5709// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005710// returned through ReferenceName and ReferenceType is set to
5711// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005712#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005713//
5714// When this is called to get a symbol name for a branch target then the
5715// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5716// SymbolValue will be looked for in the indirect symbol table to determine if
5717// it is an address for a symbol stub. If so then the symbol name for that
5718// stub is returned indirectly through ReferenceName and then ReferenceType is
5719// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5720//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005721// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005722// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5723// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5724// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005725// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005726static const char *SymbolizerSymbolLookUp(void *DisInfo,
5727 uint64_t ReferenceValue,
5728 uint64_t *ReferenceType,
5729 uint64_t ReferencePC,
5730 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005731 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005732 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005733 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005734 *ReferenceName = nullptr;
5735 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005736 return nullptr;
5737 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005738
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005739 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005740
Kevin Enderby85974882014-09-26 22:20:44 +00005741 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5742 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005743 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005744 method_reference(info, ReferenceType, ReferenceName);
5745 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5746 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5747 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005748#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005749 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005750 if (info->demangled_name != nullptr)
5751 free(info->demangled_name);
5752 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005753 info->demangled_name =
5754 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005755 if (info->demangled_name != nullptr) {
5756 *ReferenceName = info->demangled_name;
5757 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5758 } else
5759 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5760 } else
5761#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005762 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5763 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5764 *ReferenceName =
5765 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005766 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005767 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005768 else
5769 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005770 // If this is arm64 and the reference is an adrp instruction save the
5771 // instruction, passed in ReferenceValue and the address of the instruction
5772 // for use later if we see and add immediate instruction.
5773 } else if (info->O->getArch() == Triple::aarch64 &&
5774 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5775 info->adrp_inst = ReferenceValue;
5776 info->adrp_addr = ReferencePC;
5777 SymbolName = nullptr;
5778 *ReferenceName = nullptr;
5779 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5780 // If this is arm64 and reference is an add immediate instruction and we
5781 // have
5782 // seen an adrp instruction just before it and the adrp's Xd register
5783 // matches
5784 // this add's Xn register reconstruct the value being referenced and look to
5785 // see if it is a literal pointer. Note the add immediate instruction is
5786 // passed in ReferenceValue.
5787 } else if (info->O->getArch() == Triple::aarch64 &&
5788 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5789 ReferencePC - 4 == info->adrp_addr &&
5790 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5791 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5792 uint32_t addxri_inst;
5793 uint64_t adrp_imm, addxri_imm;
5794
5795 adrp_imm =
5796 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5797 if (info->adrp_inst & 0x0200000)
5798 adrp_imm |= 0xfffffffffc000000LL;
5799
5800 addxri_inst = ReferenceValue;
5801 addxri_imm = (addxri_inst >> 10) & 0xfff;
5802 if (((addxri_inst >> 22) & 0x3) == 1)
5803 addxri_imm <<= 12;
5804
5805 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5806 (adrp_imm << 12) + addxri_imm;
5807
5808 *ReferenceName =
5809 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5810 if (*ReferenceName == nullptr)
5811 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5812 // If this is arm64 and the reference is a load register instruction and we
5813 // have seen an adrp instruction just before it and the adrp's Xd register
5814 // matches this add's Xn register reconstruct the value being referenced and
5815 // look to see if it is a literal pointer. Note the load register
5816 // instruction is passed in ReferenceValue.
5817 } else if (info->O->getArch() == Triple::aarch64 &&
5818 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5819 ReferencePC - 4 == info->adrp_addr &&
5820 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5821 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5822 uint32_t ldrxui_inst;
5823 uint64_t adrp_imm, ldrxui_imm;
5824
5825 adrp_imm =
5826 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5827 if (info->adrp_inst & 0x0200000)
5828 adrp_imm |= 0xfffffffffc000000LL;
5829
5830 ldrxui_inst = ReferenceValue;
5831 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5832
5833 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5834 (adrp_imm << 12) + (ldrxui_imm << 3);
5835
5836 *ReferenceName =
5837 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5838 if (*ReferenceName == nullptr)
5839 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5840 }
5841 // If this arm64 and is an load register (PC-relative) instruction the
5842 // ReferenceValue is the PC plus the immediate value.
5843 else if (info->O->getArch() == Triple::aarch64 &&
5844 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5845 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5846 *ReferenceName =
5847 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5848 if (*ReferenceName == nullptr)
5849 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005850 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005851#if HAVE_CXXABI_H
5852 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5853 if (info->demangled_name != nullptr)
5854 free(info->demangled_name);
5855 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005856 info->demangled_name =
5857 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005858 if (info->demangled_name != nullptr) {
5859 *ReferenceName = info->demangled_name;
5860 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5861 }
5862 }
5863#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005864 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005865 *ReferenceName = nullptr;
5866 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5867 }
5868
5869 return SymbolName;
5870}
5871
Kevin Enderbybf246f52014-09-24 23:08:22 +00005872/// \brief Emits the comments that are stored in the CommentStream.
5873/// Each comment in the CommentStream must end with a newline.
5874static void emitComments(raw_svector_ostream &CommentStream,
5875 SmallString<128> &CommentsToEmit,
5876 formatted_raw_ostream &FormattedOS,
5877 const MCAsmInfo &MAI) {
5878 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005879 StringRef Comments = CommentsToEmit.str();
5880 // Get the default information for printing a comment.
5881 const char *CommentBegin = MAI.getCommentString();
5882 unsigned CommentColumn = MAI.getCommentColumn();
5883 bool IsFirst = true;
5884 while (!Comments.empty()) {
5885 if (!IsFirst)
5886 FormattedOS << '\n';
5887 // Emit a line of comments.
5888 FormattedOS.PadToColumn(CommentColumn);
5889 size_t Position = Comments.find('\n');
5890 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5891 // Move after the newline character.
5892 Comments = Comments.substr(Position + 1);
5893 IsFirst = false;
5894 }
5895 FormattedOS.flush();
5896
5897 // Tell the comment stream that the vector changed underneath it.
5898 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005899}
5900
Kevin Enderby95df54c2015-02-04 01:01:38 +00005901static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5902 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005903 const char *McpuDefault = nullptr;
5904 const Target *ThumbTarget = nullptr;
5905 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005906 if (!TheTarget) {
5907 // GetTarget prints out stuff.
5908 return;
5909 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005910 if (MCPU.empty() && McpuDefault)
5911 MCPU = McpuDefault;
5912
Ahmed Charles56440fd2014-03-06 05:51:42 +00005913 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005914 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005915 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005916 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005917
Kevin Enderbyc9595622014-08-06 23:24:41 +00005918 // Package up features to be passed to target/subtarget
5919 std::string FeaturesStr;
5920 if (MAttrs.size()) {
5921 SubtargetFeatures Features;
5922 for (unsigned i = 0; i != MAttrs.size(); ++i)
5923 Features.AddFeature(MAttrs[i]);
5924 FeaturesStr = Features.getString();
5925 }
5926
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005927 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005928 std::unique_ptr<const MCRegisterInfo> MRI(
5929 TheTarget->createMCRegInfo(TripleName));
5930 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005931 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005932 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005933 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005934 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005935 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005936 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005937 std::unique_ptr<MCSymbolizer> Symbolizer;
5938 struct DisassembleInfo SymbolizerInfo;
5939 std::unique_ptr<MCRelocationInfo> RelInfo(
5940 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5941 if (RelInfo) {
5942 Symbolizer.reset(TheTarget->createMCSymbolizer(
5943 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005944 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005945 DisAsm->setSymbolizer(std::move(Symbolizer));
5946 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005947 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005948 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005949 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005950 // Set the display preference for hex vs. decimal immediates.
5951 IP->setPrintImmHex(PrintImmHex);
5952 // Comment stream and backing vector.
5953 SmallString<128> CommentsToEmit;
5954 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005955 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5956 // if it is done then arm64 comments for string literals don't get printed
5957 // and some constant get printed instead and not setting it causes intel
5958 // (32-bit and 64-bit) comments printed with different spacing before the
5959 // comment causing different diffs with the 'C' disassembler library API.
5960 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005961
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005962 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005963 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005964 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005965 return;
5966 }
5967
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005968 // Set up thumb disassembler.
5969 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5970 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5971 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005972 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005973 std::unique_ptr<MCInstPrinter> ThumbIP;
5974 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005975 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5976 struct DisassembleInfo ThumbSymbolizerInfo;
5977 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005978 if (ThumbTarget) {
5979 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5980 ThumbAsmInfo.reset(
5981 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5982 ThumbSTI.reset(
5983 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5984 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5985 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005986 MCContext *PtrThumbCtx = ThumbCtx.get();
5987 ThumbRelInfo.reset(
5988 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5989 if (ThumbRelInfo) {
5990 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5991 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005992 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005993 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5994 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005995 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5996 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005997 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5998 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005999 // Set the display preference for hex vs. decimal immediates.
6000 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006001 }
6002
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006003 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006004 errs() << "error: couldn't initialize disassembler for target "
6005 << ThumbTripleName << '\n';
6006 return;
6007 }
6008
Charles Davis8bdfafd2013-09-01 04:28:48 +00006009 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006010
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006011 // FIXME: Using the -cfg command line option, this code used to be able to
6012 // annotate relocations with the referenced symbol's name, and if this was
6013 // inside a __[cf]string section, the data it points to. This is now replaced
6014 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006015 std::vector<SectionRef> Sections;
6016 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006017 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006018 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006019
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006020 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006021 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006022
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006023 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006024 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006025
Kevin Enderby273ae012013-06-06 17:20:50 +00006026 // Build a data in code table that is sorted on by the address of each entry.
6027 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006028 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006029 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006030 else
6031 BaseAddress = BaseSegmentAddress;
6032 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006033 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006034 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006035 uint32_t Offset;
6036 DI->getOffset(Offset);
6037 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6038 }
6039 array_pod_sort(Dices.begin(), Dices.end());
6040
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006041#ifndef NDEBUG
6042 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6043#else
6044 raw_ostream &DebugOut = nulls();
6045#endif
6046
Ahmed Charles56440fd2014-03-06 05:51:42 +00006047 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006048 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006049 // Try to find debug info and set up the DIContext for it.
6050 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006051 // A separate DSym file path was specified, parse it as a macho file,
6052 // get the sections and supply it to the section name parsing machinery.
6053 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006054 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006055 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006056 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006057 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006058 return;
6059 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006060 DbgObj =
6061 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6062 .get()
6063 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006064 }
6065
Eric Christopher7370b552012-11-12 21:40:38 +00006066 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006067 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006068 }
6069
Colin LeMahieufcc32762015-07-29 19:08:10 +00006070 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006071 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006072
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006073 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006074 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006075 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6076 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006077
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006078 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006079
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006080 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006081 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006082 continue;
6083
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006084 StringRef BytesStr;
6085 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006086 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6087 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006088 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006089
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006090 bool symbolTableWorked = false;
6091
Kevin Enderbybf246f52014-09-24 23:08:22 +00006092 // Create a map of symbol addresses to symbol names for use by
6093 // the SymbolizerSymbolLookUp() routine.
6094 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006095 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006096 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006097 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
6098 if (std::error_code EC = STOrErr.getError())
6099 report_fatal_error(EC.message());
6100 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006101 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6102 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006103 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006104 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6105 if (std::error_code EC = SymNameOrErr.getError())
6106 report_fatal_error(EC.message());
6107 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006108 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006109 if (!DisSymName.empty() && DisSymName == SymName)
6110 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006111 }
6112 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006113 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006114 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6115 return;
6116 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006117 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006118 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006119 SymbolizerInfo.O = MachOOF;
6120 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006121 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006122 SymbolizerInfo.Sections = &Sections;
6123 SymbolizerInfo.class_name = nullptr;
6124 SymbolizerInfo.selector_name = nullptr;
6125 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006126 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006127 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006128 SymbolizerInfo.adrp_addr = 0;
6129 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006130 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006131 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006132 ThumbSymbolizerInfo.O = MachOOF;
6133 ThumbSymbolizerInfo.S = Sections[SectIdx];
6134 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6135 ThumbSymbolizerInfo.Sections = &Sections;
6136 ThumbSymbolizerInfo.class_name = nullptr;
6137 ThumbSymbolizerInfo.selector_name = nullptr;
6138 ThumbSymbolizerInfo.method = nullptr;
6139 ThumbSymbolizerInfo.demangled_name = nullptr;
6140 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006141 ThumbSymbolizerInfo.adrp_addr = 0;
6142 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006143
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006144 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006145 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006146 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6147 if (std::error_code EC = SymNameOrErr.getError())
6148 report_fatal_error(EC.message());
6149 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006150
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006151 ErrorOr<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6152 if (std::error_code EC = STOrErr.getError())
6153 report_fatal_error(EC.message());
6154 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006155 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006156 continue;
6157
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006158 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006159 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006160 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006161 continue;
6162
Kevin Enderby6a221752015-03-17 17:10:57 +00006163 // If we are only disassembling one symbol see if this is that symbol.
6164 if (!DisSymName.empty() && DisSymName != SymName)
6165 continue;
6166
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006167 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006168 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006169 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006170 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006171
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006172 // Stop disassembling either at the beginning of the next symbol or at
6173 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006174 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006175 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006176 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006177 while (Symbols.size() > NextSymIdx) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006178 ErrorOr<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6179 if (std::error_code EC = STOrErr.getError())
6180 report_fatal_error(EC.message());
6181 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006182 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006183 containsNextSym =
6184 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006185 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006186 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006187 break;
6188 }
6189 ++NextSymIdx;
6190 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006191
Rafael Espindola80291272014-10-08 15:28:58 +00006192 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006193 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006194 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006195
6196 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006197
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006198 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6199 bool isThumb =
6200 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6201
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006202 outs() << SymName << ":\n";
6203 DILineInfo lastLine;
6204 for (uint64_t Index = Start; Index < End; Index += Size) {
6205 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006206
Kevin Enderbybf246f52014-09-24 23:08:22 +00006207 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006208 if (!NoLeadingAddr) {
6209 if (FullLeadingAddr) {
6210 if (MachOOF->is64Bit())
6211 outs() << format("%016" PRIx64, PC);
6212 else
6213 outs() << format("%08" PRIx64, PC);
6214 } else {
6215 outs() << format("%8" PRIx64 ":", PC);
6216 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006217 }
6218 if (!NoShowRawInsn)
6219 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006220
6221 // Check the data in code table here to see if this is data not an
6222 // instruction to be disassembled.
6223 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006224 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006225 dice_table_iterator DTI =
6226 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6227 compareDiceTableEntries);
6228 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006229 uint16_t Length;
6230 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006231 uint16_t Kind;
6232 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006233 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006234 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6235 (PC == (DTI->first + Length - 1)) && (Length & 1))
6236 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006237 continue;
6238 }
6239
Kevin Enderbybf246f52014-09-24 23:08:22 +00006240 SmallVector<char, 64> AnnotationsBytes;
6241 raw_svector_ostream Annotations(AnnotationsBytes);
6242
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006243 bool gotInst;
6244 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006245 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006246 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006247 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006248 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006249 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006250 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006251 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006252 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006253 }
6254 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006255 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006256 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006257 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006258 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006259 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006260 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006261
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006262 // Print debug info.
6263 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006264 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006265 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006266 if (dli != lastLine && dli.Line != 0)
6267 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6268 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006269 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006270 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006271 outs() << "\n";
6272 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006273 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006274 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006275 outs() << format("\t.byte 0x%02x #bad opcode\n",
6276 *(Bytes.data() + Index) & 0xff);
6277 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006278 } else if (Arch == Triple::aarch64) {
6279 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6280 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6281 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6282 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6283 outs() << format("\t.long\t0x%08x\n", opcode);
6284 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006285 } else {
6286 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6287 if (Size == 0)
6288 Size = 1; // skip illegible bytes
6289 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006290 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006291 }
6292 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006293 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006294 // Reading the symbol table didn't work, disassemble the whole section.
6295 uint64_t SectAddress = Sections[SectIdx].getAddress();
6296 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006297 uint64_t InstSize;
6298 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006299 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006300
Kevin Enderbybf246f52014-09-24 23:08:22 +00006301 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006302 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6303 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006304 if (!NoLeadingAddr) {
6305 if (FullLeadingAddr) {
6306 if (MachOOF->is64Bit())
6307 outs() << format("%016" PRIx64, PC);
6308 else
6309 outs() << format("%08" PRIx64, PC);
6310 } else {
6311 outs() << format("%8" PRIx64 ":", PC);
6312 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006313 }
6314 if (!NoShowRawInsn) {
6315 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006316 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006317 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006318 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006319 outs() << "\n";
6320 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006321 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006322 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006323 outs() << format("\t.byte 0x%02x #bad opcode\n",
6324 *(Bytes.data() + Index) & 0xff);
6325 InstSize = 1; // skip exactly one illegible byte and move on.
6326 } else {
6327 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6328 if (InstSize == 0)
6329 InstSize = 1; // skip illegible bytes
6330 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006331 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006332 }
6333 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006334 // The TripleName's need to be reset if we are called again for a different
6335 // archtecture.
6336 TripleName = "";
6337 ThumbTripleName = "";
6338
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006339 if (SymbolizerInfo.method != nullptr)
6340 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006341 if (SymbolizerInfo.demangled_name != nullptr)
6342 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006343 if (SymbolizerInfo.bindtable != nullptr)
6344 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006345 if (ThumbSymbolizerInfo.method != nullptr)
6346 free(ThumbSymbolizerInfo.method);
6347 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6348 free(ThumbSymbolizerInfo.demangled_name);
6349 if (ThumbSymbolizerInfo.bindtable != nullptr)
6350 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006351 }
6352}
Tim Northover4bd286a2014-08-01 13:07:19 +00006353
Tim Northover39c70bb2014-08-12 11:52:59 +00006354//===----------------------------------------------------------------------===//
6355// __compact_unwind section dumping
6356//===----------------------------------------------------------------------===//
6357
Tim Northover4bd286a2014-08-01 13:07:19 +00006358namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006359
6360template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006361 using llvm::support::little;
6362 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006363
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006364 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6365 Buf += sizeof(T);
6366 return Val;
6367}
Tim Northover39c70bb2014-08-12 11:52:59 +00006368
Tim Northover4bd286a2014-08-01 13:07:19 +00006369struct CompactUnwindEntry {
6370 uint32_t OffsetInSection;
6371
6372 uint64_t FunctionAddr;
6373 uint32_t Length;
6374 uint32_t CompactEncoding;
6375 uint64_t PersonalityAddr;
6376 uint64_t LSDAAddr;
6377
6378 RelocationRef FunctionReloc;
6379 RelocationRef PersonalityReloc;
6380 RelocationRef LSDAReloc;
6381
6382 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006383 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006384 if (Is64)
6385 read<uint64_t>(Contents.data() + Offset);
6386 else
6387 read<uint32_t>(Contents.data() + Offset);
6388 }
6389
6390private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006391 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006392 FunctionAddr = readNext<UIntPtr>(Buf);
6393 Length = readNext<uint32_t>(Buf);
6394 CompactEncoding = readNext<uint32_t>(Buf);
6395 PersonalityAddr = readNext<UIntPtr>(Buf);
6396 LSDAAddr = readNext<UIntPtr>(Buf);
6397 }
6398};
6399}
6400
6401/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6402/// and data being relocated, determine the best base Name and Addend to use for
6403/// display purposes.
6404///
6405/// 1. An Extern relocation will directly reference a symbol (and the data is
6406/// then already an addend), so use that.
6407/// 2. Otherwise the data is an offset in the object file's layout; try to find
6408// a symbol before it in the same section, and use the offset from there.
6409/// 3. Finally, if all that fails, fall back to an offset from the start of the
6410/// referenced section.
6411static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6412 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006413 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006414 StringRef &Name, uint64_t &Addend) {
6415 if (Reloc.getSymbol() != Obj->symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006416 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6417 if (std::error_code EC = NameOrErr.getError())
6418 report_fatal_error(EC.message());
6419 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006420 Addend = Addr;
6421 return;
6422 }
6423
6424 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006425 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006426
Rafael Espindola80291272014-10-08 15:28:58 +00006427 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006428
6429 auto Sym = Symbols.upper_bound(Addr);
6430 if (Sym == Symbols.begin()) {
6431 // The first symbol in the object is after this reference, the best we can
6432 // do is section-relative notation.
6433 RelocSection.getName(Name);
6434 Addend = Addr - SectionAddr;
6435 return;
6436 }
6437
6438 // Go back one so that SymbolAddress <= Addr.
6439 --Sym;
6440
Rafael Espindola8bab8892015-08-07 23:27:14 +00006441 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006442 if (RelocSection == *SymSection) {
6443 // There's a valid symbol in the same section before this reference.
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006444 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6445 if (std::error_code EC = NameOrErr.getError())
6446 report_fatal_error(EC.message());
6447 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006448 Addend = Addr - Sym->first;
6449 return;
6450 }
6451
6452 // There is a symbol before this reference, but it's in a different
6453 // section. Probably not helpful to mention it, so use the section name.
6454 RelocSection.getName(Name);
6455 Addend = Addr - SectionAddr;
6456}
6457
6458static void printUnwindRelocDest(const MachOObjectFile *Obj,
6459 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006460 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006461 StringRef Name;
6462 uint64_t Addend;
6463
Rafael Espindola854038e2015-06-26 14:51:16 +00006464 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006465 return;
6466
Tim Northover4bd286a2014-08-01 13:07:19 +00006467 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6468
6469 outs() << Name;
6470 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006471 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006472}
6473
6474static void
6475printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6476 std::map<uint64_t, SymbolRef> &Symbols,
6477 const SectionRef &CompactUnwind) {
6478
6479 assert(Obj->isLittleEndian() &&
6480 "There should not be a big-endian .o with __compact_unwind");
6481
6482 bool Is64 = Obj->is64Bit();
6483 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6484 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6485
6486 StringRef Contents;
6487 CompactUnwind.getContents(Contents);
6488
6489 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6490
6491 // First populate the initial raw offsets, encodings and so on from the entry.
6492 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6493 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6494 CompactUnwinds.push_back(Entry);
6495 }
6496
6497 // Next we need to look at the relocations to find out what objects are
6498 // actually being referred to.
6499 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006500 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006501
6502 uint32_t EntryIdx = RelocAddress / EntrySize;
6503 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6504 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6505
6506 if (OffsetInEntry == 0)
6507 Entry.FunctionReloc = Reloc;
6508 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6509 Entry.PersonalityReloc = Reloc;
6510 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6511 Entry.LSDAReloc = Reloc;
6512 else
6513 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6514 }
6515
6516 // Finally, we're ready to print the data we've gathered.
6517 outs() << "Contents of __compact_unwind section:\n";
6518 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006519 outs() << " Entry at offset "
6520 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006521
6522 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006523 outs() << " start: " << format("0x%" PRIx64,
6524 Entry.FunctionAddr) << ' ';
6525 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006526 outs() << '\n';
6527
6528 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006529 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6530 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006531 // 3. The 32-bit compact encoding.
6532 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006533 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006534
6535 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006536 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006537 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006538 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006539 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6540 Entry.PersonalityAddr);
6541 outs() << '\n';
6542 }
6543
6544 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006545 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006546 outs() << " LSDA: " << format("0x%" PRIx64,
6547 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006548 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6549 outs() << '\n';
6550 }
6551 }
6552}
6553
Tim Northover39c70bb2014-08-12 11:52:59 +00006554//===----------------------------------------------------------------------===//
6555// __unwind_info section dumping
6556//===----------------------------------------------------------------------===//
6557
6558static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6559 const char *Pos = PageStart;
6560 uint32_t Kind = readNext<uint32_t>(Pos);
6561 (void)Kind;
6562 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6563
6564 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6565 uint16_t NumEntries = readNext<uint16_t>(Pos);
6566
6567 Pos = PageStart + EntriesStart;
6568 for (unsigned i = 0; i < NumEntries; ++i) {
6569 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6570 uint32_t Encoding = readNext<uint32_t>(Pos);
6571
6572 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006573 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6574 << ", "
6575 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006576 }
6577}
6578
6579static void printCompressedSecondLevelUnwindPage(
6580 const char *PageStart, uint32_t FunctionBase,
6581 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6582 const char *Pos = PageStart;
6583 uint32_t Kind = readNext<uint32_t>(Pos);
6584 (void)Kind;
6585 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6586
6587 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6588 uint16_t NumEntries = readNext<uint16_t>(Pos);
6589
6590 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6591 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006592 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6593 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006594
6595 Pos = PageStart + EntriesStart;
6596 for (unsigned i = 0; i < NumEntries; ++i) {
6597 uint32_t Entry = readNext<uint32_t>(Pos);
6598 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6599 uint32_t EncodingIdx = Entry >> 24;
6600
6601 uint32_t Encoding;
6602 if (EncodingIdx < CommonEncodings.size())
6603 Encoding = CommonEncodings[EncodingIdx];
6604 else
6605 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6606
6607 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006608 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6609 << ", "
6610 << "encoding[" << EncodingIdx
6611 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006612 }
6613}
6614
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006615static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6616 std::map<uint64_t, SymbolRef> &Symbols,
6617 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006618
6619 assert(Obj->isLittleEndian() &&
6620 "There should not be a big-endian .o with __unwind_info");
6621
6622 outs() << "Contents of __unwind_info section:\n";
6623
6624 StringRef Contents;
6625 UnwindInfo.getContents(Contents);
6626 const char *Pos = Contents.data();
6627
6628 //===----------------------------------
6629 // Section header
6630 //===----------------------------------
6631
6632 uint32_t Version = readNext<uint32_t>(Pos);
6633 outs() << " Version: "
6634 << format("0x%" PRIx32, Version) << '\n';
6635 assert(Version == 1 && "only understand version 1");
6636
6637 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6638 outs() << " Common encodings array section offset: "
6639 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6640 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6641 outs() << " Number of common encodings in array: "
6642 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6643
6644 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6645 outs() << " Personality function array section offset: "
6646 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6647 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6648 outs() << " Number of personality functions in array: "
6649 << format("0x%" PRIx32, NumPersonalities) << '\n';
6650
6651 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6652 outs() << " Index array section offset: "
6653 << format("0x%" PRIx32, IndicesStart) << '\n';
6654 uint32_t NumIndices = readNext<uint32_t>(Pos);
6655 outs() << " Number of indices in array: "
6656 << format("0x%" PRIx32, NumIndices) << '\n';
6657
6658 //===----------------------------------
6659 // A shared list of common encodings
6660 //===----------------------------------
6661
6662 // These occupy indices in the range [0, N] whenever an encoding is referenced
6663 // from a compressed 2nd level index table. In practice the linker only
6664 // creates ~128 of these, so that indices are available to embed encodings in
6665 // the 2nd level index.
6666
6667 SmallVector<uint32_t, 64> CommonEncodings;
6668 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6669 Pos = Contents.data() + CommonEncodingsStart;
6670 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6671 uint32_t Encoding = readNext<uint32_t>(Pos);
6672 CommonEncodings.push_back(Encoding);
6673
6674 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6675 << '\n';
6676 }
6677
Tim Northover39c70bb2014-08-12 11:52:59 +00006678 //===----------------------------------
6679 // Personality functions used in this executable
6680 //===----------------------------------
6681
6682 // There should be only a handful of these (one per source language,
6683 // roughly). Particularly since they only get 2 bits in the compact encoding.
6684
6685 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6686 Pos = Contents.data() + PersonalitiesStart;
6687 for (unsigned i = 0; i < NumPersonalities; ++i) {
6688 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6689 outs() << " personality[" << i + 1
6690 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6691 }
6692
6693 //===----------------------------------
6694 // The level 1 index entries
6695 //===----------------------------------
6696
6697 // These specify an approximate place to start searching for the more detailed
6698 // information, sorted by PC.
6699
6700 struct IndexEntry {
6701 uint32_t FunctionOffset;
6702 uint32_t SecondLevelPageStart;
6703 uint32_t LSDAStart;
6704 };
6705
6706 SmallVector<IndexEntry, 4> IndexEntries;
6707
6708 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6709 Pos = Contents.data() + IndicesStart;
6710 for (unsigned i = 0; i < NumIndices; ++i) {
6711 IndexEntry Entry;
6712
6713 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6714 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6715 Entry.LSDAStart = readNext<uint32_t>(Pos);
6716 IndexEntries.push_back(Entry);
6717
6718 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006719 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6720 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006721 << "2nd level page offset="
6722 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006723 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006724 }
6725
Tim Northover39c70bb2014-08-12 11:52:59 +00006726 //===----------------------------------
6727 // Next come the LSDA tables
6728 //===----------------------------------
6729
6730 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6731 // the first top-level index's LSDAOffset to the last (sentinel).
6732
6733 outs() << " LSDA descriptors:\n";
6734 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6735 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6736 (2 * sizeof(uint32_t));
6737 for (int i = 0; i < NumLSDAs; ++i) {
6738 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6739 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6740 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006741 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6742 << ", "
6743 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006744 }
6745
6746 //===----------------------------------
6747 // Finally, the 2nd level indices
6748 //===----------------------------------
6749
6750 // Generally these are 4K in size, and have 2 possible forms:
6751 // + Regular stores up to 511 entries with disparate encodings
6752 // + Compressed stores up to 1021 entries if few enough compact encoding
6753 // values are used.
6754 outs() << " Second level indices:\n";
6755 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6756 // The final sentinel top-level index has no associated 2nd level page
6757 if (IndexEntries[i].SecondLevelPageStart == 0)
6758 break;
6759
6760 outs() << " Second level index[" << i << "]: "
6761 << "offset in section="
6762 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6763 << ", "
6764 << "base function offset="
6765 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6766
6767 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006768 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006769 if (Kind == 2)
6770 printRegularSecondLevelUnwindPage(Pos);
6771 else if (Kind == 3)
6772 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6773 CommonEncodings);
6774 else
6775 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006776 }
6777}
6778
Tim Northover4bd286a2014-08-01 13:07:19 +00006779void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6780 std::map<uint64_t, SymbolRef> Symbols;
6781 for (const SymbolRef &SymRef : Obj->symbols()) {
6782 // Discard any undefined or absolute symbols. They're not going to take part
6783 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006784 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006785 if (Section == Obj->section_end())
6786 continue;
6787
Rafael Espindoladea00162015-07-03 17:44:18 +00006788 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006789 Symbols.insert(std::make_pair(Addr, SymRef));
6790 }
6791
6792 for (const SectionRef &Section : Obj->sections()) {
6793 StringRef SectName;
6794 Section.getName(SectName);
6795 if (SectName == "__compact_unwind")
6796 printMachOCompactUnwindSection(Obj, Symbols, Section);
6797 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006798 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006799 }
6800}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006801
6802static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6803 uint32_t cpusubtype, uint32_t filetype,
6804 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6805 bool verbose) {
6806 outs() << "Mach header\n";
6807 outs() << " magic cputype cpusubtype caps filetype ncmds "
6808 "sizeofcmds flags\n";
6809 if (verbose) {
6810 if (magic == MachO::MH_MAGIC)
6811 outs() << " MH_MAGIC";
6812 else if (magic == MachO::MH_MAGIC_64)
6813 outs() << "MH_MAGIC_64";
6814 else
6815 outs() << format(" 0x%08" PRIx32, magic);
6816 switch (cputype) {
6817 case MachO::CPU_TYPE_I386:
6818 outs() << " I386";
6819 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6820 case MachO::CPU_SUBTYPE_I386_ALL:
6821 outs() << " ALL";
6822 break;
6823 default:
6824 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6825 break;
6826 }
6827 break;
6828 case MachO::CPU_TYPE_X86_64:
6829 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006830 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6831 case MachO::CPU_SUBTYPE_X86_64_ALL:
6832 outs() << " ALL";
6833 break;
6834 case MachO::CPU_SUBTYPE_X86_64_H:
6835 outs() << " Haswell";
6836 break;
6837 default:
6838 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6839 break;
6840 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006841 break;
6842 case MachO::CPU_TYPE_ARM:
6843 outs() << " ARM";
6844 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6845 case MachO::CPU_SUBTYPE_ARM_ALL:
6846 outs() << " ALL";
6847 break;
6848 case MachO::CPU_SUBTYPE_ARM_V4T:
6849 outs() << " V4T";
6850 break;
6851 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6852 outs() << " V5TEJ";
6853 break;
6854 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6855 outs() << " XSCALE";
6856 break;
6857 case MachO::CPU_SUBTYPE_ARM_V6:
6858 outs() << " V6";
6859 break;
6860 case MachO::CPU_SUBTYPE_ARM_V6M:
6861 outs() << " V6M";
6862 break;
6863 case MachO::CPU_SUBTYPE_ARM_V7:
6864 outs() << " V7";
6865 break;
6866 case MachO::CPU_SUBTYPE_ARM_V7EM:
6867 outs() << " V7EM";
6868 break;
6869 case MachO::CPU_SUBTYPE_ARM_V7K:
6870 outs() << " V7K";
6871 break;
6872 case MachO::CPU_SUBTYPE_ARM_V7M:
6873 outs() << " V7M";
6874 break;
6875 case MachO::CPU_SUBTYPE_ARM_V7S:
6876 outs() << " V7S";
6877 break;
6878 default:
6879 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6880 break;
6881 }
6882 break;
6883 case MachO::CPU_TYPE_ARM64:
6884 outs() << " ARM64";
6885 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6886 case MachO::CPU_SUBTYPE_ARM64_ALL:
6887 outs() << " ALL";
6888 break;
6889 default:
6890 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6891 break;
6892 }
6893 break;
6894 case MachO::CPU_TYPE_POWERPC:
6895 outs() << " PPC";
6896 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6897 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6898 outs() << " ALL";
6899 break;
6900 default:
6901 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6902 break;
6903 }
6904 break;
6905 case MachO::CPU_TYPE_POWERPC64:
6906 outs() << " PPC64";
6907 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6908 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6909 outs() << " ALL";
6910 break;
6911 default:
6912 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6913 break;
6914 }
6915 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00006916 default:
6917 outs() << format(" %7d", cputype);
6918 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6919 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006920 }
6921 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00006922 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006923 } else {
6924 outs() << format(" 0x%02" PRIx32,
6925 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
6926 }
6927 switch (filetype) {
6928 case MachO::MH_OBJECT:
6929 outs() << " OBJECT";
6930 break;
6931 case MachO::MH_EXECUTE:
6932 outs() << " EXECUTE";
6933 break;
6934 case MachO::MH_FVMLIB:
6935 outs() << " FVMLIB";
6936 break;
6937 case MachO::MH_CORE:
6938 outs() << " CORE";
6939 break;
6940 case MachO::MH_PRELOAD:
6941 outs() << " PRELOAD";
6942 break;
6943 case MachO::MH_DYLIB:
6944 outs() << " DYLIB";
6945 break;
6946 case MachO::MH_DYLIB_STUB:
6947 outs() << " DYLIB_STUB";
6948 break;
6949 case MachO::MH_DYLINKER:
6950 outs() << " DYLINKER";
6951 break;
6952 case MachO::MH_BUNDLE:
6953 outs() << " BUNDLE";
6954 break;
6955 case MachO::MH_DSYM:
6956 outs() << " DSYM";
6957 break;
6958 case MachO::MH_KEXT_BUNDLE:
6959 outs() << " KEXTBUNDLE";
6960 break;
6961 default:
6962 outs() << format(" %10u", filetype);
6963 break;
6964 }
6965 outs() << format(" %5u", ncmds);
6966 outs() << format(" %10u", sizeofcmds);
6967 uint32_t f = flags;
6968 if (f & MachO::MH_NOUNDEFS) {
6969 outs() << " NOUNDEFS";
6970 f &= ~MachO::MH_NOUNDEFS;
6971 }
6972 if (f & MachO::MH_INCRLINK) {
6973 outs() << " INCRLINK";
6974 f &= ~MachO::MH_INCRLINK;
6975 }
6976 if (f & MachO::MH_DYLDLINK) {
6977 outs() << " DYLDLINK";
6978 f &= ~MachO::MH_DYLDLINK;
6979 }
6980 if (f & MachO::MH_BINDATLOAD) {
6981 outs() << " BINDATLOAD";
6982 f &= ~MachO::MH_BINDATLOAD;
6983 }
6984 if (f & MachO::MH_PREBOUND) {
6985 outs() << " PREBOUND";
6986 f &= ~MachO::MH_PREBOUND;
6987 }
6988 if (f & MachO::MH_SPLIT_SEGS) {
6989 outs() << " SPLIT_SEGS";
6990 f &= ~MachO::MH_SPLIT_SEGS;
6991 }
6992 if (f & MachO::MH_LAZY_INIT) {
6993 outs() << " LAZY_INIT";
6994 f &= ~MachO::MH_LAZY_INIT;
6995 }
6996 if (f & MachO::MH_TWOLEVEL) {
6997 outs() << " TWOLEVEL";
6998 f &= ~MachO::MH_TWOLEVEL;
6999 }
7000 if (f & MachO::MH_FORCE_FLAT) {
7001 outs() << " FORCE_FLAT";
7002 f &= ~MachO::MH_FORCE_FLAT;
7003 }
7004 if (f & MachO::MH_NOMULTIDEFS) {
7005 outs() << " NOMULTIDEFS";
7006 f &= ~MachO::MH_NOMULTIDEFS;
7007 }
7008 if (f & MachO::MH_NOFIXPREBINDING) {
7009 outs() << " NOFIXPREBINDING";
7010 f &= ~MachO::MH_NOFIXPREBINDING;
7011 }
7012 if (f & MachO::MH_PREBINDABLE) {
7013 outs() << " PREBINDABLE";
7014 f &= ~MachO::MH_PREBINDABLE;
7015 }
7016 if (f & MachO::MH_ALLMODSBOUND) {
7017 outs() << " ALLMODSBOUND";
7018 f &= ~MachO::MH_ALLMODSBOUND;
7019 }
7020 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7021 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7022 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7023 }
7024 if (f & MachO::MH_CANONICAL) {
7025 outs() << " CANONICAL";
7026 f &= ~MachO::MH_CANONICAL;
7027 }
7028 if (f & MachO::MH_WEAK_DEFINES) {
7029 outs() << " WEAK_DEFINES";
7030 f &= ~MachO::MH_WEAK_DEFINES;
7031 }
7032 if (f & MachO::MH_BINDS_TO_WEAK) {
7033 outs() << " BINDS_TO_WEAK";
7034 f &= ~MachO::MH_BINDS_TO_WEAK;
7035 }
7036 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7037 outs() << " ALLOW_STACK_EXECUTION";
7038 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7039 }
7040 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7041 outs() << " DEAD_STRIPPABLE_DYLIB";
7042 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7043 }
7044 if (f & MachO::MH_PIE) {
7045 outs() << " PIE";
7046 f &= ~MachO::MH_PIE;
7047 }
7048 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7049 outs() << " NO_REEXPORTED_DYLIBS";
7050 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7051 }
7052 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7053 outs() << " MH_HAS_TLV_DESCRIPTORS";
7054 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7055 }
7056 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7057 outs() << " MH_NO_HEAP_EXECUTION";
7058 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7059 }
7060 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7061 outs() << " APP_EXTENSION_SAFE";
7062 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7063 }
7064 if (f != 0 || flags == 0)
7065 outs() << format(" 0x%08" PRIx32, f);
7066 } else {
7067 outs() << format(" 0x%08" PRIx32, magic);
7068 outs() << format(" %7d", cputype);
7069 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7070 outs() << format(" 0x%02" PRIx32,
7071 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7072 outs() << format(" %10u", filetype);
7073 outs() << format(" %5u", ncmds);
7074 outs() << format(" %10u", sizeofcmds);
7075 outs() << format(" 0x%08" PRIx32, flags);
7076 }
7077 outs() << "\n";
7078}
7079
Kevin Enderby956366c2014-08-29 22:30:52 +00007080static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7081 StringRef SegName, uint64_t vmaddr,
7082 uint64_t vmsize, uint64_t fileoff,
7083 uint64_t filesize, uint32_t maxprot,
7084 uint32_t initprot, uint32_t nsects,
7085 uint32_t flags, uint32_t object_size,
7086 bool verbose) {
7087 uint64_t expected_cmdsize;
7088 if (cmd == MachO::LC_SEGMENT) {
7089 outs() << " cmd LC_SEGMENT\n";
7090 expected_cmdsize = nsects;
7091 expected_cmdsize *= sizeof(struct MachO::section);
7092 expected_cmdsize += sizeof(struct MachO::segment_command);
7093 } else {
7094 outs() << " cmd LC_SEGMENT_64\n";
7095 expected_cmdsize = nsects;
7096 expected_cmdsize *= sizeof(struct MachO::section_64);
7097 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7098 }
7099 outs() << " cmdsize " << cmdsize;
7100 if (cmdsize != expected_cmdsize)
7101 outs() << " Inconsistent size\n";
7102 else
7103 outs() << "\n";
7104 outs() << " segname " << SegName << "\n";
7105 if (cmd == MachO::LC_SEGMENT_64) {
7106 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7107 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7108 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007109 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7110 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007111 }
7112 outs() << " fileoff " << fileoff;
7113 if (fileoff > object_size)
7114 outs() << " (past end of file)\n";
7115 else
7116 outs() << "\n";
7117 outs() << " filesize " << filesize;
7118 if (fileoff + filesize > object_size)
7119 outs() << " (past end of file)\n";
7120 else
7121 outs() << "\n";
7122 if (verbose) {
7123 if ((maxprot &
7124 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7125 MachO::VM_PROT_EXECUTE)) != 0)
7126 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7127 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007128 outs() << " maxprot ";
7129 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7130 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7131 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007132 }
7133 if ((initprot &
7134 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7135 MachO::VM_PROT_EXECUTE)) != 0)
7136 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7137 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007138 outs() << " initprot ";
7139 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7140 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7141 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007142 }
7143 } else {
7144 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7145 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7146 }
7147 outs() << " nsects " << nsects << "\n";
7148 if (verbose) {
7149 outs() << " flags";
7150 if (flags == 0)
7151 outs() << " (none)\n";
7152 else {
7153 if (flags & MachO::SG_HIGHVM) {
7154 outs() << " HIGHVM";
7155 flags &= ~MachO::SG_HIGHVM;
7156 }
7157 if (flags & MachO::SG_FVMLIB) {
7158 outs() << " FVMLIB";
7159 flags &= ~MachO::SG_FVMLIB;
7160 }
7161 if (flags & MachO::SG_NORELOC) {
7162 outs() << " NORELOC";
7163 flags &= ~MachO::SG_NORELOC;
7164 }
7165 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7166 outs() << " PROTECTED_VERSION_1";
7167 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7168 }
7169 if (flags)
7170 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7171 else
7172 outs() << "\n";
7173 }
7174 } else {
7175 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7176 }
7177}
7178
7179static void PrintSection(const char *sectname, const char *segname,
7180 uint64_t addr, uint64_t size, uint32_t offset,
7181 uint32_t align, uint32_t reloff, uint32_t nreloc,
7182 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7183 uint32_t cmd, const char *sg_segname,
7184 uint32_t filetype, uint32_t object_size,
7185 bool verbose) {
7186 outs() << "Section\n";
7187 outs() << " sectname " << format("%.16s\n", sectname);
7188 outs() << " segname " << format("%.16s", segname);
7189 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7190 outs() << " (does not match segment)\n";
7191 else
7192 outs() << "\n";
7193 if (cmd == MachO::LC_SEGMENT_64) {
7194 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7195 outs() << " size " << format("0x%016" PRIx64, size);
7196 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007197 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7198 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007199 }
7200 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7201 outs() << " (past end of file)\n";
7202 else
7203 outs() << "\n";
7204 outs() << " offset " << offset;
7205 if (offset > object_size)
7206 outs() << " (past end of file)\n";
7207 else
7208 outs() << "\n";
7209 uint32_t align_shifted = 1 << align;
7210 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7211 outs() << " reloff " << reloff;
7212 if (reloff > object_size)
7213 outs() << " (past end of file)\n";
7214 else
7215 outs() << "\n";
7216 outs() << " nreloc " << nreloc;
7217 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7218 outs() << " (past end of file)\n";
7219 else
7220 outs() << "\n";
7221 uint32_t section_type = flags & MachO::SECTION_TYPE;
7222 if (verbose) {
7223 outs() << " type";
7224 if (section_type == MachO::S_REGULAR)
7225 outs() << " S_REGULAR\n";
7226 else if (section_type == MachO::S_ZEROFILL)
7227 outs() << " S_ZEROFILL\n";
7228 else if (section_type == MachO::S_CSTRING_LITERALS)
7229 outs() << " S_CSTRING_LITERALS\n";
7230 else if (section_type == MachO::S_4BYTE_LITERALS)
7231 outs() << " S_4BYTE_LITERALS\n";
7232 else if (section_type == MachO::S_8BYTE_LITERALS)
7233 outs() << " S_8BYTE_LITERALS\n";
7234 else if (section_type == MachO::S_16BYTE_LITERALS)
7235 outs() << " S_16BYTE_LITERALS\n";
7236 else if (section_type == MachO::S_LITERAL_POINTERS)
7237 outs() << " S_LITERAL_POINTERS\n";
7238 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7239 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7240 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7241 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7242 else if (section_type == MachO::S_SYMBOL_STUBS)
7243 outs() << " S_SYMBOL_STUBS\n";
7244 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7245 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7246 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7247 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7248 else if (section_type == MachO::S_COALESCED)
7249 outs() << " S_COALESCED\n";
7250 else if (section_type == MachO::S_INTERPOSING)
7251 outs() << " S_INTERPOSING\n";
7252 else if (section_type == MachO::S_DTRACE_DOF)
7253 outs() << " S_DTRACE_DOF\n";
7254 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7255 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7256 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7257 outs() << " S_THREAD_LOCAL_REGULAR\n";
7258 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7259 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7260 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7261 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7262 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7263 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7264 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7265 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7266 else
7267 outs() << format("0x%08" PRIx32, section_type) << "\n";
7268 outs() << "attributes";
7269 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7270 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7271 outs() << " PURE_INSTRUCTIONS";
7272 if (section_attributes & MachO::S_ATTR_NO_TOC)
7273 outs() << " NO_TOC";
7274 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7275 outs() << " STRIP_STATIC_SYMS";
7276 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7277 outs() << " NO_DEAD_STRIP";
7278 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7279 outs() << " LIVE_SUPPORT";
7280 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7281 outs() << " SELF_MODIFYING_CODE";
7282 if (section_attributes & MachO::S_ATTR_DEBUG)
7283 outs() << " DEBUG";
7284 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7285 outs() << " SOME_INSTRUCTIONS";
7286 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7287 outs() << " EXT_RELOC";
7288 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7289 outs() << " LOC_RELOC";
7290 if (section_attributes == 0)
7291 outs() << " (none)";
7292 outs() << "\n";
7293 } else
7294 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7295 outs() << " reserved1 " << reserved1;
7296 if (section_type == MachO::S_SYMBOL_STUBS ||
7297 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7298 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7299 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7300 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7301 outs() << " (index into indirect symbol table)\n";
7302 else
7303 outs() << "\n";
7304 outs() << " reserved2 " << reserved2;
7305 if (section_type == MachO::S_SYMBOL_STUBS)
7306 outs() << " (size of stubs)\n";
7307 else
7308 outs() << "\n";
7309}
7310
David Majnemer73cc6ff2014-11-13 19:48:56 +00007311static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007312 uint32_t object_size) {
7313 outs() << " cmd LC_SYMTAB\n";
7314 outs() << " cmdsize " << st.cmdsize;
7315 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7316 outs() << " Incorrect size\n";
7317 else
7318 outs() << "\n";
7319 outs() << " symoff " << st.symoff;
7320 if (st.symoff > object_size)
7321 outs() << " (past end of file)\n";
7322 else
7323 outs() << "\n";
7324 outs() << " nsyms " << st.nsyms;
7325 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007326 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007327 big_size = st.nsyms;
7328 big_size *= sizeof(struct MachO::nlist_64);
7329 big_size += st.symoff;
7330 if (big_size > object_size)
7331 outs() << " (past end of file)\n";
7332 else
7333 outs() << "\n";
7334 } else {
7335 big_size = st.nsyms;
7336 big_size *= sizeof(struct MachO::nlist);
7337 big_size += st.symoff;
7338 if (big_size > object_size)
7339 outs() << " (past end of file)\n";
7340 else
7341 outs() << "\n";
7342 }
7343 outs() << " stroff " << st.stroff;
7344 if (st.stroff > object_size)
7345 outs() << " (past end of file)\n";
7346 else
7347 outs() << "\n";
7348 outs() << " strsize " << st.strsize;
7349 big_size = st.stroff;
7350 big_size += st.strsize;
7351 if (big_size > object_size)
7352 outs() << " (past end of file)\n";
7353 else
7354 outs() << "\n";
7355}
7356
7357static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7358 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007359 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007360 outs() << " cmd LC_DYSYMTAB\n";
7361 outs() << " cmdsize " << dyst.cmdsize;
7362 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7363 outs() << " Incorrect size\n";
7364 else
7365 outs() << "\n";
7366 outs() << " ilocalsym " << dyst.ilocalsym;
7367 if (dyst.ilocalsym > nsyms)
7368 outs() << " (greater than the number of symbols)\n";
7369 else
7370 outs() << "\n";
7371 outs() << " nlocalsym " << dyst.nlocalsym;
7372 uint64_t big_size;
7373 big_size = dyst.ilocalsym;
7374 big_size += dyst.nlocalsym;
7375 if (big_size > nsyms)
7376 outs() << " (past the end of the symbol table)\n";
7377 else
7378 outs() << "\n";
7379 outs() << " iextdefsym " << dyst.iextdefsym;
7380 if (dyst.iextdefsym > nsyms)
7381 outs() << " (greater than the number of symbols)\n";
7382 else
7383 outs() << "\n";
7384 outs() << " nextdefsym " << dyst.nextdefsym;
7385 big_size = dyst.iextdefsym;
7386 big_size += dyst.nextdefsym;
7387 if (big_size > nsyms)
7388 outs() << " (past the end of the symbol table)\n";
7389 else
7390 outs() << "\n";
7391 outs() << " iundefsym " << dyst.iundefsym;
7392 if (dyst.iundefsym > nsyms)
7393 outs() << " (greater than the number of symbols)\n";
7394 else
7395 outs() << "\n";
7396 outs() << " nundefsym " << dyst.nundefsym;
7397 big_size = dyst.iundefsym;
7398 big_size += dyst.nundefsym;
7399 if (big_size > nsyms)
7400 outs() << " (past the end of the symbol table)\n";
7401 else
7402 outs() << "\n";
7403 outs() << " tocoff " << dyst.tocoff;
7404 if (dyst.tocoff > object_size)
7405 outs() << " (past end of file)\n";
7406 else
7407 outs() << "\n";
7408 outs() << " ntoc " << dyst.ntoc;
7409 big_size = dyst.ntoc;
7410 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7411 big_size += dyst.tocoff;
7412 if (big_size > object_size)
7413 outs() << " (past end of file)\n";
7414 else
7415 outs() << "\n";
7416 outs() << " modtaboff " << dyst.modtaboff;
7417 if (dyst.modtaboff > object_size)
7418 outs() << " (past end of file)\n";
7419 else
7420 outs() << "\n";
7421 outs() << " nmodtab " << dyst.nmodtab;
7422 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007423 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007424 modtabend = dyst.nmodtab;
7425 modtabend *= sizeof(struct MachO::dylib_module_64);
7426 modtabend += dyst.modtaboff;
7427 } else {
7428 modtabend = dyst.nmodtab;
7429 modtabend *= sizeof(struct MachO::dylib_module);
7430 modtabend += dyst.modtaboff;
7431 }
7432 if (modtabend > object_size)
7433 outs() << " (past end of file)\n";
7434 else
7435 outs() << "\n";
7436 outs() << " extrefsymoff " << dyst.extrefsymoff;
7437 if (dyst.extrefsymoff > object_size)
7438 outs() << " (past end of file)\n";
7439 else
7440 outs() << "\n";
7441 outs() << " nextrefsyms " << dyst.nextrefsyms;
7442 big_size = dyst.nextrefsyms;
7443 big_size *= sizeof(struct MachO::dylib_reference);
7444 big_size += dyst.extrefsymoff;
7445 if (big_size > object_size)
7446 outs() << " (past end of file)\n";
7447 else
7448 outs() << "\n";
7449 outs() << " indirectsymoff " << dyst.indirectsymoff;
7450 if (dyst.indirectsymoff > object_size)
7451 outs() << " (past end of file)\n";
7452 else
7453 outs() << "\n";
7454 outs() << " nindirectsyms " << dyst.nindirectsyms;
7455 big_size = dyst.nindirectsyms;
7456 big_size *= sizeof(uint32_t);
7457 big_size += dyst.indirectsymoff;
7458 if (big_size > object_size)
7459 outs() << " (past end of file)\n";
7460 else
7461 outs() << "\n";
7462 outs() << " extreloff " << dyst.extreloff;
7463 if (dyst.extreloff > object_size)
7464 outs() << " (past end of file)\n";
7465 else
7466 outs() << "\n";
7467 outs() << " nextrel " << dyst.nextrel;
7468 big_size = dyst.nextrel;
7469 big_size *= sizeof(struct MachO::relocation_info);
7470 big_size += dyst.extreloff;
7471 if (big_size > object_size)
7472 outs() << " (past end of file)\n";
7473 else
7474 outs() << "\n";
7475 outs() << " locreloff " << dyst.locreloff;
7476 if (dyst.locreloff > object_size)
7477 outs() << " (past end of file)\n";
7478 else
7479 outs() << "\n";
7480 outs() << " nlocrel " << dyst.nlocrel;
7481 big_size = dyst.nlocrel;
7482 big_size *= sizeof(struct MachO::relocation_info);
7483 big_size += dyst.locreloff;
7484 if (big_size > object_size)
7485 outs() << " (past end of file)\n";
7486 else
7487 outs() << "\n";
7488}
7489
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007490static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7491 uint32_t object_size) {
7492 if (dc.cmd == MachO::LC_DYLD_INFO)
7493 outs() << " cmd LC_DYLD_INFO\n";
7494 else
7495 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7496 outs() << " cmdsize " << dc.cmdsize;
7497 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7498 outs() << " Incorrect size\n";
7499 else
7500 outs() << "\n";
7501 outs() << " rebase_off " << dc.rebase_off;
7502 if (dc.rebase_off > object_size)
7503 outs() << " (past end of file)\n";
7504 else
7505 outs() << "\n";
7506 outs() << " rebase_size " << dc.rebase_size;
7507 uint64_t big_size;
7508 big_size = dc.rebase_off;
7509 big_size += dc.rebase_size;
7510 if (big_size > object_size)
7511 outs() << " (past end of file)\n";
7512 else
7513 outs() << "\n";
7514 outs() << " bind_off " << dc.bind_off;
7515 if (dc.bind_off > object_size)
7516 outs() << " (past end of file)\n";
7517 else
7518 outs() << "\n";
7519 outs() << " bind_size " << dc.bind_size;
7520 big_size = dc.bind_off;
7521 big_size += dc.bind_size;
7522 if (big_size > object_size)
7523 outs() << " (past end of file)\n";
7524 else
7525 outs() << "\n";
7526 outs() << " weak_bind_off " << dc.weak_bind_off;
7527 if (dc.weak_bind_off > object_size)
7528 outs() << " (past end of file)\n";
7529 else
7530 outs() << "\n";
7531 outs() << " weak_bind_size " << dc.weak_bind_size;
7532 big_size = dc.weak_bind_off;
7533 big_size += dc.weak_bind_size;
7534 if (big_size > object_size)
7535 outs() << " (past end of file)\n";
7536 else
7537 outs() << "\n";
7538 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7539 if (dc.lazy_bind_off > object_size)
7540 outs() << " (past end of file)\n";
7541 else
7542 outs() << "\n";
7543 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7544 big_size = dc.lazy_bind_off;
7545 big_size += dc.lazy_bind_size;
7546 if (big_size > object_size)
7547 outs() << " (past end of file)\n";
7548 else
7549 outs() << "\n";
7550 outs() << " export_off " << dc.export_off;
7551 if (dc.export_off > object_size)
7552 outs() << " (past end of file)\n";
7553 else
7554 outs() << "\n";
7555 outs() << " export_size " << dc.export_size;
7556 big_size = dc.export_off;
7557 big_size += dc.export_size;
7558 if (big_size > object_size)
7559 outs() << " (past end of file)\n";
7560 else
7561 outs() << "\n";
7562}
7563
7564static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7565 const char *Ptr) {
7566 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7567 outs() << " cmd LC_ID_DYLINKER\n";
7568 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7569 outs() << " cmd LC_LOAD_DYLINKER\n";
7570 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7571 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7572 else
7573 outs() << " cmd ?(" << dyld.cmd << ")\n";
7574 outs() << " cmdsize " << dyld.cmdsize;
7575 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7576 outs() << " Incorrect size\n";
7577 else
7578 outs() << "\n";
7579 if (dyld.name >= dyld.cmdsize)
7580 outs() << " name ?(bad offset " << dyld.name << ")\n";
7581 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007582 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007583 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7584 }
7585}
7586
7587static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7588 outs() << " cmd LC_UUID\n";
7589 outs() << " cmdsize " << uuid.cmdsize;
7590 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7591 outs() << " Incorrect size\n";
7592 else
7593 outs() << "\n";
7594 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007595 for (int i = 0; i < 16; ++i) {
7596 outs() << format("%02" PRIX32, uuid.uuid[i]);
7597 if (i == 3 || i == 5 || i == 7 || i == 9)
7598 outs() << "-";
7599 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007600 outs() << "\n";
7601}
7602
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007603static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007604 outs() << " cmd LC_RPATH\n";
7605 outs() << " cmdsize " << rpath.cmdsize;
7606 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7607 outs() << " Incorrect size\n";
7608 else
7609 outs() << "\n";
7610 if (rpath.path >= rpath.cmdsize)
7611 outs() << " path ?(bad offset " << rpath.path << ")\n";
7612 else {
7613 const char *P = (const char *)(Ptr) + rpath.path;
7614 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7615 }
7616}
7617
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007618static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007619 StringRef LoadCmdName;
7620 switch (vd.cmd) {
7621 case MachO::LC_VERSION_MIN_MACOSX:
7622 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7623 break;
7624 case MachO::LC_VERSION_MIN_IPHONEOS:
7625 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7626 break;
7627 case MachO::LC_VERSION_MIN_TVOS:
7628 LoadCmdName = "LC_VERSION_MIN_TVOS";
7629 break;
7630 case MachO::LC_VERSION_MIN_WATCHOS:
7631 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7632 break;
7633 default:
7634 llvm_unreachable("Unknown version min load command");
7635 }
7636
7637 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007638 outs() << " cmdsize " << vd.cmdsize;
7639 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7640 outs() << " Incorrect size\n";
7641 else
7642 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007643 outs() << " version "
7644 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7645 << MachOObjectFile::getVersionMinMinor(vd, false);
7646 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7647 if (Update != 0)
7648 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007649 outs() << "\n";
7650 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007651 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007652 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007653 outs() << " sdk "
7654 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7655 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007656 }
Davide Italiano56baef32015-08-26 12:26:11 +00007657 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7658 if (Update != 0)
7659 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007660 outs() << "\n";
7661}
7662
7663static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7664 outs() << " cmd LC_SOURCE_VERSION\n";
7665 outs() << " cmdsize " << sd.cmdsize;
7666 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7667 outs() << " Incorrect size\n";
7668 else
7669 outs() << "\n";
7670 uint64_t a = (sd.version >> 40) & 0xffffff;
7671 uint64_t b = (sd.version >> 30) & 0x3ff;
7672 uint64_t c = (sd.version >> 20) & 0x3ff;
7673 uint64_t d = (sd.version >> 10) & 0x3ff;
7674 uint64_t e = sd.version & 0x3ff;
7675 outs() << " version " << a << "." << b;
7676 if (e != 0)
7677 outs() << "." << c << "." << d << "." << e;
7678 else if (d != 0)
7679 outs() << "." << c << "." << d;
7680 else if (c != 0)
7681 outs() << "." << c;
7682 outs() << "\n";
7683}
7684
7685static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7686 outs() << " cmd LC_MAIN\n";
7687 outs() << " cmdsize " << ep.cmdsize;
7688 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7689 outs() << " Incorrect size\n";
7690 else
7691 outs() << "\n";
7692 outs() << " entryoff " << ep.entryoff << "\n";
7693 outs() << " stacksize " << ep.stacksize << "\n";
7694}
7695
Kevin Enderby0804f4672014-12-16 23:25:52 +00007696static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7697 uint32_t object_size) {
7698 outs() << " cmd LC_ENCRYPTION_INFO\n";
7699 outs() << " cmdsize " << ec.cmdsize;
7700 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7701 outs() << " Incorrect size\n";
7702 else
7703 outs() << "\n";
7704 outs() << " cryptoff " << ec.cryptoff;
7705 if (ec.cryptoff > object_size)
7706 outs() << " (past end of file)\n";
7707 else
7708 outs() << "\n";
7709 outs() << " cryptsize " << ec.cryptsize;
7710 if (ec.cryptsize > object_size)
7711 outs() << " (past end of file)\n";
7712 else
7713 outs() << "\n";
7714 outs() << " cryptid " << ec.cryptid << "\n";
7715}
7716
Kevin Enderby57538292014-12-17 01:01:30 +00007717static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007718 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007719 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7720 outs() << " cmdsize " << ec.cmdsize;
7721 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7722 outs() << " Incorrect size\n";
7723 else
7724 outs() << "\n";
7725 outs() << " cryptoff " << ec.cryptoff;
7726 if (ec.cryptoff > object_size)
7727 outs() << " (past end of file)\n";
7728 else
7729 outs() << "\n";
7730 outs() << " cryptsize " << ec.cryptsize;
7731 if (ec.cryptsize > object_size)
7732 outs() << " (past end of file)\n";
7733 else
7734 outs() << "\n";
7735 outs() << " cryptid " << ec.cryptid << "\n";
7736 outs() << " pad " << ec.pad << "\n";
7737}
7738
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007739static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7740 const char *Ptr) {
7741 outs() << " cmd LC_LINKER_OPTION\n";
7742 outs() << " cmdsize " << lo.cmdsize;
7743 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7744 outs() << " Incorrect size\n";
7745 else
7746 outs() << "\n";
7747 outs() << " count " << lo.count << "\n";
7748 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7749 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7750 uint32_t i = 0;
7751 while (left > 0) {
7752 while (*string == '\0' && left > 0) {
7753 string++;
7754 left--;
7755 }
7756 if (left > 0) {
7757 i++;
7758 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007759 uint32_t NullPos = StringRef(string, left).find('\0');
7760 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007761 string += len;
7762 left -= len;
7763 }
7764 }
7765 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007766 outs() << " count " << lo.count << " does not match number of strings "
7767 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007768}
7769
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007770static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7771 const char *Ptr) {
7772 outs() << " cmd LC_SUB_FRAMEWORK\n";
7773 outs() << " cmdsize " << sub.cmdsize;
7774 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7775 outs() << " Incorrect size\n";
7776 else
7777 outs() << "\n";
7778 if (sub.umbrella < sub.cmdsize) {
7779 const char *P = Ptr + sub.umbrella;
7780 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7781 } else {
7782 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7783 }
7784}
7785
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007786static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7787 const char *Ptr) {
7788 outs() << " cmd LC_SUB_UMBRELLA\n";
7789 outs() << " cmdsize " << sub.cmdsize;
7790 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7791 outs() << " Incorrect size\n";
7792 else
7793 outs() << "\n";
7794 if (sub.sub_umbrella < sub.cmdsize) {
7795 const char *P = Ptr + sub.sub_umbrella;
7796 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7797 } else {
7798 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7799 }
7800}
7801
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007802static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007803 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007804 outs() << " cmd LC_SUB_LIBRARY\n";
7805 outs() << " cmdsize " << sub.cmdsize;
7806 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7807 outs() << " Incorrect size\n";
7808 else
7809 outs() << "\n";
7810 if (sub.sub_library < sub.cmdsize) {
7811 const char *P = Ptr + sub.sub_library;
7812 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7813 } else {
7814 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7815 }
7816}
7817
Kevin Enderby186eac32014-12-19 21:06:24 +00007818static void PrintSubClientCommand(MachO::sub_client_command sub,
7819 const char *Ptr) {
7820 outs() << " cmd LC_SUB_CLIENT\n";
7821 outs() << " cmdsize " << sub.cmdsize;
7822 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7823 outs() << " Incorrect size\n";
7824 else
7825 outs() << "\n";
7826 if (sub.client < sub.cmdsize) {
7827 const char *P = Ptr + sub.client;
7828 outs() << " client " << P << " (offset " << sub.client << ")\n";
7829 } else {
7830 outs() << " client ?(bad offset " << sub.client << ")\n";
7831 }
7832}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007833
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007834static void PrintRoutinesCommand(MachO::routines_command r) {
7835 outs() << " cmd LC_ROUTINES\n";
7836 outs() << " cmdsize " << r.cmdsize;
7837 if (r.cmdsize != sizeof(struct MachO::routines_command))
7838 outs() << " Incorrect size\n";
7839 else
7840 outs() << "\n";
7841 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7842 outs() << " init_module " << r.init_module << "\n";
7843 outs() << " reserved1 " << r.reserved1 << "\n";
7844 outs() << " reserved2 " << r.reserved2 << "\n";
7845 outs() << " reserved3 " << r.reserved3 << "\n";
7846 outs() << " reserved4 " << r.reserved4 << "\n";
7847 outs() << " reserved5 " << r.reserved5 << "\n";
7848 outs() << " reserved6 " << r.reserved6 << "\n";
7849}
7850
7851static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7852 outs() << " cmd LC_ROUTINES_64\n";
7853 outs() << " cmdsize " << r.cmdsize;
7854 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7855 outs() << " Incorrect size\n";
7856 else
7857 outs() << "\n";
7858 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7859 outs() << " init_module " << r.init_module << "\n";
7860 outs() << " reserved1 " << r.reserved1 << "\n";
7861 outs() << " reserved2 " << r.reserved2 << "\n";
7862 outs() << " reserved3 " << r.reserved3 << "\n";
7863 outs() << " reserved4 " << r.reserved4 << "\n";
7864 outs() << " reserved5 " << r.reserved5 << "\n";
7865 outs() << " reserved6 " << r.reserved6 << "\n";
7866}
7867
Kevin Enderby48ef5342014-12-23 22:56:39 +00007868static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7869 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7870 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7871 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7872 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7873 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7874 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7875 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7876 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7877 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7878 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7879 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7880 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7881 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7882 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7883 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7884 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7885 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7886 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7887 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7888 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7889 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7890}
7891
Kevin Enderby227df342014-12-23 23:43:59 +00007892static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007893 uint32_t f;
7894 outs() << "\t mmst_reg ";
7895 for (f = 0; f < 10; f++)
7896 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7897 outs() << "\n";
7898 outs() << "\t mmst_rsrv ";
7899 for (f = 0; f < 6; f++)
7900 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7901 outs() << "\n";
7902}
7903
Kevin Enderbyaefb0032014-12-24 00:16:51 +00007904static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007905 uint32_t f;
7906 outs() << "\t xmm_reg ";
7907 for (f = 0; f < 16; f++)
7908 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7909 outs() << "\n";
7910}
7911
7912static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7913 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7914 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7915 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7916 outs() << " denorm " << fpu.fpu_fcw.denorm;
7917 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7918 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7919 outs() << " undfl " << fpu.fpu_fcw.undfl;
7920 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
7921 outs() << "\t\t pc ";
7922 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
7923 outs() << "FP_PREC_24B ";
7924 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
7925 outs() << "FP_PREC_53B ";
7926 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
7927 outs() << "FP_PREC_64B ";
7928 else
7929 outs() << fpu.fpu_fcw.pc << " ";
7930 outs() << "rc ";
7931 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
7932 outs() << "FP_RND_NEAR ";
7933 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
7934 outs() << "FP_RND_DOWN ";
7935 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
7936 outs() << "FP_RND_UP ";
7937 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007938 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00007939 outs() << "\n";
7940 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
7941 outs() << " denorm " << fpu.fpu_fsw.denorm;
7942 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
7943 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
7944 outs() << " undfl " << fpu.fpu_fsw.undfl;
7945 outs() << " precis " << fpu.fpu_fsw.precis;
7946 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
7947 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
7948 outs() << " c0 " << fpu.fpu_fsw.c0;
7949 outs() << " c1 " << fpu.fpu_fsw.c1;
7950 outs() << " c2 " << fpu.fpu_fsw.c2;
7951 outs() << " tos " << fpu.fpu_fsw.tos;
7952 outs() << " c3 " << fpu.fpu_fsw.c3;
7953 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
7954 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
7955 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
7956 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
7957 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
7958 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
7959 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
7960 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
7961 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
7962 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
7963 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
7964 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
7965 outs() << "\n";
7966 outs() << "\t fpu_stmm0:\n";
7967 Print_mmst_reg(fpu.fpu_stmm0);
7968 outs() << "\t fpu_stmm1:\n";
7969 Print_mmst_reg(fpu.fpu_stmm1);
7970 outs() << "\t fpu_stmm2:\n";
7971 Print_mmst_reg(fpu.fpu_stmm2);
7972 outs() << "\t fpu_stmm3:\n";
7973 Print_mmst_reg(fpu.fpu_stmm3);
7974 outs() << "\t fpu_stmm4:\n";
7975 Print_mmst_reg(fpu.fpu_stmm4);
7976 outs() << "\t fpu_stmm5:\n";
7977 Print_mmst_reg(fpu.fpu_stmm5);
7978 outs() << "\t fpu_stmm6:\n";
7979 Print_mmst_reg(fpu.fpu_stmm6);
7980 outs() << "\t fpu_stmm7:\n";
7981 Print_mmst_reg(fpu.fpu_stmm7);
7982 outs() << "\t fpu_xmm0:\n";
7983 Print_xmm_reg(fpu.fpu_xmm0);
7984 outs() << "\t fpu_xmm1:\n";
7985 Print_xmm_reg(fpu.fpu_xmm1);
7986 outs() << "\t fpu_xmm2:\n";
7987 Print_xmm_reg(fpu.fpu_xmm2);
7988 outs() << "\t fpu_xmm3:\n";
7989 Print_xmm_reg(fpu.fpu_xmm3);
7990 outs() << "\t fpu_xmm4:\n";
7991 Print_xmm_reg(fpu.fpu_xmm4);
7992 outs() << "\t fpu_xmm5:\n";
7993 Print_xmm_reg(fpu.fpu_xmm5);
7994 outs() << "\t fpu_xmm6:\n";
7995 Print_xmm_reg(fpu.fpu_xmm6);
7996 outs() << "\t fpu_xmm7:\n";
7997 Print_xmm_reg(fpu.fpu_xmm7);
7998 outs() << "\t fpu_xmm8:\n";
7999 Print_xmm_reg(fpu.fpu_xmm8);
8000 outs() << "\t fpu_xmm9:\n";
8001 Print_xmm_reg(fpu.fpu_xmm9);
8002 outs() << "\t fpu_xmm10:\n";
8003 Print_xmm_reg(fpu.fpu_xmm10);
8004 outs() << "\t fpu_xmm11:\n";
8005 Print_xmm_reg(fpu.fpu_xmm11);
8006 outs() << "\t fpu_xmm12:\n";
8007 Print_xmm_reg(fpu.fpu_xmm12);
8008 outs() << "\t fpu_xmm13:\n";
8009 Print_xmm_reg(fpu.fpu_xmm13);
8010 outs() << "\t fpu_xmm14:\n";
8011 Print_xmm_reg(fpu.fpu_xmm14);
8012 outs() << "\t fpu_xmm15:\n";
8013 Print_xmm_reg(fpu.fpu_xmm15);
8014 outs() << "\t fpu_rsrv4:\n";
8015 for (uint32_t f = 0; f < 6; f++) {
8016 outs() << "\t ";
8017 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008018 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008019 outs() << "\n";
8020 }
8021 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8022 outs() << "\n";
8023}
8024
8025static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8026 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8027 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8028 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8029}
8030
8031static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8032 bool isLittleEndian, uint32_t cputype) {
8033 if (t.cmd == MachO::LC_THREAD)
8034 outs() << " cmd LC_THREAD\n";
8035 else if (t.cmd == MachO::LC_UNIXTHREAD)
8036 outs() << " cmd LC_UNIXTHREAD\n";
8037 else
8038 outs() << " cmd " << t.cmd << " (unknown)\n";
8039 outs() << " cmdsize " << t.cmdsize;
8040 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8041 outs() << " Incorrect size\n";
8042 else
8043 outs() << "\n";
8044
8045 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8046 const char *end = Ptr + t.cmdsize;
8047 uint32_t flavor, count, left;
8048 if (cputype == MachO::CPU_TYPE_X86_64) {
8049 while (begin < end) {
8050 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8051 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8052 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008053 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008054 flavor = 0;
8055 begin = end;
8056 }
8057 if (isLittleEndian != sys::IsLittleEndianHost)
8058 sys::swapByteOrder(flavor);
8059 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8060 memcpy((char *)&count, begin, sizeof(uint32_t));
8061 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008062 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008063 count = 0;
8064 begin = end;
8065 }
8066 if (isLittleEndian != sys::IsLittleEndianHost)
8067 sys::swapByteOrder(count);
8068 if (flavor == MachO::x86_THREAD_STATE64) {
8069 outs() << " flavor x86_THREAD_STATE64\n";
8070 if (count == MachO::x86_THREAD_STATE64_COUNT)
8071 outs() << " count x86_THREAD_STATE64_COUNT\n";
8072 else
8073 outs() << " count " << count
8074 << " (not x86_THREAD_STATE64_COUNT)\n";
8075 MachO::x86_thread_state64_t cpu64;
8076 left = end - begin;
8077 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8078 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8079 begin += sizeof(MachO::x86_thread_state64_t);
8080 } else {
8081 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8082 memcpy(&cpu64, begin, left);
8083 begin += left;
8084 }
8085 if (isLittleEndian != sys::IsLittleEndianHost)
8086 swapStruct(cpu64);
8087 Print_x86_thread_state64_t(cpu64);
8088 } else if (flavor == MachO::x86_THREAD_STATE) {
8089 outs() << " flavor x86_THREAD_STATE\n";
8090 if (count == MachO::x86_THREAD_STATE_COUNT)
8091 outs() << " count x86_THREAD_STATE_COUNT\n";
8092 else
8093 outs() << " count " << count
8094 << " (not x86_THREAD_STATE_COUNT)\n";
8095 struct MachO::x86_thread_state_t ts;
8096 left = end - begin;
8097 if (left >= sizeof(MachO::x86_thread_state_t)) {
8098 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8099 begin += sizeof(MachO::x86_thread_state_t);
8100 } else {
8101 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8102 memcpy(&ts, begin, left);
8103 begin += left;
8104 }
8105 if (isLittleEndian != sys::IsLittleEndianHost)
8106 swapStruct(ts);
8107 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8108 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8109 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8110 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8111 else
8112 outs() << "tsh.count " << ts.tsh.count
8113 << " (not x86_THREAD_STATE64_COUNT\n";
8114 Print_x86_thread_state64_t(ts.uts.ts64);
8115 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008116 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8117 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008118 }
8119 } else if (flavor == MachO::x86_FLOAT_STATE) {
8120 outs() << " flavor x86_FLOAT_STATE\n";
8121 if (count == MachO::x86_FLOAT_STATE_COUNT)
8122 outs() << " count x86_FLOAT_STATE_COUNT\n";
8123 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008124 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008125 struct MachO::x86_float_state_t fs;
8126 left = end - begin;
8127 if (left >= sizeof(MachO::x86_float_state_t)) {
8128 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8129 begin += sizeof(MachO::x86_float_state_t);
8130 } else {
8131 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8132 memcpy(&fs, begin, left);
8133 begin += left;
8134 }
8135 if (isLittleEndian != sys::IsLittleEndianHost)
8136 swapStruct(fs);
8137 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8138 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008139 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008140 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8141 else
8142 outs() << "fsh.count " << fs.fsh.count
8143 << " (not x86_FLOAT_STATE64_COUNT\n";
8144 Print_x86_float_state_t(fs.ufs.fs64);
8145 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008146 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8147 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008148 }
8149 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8150 outs() << " flavor x86_EXCEPTION_STATE\n";
8151 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8152 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8153 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008154 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008155 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8156 struct MachO::x86_exception_state_t es;
8157 left = end - begin;
8158 if (left >= sizeof(MachO::x86_exception_state_t)) {
8159 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8160 begin += sizeof(MachO::x86_exception_state_t);
8161 } else {
8162 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8163 memcpy(&es, begin, left);
8164 begin += left;
8165 }
8166 if (isLittleEndian != sys::IsLittleEndianHost)
8167 swapStruct(es);
8168 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8169 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008170 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008171 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8172 else
8173 outs() << "\t esh.count " << es.esh.count
8174 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8175 Print_x86_exception_state_t(es.ues.es64);
8176 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008177 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8178 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008179 }
8180 } else {
8181 outs() << " flavor " << flavor << " (unknown)\n";
8182 outs() << " count " << count << "\n";
8183 outs() << " state (unknown)\n";
8184 begin += count * sizeof(uint32_t);
8185 }
8186 }
8187 } else {
8188 while (begin < end) {
8189 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8190 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8191 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008192 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008193 flavor = 0;
8194 begin = end;
8195 }
8196 if (isLittleEndian != sys::IsLittleEndianHost)
8197 sys::swapByteOrder(flavor);
8198 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8199 memcpy((char *)&count, begin, sizeof(uint32_t));
8200 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008201 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008202 count = 0;
8203 begin = end;
8204 }
8205 if (isLittleEndian != sys::IsLittleEndianHost)
8206 sys::swapByteOrder(count);
8207 outs() << " flavor " << flavor << "\n";
8208 outs() << " count " << count << "\n";
8209 outs() << " state (Unknown cputype/cpusubtype)\n";
8210 begin += count * sizeof(uint32_t);
8211 }
8212 }
8213}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008214
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008215static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8216 if (dl.cmd == MachO::LC_ID_DYLIB)
8217 outs() << " cmd LC_ID_DYLIB\n";
8218 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8219 outs() << " cmd LC_LOAD_DYLIB\n";
8220 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8221 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8222 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8223 outs() << " cmd LC_REEXPORT_DYLIB\n";
8224 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8225 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8226 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8227 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8228 else
8229 outs() << " cmd " << dl.cmd << " (unknown)\n";
8230 outs() << " cmdsize " << dl.cmdsize;
8231 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8232 outs() << " Incorrect size\n";
8233 else
8234 outs() << "\n";
8235 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008236 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008237 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8238 } else {
8239 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8240 }
8241 outs() << " time stamp " << dl.dylib.timestamp << " ";
8242 time_t t = dl.dylib.timestamp;
8243 outs() << ctime(&t);
8244 outs() << " current version ";
8245 if (dl.dylib.current_version == 0xffffffff)
8246 outs() << "n/a\n";
8247 else
8248 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8249 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8250 << (dl.dylib.current_version & 0xff) << "\n";
8251 outs() << "compatibility version ";
8252 if (dl.dylib.compatibility_version == 0xffffffff)
8253 outs() << "n/a\n";
8254 else
8255 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8256 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8257 << (dl.dylib.compatibility_version & 0xff) << "\n";
8258}
8259
8260static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8261 uint32_t object_size) {
8262 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8263 outs() << " cmd LC_FUNCTION_STARTS\n";
8264 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8265 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8266 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8267 outs() << " cmd LC_FUNCTION_STARTS\n";
8268 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8269 outs() << " cmd LC_DATA_IN_CODE\n";
8270 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8271 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8272 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8273 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8274 else
8275 outs() << " cmd " << ld.cmd << " (?)\n";
8276 outs() << " cmdsize " << ld.cmdsize;
8277 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8278 outs() << " Incorrect size\n";
8279 else
8280 outs() << "\n";
8281 outs() << " dataoff " << ld.dataoff;
8282 if (ld.dataoff > object_size)
8283 outs() << " (past end of file)\n";
8284 else
8285 outs() << "\n";
8286 outs() << " datasize " << ld.datasize;
8287 uint64_t big_size = ld.dataoff;
8288 big_size += ld.datasize;
8289 if (big_size > object_size)
8290 outs() << " (past end of file)\n";
8291 else
8292 outs() << "\n";
8293}
8294
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008295static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8296 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008297 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008298 unsigned Index = 0;
8299 for (const auto &Command : Obj->load_commands()) {
8300 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008301 if (Command.C.cmd == MachO::LC_SEGMENT) {
8302 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8303 const char *sg_segname = SLC.segname;
8304 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8305 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8306 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8307 verbose);
8308 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008309 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008310 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8311 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8312 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8313 }
8314 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8315 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8316 const char *sg_segname = SLC_64.segname;
8317 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8318 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8319 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8320 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8321 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8322 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8323 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8324 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8325 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8326 sg_segname, filetype, Buf.size(), verbose);
8327 }
8328 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8329 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008330 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008331 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8332 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8333 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008334 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8335 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008336 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8337 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8338 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8339 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8340 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8341 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8342 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8343 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8344 PrintDyldLoadCommand(Dyld, Command.Ptr);
8345 } else if (Command.C.cmd == MachO::LC_UUID) {
8346 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8347 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008348 } else if (Command.C.cmd == MachO::LC_RPATH) {
8349 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8350 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008351 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008352 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8353 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8354 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008355 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8356 PrintVersionMinLoadCommand(Vd);
8357 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8358 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8359 PrintSourceVersionCommand(Sd);
8360 } else if (Command.C.cmd == MachO::LC_MAIN) {
8361 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8362 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008363 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008364 MachO::encryption_info_command Ei =
8365 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008366 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008367 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008368 MachO::encryption_info_command_64 Ei =
8369 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008370 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008371 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008372 MachO::linker_option_command Lo =
8373 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008374 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008375 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8376 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8377 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008378 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8379 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8380 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008381 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8382 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8383 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008384 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8385 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8386 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008387 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8388 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8389 PrintRoutinesCommand(Rc);
8390 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8391 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8392 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008393 } else if (Command.C.cmd == MachO::LC_THREAD ||
8394 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8395 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8396 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008397 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8398 Command.C.cmd == MachO::LC_ID_DYLIB ||
8399 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8400 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8401 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8402 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008403 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8404 PrintDylibCommand(Dl, Command.Ptr);
8405 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8406 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8407 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8408 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8409 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8410 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8411 MachO::linkedit_data_command Ld =
8412 Obj->getLinkeditDataLoadCommand(Command);
8413 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008414 } else {
8415 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8416 << ")\n";
8417 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8418 // TODO: get and print the raw bytes of the load command.
8419 }
8420 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008421 }
8422}
8423
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008424static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008425 if (Obj->is64Bit()) {
8426 MachO::mach_header_64 H_64;
8427 H_64 = Obj->getHeader64();
8428 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8429 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8430 } else {
8431 MachO::mach_header H;
8432 H = Obj->getHeader();
8433 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8434 H.sizeofcmds, H.flags, verbose);
8435 }
8436}
8437
8438void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8439 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008440 PrintMachHeader(file, !NonVerbose);
8441}
8442
8443void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8444 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008445 uint32_t filetype = 0;
8446 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008447 if (file->is64Bit()) {
8448 MachO::mach_header_64 H_64;
8449 H_64 = file->getHeader64();
8450 filetype = H_64.filetype;
8451 cputype = H_64.cputype;
8452 } else {
8453 MachO::mach_header H;
8454 H = file->getHeader();
8455 filetype = H.filetype;
8456 cputype = H.cputype;
8457 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008458 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008459}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008460
8461//===----------------------------------------------------------------------===//
8462// export trie dumping
8463//===----------------------------------------------------------------------===//
8464
8465void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008466 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8467 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008468 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8469 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8470 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8471 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8472 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8473 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8474 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8475 if (ReExport)
8476 outs() << "[re-export] ";
8477 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008478 outs() << format("0x%08llX ",
8479 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008480 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008481 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008482 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008483 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008484 if (WeakDef) {
8485 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008486 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008487 }
8488 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008489 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008490 outs() << ", ";
8491 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008492 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008493 }
8494 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008495 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008496 outs() << ", ";
8497 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008498 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008499 }
8500 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008501 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008502 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008503 outs() << format("resolver=0x%08llX", Entry.other());
8504 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008505 }
8506 outs() << "]";
8507 }
8508 if (ReExport) {
8509 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008510 int Ordinal = Entry.other() - 1;
8511 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8512 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008513 outs() << " (from " << DylibName << ")";
8514 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008515 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008516 }
8517 outs() << "\n";
8518 }
8519}
Nick Kledzikac431442014-09-12 21:34:15 +00008520
Nick Kledzikac431442014-09-12 21:34:15 +00008521//===----------------------------------------------------------------------===//
8522// rebase table dumping
8523//===----------------------------------------------------------------------===//
8524
8525namespace {
8526class SegInfo {
8527public:
8528 SegInfo(const object::MachOObjectFile *Obj);
8529
8530 StringRef segmentName(uint32_t SegIndex);
8531 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8532 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008533 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008534
8535private:
8536 struct SectionInfo {
8537 uint64_t Address;
8538 uint64_t Size;
8539 StringRef SectionName;
8540 StringRef SegmentName;
8541 uint64_t OffsetInSegment;
8542 uint64_t SegmentStartAddress;
8543 uint32_t SegmentIndex;
8544 };
8545 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8546 SmallVector<SectionInfo, 32> Sections;
8547};
8548}
8549
8550SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8551 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008552 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008553 StringRef CurSegName;
8554 uint64_t CurSegAddress;
8555 for (const SectionRef &Section : Obj->sections()) {
8556 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008557 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008558 Info.Address = Section.getAddress();
8559 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008560 Info.SegmentName =
8561 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8562 if (!Info.SegmentName.equals(CurSegName)) {
8563 ++CurSegIndex;
8564 CurSegName = Info.SegmentName;
8565 CurSegAddress = Info.Address;
8566 }
8567 Info.SegmentIndex = CurSegIndex - 1;
8568 Info.OffsetInSegment = Info.Address - CurSegAddress;
8569 Info.SegmentStartAddress = CurSegAddress;
8570 Sections.push_back(Info);
8571 }
8572}
8573
8574StringRef SegInfo::segmentName(uint32_t SegIndex) {
8575 for (const SectionInfo &SI : Sections) {
8576 if (SI.SegmentIndex == SegIndex)
8577 return SI.SegmentName;
8578 }
8579 llvm_unreachable("invalid segIndex");
8580}
8581
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008582bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8583 uint64_t OffsetInSeg) {
8584 for (const SectionInfo &SI : Sections) {
8585 if (SI.SegmentIndex != SegIndex)
8586 continue;
8587 if (SI.OffsetInSegment > OffsetInSeg)
8588 continue;
8589 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8590 continue;
8591 return true;
8592 }
8593 return false;
8594}
8595
Nick Kledzikac431442014-09-12 21:34:15 +00008596const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8597 uint64_t OffsetInSeg) {
8598 for (const SectionInfo &SI : Sections) {
8599 if (SI.SegmentIndex != SegIndex)
8600 continue;
8601 if (SI.OffsetInSegment > OffsetInSeg)
8602 continue;
8603 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8604 continue;
8605 return SI;
8606 }
8607 llvm_unreachable("segIndex and offset not in any section");
8608}
8609
8610StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8611 return findSection(SegIndex, OffsetInSeg).SectionName;
8612}
8613
8614uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8615 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8616 return SI.SegmentStartAddress + OffsetInSeg;
8617}
8618
8619void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8620 // Build table of sections so names can used in final output.
8621 SegInfo sectionTable(Obj);
8622
8623 outs() << "segment section address type\n";
8624 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8625 uint32_t SegIndex = Entry.segmentIndex();
8626 uint64_t OffsetInSeg = Entry.segmentOffset();
8627 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8628 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8629 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8630
8631 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008632 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8633 SegmentName.str().c_str(), SectionName.str().c_str(),
8634 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008635 }
8636}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008637
8638static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8639 StringRef DylibName;
8640 switch (Ordinal) {
8641 case MachO::BIND_SPECIAL_DYLIB_SELF:
8642 return "this-image";
8643 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8644 return "main-executable";
8645 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8646 return "flat-namespace";
8647 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008648 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008649 std::error_code EC =
8650 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008651 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008652 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008653 return DylibName;
8654 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008655 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008656 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008657}
8658
8659//===----------------------------------------------------------------------===//
8660// bind table dumping
8661//===----------------------------------------------------------------------===//
8662
8663void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8664 // Build table of sections so names can used in final output.
8665 SegInfo sectionTable(Obj);
8666
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008667 outs() << "segment section address type "
8668 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008669 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8670 uint32_t SegIndex = Entry.segmentIndex();
8671 uint64_t OffsetInSeg = Entry.segmentOffset();
8672 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8673 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8674 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8675
8676 // Table lines look like:
8677 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008678 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008679 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008680 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008681 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008682 << left_justify(SectionName, 18) << " "
8683 << format_hex(Address, 10, true) << " "
8684 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008685 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008686 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008687 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008688 }
8689}
8690
8691//===----------------------------------------------------------------------===//
8692// lazy bind table dumping
8693//===----------------------------------------------------------------------===//
8694
8695void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8696 // Build table of sections so names can used in final output.
8697 SegInfo sectionTable(Obj);
8698
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008699 outs() << "segment section address "
8700 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008701 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8702 uint32_t SegIndex = Entry.segmentIndex();
8703 uint64_t OffsetInSeg = Entry.segmentOffset();
8704 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8705 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8706 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8707
8708 // Table lines look like:
8709 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008710 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008711 << left_justify(SectionName, 18) << " "
8712 << format_hex(Address, 10, true) << " "
8713 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008714 << Entry.symbolName() << "\n";
8715 }
8716}
8717
Nick Kledzik56ebef42014-09-16 01:41:51 +00008718//===----------------------------------------------------------------------===//
8719// weak bind table dumping
8720//===----------------------------------------------------------------------===//
8721
8722void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8723 // Build table of sections so names can used in final output.
8724 SegInfo sectionTable(Obj);
8725
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008726 outs() << "segment section address "
8727 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008728 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8729 // Strong symbols don't have a location to update.
8730 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008731 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008732 << Entry.symbolName() << "\n";
8733 continue;
8734 }
8735 uint32_t SegIndex = Entry.segmentIndex();
8736 uint64_t OffsetInSeg = Entry.segmentOffset();
8737 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8738 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8739 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8740
8741 // Table lines look like:
8742 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008743 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008744 << left_justify(SectionName, 18) << " "
8745 << format_hex(Address, 10, true) << " "
8746 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008747 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8748 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008749 }
8750}
8751
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008752// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8753// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8754// information for that address. If the address is found its binding symbol
8755// name is returned. If not nullptr is returned.
8756static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8757 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008758 if (info->bindtable == nullptr) {
8759 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008760 SegInfo sectionTable(info->O);
8761 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8762 uint32_t SegIndex = Entry.segmentIndex();
8763 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008764 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8765 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008766 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8767 const char *SymbolName = nullptr;
8768 StringRef name = Entry.symbolName();
8769 if (!name.empty())
8770 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008771 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008772 }
8773 }
Kevin Enderby078be602014-10-23 19:53:12 +00008774 for (bind_table_iterator BI = info->bindtable->begin(),
8775 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008776 BI != BE; ++BI) {
8777 uint64_t Address = BI->first;
8778 if (ReferenceValue == Address) {
8779 const char *SymbolName = BI->second;
8780 return SymbolName;
8781 }
8782 }
8783 return nullptr;
8784}