blob: e486b1a0d6d9eb9d7072b40ed46d4198f6c2a771 [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 Kramer43a772e2011-09-19 17:56:04 +000025#include "llvm/MC/MCDisassembler.h"
26#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) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000175 uint64_t AAddr = (A.getType() != SymbolRef::ST_Function) ? 0 : A.getValue();
176 uint64_t BAddr = (B.getType() != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000177 return AAddr < BAddr;
178 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000179};
180
Kevin Enderby273ae012013-06-06 17:20:50 +0000181// Types for the storted data in code table that is built before disassembly
182// and the predicate function to sort them.
183typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
184typedef std::vector<DiceTableEntry> DiceTable;
185typedef DiceTable::iterator dice_table_iterator;
186
Kevin Enderby930fdc72014-11-06 19:00:13 +0000187// This is used to search for a data in code table entry for the PC being
188// disassembled. The j parameter has the PC in j.first. A single data in code
189// table entry can cover many bytes for each of its Kind's. So if the offset,
190// aka the i.first value, of the data in code table entry plus its Length
191// covers the PC being searched for this will return true. If not it will
192// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000193static bool compareDiceTableEntries(const DiceTableEntry &i,
194 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000195 uint16_t Length;
196 i.second.getLength(Length);
197
198 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000199}
200
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000201static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000202 unsigned short Kind) {
203 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000204
205 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000206 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000207 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000208 if (Length >= 4) {
209 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000210 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000211 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000212 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000213 Size = 4;
214 } else if (Length >= 2) {
215 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000216 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000217 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000218 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000219 Size = 2;
220 } else {
221 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000222 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000223 Value = bytes[0];
224 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000225 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000226 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000227 if (Kind == MachO::DICE_KIND_DATA)
228 outs() << "\t@ KIND_DATA\n";
229 else
230 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000231 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000232 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000234 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000235 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000236 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
237 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000238 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000239 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000242 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 outs() << "\t.short " << format("%5u", Value & 0xffff)
244 << "\t@ KIND_JUMP_TABLE16\n";
245 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000247 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
249 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000250 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000251 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000252 outs() << "\t.long " << Value;
253 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
254 outs() << "\t@ KIND_JUMP_TABLE32\n";
255 else
256 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
257 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000258 break;
259 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000260 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000261}
262
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000263static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000264 std::vector<SectionRef> &Sections,
265 std::vector<SymbolRef> &Symbols,
266 SmallVectorImpl<uint64_t> &FoundFns,
267 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000268 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000269 ErrorOr<StringRef> SymName = Symbol.getName();
270 if (std::error_code EC = SymName.getError())
271 report_fatal_error(EC.message());
272 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000273 Symbols.push_back(Symbol);
274 }
Owen Andersond9243c42011-10-17 21:37:35 +0000275
Alexey Samsonov48803e52014-03-13 14:37:36 +0000276 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000277 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000278 Section.getName(SectName);
279 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000280 }
281
Kevin Enderby273ae012013-06-06 17:20:50 +0000282 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000283 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000284 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000285 // We found a function starts segment, parse the addresses for later
286 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000287 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000288 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000289
Charles Davis8bdfafd2013-09-01 04:28:48 +0000290 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000291 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
292 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000293 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000294 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000295 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000296 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000297 }
298 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000299 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000300}
301
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000302static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
303 uint32_t n, uint32_t count,
304 uint32_t stride, uint64_t addr) {
305 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
306 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
307 if (n > nindirectsyms)
308 outs() << " (entries start past the end of the indirect symbol "
309 "table) (reserved1 field greater than the table size)";
310 else if (n + count > nindirectsyms)
311 outs() << " (entries extends past the end of the indirect symbol "
312 "table)";
313 outs() << "\n";
314 uint32_t cputype = O->getHeader().cputype;
315 if (cputype & MachO::CPU_ARCH_ABI64)
316 outs() << "address index";
317 else
318 outs() << "address index";
319 if (verbose)
320 outs() << " name\n";
321 else
322 outs() << "\n";
323 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
324 if (cputype & MachO::CPU_ARCH_ABI64)
325 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
326 else
327 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
328 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
329 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
330 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
331 outs() << "LOCAL\n";
332 continue;
333 }
334 if (indirect_symbol ==
335 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
336 outs() << "LOCAL ABSOLUTE\n";
337 continue;
338 }
339 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
340 outs() << "ABSOLUTE\n";
341 continue;
342 }
343 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000344 if (verbose) {
345 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
346 if (indirect_symbol < Symtab.nsyms) {
347 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
348 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000349 ErrorOr<StringRef> SymName = Symbol.getName();
350 if (std::error_code EC = SymName.getError())
351 report_fatal_error(EC.message());
352 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000353 } else {
354 outs() << "?";
355 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000356 }
357 outs() << "\n";
358 }
359}
360
361static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000362 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000363 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
364 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
365 for (unsigned J = 0; J < Seg.nsects; ++J) {
366 MachO::section_64 Sec = O->getSection64(Load, J);
367 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
368 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
369 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
370 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
371 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
372 section_type == MachO::S_SYMBOL_STUBS) {
373 uint32_t stride;
374 if (section_type == MachO::S_SYMBOL_STUBS)
375 stride = Sec.reserved2;
376 else
377 stride = 8;
378 if (stride == 0) {
379 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
380 << Sec.sectname << ") "
381 << "(size of stubs in reserved2 field is zero)\n";
382 continue;
383 }
384 uint32_t count = Sec.size / stride;
385 outs() << "Indirect symbols for (" << Sec.segname << ","
386 << Sec.sectname << ") " << count << " entries";
387 uint32_t n = Sec.reserved1;
388 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
389 }
390 }
391 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
392 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
393 for (unsigned J = 0; J < Seg.nsects; ++J) {
394 MachO::section Sec = O->getSection(Load, J);
395 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
396 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
397 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
398 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
399 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
400 section_type == MachO::S_SYMBOL_STUBS) {
401 uint32_t stride;
402 if (section_type == MachO::S_SYMBOL_STUBS)
403 stride = Sec.reserved2;
404 else
405 stride = 4;
406 if (stride == 0) {
407 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
408 << Sec.sectname << ") "
409 << "(size of stubs in reserved2 field is zero)\n";
410 continue;
411 }
412 uint32_t count = Sec.size / stride;
413 outs() << "Indirect symbols for (" << Sec.segname << ","
414 << Sec.sectname << ") " << count << " entries";
415 uint32_t n = Sec.reserved1;
416 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
417 }
418 }
419 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000420 }
421}
422
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000423static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
424 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
425 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
426 outs() << "Data in code table (" << nentries << " entries)\n";
427 outs() << "offset length kind\n";
428 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
429 ++DI) {
430 uint32_t Offset;
431 DI->getOffset(Offset);
432 outs() << format("0x%08" PRIx32, Offset) << " ";
433 uint16_t Length;
434 DI->getLength(Length);
435 outs() << format("%6u", Length) << " ";
436 uint16_t Kind;
437 DI->getKind(Kind);
438 if (verbose) {
439 switch (Kind) {
440 case MachO::DICE_KIND_DATA:
441 outs() << "DATA";
442 break;
443 case MachO::DICE_KIND_JUMP_TABLE8:
444 outs() << "JUMP_TABLE8";
445 break;
446 case MachO::DICE_KIND_JUMP_TABLE16:
447 outs() << "JUMP_TABLE16";
448 break;
449 case MachO::DICE_KIND_JUMP_TABLE32:
450 outs() << "JUMP_TABLE32";
451 break;
452 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
453 outs() << "ABS_JUMP_TABLE32";
454 break;
455 default:
456 outs() << format("0x%04" PRIx32, Kind);
457 break;
458 }
459 } else
460 outs() << format("0x%04" PRIx32, Kind);
461 outs() << "\n";
462 }
463}
464
Kevin Enderby9a509442015-01-27 21:28:24 +0000465static void PrintLinkOptHints(MachOObjectFile *O) {
466 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
467 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
468 uint32_t nloh = LohLC.datasize;
469 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
470 for (uint32_t i = 0; i < nloh;) {
471 unsigned n;
472 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
473 i += n;
474 outs() << " identifier " << identifier << " ";
475 if (i >= nloh)
476 return;
477 switch (identifier) {
478 case 1:
479 outs() << "AdrpAdrp\n";
480 break;
481 case 2:
482 outs() << "AdrpLdr\n";
483 break;
484 case 3:
485 outs() << "AdrpAddLdr\n";
486 break;
487 case 4:
488 outs() << "AdrpLdrGotLdr\n";
489 break;
490 case 5:
491 outs() << "AdrpAddStr\n";
492 break;
493 case 6:
494 outs() << "AdrpLdrGotStr\n";
495 break;
496 case 7:
497 outs() << "AdrpAdd\n";
498 break;
499 case 8:
500 outs() << "AdrpLdrGot\n";
501 break;
502 default:
503 outs() << "Unknown identifier value\n";
504 break;
505 }
506 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
507 i += n;
508 outs() << " narguments " << narguments << "\n";
509 if (i >= nloh)
510 return;
511
512 for (uint32_t j = 0; j < narguments; j++) {
513 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
514 i += n;
515 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
516 if (i >= nloh)
517 return;
518 }
519 }
520}
521
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000522static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000523 unsigned Index = 0;
524 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000525 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
526 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
527 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
528 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
529 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
530 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
531 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
532 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
533 if (dl.dylib.name < dl.cmdsize) {
534 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
535 if (JustId)
536 outs() << p << "\n";
537 else {
538 outs() << "\t" << p;
539 outs() << " (compatibility version "
540 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
541 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
542 << (dl.dylib.compatibility_version & 0xff) << ",";
543 outs() << " current version "
544 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
545 << ((dl.dylib.current_version >> 8) & 0xff) << "."
546 << (dl.dylib.current_version & 0xff) << ")\n";
547 }
548 } else {
549 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
550 if (Load.C.cmd == MachO::LC_ID_DYLIB)
551 outs() << "LC_ID_DYLIB ";
552 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
553 outs() << "LC_LOAD_DYLIB ";
554 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
555 outs() << "LC_LOAD_WEAK_DYLIB ";
556 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
557 outs() << "LC_LAZY_LOAD_DYLIB ";
558 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
559 outs() << "LC_REEXPORT_DYLIB ";
560 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
561 outs() << "LC_LOAD_UPWARD_DYLIB ";
562 else
563 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000564 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000565 }
566 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000567 }
568}
569
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000570typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
571
572static void CreateSymbolAddressMap(MachOObjectFile *O,
573 SymbolAddressMap *AddrMap) {
574 // Create a map of symbol addresses to symbol names.
575 for (const SymbolRef &Symbol : O->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +0000576 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000577 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
578 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000579 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000580 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
581 if (std::error_code EC = SymNameOrErr.getError())
582 report_fatal_error(EC.message());
583 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000584 if (!SymName.startswith(".objc"))
585 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000586 }
587 }
588}
589
590// GuessSymbolName is passed the address of what might be a symbol and a
591// pointer to the SymbolAddressMap. It returns the name of a symbol
592// with that address or nullptr if no symbol is found with that address.
593static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
594 const char *SymbolName = nullptr;
595 // A DenseMap can't lookup up some values.
596 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
597 StringRef name = AddrMap->lookup(value);
598 if (!name.empty())
599 SymbolName = name.data();
600 }
601 return SymbolName;
602}
603
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000604static void DumpCstringChar(const char c) {
605 char p[2];
606 p[0] = c;
607 p[1] = '\0';
608 outs().write_escaped(p);
609}
610
Kevin Enderby10ba0412015-02-04 21:38:42 +0000611static void DumpCstringSection(MachOObjectFile *O, const char *sect,
612 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000613 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000614 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000615 if (print_addresses) {
616 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000617 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000618 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000619 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000620 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000621 for (; i < sect_size && sect[i] != '\0'; i++)
622 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000623 if (i < sect_size && sect[i] == '\0')
624 outs() << "\n";
625 }
626}
627
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000628static void DumpLiteral4(uint32_t l, float f) {
629 outs() << format("0x%08" PRIx32, l);
630 if ((l & 0x7f800000) != 0x7f800000)
631 outs() << format(" (%.16e)\n", f);
632 else {
633 if (l == 0x7f800000)
634 outs() << " (+Infinity)\n";
635 else if (l == 0xff800000)
636 outs() << " (-Infinity)\n";
637 else if ((l & 0x00400000) == 0x00400000)
638 outs() << " (non-signaling Not-a-Number)\n";
639 else
640 outs() << " (signaling Not-a-Number)\n";
641 }
642}
643
644static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
645 uint32_t sect_size, uint64_t sect_addr,
646 bool print_addresses) {
647 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
648 if (print_addresses) {
649 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000650 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000651 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000652 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000653 }
654 float f;
655 memcpy(&f, sect + i, sizeof(float));
656 if (O->isLittleEndian() != sys::IsLittleEndianHost)
657 sys::swapByteOrder(f);
658 uint32_t l;
659 memcpy(&l, sect + i, sizeof(uint32_t));
660 if (O->isLittleEndian() != sys::IsLittleEndianHost)
661 sys::swapByteOrder(l);
662 DumpLiteral4(l, f);
663 }
664}
665
666static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
667 double d) {
668 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
669 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000670 Hi = (O->isLittleEndian()) ? l1 : l0;
671 Lo = (O->isLittleEndian()) ? l0 : l1;
672
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000673 // Hi is the high word, so this is equivalent to if(isfinite(d))
674 if ((Hi & 0x7ff00000) != 0x7ff00000)
675 outs() << format(" (%.16e)\n", d);
676 else {
677 if (Hi == 0x7ff00000 && Lo == 0)
678 outs() << " (+Infinity)\n";
679 else if (Hi == 0xfff00000 && Lo == 0)
680 outs() << " (-Infinity)\n";
681 else if ((Hi & 0x00080000) == 0x00080000)
682 outs() << " (non-signaling Not-a-Number)\n";
683 else
684 outs() << " (signaling Not-a-Number)\n";
685 }
686}
687
688static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
689 uint32_t sect_size, uint64_t sect_addr,
690 bool print_addresses) {
691 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
692 if (print_addresses) {
693 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000694 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000695 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000696 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000697 }
698 double d;
699 memcpy(&d, sect + i, sizeof(double));
700 if (O->isLittleEndian() != sys::IsLittleEndianHost)
701 sys::swapByteOrder(d);
702 uint32_t l0, l1;
703 memcpy(&l0, sect + i, sizeof(uint32_t));
704 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
705 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
706 sys::swapByteOrder(l0);
707 sys::swapByteOrder(l1);
708 }
709 DumpLiteral8(O, l0, l1, d);
710 }
711}
712
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000713static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
714 outs() << format("0x%08" PRIx32, l0) << " ";
715 outs() << format("0x%08" PRIx32, l1) << " ";
716 outs() << format("0x%08" PRIx32, l2) << " ";
717 outs() << format("0x%08" PRIx32, l3) << "\n";
718}
719
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000720static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
721 uint32_t sect_size, uint64_t sect_addr,
722 bool print_addresses) {
723 for (uint32_t i = 0; i < sect_size; i += 16) {
724 if (print_addresses) {
725 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000726 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000728 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000729 }
730 uint32_t l0, l1, l2, l3;
731 memcpy(&l0, sect + i, sizeof(uint32_t));
732 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
733 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
734 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
736 sys::swapByteOrder(l0);
737 sys::swapByteOrder(l1);
738 sys::swapByteOrder(l2);
739 sys::swapByteOrder(l3);
740 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000741 DumpLiteral16(l0, l1, l2, l3);
742 }
743}
744
745static void DumpLiteralPointerSection(MachOObjectFile *O,
746 const SectionRef &Section,
747 const char *sect, uint32_t sect_size,
748 uint64_t sect_addr,
749 bool print_addresses) {
750 // Collect the literal sections in this Mach-O file.
751 std::vector<SectionRef> LiteralSections;
752 for (const SectionRef &Section : O->sections()) {
753 DataRefImpl Ref = Section.getRawDataRefImpl();
754 uint32_t section_type;
755 if (O->is64Bit()) {
756 const MachO::section_64 Sec = O->getSection64(Ref);
757 section_type = Sec.flags & MachO::SECTION_TYPE;
758 } else {
759 const MachO::section Sec = O->getSection(Ref);
760 section_type = Sec.flags & MachO::SECTION_TYPE;
761 }
762 if (section_type == MachO::S_CSTRING_LITERALS ||
763 section_type == MachO::S_4BYTE_LITERALS ||
764 section_type == MachO::S_8BYTE_LITERALS ||
765 section_type == MachO::S_16BYTE_LITERALS)
766 LiteralSections.push_back(Section);
767 }
768
769 // Set the size of the literal pointer.
770 uint32_t lp_size = O->is64Bit() ? 8 : 4;
771
Eric Christopher572e03a2015-06-19 01:53:21 +0000772 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000773 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
774 for (const RelocationRef &Reloc : Section.relocations()) {
775 DataRefImpl Rel;
776 MachO::any_relocation_info RE;
777 bool isExtern = false;
778 Rel = Reloc.getRawDataRefImpl();
779 RE = O->getRelocation(Rel);
780 isExtern = O->getPlainRelocationExternal(RE);
781 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000782 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000783 symbol_iterator RelocSym = Reloc.getSymbol();
784 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
785 }
786 }
787 array_pod_sort(Relocs.begin(), Relocs.end());
788
789 // Dump each literal pointer.
790 for (uint32_t i = 0; i < sect_size; i += lp_size) {
791 if (print_addresses) {
792 if (O->is64Bit())
793 outs() << format("%016" PRIx64, sect_addr + i) << " ";
794 else
795 outs() << format("%08" PRIx64, sect_addr + i) << " ";
796 }
797 uint64_t lp;
798 if (O->is64Bit()) {
799 memcpy(&lp, sect + i, sizeof(uint64_t));
800 if (O->isLittleEndian() != sys::IsLittleEndianHost)
801 sys::swapByteOrder(lp);
802 } else {
803 uint32_t li;
804 memcpy(&li, sect + i, sizeof(uint32_t));
805 if (O->isLittleEndian() != sys::IsLittleEndianHost)
806 sys::swapByteOrder(li);
807 lp = li;
808 }
809
810 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000811 auto Reloc = std::find_if(
812 Relocs.begin(), Relocs.end(),
813 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
814 if (Reloc != Relocs.end()) {
815 symbol_iterator RelocSym = Reloc->second;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000816 ErrorOr<StringRef> SymName = RelocSym->getName();
817 if (std::error_code EC = SymName.getError())
818 report_fatal_error(EC.message());
819 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000820 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000821 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000822
823 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000824 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
825 [&](const SectionRef &R) {
826 return lp >= R.getAddress() &&
827 lp < R.getAddress() + R.getSize();
828 });
829 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000830 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000831 continue;
832 }
833
834 uint64_t SectAddress = Sect->getAddress();
835 uint64_t SectSize = Sect->getSize();
836
837 StringRef SectName;
838 Sect->getName(SectName);
839 DataRefImpl Ref = Sect->getRawDataRefImpl();
840 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
841 outs() << SegmentName << ":" << SectName << ":";
842
843 uint32_t section_type;
844 if (O->is64Bit()) {
845 const MachO::section_64 Sec = O->getSection64(Ref);
846 section_type = Sec.flags & MachO::SECTION_TYPE;
847 } else {
848 const MachO::section Sec = O->getSection(Ref);
849 section_type = Sec.flags & MachO::SECTION_TYPE;
850 }
851
852 StringRef BytesStr;
853 Sect->getContents(BytesStr);
854 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
855
856 switch (section_type) {
857 case MachO::S_CSTRING_LITERALS:
858 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
859 i++) {
860 DumpCstringChar(Contents[i]);
861 }
862 outs() << "\n";
863 break;
864 case MachO::S_4BYTE_LITERALS:
865 float f;
866 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
867 uint32_t l;
868 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
869 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
870 sys::swapByteOrder(f);
871 sys::swapByteOrder(l);
872 }
873 DumpLiteral4(l, f);
874 break;
875 case MachO::S_8BYTE_LITERALS: {
876 double d;
877 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
878 uint32_t l0, l1;
879 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
880 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
881 sizeof(uint32_t));
882 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
883 sys::swapByteOrder(f);
884 sys::swapByteOrder(l0);
885 sys::swapByteOrder(l1);
886 }
887 DumpLiteral8(O, l0, l1, d);
888 break;
889 }
890 case MachO::S_16BYTE_LITERALS: {
891 uint32_t l0, l1, l2, l3;
892 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
893 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
894 sizeof(uint32_t));
895 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
896 sizeof(uint32_t));
897 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
898 sizeof(uint32_t));
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(l0);
901 sys::swapByteOrder(l1);
902 sys::swapByteOrder(l2);
903 sys::swapByteOrder(l3);
904 }
905 DumpLiteral16(l0, l1, l2, l3);
906 break;
907 }
908 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000909 }
910}
911
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000912static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
913 uint32_t sect_size, uint64_t sect_addr,
914 SymbolAddressMap *AddrMap,
915 bool verbose) {
916 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000917 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000918 for (uint32_t i = 0; i < sect_size; i += stride) {
919 const char *SymbolName = nullptr;
920 if (O->is64Bit()) {
921 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
922 uint64_t pointer_value;
923 memcpy(&pointer_value, sect + i, stride);
924 if (O->isLittleEndian() != sys::IsLittleEndianHost)
925 sys::swapByteOrder(pointer_value);
926 outs() << format("0x%016" PRIx64, pointer_value);
927 if (verbose)
928 SymbolName = GuessSymbolName(pointer_value, AddrMap);
929 } else {
930 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
931 uint32_t pointer_value;
932 memcpy(&pointer_value, sect + i, stride);
933 if (O->isLittleEndian() != sys::IsLittleEndianHost)
934 sys::swapByteOrder(pointer_value);
935 outs() << format("0x%08" PRIx32, pointer_value);
936 if (verbose)
937 SymbolName = GuessSymbolName(pointer_value, AddrMap);
938 }
939 if (SymbolName)
940 outs() << " " << SymbolName;
941 outs() << "\n";
942 }
943}
944
945static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
946 uint32_t size, uint64_t addr) {
947 uint32_t cputype = O->getHeader().cputype;
948 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
949 uint32_t j;
950 for (uint32_t i = 0; i < size; i += j, addr += j) {
951 if (O->is64Bit())
952 outs() << format("%016" PRIx64, addr) << "\t";
953 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000954 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000955 for (j = 0; j < 16 && i + j < size; j++) {
956 uint8_t byte_word = *(sect + i + j);
957 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
958 }
959 outs() << "\n";
960 }
961 } else {
962 uint32_t j;
963 for (uint32_t i = 0; i < size; i += j, addr += j) {
964 if (O->is64Bit())
965 outs() << format("%016" PRIx64, addr) << "\t";
966 else
967 outs() << format("%08" PRIx64, sect) << "\t";
968 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
969 j += sizeof(int32_t)) {
970 if (i + j + sizeof(int32_t) < size) {
971 uint32_t long_word;
972 memcpy(&long_word, sect + i + j, sizeof(int32_t));
973 if (O->isLittleEndian() != sys::IsLittleEndianHost)
974 sys::swapByteOrder(long_word);
975 outs() << format("%08" PRIx32, long_word) << " ";
976 } else {
977 for (uint32_t k = 0; i + j + k < size; k++) {
978 uint8_t byte_word = *(sect + i + j);
979 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
980 }
981 }
982 }
983 outs() << "\n";
984 }
985 }
986}
987
Kevin Enderby95df54c2015-02-04 01:01:38 +0000988static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
989 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +0000990static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
991 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +0000992
993static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
994 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000995 SymbolAddressMap AddrMap;
996 if (verbose)
997 CreateSymbolAddressMap(O, &AddrMap);
998
Colin LeMahieufcc32762015-07-29 19:08:10 +0000999 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1000 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001001 std::pair<StringRef, StringRef> DumpSegSectName;
1002 DumpSegSectName = DumpSection.split(',');
1003 StringRef DumpSegName, DumpSectName;
1004 if (DumpSegSectName.second.size()) {
1005 DumpSegName = DumpSegSectName.first;
1006 DumpSectName = DumpSegSectName.second;
1007 } else {
1008 DumpSegName = "";
1009 DumpSectName = DumpSegSectName.first;
1010 }
1011 for (const SectionRef &Section : O->sections()) {
1012 StringRef SectName;
1013 Section.getName(SectName);
1014 DataRefImpl Ref = Section.getRawDataRefImpl();
1015 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1016 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1017 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001018
Kevin Enderby95df54c2015-02-04 01:01:38 +00001019 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001020 if (O->is64Bit()) {
1021 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001022 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001023
1024 } else {
1025 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001026 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001027 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001028 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001029
1030 StringRef BytesStr;
1031 Section.getContents(BytesStr);
1032 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1033 uint32_t sect_size = BytesStr.size();
1034 uint64_t sect_addr = Section.getAddress();
1035
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001036 outs() << "Contents of (" << SegName << "," << SectName
1037 << ") section\n";
1038
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001039 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001040 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1041 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1042 DisassembleMachO(Filename, O, SegName, SectName);
1043 continue;
1044 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001045 if (SegName == "__TEXT" && SectName == "__info_plist") {
1046 outs() << sect;
1047 continue;
1048 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001049 if (SegName == "__OBJC" && SectName == "__protocol") {
1050 DumpProtocolSection(O, sect, sect_size, sect_addr);
1051 continue;
1052 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001053 switch (section_type) {
1054 case MachO::S_REGULAR:
1055 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1056 break;
1057 case MachO::S_ZEROFILL:
1058 outs() << "zerofill section and has no contents in the file\n";
1059 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001060 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001061 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001062 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001063 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001064 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001065 break;
1066 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001067 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001068 break;
1069 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001070 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1071 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001072 case MachO::S_LITERAL_POINTERS:
1073 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001074 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001075 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001076 case MachO::S_MOD_INIT_FUNC_POINTERS:
1077 case MachO::S_MOD_TERM_FUNC_POINTERS:
1078 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1079 verbose);
1080 break;
1081 default:
1082 outs() << "Unknown section type ("
1083 << format("0x%08" PRIx32, section_type) << ")\n";
1084 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1085 break;
1086 }
1087 } else {
1088 if (section_type == MachO::S_ZEROFILL)
1089 outs() << "zerofill section and has no contents in the file\n";
1090 else
1091 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1092 }
1093 }
1094 }
1095 }
1096}
1097
Kevin Enderbycd66be52015-03-11 22:06:32 +00001098static void DumpInfoPlistSectionContents(StringRef Filename,
1099 MachOObjectFile *O) {
1100 for (const SectionRef &Section : O->sections()) {
1101 StringRef SectName;
1102 Section.getName(SectName);
1103 DataRefImpl Ref = Section.getRawDataRefImpl();
1104 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1105 if (SegName == "__TEXT" && SectName == "__info_plist") {
1106 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1107 StringRef BytesStr;
1108 Section.getContents(BytesStr);
1109 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1110 outs() << sect;
1111 return;
1112 }
1113 }
1114}
1115
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001116// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1117// and if it is and there is a list of architecture flags is specified then
1118// check to make sure this Mach-O file is one of those architectures or all
1119// architectures were specified. If not then an error is generated and this
1120// routine returns false. Else it returns true.
1121static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1122 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1123 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1124 bool ArchFound = false;
1125 MachO::mach_header H;
1126 MachO::mach_header_64 H_64;
1127 Triple T;
1128 if (MachO->is64Bit()) {
1129 H_64 = MachO->MachOObjectFile::getHeader64();
1130 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1131 } else {
1132 H = MachO->MachOObjectFile::getHeader();
1133 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1134 }
1135 unsigned i;
1136 for (i = 0; i < ArchFlags.size(); ++i) {
1137 if (ArchFlags[i] == T.getArchName())
1138 ArchFound = true;
1139 break;
1140 }
1141 if (!ArchFound) {
1142 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1143 << "architecture: " + ArchFlags[i] + "\n";
1144 return false;
1145 }
1146 }
1147 return true;
1148}
1149
Kevin Enderby0fc11822015-04-01 20:57:01 +00001150static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1151
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001152// ProcessMachO() is passed a single opened Mach-O file, which may be an
1153// archive member and or in a slice of a universal file. It prints the
1154// the file name and header info and then processes it according to the
1155// command line options.
1156static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1157 StringRef ArchiveMemberName = StringRef(),
1158 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001159 // If we are doing some processing here on the Mach-O file print the header
1160 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001161 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001162 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001163 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001164 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001165 outs() << Filename;
1166 if (!ArchiveMemberName.empty())
1167 outs() << '(' << ArchiveMemberName << ')';
1168 if (!ArchitectureName.empty())
1169 outs() << " (architecture " << ArchitectureName << ")";
1170 outs() << ":\n";
1171 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001172
1173 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001174 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001175 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001176 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001177 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001178 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001179 if (LinkOptHints)
1180 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001181 if (Relocations)
1182 PrintRelocations(MachOOF);
1183 if (SectionHeaders)
1184 PrintSectionHeaders(MachOOF);
1185 if (SectionContents)
1186 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001187 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001188 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001189 if (InfoPlist)
1190 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001191 if (DylibsUsed)
1192 PrintDylibs(MachOOF, false);
1193 if (DylibId)
1194 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001195 if (SymbolTable)
1196 PrintSymbolTable(MachOOF);
1197 if (UnwindInfo)
1198 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001199 if (PrivateHeaders) {
1200 printMachOFileHeader(MachOOF);
1201 printMachOLoadCommands(MachOOF);
1202 }
1203 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001204 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001205 if (ObjcMetaData)
1206 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001207 if (ExportsTrie)
1208 printExportsTrie(MachOOF);
1209 if (Rebase)
1210 printRebaseTable(MachOOF);
1211 if (Bind)
1212 printBindTable(MachOOF);
1213 if (LazyBind)
1214 printLazyBindTable(MachOOF);
1215 if (WeakBind)
1216 printWeakBindTable(MachOOF);
1217}
1218
Kevin Enderby131d1772015-01-09 19:22:37 +00001219// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1220static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1221 outs() << " cputype (" << cputype << ")\n";
1222 outs() << " cpusubtype (" << cpusubtype << ")\n";
1223}
1224
1225// printCPUType() helps print_fat_headers by printing the cputype and
1226// pusubtype (symbolically for the one's it knows about).
1227static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1228 switch (cputype) {
1229 case MachO::CPU_TYPE_I386:
1230 switch (cpusubtype) {
1231 case MachO::CPU_SUBTYPE_I386_ALL:
1232 outs() << " cputype CPU_TYPE_I386\n";
1233 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1234 break;
1235 default:
1236 printUnknownCPUType(cputype, cpusubtype);
1237 break;
1238 }
1239 break;
1240 case MachO::CPU_TYPE_X86_64:
1241 switch (cpusubtype) {
1242 case MachO::CPU_SUBTYPE_X86_64_ALL:
1243 outs() << " cputype CPU_TYPE_X86_64\n";
1244 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1245 break;
1246 case MachO::CPU_SUBTYPE_X86_64_H:
1247 outs() << " cputype CPU_TYPE_X86_64\n";
1248 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1249 break;
1250 default:
1251 printUnknownCPUType(cputype, cpusubtype);
1252 break;
1253 }
1254 break;
1255 case MachO::CPU_TYPE_ARM:
1256 switch (cpusubtype) {
1257 case MachO::CPU_SUBTYPE_ARM_ALL:
1258 outs() << " cputype CPU_TYPE_ARM\n";
1259 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1260 break;
1261 case MachO::CPU_SUBTYPE_ARM_V4T:
1262 outs() << " cputype CPU_TYPE_ARM\n";
1263 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1264 break;
1265 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1266 outs() << " cputype CPU_TYPE_ARM\n";
1267 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1268 break;
1269 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1270 outs() << " cputype CPU_TYPE_ARM\n";
1271 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1272 break;
1273 case MachO::CPU_SUBTYPE_ARM_V6:
1274 outs() << " cputype CPU_TYPE_ARM\n";
1275 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1276 break;
1277 case MachO::CPU_SUBTYPE_ARM_V6M:
1278 outs() << " cputype CPU_TYPE_ARM\n";
1279 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1280 break;
1281 case MachO::CPU_SUBTYPE_ARM_V7:
1282 outs() << " cputype CPU_TYPE_ARM\n";
1283 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1284 break;
1285 case MachO::CPU_SUBTYPE_ARM_V7EM:
1286 outs() << " cputype CPU_TYPE_ARM\n";
1287 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1288 break;
1289 case MachO::CPU_SUBTYPE_ARM_V7K:
1290 outs() << " cputype CPU_TYPE_ARM\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1292 break;
1293 case MachO::CPU_SUBTYPE_ARM_V7M:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1296 break;
1297 case MachO::CPU_SUBTYPE_ARM_V7S:
1298 outs() << " cputype CPU_TYPE_ARM\n";
1299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1300 break;
1301 default:
1302 printUnknownCPUType(cputype, cpusubtype);
1303 break;
1304 }
1305 break;
1306 case MachO::CPU_TYPE_ARM64:
1307 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1308 case MachO::CPU_SUBTYPE_ARM64_ALL:
1309 outs() << " cputype CPU_TYPE_ARM64\n";
1310 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1311 break;
1312 default:
1313 printUnknownCPUType(cputype, cpusubtype);
1314 break;
1315 }
1316 break;
1317 default:
1318 printUnknownCPUType(cputype, cpusubtype);
1319 break;
1320 }
1321}
1322
1323static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1324 bool verbose) {
1325 outs() << "Fat headers\n";
1326 if (verbose)
1327 outs() << "fat_magic FAT_MAGIC\n";
1328 else
1329 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1330
1331 uint32_t nfat_arch = UB->getNumberOfObjects();
1332 StringRef Buf = UB->getData();
1333 uint64_t size = Buf.size();
1334 uint64_t big_size = sizeof(struct MachO::fat_header) +
1335 nfat_arch * sizeof(struct MachO::fat_arch);
1336 outs() << "nfat_arch " << UB->getNumberOfObjects();
1337 if (nfat_arch == 0)
1338 outs() << " (malformed, contains zero architecture types)\n";
1339 else if (big_size > size)
1340 outs() << " (malformed, architectures past end of file)\n";
1341 else
1342 outs() << "\n";
1343
1344 for (uint32_t i = 0; i < nfat_arch; ++i) {
1345 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1346 uint32_t cputype = OFA.getCPUType();
1347 uint32_t cpusubtype = OFA.getCPUSubType();
1348 outs() << "architecture ";
1349 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1350 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1351 uint32_t other_cputype = other_OFA.getCPUType();
1352 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001353 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001354 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001355 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001356 outs() << "(illegal duplicate architecture) ";
1357 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001358 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001359 }
1360 if (verbose) {
1361 outs() << OFA.getArchTypeName() << "\n";
1362 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1363 } else {
1364 outs() << i << "\n";
1365 outs() << " cputype " << cputype << "\n";
1366 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1367 << "\n";
1368 }
1369 if (verbose &&
1370 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1371 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1372 else
1373 outs() << " capabilities "
1374 << format("0x%" PRIx32,
1375 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1376 outs() << " offset " << OFA.getOffset();
1377 if (OFA.getOffset() > size)
1378 outs() << " (past end of file)";
1379 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1380 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1381 outs() << "\n";
1382 outs() << " size " << OFA.getSize();
1383 big_size = OFA.getOffset() + OFA.getSize();
1384 if (big_size > size)
1385 outs() << " (past end of file)";
1386 outs() << "\n";
1387 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1388 << ")\n";
1389 }
1390}
1391
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001392static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001393 bool print_offset) {
1394 if (print_offset)
1395 outs() << C.getChildOffset() << "\t";
1396 sys::fs::perms Mode = C.getAccessMode();
1397 if (verbose) {
1398 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1399 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1400 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001401 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1402 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1403 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1404 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1405 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1406 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1407 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1408 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1409 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001410 } else {
1411 outs() << format("0%o ", Mode);
1412 }
1413
1414 unsigned UID = C.getUID();
1415 outs() << format("%3d/", UID);
1416 unsigned GID = C.getGID();
1417 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001418 ErrorOr<uint64_t> Size = C.getRawSize();
1419 if (std::error_code EC = Size.getError())
1420 report_fatal_error(EC.message());
1421 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001422
1423 StringRef RawLastModified = C.getRawLastModified();
1424 if (verbose) {
1425 unsigned Seconds;
1426 if (RawLastModified.getAsInteger(10, Seconds))
1427 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1428 else {
1429 // Since cime(3) returns a 26 character string of the form:
1430 // "Sun Sep 16 01:03:52 1973\n\0"
1431 // just print 24 characters.
1432 time_t t = Seconds;
1433 outs() << format("%.24s ", ctime(&t));
1434 }
1435 } else {
1436 outs() << RawLastModified << " ";
1437 }
1438
1439 if (verbose) {
1440 ErrorOr<StringRef> NameOrErr = C.getName();
1441 if (NameOrErr.getError()) {
1442 StringRef RawName = C.getRawName();
1443 outs() << RawName << "\n";
1444 } else {
1445 StringRef Name = NameOrErr.get();
1446 outs() << Name << "\n";
1447 }
1448 } else {
1449 StringRef RawName = C.getRawName();
1450 outs() << RawName << "\n";
1451 }
1452}
1453
1454static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001455 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1456 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001457 if (std::error_code EC = I->getError())
1458 report_fatal_error(EC.message());
1459 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001460 printArchiveChild(C, verbose, print_offset);
1461 }
1462}
1463
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001464// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1465// -arch flags selecting just those slices as specified by them and also parses
1466// archive files. Then for each individual Mach-O file ProcessMachO() is
1467// called to process the file based on the command line options.
1468void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001469 // Check for -arch all and verifiy the -arch flags are valid.
1470 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1471 if (ArchFlags[i] == "all") {
1472 ArchAll = true;
1473 } else {
1474 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1475 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1476 "'for the -arch option\n";
1477 return;
1478 }
1479 }
1480 }
1481
1482 // Attempt to open the binary.
1483 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1484 if (std::error_code EC = BinaryOrErr.getError()) {
1485 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +00001486 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001487 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001488 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001489
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001490 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1491 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001492 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001493 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001494 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1495 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001496 if (std::error_code EC = I->getError())
1497 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001498 auto &C = I->get();
1499 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001500 if (ChildOrErr.getError())
1501 continue;
1502 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1503 if (!checkMachOAndArchFlags(O, Filename))
1504 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001505 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001506 }
1507 }
1508 return;
1509 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001510 if (UniversalHeaders) {
1511 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001512 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001513 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001514 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1515 // If we have a list of architecture flags specified dump only those.
1516 if (!ArchAll && ArchFlags.size() != 0) {
1517 // Look for a slice in the universal binary that matches each ArchFlag.
1518 bool ArchFound;
1519 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1520 ArchFound = false;
1521 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1522 E = UB->end_objects();
1523 I != E; ++I) {
1524 if (ArchFlags[i] == I->getArchTypeName()) {
1525 ArchFound = true;
1526 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1527 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001528 std::string ArchitectureName = "";
1529 if (ArchFlags.size() > 1)
1530 ArchitectureName = I->getArchTypeName();
1531 if (ObjOrErr) {
1532 ObjectFile &O = *ObjOrErr.get();
1533 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001534 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001535 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1536 I->getAsArchive()) {
1537 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001538 outs() << "Archive : " << Filename;
1539 if (!ArchitectureName.empty())
1540 outs() << " (architecture " << ArchitectureName << ")";
1541 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001542 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001543 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001544 for (Archive::child_iterator AI = A->child_begin(),
1545 AE = A->child_end();
1546 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001547 if (std::error_code EC = AI->getError())
1548 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001549 auto &C = AI->get();
1550 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001551 if (ChildOrErr.getError())
1552 continue;
1553 if (MachOObjectFile *O =
1554 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001555 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001556 }
1557 }
1558 }
1559 }
1560 if (!ArchFound) {
1561 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1562 << "architecture: " + ArchFlags[i] + "\n";
1563 return;
1564 }
1565 }
1566 return;
1567 }
1568 // No architecture flags were specified so if this contains a slice that
1569 // matches the host architecture dump only that.
1570 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001571 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1572 E = UB->end_objects();
1573 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001574 if (MachOObjectFile::getHostArch().getArchName() ==
1575 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001576 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001577 std::string ArchiveName;
1578 ArchiveName.clear();
1579 if (ObjOrErr) {
1580 ObjectFile &O = *ObjOrErr.get();
1581 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001582 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001583 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1584 I->getAsArchive()) {
1585 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001586 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001587 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001588 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001589 for (Archive::child_iterator AI = A->child_begin(),
1590 AE = A->child_end();
1591 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001592 if (std::error_code EC = AI->getError())
1593 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001594 auto &C = AI->get();
1595 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001596 if (ChildOrErr.getError())
1597 continue;
1598 if (MachOObjectFile *O =
1599 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001600 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001601 }
1602 }
1603 return;
1604 }
1605 }
1606 }
1607 // Either all architectures have been specified or none have been specified
1608 // and this does not contain the host architecture so dump all the slices.
1609 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1610 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1611 E = UB->end_objects();
1612 I != E; ++I) {
1613 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001614 std::string ArchitectureName = "";
1615 if (moreThanOneArch)
1616 ArchitectureName = I->getArchTypeName();
1617 if (ObjOrErr) {
1618 ObjectFile &Obj = *ObjOrErr.get();
1619 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001620 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001621 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1622 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001623 outs() << "Archive : " << Filename;
1624 if (!ArchitectureName.empty())
1625 outs() << " (architecture " << ArchitectureName << ")";
1626 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001627 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001628 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001629 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1630 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001631 if (std::error_code EC = AI->getError())
1632 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001633 auto &C = AI->get();
1634 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 if (ChildOrErr.getError())
1636 continue;
1637 if (MachOObjectFile *O =
1638 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1639 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001640 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1641 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 }
1643 }
1644 }
1645 }
1646 return;
1647 }
1648 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1649 if (!checkMachOAndArchFlags(O, Filename))
1650 return;
1651 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001652 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001653 } else
1654 errs() << "llvm-objdump: '" << Filename << "': "
1655 << "Object is not a Mach-O file type.\n";
1656 } else
Davide Italianobbd5d162015-12-21 14:10:54 +00001657 report_error(Filename, object_error::invalid_file_type);
Rafael Espindola9b709252013-04-13 01:45:40 +00001658}
1659
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001660typedef std::pair<uint64_t, const char *> BindInfoEntry;
1661typedef std::vector<BindInfoEntry> BindTable;
1662typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001663
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001664// The block of info used by the Symbolizer call backs.
1665struct DisassembleInfo {
1666 bool verbose;
1667 MachOObjectFile *O;
1668 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001669 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001670 std::vector<SectionRef> *Sections;
1671 const char *class_name;
1672 const char *selector_name;
1673 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001674 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001675 uint64_t adrp_addr;
1676 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001677 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001678 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001679};
1680
1681// SymbolizerGetOpInfo() is the operand information call back function.
1682// This is called to get the symbolic information for operand(s) of an
1683// instruction when it is being done. This routine does this from
1684// the relocation information, symbol table, etc. That block of information
1685// is a pointer to the struct DisassembleInfo that was passed when the
1686// disassembler context was created and passed to back to here when
1687// called back by the disassembler for instruction operands that could have
1688// relocation information. The address of the instruction containing operand is
1689// at the Pc parameter. The immediate value the operand has is passed in
1690// op_info->Value and is at Offset past the start of the instruction and has a
1691// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1692// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1693// names and addends of the symbolic expression to add for the operand. The
1694// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1695// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001696static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1697 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001698 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1699 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001700 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001701
1702 // Make sure all fields returned are zero if we don't set them.
1703 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1704 op_info->Value = value;
1705
1706 // If the TagType is not the value 1 which it code knows about or if no
1707 // verbose symbolic information is wanted then just return 0, indicating no
1708 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001709 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001710 return 0;
1711
1712 unsigned int Arch = info->O->getArch();
1713 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001714 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1715 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001716 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1717 // TODO:
1718 // Search the external relocation entries of a fully linked image
1719 // (if any) for an entry that matches this segment offset.
1720 // uint32_t seg_offset = (Pc + Offset);
1721 return 0;
1722 }
1723 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1724 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001725 uint32_t sect_addr = info->S.getAddress();
1726 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1727 bool reloc_found = false;
1728 DataRefImpl Rel;
1729 MachO::any_relocation_info RE;
1730 bool isExtern = false;
1731 SymbolRef Symbol;
1732 bool r_scattered = false;
1733 uint32_t r_value, pair_r_value, r_type;
1734 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001735 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001736 if (RelocOffset == sect_offset) {
1737 Rel = Reloc.getRawDataRefImpl();
1738 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001739 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001740 r_scattered = info->O->isRelocationScattered(RE);
1741 if (r_scattered) {
1742 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001743 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1744 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1745 DataRefImpl RelNext = Rel;
1746 info->O->moveRelocationNext(RelNext);
1747 MachO::any_relocation_info RENext;
1748 RENext = info->O->getRelocation(RelNext);
1749 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001750 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001751 else
1752 return 0;
1753 }
1754 } else {
1755 isExtern = info->O->getPlainRelocationExternal(RE);
1756 if (isExtern) {
1757 symbol_iterator RelocSym = Reloc.getSymbol();
1758 Symbol = *RelocSym;
1759 }
1760 }
1761 reloc_found = true;
1762 break;
1763 }
1764 }
1765 if (reloc_found && isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001766 ErrorOr<StringRef> SymName = Symbol.getName();
1767 if (std::error_code EC = SymName.getError())
1768 report_fatal_error(EC.message());
1769 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001770 op_info->AddSymbol.Present = 1;
1771 op_info->AddSymbol.Name = name;
1772 // For i386 extern relocation entries the value in the instruction is
1773 // the offset from the symbol, and value is already set in op_info->Value.
1774 return 1;
1775 }
1776 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1777 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001778 const char *add = GuessSymbolName(r_value, info->AddrMap);
1779 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001780 uint32_t offset = value - (r_value - pair_r_value);
1781 op_info->AddSymbol.Present = 1;
1782 if (add != nullptr)
1783 op_info->AddSymbol.Name = add;
1784 else
1785 op_info->AddSymbol.Value = r_value;
1786 op_info->SubtractSymbol.Present = 1;
1787 if (sub != nullptr)
1788 op_info->SubtractSymbol.Name = sub;
1789 else
1790 op_info->SubtractSymbol.Value = pair_r_value;
1791 op_info->Value = offset;
1792 return 1;
1793 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001794 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001795 }
1796 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001797 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1798 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001799 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1800 // TODO:
1801 // Search the external relocation entries of a fully linked image
1802 // (if any) for an entry that matches this segment offset.
1803 // uint64_t seg_offset = (Pc + Offset);
1804 return 0;
1805 }
1806 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1807 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001808 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001809 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1810 bool reloc_found = false;
1811 DataRefImpl Rel;
1812 MachO::any_relocation_info RE;
1813 bool isExtern = false;
1814 SymbolRef Symbol;
1815 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001816 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001817 if (RelocOffset == sect_offset) {
1818 Rel = Reloc.getRawDataRefImpl();
1819 RE = info->O->getRelocation(Rel);
1820 // NOTE: Scattered relocations don't exist on x86_64.
1821 isExtern = info->O->getPlainRelocationExternal(RE);
1822 if (isExtern) {
1823 symbol_iterator RelocSym = Reloc.getSymbol();
1824 Symbol = *RelocSym;
1825 }
1826 reloc_found = true;
1827 break;
1828 }
1829 }
1830 if (reloc_found && isExtern) {
1831 // The Value passed in will be adjusted by the Pc if the instruction
1832 // adds the Pc. But for x86_64 external relocation entries the Value
1833 // is the offset from the external symbol.
1834 if (info->O->getAnyRelocationPCRel(RE))
1835 op_info->Value -= Pc + Offset + Size;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001836 ErrorOr<StringRef> SymName = Symbol.getName();
1837 if (std::error_code EC = SymName.getError())
1838 report_fatal_error(EC.message());
1839 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001840 unsigned Type = info->O->getAnyRelocationType(RE);
1841 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1842 DataRefImpl RelNext = Rel;
1843 info->O->moveRelocationNext(RelNext);
1844 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1845 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1846 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1847 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1848 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1849 op_info->SubtractSymbol.Present = 1;
1850 op_info->SubtractSymbol.Name = name;
1851 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1852 Symbol = *RelocSymNext;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001853 ErrorOr<StringRef> SymNameNext = Symbol.getName();
1854 if (std::error_code EC = SymNameNext.getError())
1855 report_fatal_error(EC.message());
1856 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001857 }
1858 }
1859 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1860 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1861 op_info->AddSymbol.Present = 1;
1862 op_info->AddSymbol.Name = name;
1863 return 1;
1864 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001865 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001866 }
1867 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001868 if (Offset != 0 || (Size != 4 && Size != 2))
1869 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001870 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1871 // TODO:
1872 // Search the external relocation entries of a fully linked image
1873 // (if any) for an entry that matches this segment offset.
1874 // uint32_t seg_offset = (Pc + Offset);
1875 return 0;
1876 }
1877 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1878 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001879 uint32_t sect_addr = info->S.getAddress();
1880 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001881 DataRefImpl Rel;
1882 MachO::any_relocation_info RE;
1883 bool isExtern = false;
1884 SymbolRef Symbol;
1885 bool r_scattered = false;
1886 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001887 auto Reloc =
1888 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1889 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001890 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001891 return RelocOffset == sect_offset;
1892 });
1893
1894 if (Reloc == info->S.relocations().end())
1895 return 0;
1896
1897 Rel = Reloc->getRawDataRefImpl();
1898 RE = info->O->getRelocation(Rel);
1899 r_length = info->O->getAnyRelocationLength(RE);
1900 r_scattered = info->O->isRelocationScattered(RE);
1901 if (r_scattered) {
1902 r_value = info->O->getScatteredRelocationValue(RE);
1903 r_type = info->O->getScatteredRelocationType(RE);
1904 } else {
1905 r_type = info->O->getAnyRelocationType(RE);
1906 isExtern = info->O->getPlainRelocationExternal(RE);
1907 if (isExtern) {
1908 symbol_iterator RelocSym = Reloc->getSymbol();
1909 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001910 }
1911 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001912 if (r_type == MachO::ARM_RELOC_HALF ||
1913 r_type == MachO::ARM_RELOC_SECTDIFF ||
1914 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1915 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1916 DataRefImpl RelNext = Rel;
1917 info->O->moveRelocationNext(RelNext);
1918 MachO::any_relocation_info RENext;
1919 RENext = info->O->getRelocation(RelNext);
1920 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1921 if (info->O->isRelocationScattered(RENext))
1922 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1923 }
1924
1925 if (isExtern) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001926 ErrorOr<StringRef> SymName = Symbol.getName();
1927 if (std::error_code EC = SymName.getError())
1928 report_fatal_error(EC.message());
1929 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001930 op_info->AddSymbol.Present = 1;
1931 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001932 switch (r_type) {
1933 case MachO::ARM_RELOC_HALF:
1934 if ((r_length & 0x1) == 1) {
1935 op_info->Value = value << 16 | other_half;
1936 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1937 } else {
1938 op_info->Value = other_half << 16 | value;
1939 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001940 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001941 break;
1942 default:
1943 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001944 }
1945 return 1;
1946 }
1947 // If we have a branch that is not an external relocation entry then
1948 // return 0 so the code in tryAddingSymbolicOperand() can use the
1949 // SymbolLookUp call back with the branch target address to look up the
1950 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00001951 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1952 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001953 return 0;
1954
1955 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001956 if (r_type == MachO::ARM_RELOC_HALF ||
1957 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1958 if ((r_length & 0x1) == 1)
1959 value = value << 16 | other_half;
1960 else
1961 value = other_half << 16 | value;
1962 }
1963 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1964 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1965 offset = value - r_value;
1966 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001967 }
1968
David Blaikie33dd45d02015-03-23 18:39:02 +00001969 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001970 if ((r_length & 0x1) == 1)
1971 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1972 else
1973 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001974 const char *add = GuessSymbolName(r_value, info->AddrMap);
1975 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001976 int32_t offset = value - (r_value - pair_r_value);
1977 op_info->AddSymbol.Present = 1;
1978 if (add != nullptr)
1979 op_info->AddSymbol.Name = add;
1980 else
1981 op_info->AddSymbol.Value = r_value;
1982 op_info->SubtractSymbol.Present = 1;
1983 if (sub != nullptr)
1984 op_info->SubtractSymbol.Name = sub;
1985 else
1986 op_info->SubtractSymbol.Value = pair_r_value;
1987 op_info->Value = offset;
1988 return 1;
1989 }
1990
Kevin Enderby930fdc72014-11-06 19:00:13 +00001991 op_info->AddSymbol.Present = 1;
1992 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00001993 if (r_type == MachO::ARM_RELOC_HALF) {
1994 if ((r_length & 0x1) == 1)
1995 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1996 else
1997 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001998 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001999 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002000 if (add != nullptr) {
2001 op_info->AddSymbol.Name = add;
2002 return 1;
2003 }
2004 op_info->AddSymbol.Value = value;
2005 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002006 }
2007 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002008 if (Offset != 0 || Size != 4)
2009 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002010 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2011 // TODO:
2012 // Search the external relocation entries of a fully linked image
2013 // (if any) for an entry that matches this segment offset.
2014 // uint64_t seg_offset = (Pc + Offset);
2015 return 0;
2016 }
2017 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2018 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002019 uint64_t sect_addr = info->S.getAddress();
2020 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002021 auto Reloc =
2022 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2023 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002024 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002025 return RelocOffset == sect_offset;
2026 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002027
David Blaikie33dd45d02015-03-23 18:39:02 +00002028 if (Reloc == info->S.relocations().end())
2029 return 0;
2030
2031 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2032 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2033 uint32_t r_type = info->O->getAnyRelocationType(RE);
2034 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2035 DataRefImpl RelNext = Rel;
2036 info->O->moveRelocationNext(RelNext);
2037 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2038 if (value == 0) {
2039 value = info->O->getPlainRelocationSymbolNum(RENext);
2040 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002041 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002042 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002043 // NOTE: Scattered relocations don't exist on arm64.
2044 if (!info->O->getPlainRelocationExternal(RE))
2045 return 0;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002046 ErrorOr<StringRef> SymName = Reloc->getSymbol()->getName();
2047 if (std::error_code EC = SymName.getError())
2048 report_fatal_error(EC.message());
2049 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002050 op_info->AddSymbol.Present = 1;
2051 op_info->AddSymbol.Name = name;
2052
2053 switch (r_type) {
2054 case MachO::ARM64_RELOC_PAGE21:
2055 /* @page */
2056 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2057 break;
2058 case MachO::ARM64_RELOC_PAGEOFF12:
2059 /* @pageoff */
2060 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2061 break;
2062 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2063 /* @gotpage */
2064 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2065 break;
2066 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2067 /* @gotpageoff */
2068 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2069 break;
2070 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2071 /* @tvlppage is not implemented in llvm-mc */
2072 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2073 break;
2074 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2075 /* @tvlppageoff is not implemented in llvm-mc */
2076 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2077 break;
2078 default:
2079 case MachO::ARM64_RELOC_BRANCH26:
2080 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2081 break;
2082 }
2083 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002084 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002085 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002086}
2087
Kevin Enderbybf246f52014-09-24 23:08:22 +00002088// GuessCstringPointer is passed the address of what might be a pointer to a
2089// literal string in a cstring section. If that address is in a cstring section
2090// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002091static const char *GuessCstringPointer(uint64_t ReferenceValue,
2092 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002093 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002094 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2095 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2096 for (unsigned J = 0; J < Seg.nsects; ++J) {
2097 MachO::section_64 Sec = info->O->getSection64(Load, J);
2098 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2099 if (section_type == MachO::S_CSTRING_LITERALS &&
2100 ReferenceValue >= Sec.addr &&
2101 ReferenceValue < Sec.addr + Sec.size) {
2102 uint64_t sect_offset = ReferenceValue - Sec.addr;
2103 uint64_t object_offset = Sec.offset + sect_offset;
2104 StringRef MachOContents = info->O->getData();
2105 uint64_t object_size = MachOContents.size();
2106 const char *object_addr = (const char *)MachOContents.data();
2107 if (object_offset < object_size) {
2108 const char *name = object_addr + object_offset;
2109 return name;
2110 } else {
2111 return nullptr;
2112 }
2113 }
2114 }
2115 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2116 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2117 for (unsigned J = 0; J < Seg.nsects; ++J) {
2118 MachO::section Sec = info->O->getSection(Load, J);
2119 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2120 if (section_type == MachO::S_CSTRING_LITERALS &&
2121 ReferenceValue >= Sec.addr &&
2122 ReferenceValue < Sec.addr + Sec.size) {
2123 uint64_t sect_offset = ReferenceValue - Sec.addr;
2124 uint64_t object_offset = Sec.offset + sect_offset;
2125 StringRef MachOContents = info->O->getData();
2126 uint64_t object_size = MachOContents.size();
2127 const char *object_addr = (const char *)MachOContents.data();
2128 if (object_offset < object_size) {
2129 const char *name = object_addr + object_offset;
2130 return name;
2131 } else {
2132 return nullptr;
2133 }
2134 }
2135 }
2136 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002137 }
2138 return nullptr;
2139}
2140
Kevin Enderby85974882014-09-26 22:20:44 +00002141// GuessIndirectSymbol returns the name of the indirect symbol for the
2142// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2143// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2144// symbol name being referenced by the stub or pointer.
2145static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2146 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002147 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2148 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002149 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002150 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2151 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2152 for (unsigned J = 0; J < Seg.nsects; ++J) {
2153 MachO::section_64 Sec = info->O->getSection64(Load, J);
2154 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2155 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2156 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2157 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2158 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2159 section_type == MachO::S_SYMBOL_STUBS) &&
2160 ReferenceValue >= Sec.addr &&
2161 ReferenceValue < Sec.addr + Sec.size) {
2162 uint32_t stride;
2163 if (section_type == MachO::S_SYMBOL_STUBS)
2164 stride = Sec.reserved2;
2165 else
2166 stride = 8;
2167 if (stride == 0)
2168 return nullptr;
2169 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2170 if (index < Dysymtab.nindirectsyms) {
2171 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002172 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002173 if (indirect_symbol < Symtab.nsyms) {
2174 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2175 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002176 ErrorOr<StringRef> SymName = Symbol.getName();
2177 if (std::error_code EC = SymName.getError())
2178 report_fatal_error(EC.message());
2179 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002180 return name;
2181 }
2182 }
2183 }
2184 }
2185 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2186 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2187 for (unsigned J = 0; J < Seg.nsects; ++J) {
2188 MachO::section Sec = info->O->getSection(Load, J);
2189 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2190 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2191 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2192 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2193 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2194 section_type == MachO::S_SYMBOL_STUBS) &&
2195 ReferenceValue >= Sec.addr &&
2196 ReferenceValue < Sec.addr + Sec.size) {
2197 uint32_t stride;
2198 if (section_type == MachO::S_SYMBOL_STUBS)
2199 stride = Sec.reserved2;
2200 else
2201 stride = 4;
2202 if (stride == 0)
2203 return nullptr;
2204 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2205 if (index < Dysymtab.nindirectsyms) {
2206 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002207 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002208 if (indirect_symbol < Symtab.nsyms) {
2209 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2210 SymbolRef Symbol = *Sym;
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002211 ErrorOr<StringRef> SymName = Symbol.getName();
2212 if (std::error_code EC = SymName.getError())
2213 report_fatal_error(EC.message());
2214 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002215 return name;
2216 }
2217 }
2218 }
2219 }
2220 }
Kevin Enderby85974882014-09-26 22:20:44 +00002221 }
2222 return nullptr;
2223}
2224
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002225// method_reference() is called passing it the ReferenceName that might be
2226// a reference it to an Objective-C method call. If so then it allocates and
2227// assembles a method call string with the values last seen and saved in
2228// the DisassembleInfo's class_name and selector_name fields. This is saved
2229// into the method field of the info and any previous string is free'ed.
2230// Then the class_name field in the info is set to nullptr. The method call
2231// string is set into ReferenceName and ReferenceType is set to
2232// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2233// then both ReferenceType and ReferenceName are left unchanged.
2234static void method_reference(struct DisassembleInfo *info,
2235 uint64_t *ReferenceType,
2236 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002237 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002238 if (*ReferenceName != nullptr) {
2239 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002240 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002241 if (info->method != nullptr)
2242 free(info->method);
2243 if (info->class_name != nullptr) {
2244 info->method = (char *)malloc(5 + strlen(info->class_name) +
2245 strlen(info->selector_name));
2246 if (info->method != nullptr) {
2247 strcpy(info->method, "+[");
2248 strcat(info->method, info->class_name);
2249 strcat(info->method, " ");
2250 strcat(info->method, info->selector_name);
2251 strcat(info->method, "]");
2252 *ReferenceName = info->method;
2253 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2254 }
2255 } else {
2256 info->method = (char *)malloc(9 + strlen(info->selector_name));
2257 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002258 if (Arch == Triple::x86_64)
2259 strcpy(info->method, "-[%rdi ");
2260 else if (Arch == Triple::aarch64)
2261 strcpy(info->method, "-[x0 ");
2262 else
2263 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002264 strcat(info->method, info->selector_name);
2265 strcat(info->method, "]");
2266 *ReferenceName = info->method;
2267 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2268 }
2269 }
2270 info->class_name = nullptr;
2271 }
2272 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002273 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002274 if (info->method != nullptr)
2275 free(info->method);
2276 info->method = (char *)malloc(17 + strlen(info->selector_name));
2277 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002278 if (Arch == Triple::x86_64)
2279 strcpy(info->method, "-[[%rdi super] ");
2280 else if (Arch == Triple::aarch64)
2281 strcpy(info->method, "-[[x0 super] ");
2282 else
2283 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002284 strcat(info->method, info->selector_name);
2285 strcat(info->method, "]");
2286 *ReferenceName = info->method;
2287 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2288 }
2289 info->class_name = nullptr;
2290 }
2291 }
2292 }
2293}
2294
2295// GuessPointerPointer() is passed the address of what might be a pointer to
2296// a reference to an Objective-C class, selector, message ref or cfstring.
2297// If so the value of the pointer is returned and one of the booleans are set
2298// to true. If not zero is returned and all the booleans are set to false.
2299static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2300 struct DisassembleInfo *info,
2301 bool &classref, bool &selref, bool &msgref,
2302 bool &cfstring) {
2303 classref = false;
2304 selref = false;
2305 msgref = false;
2306 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002307 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002308 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2309 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2310 for (unsigned J = 0; J < Seg.nsects; ++J) {
2311 MachO::section_64 Sec = info->O->getSection64(Load, J);
2312 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2313 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2314 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2315 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2316 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2317 ReferenceValue >= Sec.addr &&
2318 ReferenceValue < Sec.addr + Sec.size) {
2319 uint64_t sect_offset = ReferenceValue - Sec.addr;
2320 uint64_t object_offset = Sec.offset + sect_offset;
2321 StringRef MachOContents = info->O->getData();
2322 uint64_t object_size = MachOContents.size();
2323 const char *object_addr = (const char *)MachOContents.data();
2324 if (object_offset < object_size) {
2325 uint64_t pointer_value;
2326 memcpy(&pointer_value, object_addr + object_offset,
2327 sizeof(uint64_t));
2328 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2329 sys::swapByteOrder(pointer_value);
2330 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2331 selref = true;
2332 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2333 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2334 classref = true;
2335 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2336 ReferenceValue + 8 < Sec.addr + Sec.size) {
2337 msgref = true;
2338 memcpy(&pointer_value, object_addr + object_offset + 8,
2339 sizeof(uint64_t));
2340 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2341 sys::swapByteOrder(pointer_value);
2342 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2343 cfstring = true;
2344 return pointer_value;
2345 } else {
2346 return 0;
2347 }
2348 }
2349 }
2350 }
2351 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002352 }
2353 return 0;
2354}
2355
2356// get_pointer_64 returns a pointer to the bytes in the object file at the
2357// Address from a section in the Mach-O file. And indirectly returns the
2358// offset into the section, number of bytes left in the section past the offset
2359// and which section is was being referenced. If the Address is not in a
2360// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002361static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2362 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002363 DisassembleInfo *info,
2364 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002365 offset = 0;
2366 left = 0;
2367 S = SectionRef();
2368 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2369 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2370 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002371 if (SectSize == 0)
2372 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002373 if (objc_only) {
2374 StringRef SectName;
2375 ((*(info->Sections))[SectIdx]).getName(SectName);
2376 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2377 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2378 if (SegName != "__OBJC" && SectName != "__cstring")
2379 continue;
2380 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002381 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2382 S = (*(info->Sections))[SectIdx];
2383 offset = Address - SectAddress;
2384 left = SectSize - offset;
2385 StringRef SectContents;
2386 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2387 return SectContents.data() + offset;
2388 }
2389 }
2390 return nullptr;
2391}
2392
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002393static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2394 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002395 DisassembleInfo *info,
2396 bool objc_only = false) {
2397 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002398}
2399
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002400// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2401// the symbol indirectly through n_value. Based on the relocation information
2402// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002403// If no relocation information is found and a non-zero ReferenceValue for the
2404// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002405static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2406 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002407 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002408 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002409 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002410 return nullptr;
2411
2412 // See if there is an external relocation entry at the sect_offset.
2413 bool reloc_found = false;
2414 DataRefImpl Rel;
2415 MachO::any_relocation_info RE;
2416 bool isExtern = false;
2417 SymbolRef Symbol;
2418 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002419 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002420 if (RelocOffset == sect_offset) {
2421 Rel = Reloc.getRawDataRefImpl();
2422 RE = info->O->getRelocation(Rel);
2423 if (info->O->isRelocationScattered(RE))
2424 continue;
2425 isExtern = info->O->getPlainRelocationExternal(RE);
2426 if (isExtern) {
2427 symbol_iterator RelocSym = Reloc.getSymbol();
2428 Symbol = *RelocSym;
2429 }
2430 reloc_found = true;
2431 break;
2432 }
2433 }
2434 // If there is an external relocation entry for a symbol in this section
2435 // at this section_offset then use that symbol's value for the n_value
2436 // and return its name.
2437 const char *SymbolName = nullptr;
2438 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002439 n_value = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002440 ErrorOr<StringRef> NameOrError = Symbol.getName();
2441 if (std::error_code EC = NameOrError.getError())
2442 report_fatal_error(EC.message());
2443 StringRef Name = *NameOrError;
2444 if (!Name.empty()) {
2445 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002446 return SymbolName;
2447 }
2448 }
2449
2450 // TODO: For fully linked images, look through the external relocation
2451 // entries off the dynamic symtab command. For these the r_offset is from the
2452 // start of the first writeable segment in the Mach-O file. So the offset
2453 // to this section from that segment is passed to this routine by the caller,
2454 // as the database_offset. Which is the difference of the section's starting
2455 // address and the first writable segment.
2456 //
2457 // NOTE: need add passing the database_offset to this routine.
2458
Kevin Enderby0fc11822015-04-01 20:57:01 +00002459 // We did not find an external relocation entry so look up the ReferenceValue
2460 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002461 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002462
2463 return SymbolName;
2464}
2465
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002466static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2467 DisassembleInfo *info,
2468 uint32_t ReferenceValue) {
2469 uint64_t n_value64;
2470 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2471}
2472
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002473// These are structs in the Objective-C meta data and read to produce the
2474// comments for disassembly. While these are part of the ABI they are no
2475// public defintions. So the are here not in include/llvm/Support/MachO.h .
2476
2477// The cfstring object in a 64-bit Mach-O file.
2478struct cfstring64_t {
2479 uint64_t isa; // class64_t * (64-bit pointer)
2480 uint64_t flags; // flag bits
2481 uint64_t characters; // char * (64-bit pointer)
2482 uint64_t length; // number of non-NULL characters in above
2483};
2484
2485// The class object in a 64-bit Mach-O file.
2486struct class64_t {
2487 uint64_t isa; // class64_t * (64-bit pointer)
2488 uint64_t superclass; // class64_t * (64-bit pointer)
2489 uint64_t cache; // Cache (64-bit pointer)
2490 uint64_t vtable; // IMP * (64-bit pointer)
2491 uint64_t data; // class_ro64_t * (64-bit pointer)
2492};
2493
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002494struct class32_t {
2495 uint32_t isa; /* class32_t * (32-bit pointer) */
2496 uint32_t superclass; /* class32_t * (32-bit pointer) */
2497 uint32_t cache; /* Cache (32-bit pointer) */
2498 uint32_t vtable; /* IMP * (32-bit pointer) */
2499 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2500};
2501
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002502struct class_ro64_t {
2503 uint32_t flags;
2504 uint32_t instanceStart;
2505 uint32_t instanceSize;
2506 uint32_t reserved;
2507 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2508 uint64_t name; // const char * (64-bit pointer)
2509 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2510 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2511 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2512 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2513 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2514};
2515
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002516struct class_ro32_t {
2517 uint32_t flags;
2518 uint32_t instanceStart;
2519 uint32_t instanceSize;
2520 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2521 uint32_t name; /* const char * (32-bit pointer) */
2522 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2523 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2524 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2525 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2526 uint32_t baseProperties; /* const struct objc_property_list *
2527 (32-bit pointer) */
2528};
2529
2530/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002531#define RO_META (1 << 0)
2532#define RO_ROOT (1 << 1)
2533#define RO_HAS_CXX_STRUCTORS (1 << 2)
2534
2535struct method_list64_t {
2536 uint32_t entsize;
2537 uint32_t count;
2538 /* struct method64_t first; These structures follow inline */
2539};
2540
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002541struct method_list32_t {
2542 uint32_t entsize;
2543 uint32_t count;
2544 /* struct method32_t first; These structures follow inline */
2545};
2546
Kevin Enderby0fc11822015-04-01 20:57:01 +00002547struct method64_t {
2548 uint64_t name; /* SEL (64-bit pointer) */
2549 uint64_t types; /* const char * (64-bit pointer) */
2550 uint64_t imp; /* IMP (64-bit pointer) */
2551};
2552
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002553struct method32_t {
2554 uint32_t name; /* SEL (32-bit pointer) */
2555 uint32_t types; /* const char * (32-bit pointer) */
2556 uint32_t imp; /* IMP (32-bit pointer) */
2557};
2558
Kevin Enderby0fc11822015-04-01 20:57:01 +00002559struct protocol_list64_t {
2560 uint64_t count; /* uintptr_t (a 64-bit value) */
2561 /* struct protocol64_t * list[0]; These pointers follow inline */
2562};
2563
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002564struct protocol_list32_t {
2565 uint32_t count; /* uintptr_t (a 32-bit value) */
2566 /* struct protocol32_t * list[0]; These pointers follow inline */
2567};
2568
Kevin Enderby0fc11822015-04-01 20:57:01 +00002569struct protocol64_t {
2570 uint64_t isa; /* id * (64-bit pointer) */
2571 uint64_t name; /* const char * (64-bit pointer) */
2572 uint64_t protocols; /* struct protocol_list64_t *
2573 (64-bit pointer) */
2574 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2575 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2576 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2577 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2578 uint64_t instanceProperties; /* struct objc_property_list *
2579 (64-bit pointer) */
2580};
2581
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002582struct protocol32_t {
2583 uint32_t isa; /* id * (32-bit pointer) */
2584 uint32_t name; /* const char * (32-bit pointer) */
2585 uint32_t protocols; /* struct protocol_list_t *
2586 (32-bit pointer) */
2587 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2588 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2589 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2590 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2591 uint32_t instanceProperties; /* struct objc_property_list *
2592 (32-bit pointer) */
2593};
2594
Kevin Enderby0fc11822015-04-01 20:57:01 +00002595struct ivar_list64_t {
2596 uint32_t entsize;
2597 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002598 /* struct ivar64_t first; These structures follow inline */
2599};
2600
2601struct ivar_list32_t {
2602 uint32_t entsize;
2603 uint32_t count;
2604 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002605};
2606
2607struct ivar64_t {
2608 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2609 uint64_t name; /* const char * (64-bit pointer) */
2610 uint64_t type; /* const char * (64-bit pointer) */
2611 uint32_t alignment;
2612 uint32_t size;
2613};
2614
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002615struct ivar32_t {
2616 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2617 uint32_t name; /* const char * (32-bit pointer) */
2618 uint32_t type; /* const char * (32-bit pointer) */
2619 uint32_t alignment;
2620 uint32_t size;
2621};
2622
Kevin Enderby0fc11822015-04-01 20:57:01 +00002623struct objc_property_list64 {
2624 uint32_t entsize;
2625 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002626 /* struct objc_property64 first; These structures follow inline */
2627};
2628
2629struct objc_property_list32 {
2630 uint32_t entsize;
2631 uint32_t count;
2632 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002633};
2634
2635struct objc_property64 {
2636 uint64_t name; /* const char * (64-bit pointer) */
2637 uint64_t attributes; /* const char * (64-bit pointer) */
2638};
2639
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002640struct objc_property32 {
2641 uint32_t name; /* const char * (32-bit pointer) */
2642 uint32_t attributes; /* const char * (32-bit pointer) */
2643};
2644
Kevin Enderby0fc11822015-04-01 20:57:01 +00002645struct category64_t {
2646 uint64_t name; /* const char * (64-bit pointer) */
2647 uint64_t cls; /* struct class_t * (64-bit pointer) */
2648 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2649 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2650 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2651 uint64_t instanceProperties; /* struct objc_property_list *
2652 (64-bit pointer) */
2653};
2654
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002655struct category32_t {
2656 uint32_t name; /* const char * (32-bit pointer) */
2657 uint32_t cls; /* struct class_t * (32-bit pointer) */
2658 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2659 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2660 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2661 uint32_t instanceProperties; /* struct objc_property_list *
2662 (32-bit pointer) */
2663};
2664
Kevin Enderby0fc11822015-04-01 20:57:01 +00002665struct objc_image_info64 {
2666 uint32_t version;
2667 uint32_t flags;
2668};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002669struct objc_image_info32 {
2670 uint32_t version;
2671 uint32_t flags;
2672};
Kevin Enderby846c0002015-04-16 17:19:59 +00002673struct imageInfo_t {
2674 uint32_t version;
2675 uint32_t flags;
2676};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002677/* masks for objc_image_info.flags */
2678#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2679#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2680
2681struct message_ref64 {
2682 uint64_t imp; /* IMP (64-bit pointer) */
2683 uint64_t sel; /* SEL (64-bit pointer) */
2684};
2685
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002686struct message_ref32 {
2687 uint32_t imp; /* IMP (32-bit pointer) */
2688 uint32_t sel; /* SEL (32-bit pointer) */
2689};
2690
Kevin Enderby846c0002015-04-16 17:19:59 +00002691// Objective-C 1 (32-bit only) meta data structs.
2692
2693struct objc_module_t {
2694 uint32_t version;
2695 uint32_t size;
2696 uint32_t name; /* char * (32-bit pointer) */
2697 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2698};
2699
2700struct objc_symtab_t {
2701 uint32_t sel_ref_cnt;
2702 uint32_t refs; /* SEL * (32-bit pointer) */
2703 uint16_t cls_def_cnt;
2704 uint16_t cat_def_cnt;
2705 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2706};
2707
2708struct objc_class_t {
2709 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2710 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2711 uint32_t name; /* const char * (32-bit pointer) */
2712 int32_t version;
2713 int32_t info;
2714 int32_t instance_size;
2715 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2716 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2717 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2718 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2719};
2720
2721#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2722// class is not a metaclass
2723#define CLS_CLASS 0x1
2724// class is a metaclass
2725#define CLS_META 0x2
2726
2727struct objc_category_t {
2728 uint32_t category_name; /* char * (32-bit pointer) */
2729 uint32_t class_name; /* char * (32-bit pointer) */
2730 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2731 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2732 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2733};
2734
2735struct objc_ivar_t {
2736 uint32_t ivar_name; /* char * (32-bit pointer) */
2737 uint32_t ivar_type; /* char * (32-bit pointer) */
2738 int32_t ivar_offset;
2739};
2740
2741struct objc_ivar_list_t {
2742 int32_t ivar_count;
2743 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2744};
2745
2746struct objc_method_list_t {
2747 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2748 int32_t method_count;
2749 // struct objc_method_t method_list[1]; /* variable length structure */
2750};
2751
2752struct objc_method_t {
2753 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2754 uint32_t method_types; /* char * (32-bit pointer) */
2755 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2756 (32-bit pointer) */
2757};
2758
2759struct objc_protocol_list_t {
2760 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2761 int32_t count;
2762 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2763 // (32-bit pointer) */
2764};
2765
2766struct objc_protocol_t {
2767 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2768 uint32_t protocol_name; /* char * (32-bit pointer) */
2769 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2770 uint32_t instance_methods; /* struct objc_method_description_list *
2771 (32-bit pointer) */
2772 uint32_t class_methods; /* struct objc_method_description_list *
2773 (32-bit pointer) */
2774};
2775
2776struct objc_method_description_list_t {
2777 int32_t count;
2778 // struct objc_method_description_t list[1];
2779};
2780
2781struct objc_method_description_t {
2782 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2783 uint32_t types; /* char * (32-bit pointer) */
2784};
2785
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002786inline void swapStruct(struct cfstring64_t &cfs) {
2787 sys::swapByteOrder(cfs.isa);
2788 sys::swapByteOrder(cfs.flags);
2789 sys::swapByteOrder(cfs.characters);
2790 sys::swapByteOrder(cfs.length);
2791}
2792
2793inline void swapStruct(struct class64_t &c) {
2794 sys::swapByteOrder(c.isa);
2795 sys::swapByteOrder(c.superclass);
2796 sys::swapByteOrder(c.cache);
2797 sys::swapByteOrder(c.vtable);
2798 sys::swapByteOrder(c.data);
2799}
2800
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002801inline void swapStruct(struct class32_t &c) {
2802 sys::swapByteOrder(c.isa);
2803 sys::swapByteOrder(c.superclass);
2804 sys::swapByteOrder(c.cache);
2805 sys::swapByteOrder(c.vtable);
2806 sys::swapByteOrder(c.data);
2807}
2808
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002809inline void swapStruct(struct class_ro64_t &cro) {
2810 sys::swapByteOrder(cro.flags);
2811 sys::swapByteOrder(cro.instanceStart);
2812 sys::swapByteOrder(cro.instanceSize);
2813 sys::swapByteOrder(cro.reserved);
2814 sys::swapByteOrder(cro.ivarLayout);
2815 sys::swapByteOrder(cro.name);
2816 sys::swapByteOrder(cro.baseMethods);
2817 sys::swapByteOrder(cro.baseProtocols);
2818 sys::swapByteOrder(cro.ivars);
2819 sys::swapByteOrder(cro.weakIvarLayout);
2820 sys::swapByteOrder(cro.baseProperties);
2821}
2822
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002823inline void swapStruct(struct class_ro32_t &cro) {
2824 sys::swapByteOrder(cro.flags);
2825 sys::swapByteOrder(cro.instanceStart);
2826 sys::swapByteOrder(cro.instanceSize);
2827 sys::swapByteOrder(cro.ivarLayout);
2828 sys::swapByteOrder(cro.name);
2829 sys::swapByteOrder(cro.baseMethods);
2830 sys::swapByteOrder(cro.baseProtocols);
2831 sys::swapByteOrder(cro.ivars);
2832 sys::swapByteOrder(cro.weakIvarLayout);
2833 sys::swapByteOrder(cro.baseProperties);
2834}
2835
Kevin Enderby0fc11822015-04-01 20:57:01 +00002836inline void swapStruct(struct method_list64_t &ml) {
2837 sys::swapByteOrder(ml.entsize);
2838 sys::swapByteOrder(ml.count);
2839}
2840
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002841inline void swapStruct(struct method_list32_t &ml) {
2842 sys::swapByteOrder(ml.entsize);
2843 sys::swapByteOrder(ml.count);
2844}
2845
Kevin Enderby0fc11822015-04-01 20:57:01 +00002846inline void swapStruct(struct method64_t &m) {
2847 sys::swapByteOrder(m.name);
2848 sys::swapByteOrder(m.types);
2849 sys::swapByteOrder(m.imp);
2850}
2851
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002852inline void swapStruct(struct method32_t &m) {
2853 sys::swapByteOrder(m.name);
2854 sys::swapByteOrder(m.types);
2855 sys::swapByteOrder(m.imp);
2856}
2857
Kevin Enderby0fc11822015-04-01 20:57:01 +00002858inline void swapStruct(struct protocol_list64_t &pl) {
2859 sys::swapByteOrder(pl.count);
2860}
2861
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002862inline void swapStruct(struct protocol_list32_t &pl) {
2863 sys::swapByteOrder(pl.count);
2864}
2865
Kevin Enderby0fc11822015-04-01 20:57:01 +00002866inline void swapStruct(struct protocol64_t &p) {
2867 sys::swapByteOrder(p.isa);
2868 sys::swapByteOrder(p.name);
2869 sys::swapByteOrder(p.protocols);
2870 sys::swapByteOrder(p.instanceMethods);
2871 sys::swapByteOrder(p.classMethods);
2872 sys::swapByteOrder(p.optionalInstanceMethods);
2873 sys::swapByteOrder(p.optionalClassMethods);
2874 sys::swapByteOrder(p.instanceProperties);
2875}
2876
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002877inline void swapStruct(struct protocol32_t &p) {
2878 sys::swapByteOrder(p.isa);
2879 sys::swapByteOrder(p.name);
2880 sys::swapByteOrder(p.protocols);
2881 sys::swapByteOrder(p.instanceMethods);
2882 sys::swapByteOrder(p.classMethods);
2883 sys::swapByteOrder(p.optionalInstanceMethods);
2884 sys::swapByteOrder(p.optionalClassMethods);
2885 sys::swapByteOrder(p.instanceProperties);
2886}
2887
Kevin Enderby0fc11822015-04-01 20:57:01 +00002888inline void swapStruct(struct ivar_list64_t &il) {
2889 sys::swapByteOrder(il.entsize);
2890 sys::swapByteOrder(il.count);
2891}
2892
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002893inline void swapStruct(struct ivar_list32_t &il) {
2894 sys::swapByteOrder(il.entsize);
2895 sys::swapByteOrder(il.count);
2896}
2897
Kevin Enderby0fc11822015-04-01 20:57:01 +00002898inline void swapStruct(struct ivar64_t &i) {
2899 sys::swapByteOrder(i.offset);
2900 sys::swapByteOrder(i.name);
2901 sys::swapByteOrder(i.type);
2902 sys::swapByteOrder(i.alignment);
2903 sys::swapByteOrder(i.size);
2904}
2905
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002906inline void swapStruct(struct ivar32_t &i) {
2907 sys::swapByteOrder(i.offset);
2908 sys::swapByteOrder(i.name);
2909 sys::swapByteOrder(i.type);
2910 sys::swapByteOrder(i.alignment);
2911 sys::swapByteOrder(i.size);
2912}
2913
Kevin Enderby0fc11822015-04-01 20:57:01 +00002914inline void swapStruct(struct objc_property_list64 &pl) {
2915 sys::swapByteOrder(pl.entsize);
2916 sys::swapByteOrder(pl.count);
2917}
2918
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002919inline void swapStruct(struct objc_property_list32 &pl) {
2920 sys::swapByteOrder(pl.entsize);
2921 sys::swapByteOrder(pl.count);
2922}
2923
Kevin Enderby0fc11822015-04-01 20:57:01 +00002924inline void swapStruct(struct objc_property64 &op) {
2925 sys::swapByteOrder(op.name);
2926 sys::swapByteOrder(op.attributes);
2927}
2928
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002929inline void swapStruct(struct objc_property32 &op) {
2930 sys::swapByteOrder(op.name);
2931 sys::swapByteOrder(op.attributes);
2932}
2933
Kevin Enderby0fc11822015-04-01 20:57:01 +00002934inline void swapStruct(struct category64_t &c) {
2935 sys::swapByteOrder(c.name);
2936 sys::swapByteOrder(c.cls);
2937 sys::swapByteOrder(c.instanceMethods);
2938 sys::swapByteOrder(c.classMethods);
2939 sys::swapByteOrder(c.protocols);
2940 sys::swapByteOrder(c.instanceProperties);
2941}
2942
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002943inline void swapStruct(struct category32_t &c) {
2944 sys::swapByteOrder(c.name);
2945 sys::swapByteOrder(c.cls);
2946 sys::swapByteOrder(c.instanceMethods);
2947 sys::swapByteOrder(c.classMethods);
2948 sys::swapByteOrder(c.protocols);
2949 sys::swapByteOrder(c.instanceProperties);
2950}
2951
Kevin Enderby0fc11822015-04-01 20:57:01 +00002952inline void swapStruct(struct objc_image_info64 &o) {
2953 sys::swapByteOrder(o.version);
2954 sys::swapByteOrder(o.flags);
2955}
2956
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002957inline void swapStruct(struct objc_image_info32 &o) {
2958 sys::swapByteOrder(o.version);
2959 sys::swapByteOrder(o.flags);
2960}
2961
Kevin Enderby846c0002015-04-16 17:19:59 +00002962inline void swapStruct(struct imageInfo_t &o) {
2963 sys::swapByteOrder(o.version);
2964 sys::swapByteOrder(o.flags);
2965}
2966
Kevin Enderby0fc11822015-04-01 20:57:01 +00002967inline void swapStruct(struct message_ref64 &mr) {
2968 sys::swapByteOrder(mr.imp);
2969 sys::swapByteOrder(mr.sel);
2970}
2971
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002972inline void swapStruct(struct message_ref32 &mr) {
2973 sys::swapByteOrder(mr.imp);
2974 sys::swapByteOrder(mr.sel);
2975}
2976
Kevin Enderby846c0002015-04-16 17:19:59 +00002977inline void swapStruct(struct objc_module_t &module) {
2978 sys::swapByteOrder(module.version);
2979 sys::swapByteOrder(module.size);
2980 sys::swapByteOrder(module.name);
2981 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00002982}
Kevin Enderby846c0002015-04-16 17:19:59 +00002983
2984inline void swapStruct(struct objc_symtab_t &symtab) {
2985 sys::swapByteOrder(symtab.sel_ref_cnt);
2986 sys::swapByteOrder(symtab.refs);
2987 sys::swapByteOrder(symtab.cls_def_cnt);
2988 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00002989}
Kevin Enderby846c0002015-04-16 17:19:59 +00002990
2991inline void swapStruct(struct objc_class_t &objc_class) {
2992 sys::swapByteOrder(objc_class.isa);
2993 sys::swapByteOrder(objc_class.super_class);
2994 sys::swapByteOrder(objc_class.name);
2995 sys::swapByteOrder(objc_class.version);
2996 sys::swapByteOrder(objc_class.info);
2997 sys::swapByteOrder(objc_class.instance_size);
2998 sys::swapByteOrder(objc_class.ivars);
2999 sys::swapByteOrder(objc_class.methodLists);
3000 sys::swapByteOrder(objc_class.cache);
3001 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003002}
Kevin Enderby846c0002015-04-16 17:19:59 +00003003
3004inline void swapStruct(struct objc_category_t &objc_category) {
3005 sys::swapByteOrder(objc_category.category_name);
3006 sys::swapByteOrder(objc_category.class_name);
3007 sys::swapByteOrder(objc_category.instance_methods);
3008 sys::swapByteOrder(objc_category.class_methods);
3009 sys::swapByteOrder(objc_category.protocols);
3010}
3011
3012inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3013 sys::swapByteOrder(objc_ivar_list.ivar_count);
3014}
3015
3016inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3017 sys::swapByteOrder(objc_ivar.ivar_name);
3018 sys::swapByteOrder(objc_ivar.ivar_type);
3019 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003020}
Kevin Enderby846c0002015-04-16 17:19:59 +00003021
3022inline void swapStruct(struct objc_method_list_t &method_list) {
3023 sys::swapByteOrder(method_list.obsolete);
3024 sys::swapByteOrder(method_list.method_count);
3025}
3026
3027inline void swapStruct(struct objc_method_t &method) {
3028 sys::swapByteOrder(method.method_name);
3029 sys::swapByteOrder(method.method_types);
3030 sys::swapByteOrder(method.method_imp);
3031}
3032
3033inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3034 sys::swapByteOrder(protocol_list.next);
3035 sys::swapByteOrder(protocol_list.count);
3036}
3037
3038inline void swapStruct(struct objc_protocol_t &protocol) {
3039 sys::swapByteOrder(protocol.isa);
3040 sys::swapByteOrder(protocol.protocol_name);
3041 sys::swapByteOrder(protocol.protocol_list);
3042 sys::swapByteOrder(protocol.instance_methods);
3043 sys::swapByteOrder(protocol.class_methods);
3044}
3045
3046inline void swapStruct(struct objc_method_description_list_t &mdl) {
3047 sys::swapByteOrder(mdl.count);
3048}
3049
3050inline void swapStruct(struct objc_method_description_t &md) {
3051 sys::swapByteOrder(md.name);
3052 sys::swapByteOrder(md.types);
3053}
3054
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003055static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3056 struct DisassembleInfo *info);
3057
3058// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3059// to an Objective-C class and returns the class name. It is also passed the
3060// address of the pointer, so when the pointer is zero as it can be in an .o
3061// file, that is used to look for an external relocation entry with a symbol
3062// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003063static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3064 uint64_t ReferenceValue,
3065 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003066 const char *r;
3067 uint32_t offset, left;
3068 SectionRef S;
3069
3070 // The pointer_value can be 0 in an object file and have a relocation
3071 // entry for the class symbol at the ReferenceValue (the address of the
3072 // pointer).
3073 if (pointer_value == 0) {
3074 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3075 if (r == nullptr || left < sizeof(uint64_t))
3076 return nullptr;
3077 uint64_t n_value;
3078 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3079 if (symbol_name == nullptr)
3080 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003081 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003082 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3083 return class_name + 2;
3084 else
3085 return nullptr;
3086 }
3087
3088 // The case were the pointer_value is non-zero and points to a class defined
3089 // in this Mach-O file.
3090 r = get_pointer_64(pointer_value, offset, left, S, info);
3091 if (r == nullptr || left < sizeof(struct class64_t))
3092 return nullptr;
3093 struct class64_t c;
3094 memcpy(&c, r, sizeof(struct class64_t));
3095 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3096 swapStruct(c);
3097 if (c.data == 0)
3098 return nullptr;
3099 r = get_pointer_64(c.data, offset, left, S, info);
3100 if (r == nullptr || left < sizeof(struct class_ro64_t))
3101 return nullptr;
3102 struct class_ro64_t cro;
3103 memcpy(&cro, r, sizeof(struct class_ro64_t));
3104 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3105 swapStruct(cro);
3106 if (cro.name == 0)
3107 return nullptr;
3108 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3109 return name;
3110}
3111
3112// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3113// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003114static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3115 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003116 const char *r, *name;
3117 uint32_t offset, left;
3118 SectionRef S;
3119 struct cfstring64_t cfs;
3120 uint64_t cfs_characters;
3121
3122 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3123 if (r == nullptr || left < sizeof(struct cfstring64_t))
3124 return nullptr;
3125 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3126 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3127 swapStruct(cfs);
3128 if (cfs.characters == 0) {
3129 uint64_t n_value;
3130 const char *symbol_name = get_symbol_64(
3131 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3132 if (symbol_name == nullptr)
3133 return nullptr;
3134 cfs_characters = n_value;
3135 } else
3136 cfs_characters = cfs.characters;
3137 name = get_pointer_64(cfs_characters, offset, left, S, info);
3138
3139 return name;
3140}
3141
3142// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3143// of a pointer to an Objective-C selector reference when the pointer value is
3144// zero as in a .o file and is likely to have a external relocation entry with
3145// who's symbol's n_value is the real pointer to the selector name. If that is
3146// the case the real pointer to the selector name is returned else 0 is
3147// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003148static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3149 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003150 uint32_t offset, left;
3151 SectionRef S;
3152
3153 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3154 if (r == nullptr || left < sizeof(uint64_t))
3155 return 0;
3156 uint64_t n_value;
3157 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3158 if (symbol_name == nullptr)
3159 return 0;
3160 return n_value;
3161}
3162
Kevin Enderby0fc11822015-04-01 20:57:01 +00003163static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3164 const char *sectname) {
3165 for (const SectionRef &Section : O->sections()) {
3166 StringRef SectName;
3167 Section.getName(SectName);
3168 DataRefImpl Ref = Section.getRawDataRefImpl();
3169 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3170 if (SegName == segname && SectName == sectname)
3171 return Section;
3172 }
3173 return SectionRef();
3174}
3175
3176static void
3177walk_pointer_list_64(const char *listname, const SectionRef S,
3178 MachOObjectFile *O, struct DisassembleInfo *info,
3179 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3180 if (S == SectionRef())
3181 return;
3182
3183 StringRef SectName;
3184 S.getName(SectName);
3185 DataRefImpl Ref = S.getRawDataRefImpl();
3186 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3187 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3188
3189 StringRef BytesStr;
3190 S.getContents(BytesStr);
3191 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3192
3193 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3194 uint32_t left = S.getSize() - i;
3195 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3196 uint64_t p = 0;
3197 memcpy(&p, Contents + i, size);
3198 if (i + sizeof(uint64_t) > S.getSize())
3199 outs() << listname << " list pointer extends past end of (" << SegName
3200 << "," << SectName << ") section\n";
3201 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3202
3203 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3204 sys::swapByteOrder(p);
3205
3206 uint64_t n_value = 0;
3207 const char *name = get_symbol_64(i, S, info, n_value, p);
3208 if (name == nullptr)
3209 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3210
3211 if (n_value != 0) {
3212 outs() << format("0x%" PRIx64, n_value);
3213 if (p != 0)
3214 outs() << " + " << format("0x%" PRIx64, p);
3215 } else
3216 outs() << format("0x%" PRIx64, p);
3217 if (name != nullptr)
3218 outs() << " " << name;
3219 outs() << "\n";
3220
3221 p += n_value;
3222 if (func)
3223 func(p, info);
3224 }
3225}
3226
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003227static void
3228walk_pointer_list_32(const char *listname, const SectionRef S,
3229 MachOObjectFile *O, struct DisassembleInfo *info,
3230 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3231 if (S == SectionRef())
3232 return;
3233
3234 StringRef SectName;
3235 S.getName(SectName);
3236 DataRefImpl Ref = S.getRawDataRefImpl();
3237 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3238 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3239
3240 StringRef BytesStr;
3241 S.getContents(BytesStr);
3242 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3243
3244 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3245 uint32_t left = S.getSize() - i;
3246 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3247 uint32_t p = 0;
3248 memcpy(&p, Contents + i, size);
3249 if (i + sizeof(uint32_t) > S.getSize())
3250 outs() << listname << " list pointer extends past end of (" << SegName
3251 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003252 uint32_t Address = S.getAddress() + i;
3253 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003254
3255 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3256 sys::swapByteOrder(p);
3257 outs() << format("0x%" PRIx32, p);
3258
3259 const char *name = get_symbol_32(i, S, info, p);
3260 if (name != nullptr)
3261 outs() << " " << name;
3262 outs() << "\n";
3263
3264 if (func)
3265 func(p, info);
3266 }
3267}
3268
3269static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003270 if (layout_map == nullptr)
3271 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003272 outs() << " layout map: ";
3273 do {
3274 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3275 left--;
3276 layout_map++;
3277 } while (*layout_map != '\0' && left != 0);
3278 outs() << "\n";
3279}
3280
Kevin Enderby0fc11822015-04-01 20:57:01 +00003281static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3282 uint32_t offset, left;
3283 SectionRef S;
3284 const char *layout_map;
3285
3286 if (p == 0)
3287 return;
3288 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003289 print_layout_map(layout_map, left);
3290}
3291
3292static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3293 uint32_t offset, left;
3294 SectionRef S;
3295 const char *layout_map;
3296
3297 if (p == 0)
3298 return;
3299 layout_map = get_pointer_32(p, offset, left, S, info);
3300 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003301}
3302
3303static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3304 const char *indent) {
3305 struct method_list64_t ml;
3306 struct method64_t m;
3307 const char *r;
3308 uint32_t offset, xoffset, left, i;
3309 SectionRef S, xS;
3310 const char *name, *sym_name;
3311 uint64_t n_value;
3312
3313 r = get_pointer_64(p, offset, left, S, info);
3314 if (r == nullptr)
3315 return;
3316 memset(&ml, '\0', sizeof(struct method_list64_t));
3317 if (left < sizeof(struct method_list64_t)) {
3318 memcpy(&ml, r, left);
3319 outs() << " (method_list_t entends past the end of the section)\n";
3320 } else
3321 memcpy(&ml, r, sizeof(struct method_list64_t));
3322 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3323 swapStruct(ml);
3324 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3325 outs() << indent << "\t\t count " << ml.count << "\n";
3326
3327 p += sizeof(struct method_list64_t);
3328 offset += sizeof(struct method_list64_t);
3329 for (i = 0; i < ml.count; i++) {
3330 r = get_pointer_64(p, offset, left, S, info);
3331 if (r == nullptr)
3332 return;
3333 memset(&m, '\0', sizeof(struct method64_t));
3334 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003335 memcpy(&m, r, left);
3336 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003337 } else
3338 memcpy(&m, r, sizeof(struct method64_t));
3339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3340 swapStruct(m);
3341
3342 outs() << indent << "\t\t name ";
3343 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3344 info, n_value, m.name);
3345 if (n_value != 0) {
3346 if (info->verbose && sym_name != nullptr)
3347 outs() << sym_name;
3348 else
3349 outs() << format("0x%" PRIx64, n_value);
3350 if (m.name != 0)
3351 outs() << " + " << format("0x%" PRIx64, m.name);
3352 } else
3353 outs() << format("0x%" PRIx64, m.name);
3354 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3355 if (name != nullptr)
3356 outs() << format(" %.*s", left, name);
3357 outs() << "\n";
3358
3359 outs() << indent << "\t\t types ";
3360 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3361 info, n_value, m.types);
3362 if (n_value != 0) {
3363 if (info->verbose && sym_name != nullptr)
3364 outs() << sym_name;
3365 else
3366 outs() << format("0x%" PRIx64, n_value);
3367 if (m.types != 0)
3368 outs() << " + " << format("0x%" PRIx64, m.types);
3369 } else
3370 outs() << format("0x%" PRIx64, m.types);
3371 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3372 if (name != nullptr)
3373 outs() << format(" %.*s", left, name);
3374 outs() << "\n";
3375
3376 outs() << indent << "\t\t imp ";
3377 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3378 n_value, m.imp);
3379 if (info->verbose && name == nullptr) {
3380 if (n_value != 0) {
3381 outs() << format("0x%" PRIx64, n_value) << " ";
3382 if (m.imp != 0)
3383 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3384 } else
3385 outs() << format("0x%" PRIx64, m.imp) << " ";
3386 }
3387 if (name != nullptr)
3388 outs() << name;
3389 outs() << "\n";
3390
3391 p += sizeof(struct method64_t);
3392 offset += sizeof(struct method64_t);
3393 }
3394}
3395
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003396static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3397 const char *indent) {
3398 struct method_list32_t ml;
3399 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003400 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003401 uint32_t offset, xoffset, left, i;
3402 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003403
3404 r = get_pointer_32(p, offset, left, S, info);
3405 if (r == nullptr)
3406 return;
3407 memset(&ml, '\0', sizeof(struct method_list32_t));
3408 if (left < sizeof(struct method_list32_t)) {
3409 memcpy(&ml, r, left);
3410 outs() << " (method_list_t entends past the end of the section)\n";
3411 } else
3412 memcpy(&ml, r, sizeof(struct method_list32_t));
3413 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3414 swapStruct(ml);
3415 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3416 outs() << indent << "\t\t count " << ml.count << "\n";
3417
3418 p += sizeof(struct method_list32_t);
3419 offset += sizeof(struct method_list32_t);
3420 for (i = 0; i < ml.count; i++) {
3421 r = get_pointer_32(p, offset, left, S, info);
3422 if (r == nullptr)
3423 return;
3424 memset(&m, '\0', sizeof(struct method32_t));
3425 if (left < sizeof(struct method32_t)) {
3426 memcpy(&ml, r, left);
3427 outs() << indent << " (method_t entends past the end of the section)\n";
3428 } else
3429 memcpy(&m, r, sizeof(struct method32_t));
3430 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3431 swapStruct(m);
3432
3433 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3434 name = get_pointer_32(m.name, xoffset, left, xS, info);
3435 if (name != nullptr)
3436 outs() << format(" %.*s", left, name);
3437 outs() << "\n";
3438
3439 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3440 name = get_pointer_32(m.types, xoffset, left, xS, info);
3441 if (name != nullptr)
3442 outs() << format(" %.*s", left, name);
3443 outs() << "\n";
3444
3445 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3446 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3447 m.imp);
3448 if (name != nullptr)
3449 outs() << " " << name;
3450 outs() << "\n";
3451
3452 p += sizeof(struct method32_t);
3453 offset += sizeof(struct method32_t);
3454 }
3455}
3456
Kevin Enderby846c0002015-04-16 17:19:59 +00003457static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3458 uint32_t offset, left, xleft;
3459 SectionRef S;
3460 struct objc_method_list_t method_list;
3461 struct objc_method_t method;
3462 const char *r, *methods, *name, *SymbolName;
3463 int32_t i;
3464
3465 r = get_pointer_32(p, offset, left, S, info, true);
3466 if (r == nullptr)
3467 return true;
3468
3469 outs() << "\n";
3470 if (left > sizeof(struct objc_method_list_t)) {
3471 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3472 } else {
3473 outs() << "\t\t objc_method_list extends past end of the section\n";
3474 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3475 memcpy(&method_list, r, left);
3476 }
3477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3478 swapStruct(method_list);
3479
3480 outs() << "\t\t obsolete "
3481 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3482 outs() << "\t\t method_count " << method_list.method_count << "\n";
3483
3484 methods = r + sizeof(struct objc_method_list_t);
3485 for (i = 0; i < method_list.method_count; i++) {
3486 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3487 outs() << "\t\t remaining method's extend past the of the section\n";
3488 break;
3489 }
3490 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3491 sizeof(struct objc_method_t));
3492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3493 swapStruct(method);
3494
3495 outs() << "\t\t method_name "
3496 << format("0x%08" PRIx32, method.method_name);
3497 if (info->verbose) {
3498 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3499 if (name != nullptr)
3500 outs() << format(" %.*s", xleft, name);
3501 else
3502 outs() << " (not in an __OBJC section)";
3503 }
3504 outs() << "\n";
3505
3506 outs() << "\t\t method_types "
3507 << format("0x%08" PRIx32, method.method_types);
3508 if (info->verbose) {
3509 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3510 if (name != nullptr)
3511 outs() << format(" %.*s", xleft, name);
3512 else
3513 outs() << " (not in an __OBJC section)";
3514 }
3515 outs() << "\n";
3516
3517 outs() << "\t\t method_imp "
3518 << format("0x%08" PRIx32, method.method_imp) << " ";
3519 if (info->verbose) {
3520 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3521 if (SymbolName != nullptr)
3522 outs() << SymbolName;
3523 }
3524 outs() << "\n";
3525 }
3526 return false;
3527}
3528
Kevin Enderby0fc11822015-04-01 20:57:01 +00003529static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3530 struct protocol_list64_t pl;
3531 uint64_t q, n_value;
3532 struct protocol64_t pc;
3533 const char *r;
3534 uint32_t offset, xoffset, left, i;
3535 SectionRef S, xS;
3536 const char *name, *sym_name;
3537
3538 r = get_pointer_64(p, offset, left, S, info);
3539 if (r == nullptr)
3540 return;
3541 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3542 if (left < sizeof(struct protocol_list64_t)) {
3543 memcpy(&pl, r, left);
3544 outs() << " (protocol_list_t entends past the end of the section)\n";
3545 } else
3546 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3548 swapStruct(pl);
3549 outs() << " count " << pl.count << "\n";
3550
3551 p += sizeof(struct protocol_list64_t);
3552 offset += sizeof(struct protocol_list64_t);
3553 for (i = 0; i < pl.count; i++) {
3554 r = get_pointer_64(p, offset, left, S, info);
3555 if (r == nullptr)
3556 return;
3557 q = 0;
3558 if (left < sizeof(uint64_t)) {
3559 memcpy(&q, r, left);
3560 outs() << " (protocol_t * entends past the end of the section)\n";
3561 } else
3562 memcpy(&q, r, sizeof(uint64_t));
3563 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3564 sys::swapByteOrder(q);
3565
3566 outs() << "\t\t list[" << i << "] ";
3567 sym_name = get_symbol_64(offset, S, info, n_value, q);
3568 if (n_value != 0) {
3569 if (info->verbose && sym_name != nullptr)
3570 outs() << sym_name;
3571 else
3572 outs() << format("0x%" PRIx64, n_value);
3573 if (q != 0)
3574 outs() << " + " << format("0x%" PRIx64, q);
3575 } else
3576 outs() << format("0x%" PRIx64, q);
3577 outs() << " (struct protocol_t *)\n";
3578
3579 r = get_pointer_64(q + n_value, offset, left, S, info);
3580 if (r == nullptr)
3581 return;
3582 memset(&pc, '\0', sizeof(struct protocol64_t));
3583 if (left < sizeof(struct protocol64_t)) {
3584 memcpy(&pc, r, left);
3585 outs() << " (protocol_t entends past the end of the section)\n";
3586 } else
3587 memcpy(&pc, r, sizeof(struct protocol64_t));
3588 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3589 swapStruct(pc);
3590
3591 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3592
3593 outs() << "\t\t\t name ";
3594 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3595 info, n_value, pc.name);
3596 if (n_value != 0) {
3597 if (info->verbose && sym_name != nullptr)
3598 outs() << sym_name;
3599 else
3600 outs() << format("0x%" PRIx64, n_value);
3601 if (pc.name != 0)
3602 outs() << " + " << format("0x%" PRIx64, pc.name);
3603 } else
3604 outs() << format("0x%" PRIx64, pc.name);
3605 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3606 if (name != nullptr)
3607 outs() << format(" %.*s", left, name);
3608 outs() << "\n";
3609
3610 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3611
3612 outs() << "\t\t instanceMethods ";
3613 sym_name =
3614 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3615 S, info, n_value, pc.instanceMethods);
3616 if (n_value != 0) {
3617 if (info->verbose && sym_name != nullptr)
3618 outs() << sym_name;
3619 else
3620 outs() << format("0x%" PRIx64, n_value);
3621 if (pc.instanceMethods != 0)
3622 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3623 } else
3624 outs() << format("0x%" PRIx64, pc.instanceMethods);
3625 outs() << " (struct method_list_t *)\n";
3626 if (pc.instanceMethods + n_value != 0)
3627 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3628
3629 outs() << "\t\t classMethods ";
3630 sym_name =
3631 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3632 info, n_value, pc.classMethods);
3633 if (n_value != 0) {
3634 if (info->verbose && sym_name != nullptr)
3635 outs() << sym_name;
3636 else
3637 outs() << format("0x%" PRIx64, n_value);
3638 if (pc.classMethods != 0)
3639 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3640 } else
3641 outs() << format("0x%" PRIx64, pc.classMethods);
3642 outs() << " (struct method_list_t *)\n";
3643 if (pc.classMethods + n_value != 0)
3644 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3645
3646 outs() << "\t optionalInstanceMethods "
3647 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3648 outs() << "\t optionalClassMethods "
3649 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3650 outs() << "\t instanceProperties "
3651 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3652
3653 p += sizeof(uint64_t);
3654 offset += sizeof(uint64_t);
3655 }
3656}
3657
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003658static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3659 struct protocol_list32_t pl;
3660 uint32_t q;
3661 struct protocol32_t pc;
3662 const char *r;
3663 uint32_t offset, xoffset, left, i;
3664 SectionRef S, xS;
3665 const char *name;
3666
3667 r = get_pointer_32(p, offset, left, S, info);
3668 if (r == nullptr)
3669 return;
3670 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3671 if (left < sizeof(struct protocol_list32_t)) {
3672 memcpy(&pl, r, left);
3673 outs() << " (protocol_list_t entends past the end of the section)\n";
3674 } else
3675 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3676 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3677 swapStruct(pl);
3678 outs() << " count " << pl.count << "\n";
3679
3680 p += sizeof(struct protocol_list32_t);
3681 offset += sizeof(struct protocol_list32_t);
3682 for (i = 0; i < pl.count; i++) {
3683 r = get_pointer_32(p, offset, left, S, info);
3684 if (r == nullptr)
3685 return;
3686 q = 0;
3687 if (left < sizeof(uint32_t)) {
3688 memcpy(&q, r, left);
3689 outs() << " (protocol_t * entends past the end of the section)\n";
3690 } else
3691 memcpy(&q, r, sizeof(uint32_t));
3692 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3693 sys::swapByteOrder(q);
3694 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3695 << " (struct protocol_t *)\n";
3696 r = get_pointer_32(q, offset, left, S, info);
3697 if (r == nullptr)
3698 return;
3699 memset(&pc, '\0', sizeof(struct protocol32_t));
3700 if (left < sizeof(struct protocol32_t)) {
3701 memcpy(&pc, r, left);
3702 outs() << " (protocol_t entends past the end of the section)\n";
3703 } else
3704 memcpy(&pc, r, sizeof(struct protocol32_t));
3705 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3706 swapStruct(pc);
3707 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3708 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3709 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3710 if (name != nullptr)
3711 outs() << format(" %.*s", left, name);
3712 outs() << "\n";
3713 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3714 outs() << "\t\t instanceMethods "
3715 << format("0x%" PRIx32, pc.instanceMethods)
3716 << " (struct method_list_t *)\n";
3717 if (pc.instanceMethods != 0)
3718 print_method_list32_t(pc.instanceMethods, info, "\t");
3719 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3720 << " (struct method_list_t *)\n";
3721 if (pc.classMethods != 0)
3722 print_method_list32_t(pc.classMethods, info, "\t");
3723 outs() << "\t optionalInstanceMethods "
3724 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3725 outs() << "\t optionalClassMethods "
3726 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3727 outs() << "\t instanceProperties "
3728 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3729 p += sizeof(uint32_t);
3730 offset += sizeof(uint32_t);
3731 }
3732}
3733
Kevin Enderby846c0002015-04-16 17:19:59 +00003734static void print_indent(uint32_t indent) {
3735 for (uint32_t i = 0; i < indent;) {
3736 if (indent - i >= 8) {
3737 outs() << "\t";
3738 i += 8;
3739 } else {
3740 for (uint32_t j = i; j < indent; j++)
3741 outs() << " ";
3742 return;
3743 }
3744 }
3745}
3746
3747static bool print_method_description_list(uint32_t p, uint32_t indent,
3748 struct DisassembleInfo *info) {
3749 uint32_t offset, left, xleft;
3750 SectionRef S;
3751 struct objc_method_description_list_t mdl;
3752 struct objc_method_description_t md;
3753 const char *r, *list, *name;
3754 int32_t i;
3755
3756 r = get_pointer_32(p, offset, left, S, info, true);
3757 if (r == nullptr)
3758 return true;
3759
3760 outs() << "\n";
3761 if (left > sizeof(struct objc_method_description_list_t)) {
3762 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3763 } else {
3764 print_indent(indent);
3765 outs() << " objc_method_description_list extends past end of the section\n";
3766 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3767 memcpy(&mdl, r, left);
3768 }
3769 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3770 swapStruct(mdl);
3771
3772 print_indent(indent);
3773 outs() << " count " << mdl.count << "\n";
3774
3775 list = r + sizeof(struct objc_method_description_list_t);
3776 for (i = 0; i < mdl.count; i++) {
3777 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3778 print_indent(indent);
3779 outs() << " remaining list entries extend past the of the section\n";
3780 break;
3781 }
3782 print_indent(indent);
3783 outs() << " list[" << i << "]\n";
3784 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3785 sizeof(struct objc_method_description_t));
3786 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3787 swapStruct(md);
3788
3789 print_indent(indent);
3790 outs() << " name " << format("0x%08" PRIx32, md.name);
3791 if (info->verbose) {
3792 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3793 if (name != nullptr)
3794 outs() << format(" %.*s", xleft, name);
3795 else
3796 outs() << " (not in an __OBJC section)";
3797 }
3798 outs() << "\n";
3799
3800 print_indent(indent);
3801 outs() << " types " << format("0x%08" PRIx32, md.types);
3802 if (info->verbose) {
3803 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3804 if (name != nullptr)
3805 outs() << format(" %.*s", xleft, name);
3806 else
3807 outs() << " (not in an __OBJC section)";
3808 }
3809 outs() << "\n";
3810 }
3811 return false;
3812}
3813
3814static bool print_protocol_list(uint32_t p, uint32_t indent,
3815 struct DisassembleInfo *info);
3816
3817static bool print_protocol(uint32_t p, uint32_t indent,
3818 struct DisassembleInfo *info) {
3819 uint32_t offset, left;
3820 SectionRef S;
3821 struct objc_protocol_t protocol;
3822 const char *r, *name;
3823
3824 r = get_pointer_32(p, offset, left, S, info, true);
3825 if (r == nullptr)
3826 return true;
3827
3828 outs() << "\n";
3829 if (left >= sizeof(struct objc_protocol_t)) {
3830 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3831 } else {
3832 print_indent(indent);
3833 outs() << " Protocol extends past end of the section\n";
3834 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3835 memcpy(&protocol, r, left);
3836 }
3837 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3838 swapStruct(protocol);
3839
3840 print_indent(indent);
3841 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3842 << "\n";
3843
3844 print_indent(indent);
3845 outs() << " protocol_name "
3846 << format("0x%08" PRIx32, protocol.protocol_name);
3847 if (info->verbose) {
3848 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3849 if (name != nullptr)
3850 outs() << format(" %.*s", left, name);
3851 else
3852 outs() << " (not in an __OBJC section)";
3853 }
3854 outs() << "\n";
3855
3856 print_indent(indent);
3857 outs() << " protocol_list "
3858 << format("0x%08" PRIx32, protocol.protocol_list);
3859 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3860 outs() << " (not in an __OBJC section)\n";
3861
3862 print_indent(indent);
3863 outs() << " instance_methods "
3864 << format("0x%08" PRIx32, protocol.instance_methods);
3865 if (print_method_description_list(protocol.instance_methods, indent, info))
3866 outs() << " (not in an __OBJC section)\n";
3867
3868 print_indent(indent);
3869 outs() << " class_methods "
3870 << format("0x%08" PRIx32, protocol.class_methods);
3871 if (print_method_description_list(protocol.class_methods, indent, info))
3872 outs() << " (not in an __OBJC section)\n";
3873
3874 return false;
3875}
3876
3877static bool print_protocol_list(uint32_t p, uint32_t indent,
3878 struct DisassembleInfo *info) {
3879 uint32_t offset, left, l;
3880 SectionRef S;
3881 struct objc_protocol_list_t protocol_list;
3882 const char *r, *list;
3883 int32_t i;
3884
3885 r = get_pointer_32(p, offset, left, S, info, true);
3886 if (r == nullptr)
3887 return true;
3888
3889 outs() << "\n";
3890 if (left > sizeof(struct objc_protocol_list_t)) {
3891 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3892 } else {
3893 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3894 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3895 memcpy(&protocol_list, r, left);
3896 }
3897 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3898 swapStruct(protocol_list);
3899
3900 print_indent(indent);
3901 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3902 << "\n";
3903 print_indent(indent);
3904 outs() << " count " << protocol_list.count << "\n";
3905
3906 list = r + sizeof(struct objc_protocol_list_t);
3907 for (i = 0; i < protocol_list.count; i++) {
3908 if ((i + 1) * sizeof(uint32_t) > left) {
3909 outs() << "\t\t remaining list entries extend past the of the section\n";
3910 break;
3911 }
3912 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3913 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3914 sys::swapByteOrder(l);
3915
3916 print_indent(indent);
3917 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3918 if (print_protocol(l, indent, info))
3919 outs() << "(not in an __OBJC section)\n";
3920 }
3921 return false;
3922}
3923
Kevin Enderby0fc11822015-04-01 20:57:01 +00003924static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
3925 struct ivar_list64_t il;
3926 struct ivar64_t i;
3927 const char *r;
3928 uint32_t offset, xoffset, left, j;
3929 SectionRef S, xS;
3930 const char *name, *sym_name, *ivar_offset_p;
3931 uint64_t ivar_offset, n_value;
3932
3933 r = get_pointer_64(p, offset, left, S, info);
3934 if (r == nullptr)
3935 return;
3936 memset(&il, '\0', sizeof(struct ivar_list64_t));
3937 if (left < sizeof(struct ivar_list64_t)) {
3938 memcpy(&il, r, left);
3939 outs() << " (ivar_list_t entends past the end of the section)\n";
3940 } else
3941 memcpy(&il, r, sizeof(struct ivar_list64_t));
3942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3943 swapStruct(il);
3944 outs() << " entsize " << il.entsize << "\n";
3945 outs() << " count " << il.count << "\n";
3946
3947 p += sizeof(struct ivar_list64_t);
3948 offset += sizeof(struct ivar_list64_t);
3949 for (j = 0; j < il.count; j++) {
3950 r = get_pointer_64(p, offset, left, S, info);
3951 if (r == nullptr)
3952 return;
3953 memset(&i, '\0', sizeof(struct ivar64_t));
3954 if (left < sizeof(struct ivar64_t)) {
3955 memcpy(&i, r, left);
3956 outs() << " (ivar_t entends past the end of the section)\n";
3957 } else
3958 memcpy(&i, r, sizeof(struct ivar64_t));
3959 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3960 swapStruct(i);
3961
3962 outs() << "\t\t\t offset ";
3963 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
3964 info, n_value, i.offset);
3965 if (n_value != 0) {
3966 if (info->verbose && sym_name != nullptr)
3967 outs() << sym_name;
3968 else
3969 outs() << format("0x%" PRIx64, n_value);
3970 if (i.offset != 0)
3971 outs() << " + " << format("0x%" PRIx64, i.offset);
3972 } else
3973 outs() << format("0x%" PRIx64, i.offset);
3974 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
3975 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
3976 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
3977 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3978 sys::swapByteOrder(ivar_offset);
3979 outs() << " " << ivar_offset << "\n";
3980 } else
3981 outs() << "\n";
3982
3983 outs() << "\t\t\t name ";
3984 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
3985 n_value, i.name);
3986 if (n_value != 0) {
3987 if (info->verbose && sym_name != nullptr)
3988 outs() << sym_name;
3989 else
3990 outs() << format("0x%" PRIx64, n_value);
3991 if (i.name != 0)
3992 outs() << " + " << format("0x%" PRIx64, i.name);
3993 } else
3994 outs() << format("0x%" PRIx64, i.name);
3995 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
3996 if (name != nullptr)
3997 outs() << format(" %.*s", left, name);
3998 outs() << "\n";
3999
4000 outs() << "\t\t\t type ";
4001 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4002 n_value, i.name);
4003 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4004 if (n_value != 0) {
4005 if (info->verbose && sym_name != nullptr)
4006 outs() << sym_name;
4007 else
4008 outs() << format("0x%" PRIx64, n_value);
4009 if (i.type != 0)
4010 outs() << " + " << format("0x%" PRIx64, i.type);
4011 } else
4012 outs() << format("0x%" PRIx64, i.type);
4013 if (name != nullptr)
4014 outs() << format(" %.*s", left, name);
4015 outs() << "\n";
4016
4017 outs() << "\t\t\talignment " << i.alignment << "\n";
4018 outs() << "\t\t\t size " << i.size << "\n";
4019
4020 p += sizeof(struct ivar64_t);
4021 offset += sizeof(struct ivar64_t);
4022 }
4023}
4024
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004025static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4026 struct ivar_list32_t il;
4027 struct ivar32_t i;
4028 const char *r;
4029 uint32_t offset, xoffset, left, j;
4030 SectionRef S, xS;
4031 const char *name, *ivar_offset_p;
4032 uint32_t ivar_offset;
4033
4034 r = get_pointer_32(p, offset, left, S, info);
4035 if (r == nullptr)
4036 return;
4037 memset(&il, '\0', sizeof(struct ivar_list32_t));
4038 if (left < sizeof(struct ivar_list32_t)) {
4039 memcpy(&il, r, left);
4040 outs() << " (ivar_list_t entends past the end of the section)\n";
4041 } else
4042 memcpy(&il, r, sizeof(struct ivar_list32_t));
4043 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4044 swapStruct(il);
4045 outs() << " entsize " << il.entsize << "\n";
4046 outs() << " count " << il.count << "\n";
4047
4048 p += sizeof(struct ivar_list32_t);
4049 offset += sizeof(struct ivar_list32_t);
4050 for (j = 0; j < il.count; j++) {
4051 r = get_pointer_32(p, offset, left, S, info);
4052 if (r == nullptr)
4053 return;
4054 memset(&i, '\0', sizeof(struct ivar32_t));
4055 if (left < sizeof(struct ivar32_t)) {
4056 memcpy(&i, r, left);
4057 outs() << " (ivar_t entends past the end of the section)\n";
4058 } else
4059 memcpy(&i, r, sizeof(struct ivar32_t));
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4061 swapStruct(i);
4062
4063 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4064 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4065 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4066 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4067 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4068 sys::swapByteOrder(ivar_offset);
4069 outs() << " " << ivar_offset << "\n";
4070 } else
4071 outs() << "\n";
4072
4073 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4074 name = get_pointer_32(i.name, xoffset, left, xS, info);
4075 if (name != nullptr)
4076 outs() << format(" %.*s", left, name);
4077 outs() << "\n";
4078
4079 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4080 name = get_pointer_32(i.type, xoffset, left, xS, info);
4081 if (name != nullptr)
4082 outs() << format(" %.*s", left, name);
4083 outs() << "\n";
4084
4085 outs() << "\t\t\talignment " << i.alignment << "\n";
4086 outs() << "\t\t\t size " << i.size << "\n";
4087
4088 p += sizeof(struct ivar32_t);
4089 offset += sizeof(struct ivar32_t);
4090 }
4091}
4092
Kevin Enderby0fc11822015-04-01 20:57:01 +00004093static void print_objc_property_list64(uint64_t p,
4094 struct DisassembleInfo *info) {
4095 struct objc_property_list64 opl;
4096 struct objc_property64 op;
4097 const char *r;
4098 uint32_t offset, xoffset, left, j;
4099 SectionRef S, xS;
4100 const char *name, *sym_name;
4101 uint64_t n_value;
4102
4103 r = get_pointer_64(p, offset, left, S, info);
4104 if (r == nullptr)
4105 return;
4106 memset(&opl, '\0', sizeof(struct objc_property_list64));
4107 if (left < sizeof(struct objc_property_list64)) {
4108 memcpy(&opl, r, left);
4109 outs() << " (objc_property_list entends past the end of the section)\n";
4110 } else
4111 memcpy(&opl, r, sizeof(struct objc_property_list64));
4112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4113 swapStruct(opl);
4114 outs() << " entsize " << opl.entsize << "\n";
4115 outs() << " count " << opl.count << "\n";
4116
4117 p += sizeof(struct objc_property_list64);
4118 offset += sizeof(struct objc_property_list64);
4119 for (j = 0; j < opl.count; j++) {
4120 r = get_pointer_64(p, offset, left, S, info);
4121 if (r == nullptr)
4122 return;
4123 memset(&op, '\0', sizeof(struct objc_property64));
4124 if (left < sizeof(struct objc_property64)) {
4125 memcpy(&op, r, left);
4126 outs() << " (objc_property entends past the end of the section)\n";
4127 } else
4128 memcpy(&op, r, sizeof(struct objc_property64));
4129 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4130 swapStruct(op);
4131
4132 outs() << "\t\t\t name ";
4133 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4134 info, n_value, op.name);
4135 if (n_value != 0) {
4136 if (info->verbose && sym_name != nullptr)
4137 outs() << sym_name;
4138 else
4139 outs() << format("0x%" PRIx64, n_value);
4140 if (op.name != 0)
4141 outs() << " + " << format("0x%" PRIx64, op.name);
4142 } else
4143 outs() << format("0x%" PRIx64, op.name);
4144 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4145 if (name != nullptr)
4146 outs() << format(" %.*s", left, name);
4147 outs() << "\n";
4148
4149 outs() << "\t\t\tattributes ";
4150 sym_name =
4151 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4152 info, n_value, op.attributes);
4153 if (n_value != 0) {
4154 if (info->verbose && sym_name != nullptr)
4155 outs() << sym_name;
4156 else
4157 outs() << format("0x%" PRIx64, n_value);
4158 if (op.attributes != 0)
4159 outs() << " + " << format("0x%" PRIx64, op.attributes);
4160 } else
4161 outs() << format("0x%" PRIx64, op.attributes);
4162 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4163 if (name != nullptr)
4164 outs() << format(" %.*s", left, name);
4165 outs() << "\n";
4166
4167 p += sizeof(struct objc_property64);
4168 offset += sizeof(struct objc_property64);
4169 }
4170}
4171
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004172static void print_objc_property_list32(uint32_t p,
4173 struct DisassembleInfo *info) {
4174 struct objc_property_list32 opl;
4175 struct objc_property32 op;
4176 const char *r;
4177 uint32_t offset, xoffset, left, j;
4178 SectionRef S, xS;
4179 const char *name;
4180
4181 r = get_pointer_32(p, offset, left, S, info);
4182 if (r == nullptr)
4183 return;
4184 memset(&opl, '\0', sizeof(struct objc_property_list32));
4185 if (left < sizeof(struct objc_property_list32)) {
4186 memcpy(&opl, r, left);
4187 outs() << " (objc_property_list entends past the end of the section)\n";
4188 } else
4189 memcpy(&opl, r, sizeof(struct objc_property_list32));
4190 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4191 swapStruct(opl);
4192 outs() << " entsize " << opl.entsize << "\n";
4193 outs() << " count " << opl.count << "\n";
4194
4195 p += sizeof(struct objc_property_list32);
4196 offset += sizeof(struct objc_property_list32);
4197 for (j = 0; j < opl.count; j++) {
4198 r = get_pointer_32(p, offset, left, S, info);
4199 if (r == nullptr)
4200 return;
4201 memset(&op, '\0', sizeof(struct objc_property32));
4202 if (left < sizeof(struct objc_property32)) {
4203 memcpy(&op, r, left);
4204 outs() << " (objc_property entends past the end of the section)\n";
4205 } else
4206 memcpy(&op, r, sizeof(struct objc_property32));
4207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4208 swapStruct(op);
4209
4210 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4211 name = get_pointer_32(op.name, xoffset, left, xS, info);
4212 if (name != nullptr)
4213 outs() << format(" %.*s", left, name);
4214 outs() << "\n";
4215
4216 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4217 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4218 if (name != nullptr)
4219 outs() << format(" %.*s", left, name);
4220 outs() << "\n";
4221
4222 p += sizeof(struct objc_property32);
4223 offset += sizeof(struct objc_property32);
4224 }
4225}
4226
Richard Smith81ff44d2015-10-09 22:09:56 +00004227static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004228 bool &is_meta_class) {
4229 struct class_ro64_t cro;
4230 const char *r;
4231 uint32_t offset, xoffset, left;
4232 SectionRef S, xS;
4233 const char *name, *sym_name;
4234 uint64_t n_value;
4235
4236 r = get_pointer_64(p, offset, left, S, info);
4237 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004238 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004239 memset(&cro, '\0', sizeof(struct class_ro64_t));
4240 if (left < sizeof(struct class_ro64_t)) {
4241 memcpy(&cro, r, left);
4242 outs() << " (class_ro_t entends past the end of the section)\n";
4243 } else
4244 memcpy(&cro, r, sizeof(struct class_ro64_t));
4245 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4246 swapStruct(cro);
4247 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4248 if (cro.flags & RO_META)
4249 outs() << " RO_META";
4250 if (cro.flags & RO_ROOT)
4251 outs() << " RO_ROOT";
4252 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4253 outs() << " RO_HAS_CXX_STRUCTORS";
4254 outs() << "\n";
4255 outs() << " instanceStart " << cro.instanceStart << "\n";
4256 outs() << " instanceSize " << cro.instanceSize << "\n";
4257 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4258 << "\n";
4259 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4260 << "\n";
4261 print_layout_map64(cro.ivarLayout, info);
4262
4263 outs() << " name ";
4264 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4265 info, n_value, cro.name);
4266 if (n_value != 0) {
4267 if (info->verbose && sym_name != nullptr)
4268 outs() << sym_name;
4269 else
4270 outs() << format("0x%" PRIx64, n_value);
4271 if (cro.name != 0)
4272 outs() << " + " << format("0x%" PRIx64, cro.name);
4273 } else
4274 outs() << format("0x%" PRIx64, cro.name);
4275 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4276 if (name != nullptr)
4277 outs() << format(" %.*s", left, name);
4278 outs() << "\n";
4279
4280 outs() << " baseMethods ";
4281 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4282 S, info, n_value, cro.baseMethods);
4283 if (n_value != 0) {
4284 if (info->verbose && sym_name != nullptr)
4285 outs() << sym_name;
4286 else
4287 outs() << format("0x%" PRIx64, n_value);
4288 if (cro.baseMethods != 0)
4289 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4290 } else
4291 outs() << format("0x%" PRIx64, cro.baseMethods);
4292 outs() << " (struct method_list_t *)\n";
4293 if (cro.baseMethods + n_value != 0)
4294 print_method_list64_t(cro.baseMethods + n_value, info, "");
4295
4296 outs() << " baseProtocols ";
4297 sym_name =
4298 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4299 info, n_value, cro.baseProtocols);
4300 if (n_value != 0) {
4301 if (info->verbose && sym_name != nullptr)
4302 outs() << sym_name;
4303 else
4304 outs() << format("0x%" PRIx64, n_value);
4305 if (cro.baseProtocols != 0)
4306 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4307 } else
4308 outs() << format("0x%" PRIx64, cro.baseProtocols);
4309 outs() << "\n";
4310 if (cro.baseProtocols + n_value != 0)
4311 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4312
4313 outs() << " ivars ";
4314 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004315 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004316 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.ivars != 0)
4322 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4323 } else
4324 outs() << format("0x%" PRIx64, cro.ivars);
4325 outs() << "\n";
4326 if (cro.ivars + n_value != 0)
4327 print_ivar_list64_t(cro.ivars + n_value, info);
4328
4329 outs() << " weakIvarLayout ";
4330 sym_name =
4331 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4332 info, n_value, cro.weakIvarLayout);
4333 if (n_value != 0) {
4334 if (info->verbose && sym_name != nullptr)
4335 outs() << sym_name;
4336 else
4337 outs() << format("0x%" PRIx64, n_value);
4338 if (cro.weakIvarLayout != 0)
4339 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4340 } else
4341 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4342 outs() << "\n";
4343 print_layout_map64(cro.weakIvarLayout + n_value, info);
4344
4345 outs() << " baseProperties ";
4346 sym_name =
4347 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4348 info, n_value, cro.baseProperties);
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.baseProperties != 0)
4355 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4356 } else
4357 outs() << format("0x%" PRIx64, cro.baseProperties);
4358 outs() << "\n";
4359 if (cro.baseProperties + n_value != 0)
4360 print_objc_property_list64(cro.baseProperties + n_value, info);
4361
Rafael Espindolab9091322015-10-24 23:19:10 +00004362 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004363 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004364}
4365
Richard Smith81ff44d2015-10-09 22:09:56 +00004366static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004367 bool &is_meta_class) {
4368 struct class_ro32_t cro;
4369 const char *r;
4370 uint32_t offset, xoffset, left;
4371 SectionRef S, xS;
4372 const char *name;
4373
4374 r = get_pointer_32(p, offset, left, S, info);
4375 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004376 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004377 memset(&cro, '\0', sizeof(struct class_ro32_t));
4378 if (left < sizeof(struct class_ro32_t)) {
4379 memcpy(&cro, r, left);
4380 outs() << " (class_ro_t entends past the end of the section)\n";
4381 } else
4382 memcpy(&cro, r, sizeof(struct class_ro32_t));
4383 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4384 swapStruct(cro);
4385 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4386 if (cro.flags & RO_META)
4387 outs() << " RO_META";
4388 if (cro.flags & RO_ROOT)
4389 outs() << " RO_ROOT";
4390 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4391 outs() << " RO_HAS_CXX_STRUCTORS";
4392 outs() << "\n";
4393 outs() << " instanceStart " << cro.instanceStart << "\n";
4394 outs() << " instanceSize " << cro.instanceSize << "\n";
4395 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4396 << "\n";
4397 print_layout_map32(cro.ivarLayout, info);
4398
4399 outs() << " name " << format("0x%" PRIx32, cro.name);
4400 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4401 if (name != nullptr)
4402 outs() << format(" %.*s", left, name);
4403 outs() << "\n";
4404
4405 outs() << " baseMethods "
4406 << format("0x%" PRIx32, cro.baseMethods)
4407 << " (struct method_list_t *)\n";
4408 if (cro.baseMethods != 0)
4409 print_method_list32_t(cro.baseMethods, info, "");
4410
4411 outs() << " baseProtocols "
4412 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4413 if (cro.baseProtocols != 0)
4414 print_protocol_list32_t(cro.baseProtocols, info);
4415 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4416 << "\n";
4417 if (cro.ivars != 0)
4418 print_ivar_list32_t(cro.ivars, info);
4419 outs() << " weakIvarLayout "
4420 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4421 print_layout_map32(cro.weakIvarLayout, info);
4422 outs() << " baseProperties "
4423 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4424 if (cro.baseProperties != 0)
4425 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004426 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004427 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004428}
4429
Kevin Enderby0fc11822015-04-01 20:57:01 +00004430static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4431 struct class64_t c;
4432 const char *r;
4433 uint32_t offset, left;
4434 SectionRef S;
4435 const char *name;
4436 uint64_t isa_n_value, n_value;
4437
4438 r = get_pointer_64(p, offset, left, S, info);
4439 if (r == nullptr || left < sizeof(struct class64_t))
4440 return;
4441 memset(&c, '\0', sizeof(struct class64_t));
4442 if (left < sizeof(struct class64_t)) {
4443 memcpy(&c, r, left);
4444 outs() << " (class_t entends past the end of the section)\n";
4445 } else
4446 memcpy(&c, r, sizeof(struct class64_t));
4447 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4448 swapStruct(c);
4449
4450 outs() << " isa " << format("0x%" PRIx64, c.isa);
4451 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4452 isa_n_value, c.isa);
4453 if (name != nullptr)
4454 outs() << " " << name;
4455 outs() << "\n";
4456
4457 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4458 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4459 n_value, c.superclass);
4460 if (name != nullptr)
4461 outs() << " " << name;
4462 outs() << "\n";
4463
4464 outs() << " cache " << format("0x%" PRIx64, c.cache);
4465 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4466 n_value, c.cache);
4467 if (name != nullptr)
4468 outs() << " " << name;
4469 outs() << "\n";
4470
4471 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4472 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4473 n_value, c.vtable);
4474 if (name != nullptr)
4475 outs() << " " << name;
4476 outs() << "\n";
4477
4478 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4479 n_value, c.data);
4480 outs() << " data ";
4481 if (n_value != 0) {
4482 if (info->verbose && name != nullptr)
4483 outs() << name;
4484 else
4485 outs() << format("0x%" PRIx64, n_value);
4486 if (c.data != 0)
4487 outs() << " + " << format("0x%" PRIx64, c.data);
4488 } else
4489 outs() << format("0x%" PRIx64, c.data);
4490 outs() << " (struct class_ro_t *)";
4491
4492 // This is a Swift class if some of the low bits of the pointer are set.
4493 if ((c.data + n_value) & 0x7)
4494 outs() << " Swift class";
4495 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004496 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004497 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4498 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004499
Kevin Enderbyaac75382015-10-08 16:56:35 +00004500 if (!is_meta_class &&
4501 c.isa + isa_n_value != p &&
4502 c.isa + isa_n_value != 0 &&
4503 info->depth < 100) {
4504 info->depth++;
4505 outs() << "Meta Class\n";
4506 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004507 }
4508}
4509
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004510static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4511 struct class32_t c;
4512 const char *r;
4513 uint32_t offset, left;
4514 SectionRef S;
4515 const char *name;
4516
4517 r = get_pointer_32(p, offset, left, S, info);
4518 if (r == nullptr)
4519 return;
4520 memset(&c, '\0', sizeof(struct class32_t));
4521 if (left < sizeof(struct class32_t)) {
4522 memcpy(&c, r, left);
4523 outs() << " (class_t entends past the end of the section)\n";
4524 } else
4525 memcpy(&c, r, sizeof(struct class32_t));
4526 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4527 swapStruct(c);
4528
4529 outs() << " isa " << format("0x%" PRIx32, c.isa);
4530 name =
4531 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4532 if (name != nullptr)
4533 outs() << " " << name;
4534 outs() << "\n";
4535
4536 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4537 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4538 c.superclass);
4539 if (name != nullptr)
4540 outs() << " " << name;
4541 outs() << "\n";
4542
4543 outs() << " cache " << format("0x%" PRIx32, c.cache);
4544 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4545 c.cache);
4546 if (name != nullptr)
4547 outs() << " " << name;
4548 outs() << "\n";
4549
4550 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4551 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4552 c.vtable);
4553 if (name != nullptr)
4554 outs() << " " << name;
4555 outs() << "\n";
4556
4557 name =
4558 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4559 outs() << " data " << format("0x%" PRIx32, c.data)
4560 << " (struct class_ro_t *)";
4561
4562 // This is a Swift class if some of the low bits of the pointer are set.
4563 if (c.data & 0x3)
4564 outs() << " Swift class";
4565 outs() << "\n";
4566 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004567 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4568 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004569
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004570 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004571 outs() << "Meta Class\n";
4572 print_class32_t(c.isa, info);
4573 }
4574}
4575
Kevin Enderby846c0002015-04-16 17:19:59 +00004576static void print_objc_class_t(struct objc_class_t *objc_class,
4577 struct DisassembleInfo *info) {
4578 uint32_t offset, left, xleft;
4579 const char *name, *p, *ivar_list;
4580 SectionRef S;
4581 int32_t i;
4582 struct objc_ivar_list_t objc_ivar_list;
4583 struct objc_ivar_t ivar;
4584
4585 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4586 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4587 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4588 if (name != nullptr)
4589 outs() << format(" %.*s", left, name);
4590 else
4591 outs() << " (not in an __OBJC section)";
4592 }
4593 outs() << "\n";
4594
4595 outs() << "\t super_class "
4596 << format("0x%08" PRIx32, objc_class->super_class);
4597 if (info->verbose) {
4598 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4599 if (name != nullptr)
4600 outs() << format(" %.*s", left, name);
4601 else
4602 outs() << " (not in an __OBJC section)";
4603 }
4604 outs() << "\n";
4605
4606 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4607 if (info->verbose) {
4608 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4609 if (name != nullptr)
4610 outs() << format(" %.*s", left, name);
4611 else
4612 outs() << " (not in an __OBJC section)";
4613 }
4614 outs() << "\n";
4615
4616 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4617 << "\n";
4618
4619 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4620 if (info->verbose) {
4621 if (CLS_GETINFO(objc_class, CLS_CLASS))
4622 outs() << " CLS_CLASS";
4623 else if (CLS_GETINFO(objc_class, CLS_META))
4624 outs() << " CLS_META";
4625 }
4626 outs() << "\n";
4627
4628 outs() << "\t instance_size "
4629 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4630
4631 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4632 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4633 if (p != nullptr) {
4634 if (left > sizeof(struct objc_ivar_list_t)) {
4635 outs() << "\n";
4636 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4637 } else {
4638 outs() << " (entends past the end of the section)\n";
4639 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4640 memcpy(&objc_ivar_list, p, left);
4641 }
4642 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4643 swapStruct(objc_ivar_list);
4644 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4645 ivar_list = p + sizeof(struct objc_ivar_list_t);
4646 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4647 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4648 outs() << "\t\t remaining ivar's extend past the of the section\n";
4649 break;
4650 }
4651 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4652 sizeof(struct objc_ivar_t));
4653 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4654 swapStruct(ivar);
4655
4656 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4657 if (info->verbose) {
4658 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4659 if (name != nullptr)
4660 outs() << format(" %.*s", xleft, name);
4661 else
4662 outs() << " (not in an __OBJC section)";
4663 }
4664 outs() << "\n";
4665
4666 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4667 if (info->verbose) {
4668 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4669 if (name != nullptr)
4670 outs() << format(" %.*s", xleft, name);
4671 else
4672 outs() << " (not in an __OBJC section)";
4673 }
4674 outs() << "\n";
4675
4676 outs() << "\t\t ivar_offset "
4677 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4678 }
4679 } else {
4680 outs() << " (not in an __OBJC section)\n";
4681 }
4682
4683 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4684 if (print_method_list(objc_class->methodLists, info))
4685 outs() << " (not in an __OBJC section)\n";
4686
4687 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4688 << "\n";
4689
4690 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4691 if (print_protocol_list(objc_class->protocols, 16, info))
4692 outs() << " (not in an __OBJC section)\n";
4693}
4694
4695static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4696 struct DisassembleInfo *info) {
4697 uint32_t offset, left;
4698 const char *name;
4699 SectionRef S;
4700
4701 outs() << "\t category name "
4702 << format("0x%08" PRIx32, objc_category->category_name);
4703 if (info->verbose) {
4704 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4705 true);
4706 if (name != nullptr)
4707 outs() << format(" %.*s", left, name);
4708 else
4709 outs() << " (not in an __OBJC section)";
4710 }
4711 outs() << "\n";
4712
4713 outs() << "\t\t class name "
4714 << format("0x%08" PRIx32, objc_category->class_name);
4715 if (info->verbose) {
4716 name =
4717 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4718 if (name != nullptr)
4719 outs() << format(" %.*s", left, name);
4720 else
4721 outs() << " (not in an __OBJC section)";
4722 }
4723 outs() << "\n";
4724
4725 outs() << "\t instance methods "
4726 << format("0x%08" PRIx32, objc_category->instance_methods);
4727 if (print_method_list(objc_category->instance_methods, info))
4728 outs() << " (not in an __OBJC section)\n";
4729
4730 outs() << "\t class methods "
4731 << format("0x%08" PRIx32, objc_category->class_methods);
4732 if (print_method_list(objc_category->class_methods, info))
4733 outs() << " (not in an __OBJC section)\n";
4734}
4735
Kevin Enderby0fc11822015-04-01 20:57:01 +00004736static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4737 struct category64_t c;
4738 const char *r;
4739 uint32_t offset, xoffset, left;
4740 SectionRef S, xS;
4741 const char *name, *sym_name;
4742 uint64_t n_value;
4743
4744 r = get_pointer_64(p, offset, left, S, info);
4745 if (r == nullptr)
4746 return;
4747 memset(&c, '\0', sizeof(struct category64_t));
4748 if (left < sizeof(struct category64_t)) {
4749 memcpy(&c, r, left);
4750 outs() << " (category_t entends past the end of the section)\n";
4751 } else
4752 memcpy(&c, r, sizeof(struct category64_t));
4753 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4754 swapStruct(c);
4755
4756 outs() << " name ";
4757 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4758 info, n_value, c.name);
4759 if (n_value != 0) {
4760 if (info->verbose && sym_name != nullptr)
4761 outs() << sym_name;
4762 else
4763 outs() << format("0x%" PRIx64, n_value);
4764 if (c.name != 0)
4765 outs() << " + " << format("0x%" PRIx64, c.name);
4766 } else
4767 outs() << format("0x%" PRIx64, c.name);
4768 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4769 if (name != nullptr)
4770 outs() << format(" %.*s", left, name);
4771 outs() << "\n";
4772
4773 outs() << " cls ";
4774 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4775 n_value, c.cls);
4776 if (n_value != 0) {
4777 if (info->verbose && sym_name != nullptr)
4778 outs() << sym_name;
4779 else
4780 outs() << format("0x%" PRIx64, n_value);
4781 if (c.cls != 0)
4782 outs() << " + " << format("0x%" PRIx64, c.cls);
4783 } else
4784 outs() << format("0x%" PRIx64, c.cls);
4785 outs() << "\n";
4786 if (c.cls + n_value != 0)
4787 print_class64_t(c.cls + n_value, info);
4788
4789 outs() << " instanceMethods ";
4790 sym_name =
4791 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4792 info, n_value, c.instanceMethods);
4793 if (n_value != 0) {
4794 if (info->verbose && sym_name != nullptr)
4795 outs() << sym_name;
4796 else
4797 outs() << format("0x%" PRIx64, n_value);
4798 if (c.instanceMethods != 0)
4799 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4800 } else
4801 outs() << format("0x%" PRIx64, c.instanceMethods);
4802 outs() << "\n";
4803 if (c.instanceMethods + n_value != 0)
4804 print_method_list64_t(c.instanceMethods + n_value, info, "");
4805
4806 outs() << " classMethods ";
4807 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4808 S, info, n_value, c.classMethods);
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.classMethods != 0)
4815 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4816 } else
4817 outs() << format("0x%" PRIx64, c.classMethods);
4818 outs() << "\n";
4819 if (c.classMethods + n_value != 0)
4820 print_method_list64_t(c.classMethods + n_value, info, "");
4821
4822 outs() << " protocols ";
4823 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4824 info, n_value, c.protocols);
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.protocols != 0)
4831 outs() << " + " << format("0x%" PRIx64, c.protocols);
4832 } else
4833 outs() << format("0x%" PRIx64, c.protocols);
4834 outs() << "\n";
4835 if (c.protocols + n_value != 0)
4836 print_protocol_list64_t(c.protocols + n_value, info);
4837
4838 outs() << "instanceProperties ";
4839 sym_name =
4840 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4841 S, info, n_value, c.instanceProperties);
4842 if (n_value != 0) {
4843 if (info->verbose && sym_name != nullptr)
4844 outs() << sym_name;
4845 else
4846 outs() << format("0x%" PRIx64, n_value);
4847 if (c.instanceProperties != 0)
4848 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4849 } else
4850 outs() << format("0x%" PRIx64, c.instanceProperties);
4851 outs() << "\n";
4852 if (c.instanceProperties + n_value != 0)
4853 print_objc_property_list64(c.instanceProperties + n_value, info);
4854}
4855
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004856static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4857 struct category32_t c;
4858 const char *r;
4859 uint32_t offset, left;
4860 SectionRef S, xS;
4861 const char *name;
4862
4863 r = get_pointer_32(p, offset, left, S, info);
4864 if (r == nullptr)
4865 return;
4866 memset(&c, '\0', sizeof(struct category32_t));
4867 if (left < sizeof(struct category32_t)) {
4868 memcpy(&c, r, left);
4869 outs() << " (category_t entends past the end of the section)\n";
4870 } else
4871 memcpy(&c, r, sizeof(struct category32_t));
4872 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4873 swapStruct(c);
4874
4875 outs() << " name " << format("0x%" PRIx32, c.name);
4876 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4877 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004878 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004879 outs() << " " << name;
4880 outs() << "\n";
4881
4882 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4883 if (c.cls != 0)
4884 print_class32_t(c.cls, info);
4885 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4886 << "\n";
4887 if (c.instanceMethods != 0)
4888 print_method_list32_t(c.instanceMethods, info, "");
4889 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4890 << "\n";
4891 if (c.classMethods != 0)
4892 print_method_list32_t(c.classMethods, info, "");
4893 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4894 if (c.protocols != 0)
4895 print_protocol_list32_t(c.protocols, info);
4896 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4897 << "\n";
4898 if (c.instanceProperties != 0)
4899 print_objc_property_list32(c.instanceProperties, info);
4900}
4901
Kevin Enderby0fc11822015-04-01 20:57:01 +00004902static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4903 uint32_t i, left, offset, xoffset;
4904 uint64_t p, n_value;
4905 struct message_ref64 mr;
4906 const char *name, *sym_name;
4907 const char *r;
4908 SectionRef xS;
4909
4910 if (S == SectionRef())
4911 return;
4912
4913 StringRef SectName;
4914 S.getName(SectName);
4915 DataRefImpl Ref = S.getRawDataRefImpl();
4916 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4917 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4918 offset = 0;
4919 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4920 p = S.getAddress() + i;
4921 r = get_pointer_64(p, offset, left, S, info);
4922 if (r == nullptr)
4923 return;
4924 memset(&mr, '\0', sizeof(struct message_ref64));
4925 if (left < sizeof(struct message_ref64)) {
4926 memcpy(&mr, r, left);
4927 outs() << " (message_ref entends past the end of the section)\n";
4928 } else
4929 memcpy(&mr, r, sizeof(struct message_ref64));
4930 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4931 swapStruct(mr);
4932
4933 outs() << " imp ";
4934 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
4935 n_value, mr.imp);
4936 if (n_value != 0) {
4937 outs() << format("0x%" PRIx64, n_value) << " ";
4938 if (mr.imp != 0)
4939 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
4940 } else
4941 outs() << format("0x%" PRIx64, mr.imp) << " ";
4942 if (name != nullptr)
4943 outs() << " " << name;
4944 outs() << "\n";
4945
4946 outs() << " sel ";
4947 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
4948 info, n_value, mr.sel);
4949 if (n_value != 0) {
4950 if (info->verbose && sym_name != nullptr)
4951 outs() << sym_name;
4952 else
4953 outs() << format("0x%" PRIx64, n_value);
4954 if (mr.sel != 0)
4955 outs() << " + " << format("0x%" PRIx64, mr.sel);
4956 } else
4957 outs() << format("0x%" PRIx64, mr.sel);
4958 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
4959 if (name != nullptr)
4960 outs() << format(" %.*s", left, name);
4961 outs() << "\n";
4962
4963 offset += sizeof(struct message_ref64);
4964 }
4965}
4966
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004967static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
4968 uint32_t i, left, offset, xoffset, p;
4969 struct message_ref32 mr;
4970 const char *name, *r;
4971 SectionRef xS;
4972
4973 if (S == SectionRef())
4974 return;
4975
4976 StringRef SectName;
4977 S.getName(SectName);
4978 DataRefImpl Ref = S.getRawDataRefImpl();
4979 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4980 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4981 offset = 0;
4982 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4983 p = S.getAddress() + i;
4984 r = get_pointer_32(p, offset, left, S, info);
4985 if (r == nullptr)
4986 return;
4987 memset(&mr, '\0', sizeof(struct message_ref32));
4988 if (left < sizeof(struct message_ref32)) {
4989 memcpy(&mr, r, left);
4990 outs() << " (message_ref entends past the end of the section)\n";
4991 } else
4992 memcpy(&mr, r, sizeof(struct message_ref32));
4993 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4994 swapStruct(mr);
4995
4996 outs() << " imp " << format("0x%" PRIx32, mr.imp);
4997 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
4998 mr.imp);
4999 if (name != nullptr)
5000 outs() << " " << name;
5001 outs() << "\n";
5002
5003 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5004 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5005 if (name != nullptr)
5006 outs() << " " << name;
5007 outs() << "\n";
5008
5009 offset += sizeof(struct message_ref32);
5010 }
5011}
5012
Kevin Enderby0fc11822015-04-01 20:57:01 +00005013static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5014 uint32_t left, offset, swift_version;
5015 uint64_t p;
5016 struct objc_image_info64 o;
5017 const char *r;
5018
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005019 if (S == SectionRef())
5020 return;
5021
Kevin Enderby0fc11822015-04-01 20:57:01 +00005022 StringRef SectName;
5023 S.getName(SectName);
5024 DataRefImpl Ref = S.getRawDataRefImpl();
5025 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5026 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5027 p = S.getAddress();
5028 r = get_pointer_64(p, offset, left, S, info);
5029 if (r == nullptr)
5030 return;
5031 memset(&o, '\0', sizeof(struct objc_image_info64));
5032 if (left < sizeof(struct objc_image_info64)) {
5033 memcpy(&o, r, left);
5034 outs() << " (objc_image_info entends past the end of the section)\n";
5035 } else
5036 memcpy(&o, r, sizeof(struct objc_image_info64));
5037 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5038 swapStruct(o);
5039 outs() << " version " << o.version << "\n";
5040 outs() << " flags " << format("0x%" PRIx32, o.flags);
5041 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5042 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5043 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5044 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5045 swift_version = (o.flags >> 8) & 0xff;
5046 if (swift_version != 0) {
5047 if (swift_version == 1)
5048 outs() << " Swift 1.0";
5049 else if (swift_version == 2)
5050 outs() << " Swift 1.1";
5051 else
5052 outs() << " unknown future Swift version (" << swift_version << ")";
5053 }
5054 outs() << "\n";
5055}
5056
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005057static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5058 uint32_t left, offset, swift_version, p;
5059 struct objc_image_info32 o;
5060 const char *r;
5061
5062 StringRef SectName;
5063 S.getName(SectName);
5064 DataRefImpl Ref = S.getRawDataRefImpl();
5065 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5066 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5067 p = S.getAddress();
5068 r = get_pointer_32(p, offset, left, S, info);
5069 if (r == nullptr)
5070 return;
5071 memset(&o, '\0', sizeof(struct objc_image_info32));
5072 if (left < sizeof(struct objc_image_info32)) {
5073 memcpy(&o, r, left);
5074 outs() << " (objc_image_info entends past the end of the section)\n";
5075 } else
5076 memcpy(&o, r, sizeof(struct objc_image_info32));
5077 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5078 swapStruct(o);
5079 outs() << " version " << o.version << "\n";
5080 outs() << " flags " << format("0x%" PRIx32, o.flags);
5081 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5082 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5083 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5084 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5085 swift_version = (o.flags >> 8) & 0xff;
5086 if (swift_version != 0) {
5087 if (swift_version == 1)
5088 outs() << " Swift 1.0";
5089 else if (swift_version == 2)
5090 outs() << " Swift 1.1";
5091 else
5092 outs() << " unknown future Swift version (" << swift_version << ")";
5093 }
5094 outs() << "\n";
5095}
5096
Kevin Enderby846c0002015-04-16 17:19:59 +00005097static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5098 uint32_t left, offset, p;
5099 struct imageInfo_t o;
5100 const char *r;
5101
5102 StringRef SectName;
5103 S.getName(SectName);
5104 DataRefImpl Ref = S.getRawDataRefImpl();
5105 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5106 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5107 p = S.getAddress();
5108 r = get_pointer_32(p, offset, left, S, info);
5109 if (r == nullptr)
5110 return;
5111 memset(&o, '\0', sizeof(struct imageInfo_t));
5112 if (left < sizeof(struct imageInfo_t)) {
5113 memcpy(&o, r, left);
5114 outs() << " (imageInfo entends past the end of the section)\n";
5115 } else
5116 memcpy(&o, r, sizeof(struct imageInfo_t));
5117 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5118 swapStruct(o);
5119 outs() << " version " << o.version << "\n";
5120 outs() << " flags " << format("0x%" PRIx32, o.flags);
5121 if (o.flags & 0x1)
5122 outs() << " F&C";
5123 if (o.flags & 0x2)
5124 outs() << " GC";
5125 if (o.flags & 0x4)
5126 outs() << " GC-only";
5127 else
5128 outs() << " RR";
5129 outs() << "\n";
5130}
5131
Kevin Enderby0fc11822015-04-01 20:57:01 +00005132static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5133 SymbolAddressMap AddrMap;
5134 if (verbose)
5135 CreateSymbolAddressMap(O, &AddrMap);
5136
5137 std::vector<SectionRef> Sections;
5138 for (const SectionRef &Section : O->sections()) {
5139 StringRef SectName;
5140 Section.getName(SectName);
5141 Sections.push_back(Section);
5142 }
5143
5144 struct DisassembleInfo info;
5145 // Set up the block of info used by the Symbolizer call backs.
5146 info.verbose = verbose;
5147 info.O = O;
5148 info.AddrMap = &AddrMap;
5149 info.Sections = &Sections;
5150 info.class_name = nullptr;
5151 info.selector_name = nullptr;
5152 info.method = nullptr;
5153 info.demangled_name = nullptr;
5154 info.bindtable = nullptr;
5155 info.adrp_addr = 0;
5156 info.adrp_inst = 0;
5157
Kevin Enderbyaac75382015-10-08 16:56:35 +00005158 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005159 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5160 if (CL == SectionRef())
5161 CL = get_section(O, "__DATA", "__objc_classlist");
5162 info.S = CL;
5163 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005164
Davide Italiano62507042015-12-11 22:27:59 +00005165 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5166 if (CR == SectionRef())
5167 CR = get_section(O, "__DATA", "__objc_classrefs");
5168 info.S = CR;
5169 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005170
Davide Italiano62507042015-12-11 22:27:59 +00005171 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5172 if (SR == SectionRef())
5173 SR = get_section(O, "__DATA", "__objc_superrefs");
5174 info.S = SR;
5175 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005176
Davide Italiano62507042015-12-11 22:27:59 +00005177 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5178 if (CA == SectionRef())
5179 CA = get_section(O, "__DATA", "__objc_catlist");
5180 info.S = CA;
5181 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005182
Davide Italiano62507042015-12-11 22:27:59 +00005183 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5184 if (PL == SectionRef())
5185 PL = get_section(O, "__DATA", "__objc_protolist");
5186 info.S = PL;
5187 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005188
Davide Italiano62507042015-12-11 22:27:59 +00005189 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5190 if (MR == SectionRef())
5191 MR = get_section(O, "__DATA", "__objc_msgrefs");
5192 info.S = MR;
5193 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005194
Davide Italiano62507042015-12-11 22:27:59 +00005195 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5196 if (II == SectionRef())
5197 II = get_section(O, "__DATA", "__objc_imageinfo");
5198 info.S = II;
5199 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005200
5201 if (info.bindtable != nullptr)
5202 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005203}
5204
5205static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005206 SymbolAddressMap AddrMap;
5207 if (verbose)
5208 CreateSymbolAddressMap(O, &AddrMap);
5209
5210 std::vector<SectionRef> Sections;
5211 for (const SectionRef &Section : O->sections()) {
5212 StringRef SectName;
5213 Section.getName(SectName);
5214 Sections.push_back(Section);
5215 }
5216
5217 struct DisassembleInfo info;
5218 // Set up the block of info used by the Symbolizer call backs.
5219 info.verbose = verbose;
5220 info.O = O;
5221 info.AddrMap = &AddrMap;
5222 info.Sections = &Sections;
5223 info.class_name = nullptr;
5224 info.selector_name = nullptr;
5225 info.method = nullptr;
5226 info.demangled_name = nullptr;
5227 info.bindtable = nullptr;
5228 info.adrp_addr = 0;
5229 info.adrp_inst = 0;
5230
5231 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5232 if (CL != SectionRef()) {
5233 info.S = CL;
5234 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5235 } else {
5236 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5237 info.S = CL;
5238 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5239 }
5240
5241 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5242 if (CR != SectionRef()) {
5243 info.S = CR;
5244 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5245 } else {
5246 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5247 info.S = CR;
5248 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5249 }
5250
5251 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5252 if (SR != SectionRef()) {
5253 info.S = SR;
5254 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5255 } else {
5256 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5257 info.S = SR;
5258 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5259 }
5260
5261 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5262 if (CA != SectionRef()) {
5263 info.S = CA;
5264 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5265 } else {
5266 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5267 info.S = CA;
5268 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5269 }
5270
5271 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5272 if (PL != SectionRef()) {
5273 info.S = PL;
5274 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5275 } else {
5276 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5277 info.S = PL;
5278 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5279 }
5280
5281 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5282 if (MR != SectionRef()) {
5283 info.S = MR;
5284 print_message_refs32(MR, &info);
5285 } else {
5286 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5287 info.S = MR;
5288 print_message_refs32(MR, &info);
5289 }
5290
5291 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5292 if (II != SectionRef()) {
5293 info.S = II;
5294 print_image_info32(II, &info);
5295 } else {
5296 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5297 info.S = II;
5298 print_image_info32(II, &info);
5299 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005300}
5301
5302static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005303 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5304 const char *r, *name, *defs;
5305 struct objc_module_t module;
5306 SectionRef S, xS;
5307 struct objc_symtab_t symtab;
5308 struct objc_class_t objc_class;
5309 struct objc_category_t objc_category;
5310
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005311 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005312 S = get_section(O, "__OBJC", "__module_info");
5313 if (S == SectionRef())
5314 return false;
5315
5316 SymbolAddressMap AddrMap;
5317 if (verbose)
5318 CreateSymbolAddressMap(O, &AddrMap);
5319
5320 std::vector<SectionRef> Sections;
5321 for (const SectionRef &Section : O->sections()) {
5322 StringRef SectName;
5323 Section.getName(SectName);
5324 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005325 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005326
5327 struct DisassembleInfo info;
5328 // Set up the block of info used by the Symbolizer call backs.
5329 info.verbose = verbose;
5330 info.O = O;
5331 info.AddrMap = &AddrMap;
5332 info.Sections = &Sections;
5333 info.class_name = nullptr;
5334 info.selector_name = nullptr;
5335 info.method = nullptr;
5336 info.demangled_name = nullptr;
5337 info.bindtable = nullptr;
5338 info.adrp_addr = 0;
5339 info.adrp_inst = 0;
5340
5341 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5342 p = S.getAddress() + i;
5343 r = get_pointer_32(p, offset, left, S, &info, true);
5344 if (r == nullptr)
5345 return true;
5346 memset(&module, '\0', sizeof(struct objc_module_t));
5347 if (left < sizeof(struct objc_module_t)) {
5348 memcpy(&module, r, left);
5349 outs() << " (module extends past end of __module_info section)\n";
5350 } else
5351 memcpy(&module, r, sizeof(struct objc_module_t));
5352 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5353 swapStruct(module);
5354
5355 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5356 outs() << " version " << module.version << "\n";
5357 outs() << " size " << module.size << "\n";
5358 outs() << " name ";
5359 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5360 if (name != nullptr)
5361 outs() << format("%.*s", left, name);
5362 else
5363 outs() << format("0x%08" PRIx32, module.name)
5364 << "(not in an __OBJC section)";
5365 outs() << "\n";
5366
5367 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5368 if (module.symtab == 0 || r == nullptr) {
5369 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5370 << " (not in an __OBJC section)\n";
5371 continue;
5372 }
5373 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5374 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5375 defs_left = 0;
5376 defs = nullptr;
5377 if (left < sizeof(struct objc_symtab_t)) {
5378 memcpy(&symtab, r, left);
5379 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5380 } else {
5381 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5382 if (left > sizeof(struct objc_symtab_t)) {
5383 defs_left = left - sizeof(struct objc_symtab_t);
5384 defs = r + sizeof(struct objc_symtab_t);
5385 }
5386 }
5387 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5388 swapStruct(symtab);
5389
5390 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5391 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5392 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5393 if (r == nullptr)
5394 outs() << " (not in an __OBJC section)";
5395 outs() << "\n";
5396 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5397 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5398 if (symtab.cls_def_cnt > 0)
5399 outs() << "\tClass Definitions\n";
5400 for (j = 0; j < symtab.cls_def_cnt; j++) {
5401 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5402 outs() << "\t(remaining class defs entries entends past the end of the "
5403 << "section)\n";
5404 break;
5405 }
5406 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5407 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5408 sys::swapByteOrder(def);
5409
5410 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5411 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5412 if (r != nullptr) {
5413 if (left > sizeof(struct objc_class_t)) {
5414 outs() << "\n";
5415 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5416 } else {
5417 outs() << " (entends past the end of the section)\n";
5418 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5419 memcpy(&objc_class, r, left);
5420 }
5421 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5422 swapStruct(objc_class);
5423 print_objc_class_t(&objc_class, &info);
5424 } else {
5425 outs() << "(not in an __OBJC section)\n";
5426 }
5427
5428 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5429 outs() << "\tMeta Class";
5430 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5431 if (r != nullptr) {
5432 if (left > sizeof(struct objc_class_t)) {
5433 outs() << "\n";
5434 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5435 } else {
5436 outs() << " (entends past the end of the section)\n";
5437 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5438 memcpy(&objc_class, r, left);
5439 }
5440 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5441 swapStruct(objc_class);
5442 print_objc_class_t(&objc_class, &info);
5443 } else {
5444 outs() << "(not in an __OBJC section)\n";
5445 }
5446 }
5447 }
5448 if (symtab.cat_def_cnt > 0)
5449 outs() << "\tCategory Definitions\n";
5450 for (j = 0; j < symtab.cat_def_cnt; j++) {
5451 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5452 outs() << "\t(remaining category defs entries entends past the end of "
5453 << "the section)\n";
5454 break;
5455 }
5456 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5457 sizeof(uint32_t));
5458 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5459 sys::swapByteOrder(def);
5460
5461 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5462 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5463 << format("0x%08" PRIx32, def);
5464 if (r != nullptr) {
5465 if (left > sizeof(struct objc_category_t)) {
5466 outs() << "\n";
5467 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5468 } else {
5469 outs() << " (entends past the end of the section)\n";
5470 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5471 memcpy(&objc_category, r, left);
5472 }
5473 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5474 swapStruct(objc_category);
5475 print_objc_objc_category_t(&objc_category, &info);
5476 } else {
5477 outs() << "(not in an __OBJC section)\n";
5478 }
5479 }
5480 }
5481 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5482 if (II != SectionRef())
5483 print_image_info(II, &info);
5484
5485 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005486}
5487
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005488static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5489 uint32_t size, uint32_t addr) {
5490 SymbolAddressMap AddrMap;
5491 CreateSymbolAddressMap(O, &AddrMap);
5492
5493 std::vector<SectionRef> Sections;
5494 for (const SectionRef &Section : O->sections()) {
5495 StringRef SectName;
5496 Section.getName(SectName);
5497 Sections.push_back(Section);
5498 }
5499
5500 struct DisassembleInfo info;
5501 // Set up the block of info used by the Symbolizer call backs.
5502 info.verbose = true;
5503 info.O = O;
5504 info.AddrMap = &AddrMap;
5505 info.Sections = &Sections;
5506 info.class_name = nullptr;
5507 info.selector_name = nullptr;
5508 info.method = nullptr;
5509 info.demangled_name = nullptr;
5510 info.bindtable = nullptr;
5511 info.adrp_addr = 0;
5512 info.adrp_inst = 0;
5513
5514 const char *p;
5515 struct objc_protocol_t protocol;
5516 uint32_t left, paddr;
5517 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5518 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5519 left = size - (p - sect);
5520 if (left < sizeof(struct objc_protocol_t)) {
5521 outs() << "Protocol extends past end of __protocol section\n";
5522 memcpy(&protocol, p, left);
5523 } else
5524 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5525 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5526 swapStruct(protocol);
5527 paddr = addr + (p - sect);
5528 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5529 if (print_protocol(paddr, 0, &info))
5530 outs() << "(not in an __OBJC section)\n";
5531 }
5532}
5533
Kevin Enderby0fc11822015-04-01 20:57:01 +00005534static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5535 if (O->is64Bit())
5536 printObjc2_64bit_MetaData(O, verbose);
5537 else {
5538 MachO::mach_header H;
5539 H = O->getHeader();
5540 if (H.cputype == MachO::CPU_TYPE_ARM)
5541 printObjc2_32bit_MetaData(O, verbose);
5542 else {
5543 // This is the 32-bit non-arm cputype case. Which is normally
5544 // the first Objective-C ABI. But it may be the case of a
5545 // binary for the iOS simulator which is the second Objective-C
5546 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5547 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005548 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005549 printObjc2_32bit_MetaData(O, verbose);
5550 }
5551 }
5552}
5553
Kevin Enderbybf246f52014-09-24 23:08:22 +00005554// GuessLiteralPointer returns a string which for the item in the Mach-O file
5555// for the address passed in as ReferenceValue for printing as a comment with
5556// the instruction and also returns the corresponding type of that item
5557// indirectly through ReferenceType.
5558//
5559// If ReferenceValue is an address of literal cstring then a pointer to the
5560// cstring is returned and ReferenceType is set to
5561// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5562//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005563// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5564// Class ref that name is returned and the ReferenceType is set accordingly.
5565//
5566// Lastly, literals which are Symbol address in a literal pool are looked for
5567// and if found the symbol name is returned and ReferenceType is set to
5568// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5569//
5570// If there is no item in the Mach-O file for the address passed in as
5571// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005572static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5573 uint64_t ReferencePC,
5574 uint64_t *ReferenceType,
5575 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005576 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005577 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5578 uint64_t sect_addr = info->S.getAddress();
5579 uint64_t sect_offset = ReferencePC - sect_addr;
5580 bool reloc_found = false;
5581 DataRefImpl Rel;
5582 MachO::any_relocation_info RE;
5583 bool isExtern = false;
5584 SymbolRef Symbol;
5585 for (const RelocationRef &Reloc : info->S.relocations()) {
5586 uint64_t RelocOffset = Reloc.getOffset();
5587 if (RelocOffset == sect_offset) {
5588 Rel = Reloc.getRawDataRefImpl();
5589 RE = info->O->getRelocation(Rel);
5590 if (info->O->isRelocationScattered(RE))
5591 continue;
5592 isExtern = info->O->getPlainRelocationExternal(RE);
5593 if (isExtern) {
5594 symbol_iterator RelocSym = Reloc.getSymbol();
5595 Symbol = *RelocSym;
5596 }
5597 reloc_found = true;
5598 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005599 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005600 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005601 // If there is an external relocation entry for a symbol in a section
5602 // then used that symbol's value for the value of the reference.
5603 if (reloc_found && isExtern) {
5604 if (info->O->getAnyRelocationPCRel(RE)) {
5605 unsigned Type = info->O->getAnyRelocationType(RE);
5606 if (Type == MachO::X86_64_RELOC_SIGNED) {
5607 ReferenceValue = Symbol.getValue();
5608 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005609 }
5610 }
5611 }
5612
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005613 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5614 // Message refs and Class refs.
5615 bool classref, selref, msgref, cfstring;
5616 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5617 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005618 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005619 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5620 // And the pointer_value in that section is typically zero as it will be
5621 // set by dyld as part of the "bind information".
5622 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5623 if (name != nullptr) {
5624 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005625 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005626 if (class_name != nullptr && class_name[1] == '_' &&
5627 class_name[2] != '\0') {
5628 info->class_name = class_name + 2;
5629 return name;
5630 }
5631 }
5632 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005633
David Blaikie33dd45d02015-03-23 18:39:02 +00005634 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005635 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5636 const char *name =
5637 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5638 if (name != nullptr)
5639 info->class_name = name;
5640 else
5641 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005642 return name;
5643 }
5644
David Blaikie33dd45d02015-03-23 18:39:02 +00005645 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005646 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5647 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5648 return name;
5649 }
5650
David Blaikie33dd45d02015-03-23 18:39:02 +00005651 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005652 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5653
5654 if (pointer_value != 0)
5655 ReferenceValue = pointer_value;
5656
5657 const char *name = GuessCstringPointer(ReferenceValue, info);
5658 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005659 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005660 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5661 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005662 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005663 info->class_name = nullptr;
5664 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5665 info->selector_name = name;
5666 } else
5667 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5668 return name;
5669 }
5670
5671 // Lastly look for an indirect symbol with this ReferenceValue which is in
5672 // a literal pool. If found return that symbol name.
5673 name = GuessIndirectSymbol(ReferenceValue, info);
5674 if (name) {
5675 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5676 return name;
5677 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005678
5679 return nullptr;
5680}
5681
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005682// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005683// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005684// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5685// is created and returns the symbol name that matches the ReferenceValue or
5686// nullptr if none. The ReferenceType is passed in for the IN type of
5687// reference the instruction is making from the values in defined in the header
5688// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5689// Out type and the ReferenceName will also be set which is added as a comment
5690// to the disassembled instruction.
5691//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005692#if HAVE_CXXABI_H
5693// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005694// returned through ReferenceName and ReferenceType is set to
5695// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005696#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005697//
5698// When this is called to get a symbol name for a branch target then the
5699// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5700// SymbolValue will be looked for in the indirect symbol table to determine if
5701// it is an address for a symbol stub. If so then the symbol name for that
5702// stub is returned indirectly through ReferenceName and then ReferenceType is
5703// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5704//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005705// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005706// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5707// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5708// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005709// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005710static const char *SymbolizerSymbolLookUp(void *DisInfo,
5711 uint64_t ReferenceValue,
5712 uint64_t *ReferenceType,
5713 uint64_t ReferencePC,
5714 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005715 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005716 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005717 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005718 *ReferenceName = nullptr;
5719 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005720 return nullptr;
5721 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005722
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005723 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005724
Kevin Enderby85974882014-09-26 22:20:44 +00005725 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5726 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005727 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005728 method_reference(info, ReferenceType, ReferenceName);
5729 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5730 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5731 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005732#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005733 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005734 if (info->demangled_name != nullptr)
5735 free(info->demangled_name);
5736 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005737 info->demangled_name =
5738 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005739 if (info->demangled_name != nullptr) {
5740 *ReferenceName = info->demangled_name;
5741 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5742 } else
5743 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5744 } else
5745#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005746 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5747 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5748 *ReferenceName =
5749 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005750 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005751 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005752 else
5753 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005754 // If this is arm64 and the reference is an adrp instruction save the
5755 // instruction, passed in ReferenceValue and the address of the instruction
5756 // for use later if we see and add immediate instruction.
5757 } else if (info->O->getArch() == Triple::aarch64 &&
5758 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5759 info->adrp_inst = ReferenceValue;
5760 info->adrp_addr = ReferencePC;
5761 SymbolName = nullptr;
5762 *ReferenceName = nullptr;
5763 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5764 // If this is arm64 and reference is an add immediate instruction and we
5765 // have
5766 // seen an adrp instruction just before it and the adrp's Xd register
5767 // matches
5768 // this add's Xn register reconstruct the value being referenced and look to
5769 // see if it is a literal pointer. Note the add immediate instruction is
5770 // passed in ReferenceValue.
5771 } else if (info->O->getArch() == Triple::aarch64 &&
5772 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5773 ReferencePC - 4 == info->adrp_addr &&
5774 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5775 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5776 uint32_t addxri_inst;
5777 uint64_t adrp_imm, addxri_imm;
5778
5779 adrp_imm =
5780 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5781 if (info->adrp_inst & 0x0200000)
5782 adrp_imm |= 0xfffffffffc000000LL;
5783
5784 addxri_inst = ReferenceValue;
5785 addxri_imm = (addxri_inst >> 10) & 0xfff;
5786 if (((addxri_inst >> 22) & 0x3) == 1)
5787 addxri_imm <<= 12;
5788
5789 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5790 (adrp_imm << 12) + addxri_imm;
5791
5792 *ReferenceName =
5793 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5794 if (*ReferenceName == nullptr)
5795 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5796 // If this is arm64 and the reference is a load register instruction and we
5797 // have seen an adrp instruction just before it and the adrp's Xd register
5798 // matches this add's Xn register reconstruct the value being referenced and
5799 // look to see if it is a literal pointer. Note the load register
5800 // instruction is passed in ReferenceValue.
5801 } else if (info->O->getArch() == Triple::aarch64 &&
5802 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5803 ReferencePC - 4 == info->adrp_addr &&
5804 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5805 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5806 uint32_t ldrxui_inst;
5807 uint64_t adrp_imm, ldrxui_imm;
5808
5809 adrp_imm =
5810 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5811 if (info->adrp_inst & 0x0200000)
5812 adrp_imm |= 0xfffffffffc000000LL;
5813
5814 ldrxui_inst = ReferenceValue;
5815 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5816
5817 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5818 (adrp_imm << 12) + (ldrxui_imm << 3);
5819
5820 *ReferenceName =
5821 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5822 if (*ReferenceName == nullptr)
5823 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5824 }
5825 // If this arm64 and is an load register (PC-relative) instruction the
5826 // ReferenceValue is the PC plus the immediate value.
5827 else if (info->O->getArch() == Triple::aarch64 &&
5828 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5829 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5830 *ReferenceName =
5831 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5832 if (*ReferenceName == nullptr)
5833 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005834 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005835#if HAVE_CXXABI_H
5836 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5837 if (info->demangled_name != nullptr)
5838 free(info->demangled_name);
5839 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005840 info->demangled_name =
5841 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005842 if (info->demangled_name != nullptr) {
5843 *ReferenceName = info->demangled_name;
5844 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5845 }
5846 }
5847#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005848 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005849 *ReferenceName = nullptr;
5850 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5851 }
5852
5853 return SymbolName;
5854}
5855
Kevin Enderbybf246f52014-09-24 23:08:22 +00005856/// \brief Emits the comments that are stored in the CommentStream.
5857/// Each comment in the CommentStream must end with a newline.
5858static void emitComments(raw_svector_ostream &CommentStream,
5859 SmallString<128> &CommentsToEmit,
5860 formatted_raw_ostream &FormattedOS,
5861 const MCAsmInfo &MAI) {
5862 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005863 StringRef Comments = CommentsToEmit.str();
5864 // Get the default information for printing a comment.
5865 const char *CommentBegin = MAI.getCommentString();
5866 unsigned CommentColumn = MAI.getCommentColumn();
5867 bool IsFirst = true;
5868 while (!Comments.empty()) {
5869 if (!IsFirst)
5870 FormattedOS << '\n';
5871 // Emit a line of comments.
5872 FormattedOS.PadToColumn(CommentColumn);
5873 size_t Position = Comments.find('\n');
5874 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5875 // Move after the newline character.
5876 Comments = Comments.substr(Position + 1);
5877 IsFirst = false;
5878 }
5879 FormattedOS.flush();
5880
5881 // Tell the comment stream that the vector changed underneath it.
5882 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005883}
5884
Kevin Enderby95df54c2015-02-04 01:01:38 +00005885static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5886 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005887 const char *McpuDefault = nullptr;
5888 const Target *ThumbTarget = nullptr;
5889 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005890 if (!TheTarget) {
5891 // GetTarget prints out stuff.
5892 return;
5893 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005894 if (MCPU.empty() && McpuDefault)
5895 MCPU = McpuDefault;
5896
Ahmed Charles56440fd2014-03-06 05:51:42 +00005897 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005898 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005899 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005900 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005901
Kevin Enderbyc9595622014-08-06 23:24:41 +00005902 // Package up features to be passed to target/subtarget
5903 std::string FeaturesStr;
5904 if (MAttrs.size()) {
5905 SubtargetFeatures Features;
5906 for (unsigned i = 0; i != MAttrs.size(); ++i)
5907 Features.AddFeature(MAttrs[i]);
5908 FeaturesStr = Features.getString();
5909 }
5910
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005911 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005912 std::unique_ptr<const MCRegisterInfo> MRI(
5913 TheTarget->createMCRegInfo(TripleName));
5914 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005915 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005916 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005917 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005918 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005919 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005920 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005921 std::unique_ptr<MCSymbolizer> Symbolizer;
5922 struct DisassembleInfo SymbolizerInfo;
5923 std::unique_ptr<MCRelocationInfo> RelInfo(
5924 TheTarget->createMCRelocationInfo(TripleName, Ctx));
5925 if (RelInfo) {
5926 Symbolizer.reset(TheTarget->createMCSymbolizer(
5927 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005928 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005929 DisAsm->setSymbolizer(std::move(Symbolizer));
5930 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005931 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00005932 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005933 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005934 // Set the display preference for hex vs. decimal immediates.
5935 IP->setPrintImmHex(PrintImmHex);
5936 // Comment stream and backing vector.
5937 SmallString<128> CommentsToEmit;
5938 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00005939 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
5940 // if it is done then arm64 comments for string literals don't get printed
5941 // and some constant get printed instead and not setting it causes intel
5942 // (32-bit and 64-bit) comments printed with different spacing before the
5943 // comment causing different diffs with the 'C' disassembler library API.
5944 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005945
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005946 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00005947 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00005948 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005949 return;
5950 }
5951
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005952 // Set up thumb disassembler.
5953 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
5954 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
5955 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005956 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005957 std::unique_ptr<MCInstPrinter> ThumbIP;
5958 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00005959 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
5960 struct DisassembleInfo ThumbSymbolizerInfo;
5961 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005962 if (ThumbTarget) {
5963 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
5964 ThumbAsmInfo.reset(
5965 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
5966 ThumbSTI.reset(
5967 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
5968 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
5969 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005970 MCContext *PtrThumbCtx = ThumbCtx.get();
5971 ThumbRelInfo.reset(
5972 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
5973 if (ThumbRelInfo) {
5974 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
5975 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00005976 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00005977 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
5978 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005979 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
5980 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00005981 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
5982 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00005983 // Set the display preference for hex vs. decimal immediates.
5984 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005985 }
5986
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005987 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005988 errs() << "error: couldn't initialize disassembler for target "
5989 << ThumbTripleName << '\n';
5990 return;
5991 }
5992
Charles Davis8bdfafd2013-09-01 04:28:48 +00005993 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005994
Ahmed Bougachaaa790682013-05-24 01:07:04 +00005995 // FIXME: Using the -cfg command line option, this code used to be able to
5996 // annotate relocations with the referenced symbol's name, and if this was
5997 // inside a __[cf]string section, the data it points to. This is now replaced
5998 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00005999 std::vector<SectionRef> Sections;
6000 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006001 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006002 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006003
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006004 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006005 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006006
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006007 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006008 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006009
Kevin Enderby273ae012013-06-06 17:20:50 +00006010 // Build a data in code table that is sorted on by the address of each entry.
6011 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006012 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006013 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006014 else
6015 BaseAddress = BaseSegmentAddress;
6016 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006017 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006018 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006019 uint32_t Offset;
6020 DI->getOffset(Offset);
6021 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6022 }
6023 array_pod_sort(Dices.begin(), Dices.end());
6024
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006025#ifndef NDEBUG
6026 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6027#else
6028 raw_ostream &DebugOut = nulls();
6029#endif
6030
Ahmed Charles56440fd2014-03-06 05:51:42 +00006031 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006032 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006033 // Try to find debug info and set up the DIContext for it.
6034 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006035 // A separate DSym file path was specified, parse it as a macho file,
6036 // get the sections and supply it to the section name parsing machinery.
6037 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006038 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006039 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006040 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006041 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006042 return;
6043 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006044 DbgObj =
6045 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6046 .get()
6047 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006048 }
6049
Eric Christopher7370b552012-11-12 21:40:38 +00006050 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006051 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006052 }
6053
Colin LeMahieufcc32762015-07-29 19:08:10 +00006054 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006055 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006056
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006057 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006058 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006059 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6060 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006061
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006062 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006063
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006064 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006065 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006066 continue;
6067
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006068 StringRef BytesStr;
6069 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006070 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6071 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006072 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006073
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006074 bool symbolTableWorked = false;
6075
Kevin Enderbybf246f52014-09-24 23:08:22 +00006076 // Create a map of symbol addresses to symbol names for use by
6077 // the SymbolizerSymbolLookUp() routine.
6078 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006079 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006080 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006081 SymbolRef::Type ST = Symbol.getType();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006082 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6083 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006084 uint64_t Address = Symbol.getValue();
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006085 ErrorOr<StringRef> SymNameOrErr = Symbol.getName();
6086 if (std::error_code EC = SymNameOrErr.getError())
6087 report_fatal_error(EC.message());
6088 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006089 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006090 if (!DisSymName.empty() && DisSymName == SymName)
6091 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006092 }
6093 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006094 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006095 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6096 return;
6097 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006098 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006099 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006100 SymbolizerInfo.O = MachOOF;
6101 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006102 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006103 SymbolizerInfo.Sections = &Sections;
6104 SymbolizerInfo.class_name = nullptr;
6105 SymbolizerInfo.selector_name = nullptr;
6106 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006107 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006108 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006109 SymbolizerInfo.adrp_addr = 0;
6110 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006111 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006112 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006113 ThumbSymbolizerInfo.O = MachOOF;
6114 ThumbSymbolizerInfo.S = Sections[SectIdx];
6115 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6116 ThumbSymbolizerInfo.Sections = &Sections;
6117 ThumbSymbolizerInfo.class_name = nullptr;
6118 ThumbSymbolizerInfo.selector_name = nullptr;
6119 ThumbSymbolizerInfo.method = nullptr;
6120 ThumbSymbolizerInfo.demangled_name = nullptr;
6121 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006122 ThumbSymbolizerInfo.adrp_addr = 0;
6123 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006124
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006125 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006126 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006127 ErrorOr<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6128 if (std::error_code EC = SymNameOrErr.getError())
6129 report_fatal_error(EC.message());
6130 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006131
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006132 SymbolRef::Type ST = Symbols[SymIdx].getType();
Kuba Breckade833222015-11-12 09:40:29 +00006133 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006134 continue;
6135
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006136 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006137 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006138 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006139 continue;
6140
Kevin Enderby6a221752015-03-17 17:10:57 +00006141 // If we are only disassembling one symbol see if this is that symbol.
6142 if (!DisSymName.empty() && DisSymName != SymName)
6143 continue;
6144
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006145 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006146 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006147 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006148 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006149
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006150 // Stop disassembling either at the beginning of the next symbol or at
6151 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006152 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006153 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006154 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006155 while (Symbols.size() > NextSymIdx) {
Rafael Espindola2fa80cc2015-06-26 12:18:49 +00006156 SymbolRef::Type NextSymType = Symbols[NextSymIdx].getType();
Owen Andersond9243c42011-10-17 21:37:35 +00006157 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006158 containsNextSym =
6159 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006160 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006161 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006162 break;
6163 }
6164 ++NextSymIdx;
6165 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006166
Rafael Espindola80291272014-10-08 15:28:58 +00006167 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006168 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006169 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006170
6171 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006172
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006173 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6174 bool isThumb =
6175 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6176
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006177 outs() << SymName << ":\n";
6178 DILineInfo lastLine;
6179 for (uint64_t Index = Start; Index < End; Index += Size) {
6180 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006181
Kevin Enderbybf246f52014-09-24 23:08:22 +00006182 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006183 if (!NoLeadingAddr) {
6184 if (FullLeadingAddr) {
6185 if (MachOOF->is64Bit())
6186 outs() << format("%016" PRIx64, PC);
6187 else
6188 outs() << format("%08" PRIx64, PC);
6189 } else {
6190 outs() << format("%8" PRIx64 ":", PC);
6191 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006192 }
6193 if (!NoShowRawInsn)
6194 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006195
6196 // Check the data in code table here to see if this is data not an
6197 // instruction to be disassembled.
6198 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006199 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006200 dice_table_iterator DTI =
6201 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6202 compareDiceTableEntries);
6203 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006204 uint16_t Length;
6205 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006206 uint16_t Kind;
6207 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006208 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006209 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6210 (PC == (DTI->first + Length - 1)) && (Length & 1))
6211 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006212 continue;
6213 }
6214
Kevin Enderbybf246f52014-09-24 23:08:22 +00006215 SmallVector<char, 64> AnnotationsBytes;
6216 raw_svector_ostream Annotations(AnnotationsBytes);
6217
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006218 bool gotInst;
6219 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006220 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006221 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006222 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006223 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006224 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006225 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006226 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006227 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006228 }
6229 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006230 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006231 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006232 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006233 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006234 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006235 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006236
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006237 // Print debug info.
6238 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006239 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006240 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006241 if (dli != lastLine && dli.Line != 0)
6242 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6243 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006244 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006245 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006246 outs() << "\n";
6247 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006248 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006249 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006250 outs() << format("\t.byte 0x%02x #bad opcode\n",
6251 *(Bytes.data() + Index) & 0xff);
6252 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006253 } else if (Arch == Triple::aarch64) {
6254 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6255 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6256 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6257 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6258 outs() << format("\t.long\t0x%08x\n", opcode);
6259 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006260 } else {
6261 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6262 if (Size == 0)
6263 Size = 1; // skip illegible bytes
6264 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006265 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006266 }
6267 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006268 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006269 // Reading the symbol table didn't work, disassemble the whole section.
6270 uint64_t SectAddress = Sections[SectIdx].getAddress();
6271 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006272 uint64_t InstSize;
6273 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006274 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006275
Kevin Enderbybf246f52014-09-24 23:08:22 +00006276 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006277 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6278 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006279 if (!NoLeadingAddr) {
6280 if (FullLeadingAddr) {
6281 if (MachOOF->is64Bit())
6282 outs() << format("%016" PRIx64, PC);
6283 else
6284 outs() << format("%08" PRIx64, PC);
6285 } else {
6286 outs() << format("%8" PRIx64 ":", PC);
6287 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006288 }
6289 if (!NoShowRawInsn) {
6290 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006291 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006292 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006293 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006294 outs() << "\n";
6295 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006296 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006297 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006298 outs() << format("\t.byte 0x%02x #bad opcode\n",
6299 *(Bytes.data() + Index) & 0xff);
6300 InstSize = 1; // skip exactly one illegible byte and move on.
6301 } else {
6302 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6303 if (InstSize == 0)
6304 InstSize = 1; // skip illegible bytes
6305 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006306 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006307 }
6308 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006309 // The TripleName's need to be reset if we are called again for a different
6310 // archtecture.
6311 TripleName = "";
6312 ThumbTripleName = "";
6313
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006314 if (SymbolizerInfo.method != nullptr)
6315 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006316 if (SymbolizerInfo.demangled_name != nullptr)
6317 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006318 if (SymbolizerInfo.bindtable != nullptr)
6319 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006320 if (ThumbSymbolizerInfo.method != nullptr)
6321 free(ThumbSymbolizerInfo.method);
6322 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6323 free(ThumbSymbolizerInfo.demangled_name);
6324 if (ThumbSymbolizerInfo.bindtable != nullptr)
6325 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006326 }
6327}
Tim Northover4bd286a2014-08-01 13:07:19 +00006328
Tim Northover39c70bb2014-08-12 11:52:59 +00006329//===----------------------------------------------------------------------===//
6330// __compact_unwind section dumping
6331//===----------------------------------------------------------------------===//
6332
Tim Northover4bd286a2014-08-01 13:07:19 +00006333namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006334
6335template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006336 using llvm::support::little;
6337 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006338
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006339 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6340 Buf += sizeof(T);
6341 return Val;
6342}
Tim Northover39c70bb2014-08-12 11:52:59 +00006343
Tim Northover4bd286a2014-08-01 13:07:19 +00006344struct CompactUnwindEntry {
6345 uint32_t OffsetInSection;
6346
6347 uint64_t FunctionAddr;
6348 uint32_t Length;
6349 uint32_t CompactEncoding;
6350 uint64_t PersonalityAddr;
6351 uint64_t LSDAAddr;
6352
6353 RelocationRef FunctionReloc;
6354 RelocationRef PersonalityReloc;
6355 RelocationRef LSDAReloc;
6356
6357 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006358 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006359 if (Is64)
6360 read<uint64_t>(Contents.data() + Offset);
6361 else
6362 read<uint32_t>(Contents.data() + Offset);
6363 }
6364
6365private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006366 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006367 FunctionAddr = readNext<UIntPtr>(Buf);
6368 Length = readNext<uint32_t>(Buf);
6369 CompactEncoding = readNext<uint32_t>(Buf);
6370 PersonalityAddr = readNext<UIntPtr>(Buf);
6371 LSDAAddr = readNext<UIntPtr>(Buf);
6372 }
6373};
6374}
6375
6376/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6377/// and data being relocated, determine the best base Name and Addend to use for
6378/// display purposes.
6379///
6380/// 1. An Extern relocation will directly reference a symbol (and the data is
6381/// then already an addend), so use that.
6382/// 2. Otherwise the data is an offset in the object file's layout; try to find
6383// a symbol before it in the same section, and use the offset from there.
6384/// 3. Finally, if all that fails, fall back to an offset from the start of the
6385/// referenced section.
6386static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6387 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006388 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006389 StringRef &Name, uint64_t &Addend) {
6390 if (Reloc.getSymbol() != Obj->symbol_end()) {
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006391 ErrorOr<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6392 if (std::error_code EC = NameOrErr.getError())
6393 report_fatal_error(EC.message());
6394 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006395 Addend = Addr;
6396 return;
6397 }
6398
6399 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006400 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006401
Rafael Espindola80291272014-10-08 15:28:58 +00006402 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006403
6404 auto Sym = Symbols.upper_bound(Addr);
6405 if (Sym == Symbols.begin()) {
6406 // The first symbol in the object is after this reference, the best we can
6407 // do is section-relative notation.
6408 RelocSection.getName(Name);
6409 Addend = Addr - SectionAddr;
6410 return;
6411 }
6412
6413 // Go back one so that SymbolAddress <= Addr.
6414 --Sym;
6415
Rafael Espindola8bab8892015-08-07 23:27:14 +00006416 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006417 if (RelocSection == *SymSection) {
6418 // There's a valid symbol in the same section before this reference.
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006419 ErrorOr<StringRef> NameOrErr = Sym->second.getName();
6420 if (std::error_code EC = NameOrErr.getError())
6421 report_fatal_error(EC.message());
6422 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006423 Addend = Addr - Sym->first;
6424 return;
6425 }
6426
6427 // There is a symbol before this reference, but it's in a different
6428 // section. Probably not helpful to mention it, so use the section name.
6429 RelocSection.getName(Name);
6430 Addend = Addr - SectionAddr;
6431}
6432
6433static void printUnwindRelocDest(const MachOObjectFile *Obj,
6434 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006435 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006436 StringRef Name;
6437 uint64_t Addend;
6438
Rafael Espindola854038e2015-06-26 14:51:16 +00006439 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006440 return;
6441
Tim Northover4bd286a2014-08-01 13:07:19 +00006442 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6443
6444 outs() << Name;
6445 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006446 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006447}
6448
6449static void
6450printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6451 std::map<uint64_t, SymbolRef> &Symbols,
6452 const SectionRef &CompactUnwind) {
6453
6454 assert(Obj->isLittleEndian() &&
6455 "There should not be a big-endian .o with __compact_unwind");
6456
6457 bool Is64 = Obj->is64Bit();
6458 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6459 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6460
6461 StringRef Contents;
6462 CompactUnwind.getContents(Contents);
6463
6464 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6465
6466 // First populate the initial raw offsets, encodings and so on from the entry.
6467 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6468 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6469 CompactUnwinds.push_back(Entry);
6470 }
6471
6472 // Next we need to look at the relocations to find out what objects are
6473 // actually being referred to.
6474 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006475 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006476
6477 uint32_t EntryIdx = RelocAddress / EntrySize;
6478 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6479 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6480
6481 if (OffsetInEntry == 0)
6482 Entry.FunctionReloc = Reloc;
6483 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6484 Entry.PersonalityReloc = Reloc;
6485 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6486 Entry.LSDAReloc = Reloc;
6487 else
6488 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6489 }
6490
6491 // Finally, we're ready to print the data we've gathered.
6492 outs() << "Contents of __compact_unwind section:\n";
6493 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006494 outs() << " Entry at offset "
6495 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006496
6497 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006498 outs() << " start: " << format("0x%" PRIx64,
6499 Entry.FunctionAddr) << ' ';
6500 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006501 outs() << '\n';
6502
6503 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006504 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6505 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006506 // 3. The 32-bit compact encoding.
6507 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006508 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006509
6510 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006511 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006512 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006513 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006514 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6515 Entry.PersonalityAddr);
6516 outs() << '\n';
6517 }
6518
6519 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006520 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006521 outs() << " LSDA: " << format("0x%" PRIx64,
6522 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006523 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6524 outs() << '\n';
6525 }
6526 }
6527}
6528
Tim Northover39c70bb2014-08-12 11:52:59 +00006529//===----------------------------------------------------------------------===//
6530// __unwind_info section dumping
6531//===----------------------------------------------------------------------===//
6532
6533static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6534 const char *Pos = PageStart;
6535 uint32_t Kind = readNext<uint32_t>(Pos);
6536 (void)Kind;
6537 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6538
6539 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6540 uint16_t NumEntries = readNext<uint16_t>(Pos);
6541
6542 Pos = PageStart + EntriesStart;
6543 for (unsigned i = 0; i < NumEntries; ++i) {
6544 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6545 uint32_t Encoding = readNext<uint32_t>(Pos);
6546
6547 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006548 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6549 << ", "
6550 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006551 }
6552}
6553
6554static void printCompressedSecondLevelUnwindPage(
6555 const char *PageStart, uint32_t FunctionBase,
6556 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6557 const char *Pos = PageStart;
6558 uint32_t Kind = readNext<uint32_t>(Pos);
6559 (void)Kind;
6560 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6561
6562 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6563 uint16_t NumEntries = readNext<uint16_t>(Pos);
6564
6565 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6566 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006567 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6568 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006569
6570 Pos = PageStart + EntriesStart;
6571 for (unsigned i = 0; i < NumEntries; ++i) {
6572 uint32_t Entry = readNext<uint32_t>(Pos);
6573 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6574 uint32_t EncodingIdx = Entry >> 24;
6575
6576 uint32_t Encoding;
6577 if (EncodingIdx < CommonEncodings.size())
6578 Encoding = CommonEncodings[EncodingIdx];
6579 else
6580 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6581
6582 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006583 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6584 << ", "
6585 << "encoding[" << EncodingIdx
6586 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006587 }
6588}
6589
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006590static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6591 std::map<uint64_t, SymbolRef> &Symbols,
6592 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006593
6594 assert(Obj->isLittleEndian() &&
6595 "There should not be a big-endian .o with __unwind_info");
6596
6597 outs() << "Contents of __unwind_info section:\n";
6598
6599 StringRef Contents;
6600 UnwindInfo.getContents(Contents);
6601 const char *Pos = Contents.data();
6602
6603 //===----------------------------------
6604 // Section header
6605 //===----------------------------------
6606
6607 uint32_t Version = readNext<uint32_t>(Pos);
6608 outs() << " Version: "
6609 << format("0x%" PRIx32, Version) << '\n';
6610 assert(Version == 1 && "only understand version 1");
6611
6612 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6613 outs() << " Common encodings array section offset: "
6614 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6615 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6616 outs() << " Number of common encodings in array: "
6617 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6618
6619 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6620 outs() << " Personality function array section offset: "
6621 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6622 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6623 outs() << " Number of personality functions in array: "
6624 << format("0x%" PRIx32, NumPersonalities) << '\n';
6625
6626 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6627 outs() << " Index array section offset: "
6628 << format("0x%" PRIx32, IndicesStart) << '\n';
6629 uint32_t NumIndices = readNext<uint32_t>(Pos);
6630 outs() << " Number of indices in array: "
6631 << format("0x%" PRIx32, NumIndices) << '\n';
6632
6633 //===----------------------------------
6634 // A shared list of common encodings
6635 //===----------------------------------
6636
6637 // These occupy indices in the range [0, N] whenever an encoding is referenced
6638 // from a compressed 2nd level index table. In practice the linker only
6639 // creates ~128 of these, so that indices are available to embed encodings in
6640 // the 2nd level index.
6641
6642 SmallVector<uint32_t, 64> CommonEncodings;
6643 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6644 Pos = Contents.data() + CommonEncodingsStart;
6645 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6646 uint32_t Encoding = readNext<uint32_t>(Pos);
6647 CommonEncodings.push_back(Encoding);
6648
6649 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6650 << '\n';
6651 }
6652
Tim Northover39c70bb2014-08-12 11:52:59 +00006653 //===----------------------------------
6654 // Personality functions used in this executable
6655 //===----------------------------------
6656
6657 // There should be only a handful of these (one per source language,
6658 // roughly). Particularly since they only get 2 bits in the compact encoding.
6659
6660 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6661 Pos = Contents.data() + PersonalitiesStart;
6662 for (unsigned i = 0; i < NumPersonalities; ++i) {
6663 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6664 outs() << " personality[" << i + 1
6665 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6666 }
6667
6668 //===----------------------------------
6669 // The level 1 index entries
6670 //===----------------------------------
6671
6672 // These specify an approximate place to start searching for the more detailed
6673 // information, sorted by PC.
6674
6675 struct IndexEntry {
6676 uint32_t FunctionOffset;
6677 uint32_t SecondLevelPageStart;
6678 uint32_t LSDAStart;
6679 };
6680
6681 SmallVector<IndexEntry, 4> IndexEntries;
6682
6683 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6684 Pos = Contents.data() + IndicesStart;
6685 for (unsigned i = 0; i < NumIndices; ++i) {
6686 IndexEntry Entry;
6687
6688 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6689 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6690 Entry.LSDAStart = readNext<uint32_t>(Pos);
6691 IndexEntries.push_back(Entry);
6692
6693 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006694 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6695 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006696 << "2nd level page offset="
6697 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006698 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006699 }
6700
Tim Northover39c70bb2014-08-12 11:52:59 +00006701 //===----------------------------------
6702 // Next come the LSDA tables
6703 //===----------------------------------
6704
6705 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6706 // the first top-level index's LSDAOffset to the last (sentinel).
6707
6708 outs() << " LSDA descriptors:\n";
6709 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6710 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6711 (2 * sizeof(uint32_t));
6712 for (int i = 0; i < NumLSDAs; ++i) {
6713 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6714 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6715 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006716 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6717 << ", "
6718 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006719 }
6720
6721 //===----------------------------------
6722 // Finally, the 2nd level indices
6723 //===----------------------------------
6724
6725 // Generally these are 4K in size, and have 2 possible forms:
6726 // + Regular stores up to 511 entries with disparate encodings
6727 // + Compressed stores up to 1021 entries if few enough compact encoding
6728 // values are used.
6729 outs() << " Second level indices:\n";
6730 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6731 // The final sentinel top-level index has no associated 2nd level page
6732 if (IndexEntries[i].SecondLevelPageStart == 0)
6733 break;
6734
6735 outs() << " Second level index[" << i << "]: "
6736 << "offset in section="
6737 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6738 << ", "
6739 << "base function offset="
6740 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6741
6742 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006743 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006744 if (Kind == 2)
6745 printRegularSecondLevelUnwindPage(Pos);
6746 else if (Kind == 3)
6747 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6748 CommonEncodings);
6749 else
6750 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006751 }
6752}
6753
Pete Cooper98052532015-12-18 19:45:38 +00006754static unsigned getSizeForEncoding(bool is64Bit,
6755 unsigned symbolEncoding) {
6756 unsigned format = symbolEncoding & 0x0f;
6757 switch (format) {
6758 default: llvm_unreachable("Unknown Encoding");
6759 case dwarf::DW_EH_PE_absptr:
6760 case dwarf::DW_EH_PE_signed:
6761 return is64Bit ? 8 : 4;
6762 case dwarf::DW_EH_PE_udata2:
6763 case dwarf::DW_EH_PE_sdata2:
6764 return 2;
6765 case dwarf::DW_EH_PE_udata4:
6766 case dwarf::DW_EH_PE_sdata4:
6767 return 4;
6768 case dwarf::DW_EH_PE_udata8:
6769 case dwarf::DW_EH_PE_sdata8:
6770 return 8;
6771 }
6772}
6773
6774static uint64_t readPointer(const char *&Pos, bool is64Bit, unsigned Encoding) {
6775 switch (getSizeForEncoding(is64Bit, Encoding)) {
6776 case 2:
6777 return readNext<uint16_t>(Pos);
6778 break;
6779 case 4:
6780 return readNext<uint32_t>(Pos);
6781 break;
6782 case 8:
6783 return readNext<uint64_t>(Pos);
6784 break;
6785 default:
6786 llvm_unreachable("Illegal data size");
6787 }
6788}
6789
6790static void printMachOEHFrameSection(const MachOObjectFile *Obj,
6791 std::map<uint64_t, SymbolRef> &Symbols,
6792 const SectionRef &EHFrame) {
6793 if (!Obj->isLittleEndian()) {
6794 outs() << "warning: cannot handle big endian __eh_frame section\n";
6795 return;
6796 }
6797
6798 bool is64Bit = Obj->is64Bit();
6799
6800 outs() << "Contents of __eh_frame section:\n";
6801
6802 StringRef Contents;
6803 EHFrame.getContents(Contents);
6804
6805 /// A few fields of the CIE are used when decoding the FDE's. This struct
6806 /// will cache those fields we need so that we don't have to decode it
6807 /// repeatedly for each FDE that references it.
6808 struct DecodedCIE {
6809 Optional<uint32_t> FDEPointerEncoding;
6810 Optional<uint32_t> LSDAPointerEncoding;
6811 bool hasAugmentationLength;
6812 };
6813
6814 // Map from the start offset of the CIE to the cached data for that CIE.
6815 DenseMap<uint64_t, DecodedCIE> CachedCIEs;
6816
6817 for (const char *Pos = Contents.data(), *End = Contents.end(); Pos != End; ) {
6818
6819 const char *EntryStartPos = Pos;
6820
6821 uint64_t Length = readNext<uint32_t>(Pos);
6822 if (Length == 0xffffffff)
6823 Length = readNext<uint64_t>(Pos);
6824
6825 // Save the Pos so that we can check the length we encoded against what we
6826 // end up decoding.
6827 const char *PosAfterLength = Pos;
6828 const char *EntryEndPos = PosAfterLength + Length;
6829
6830 assert(EntryEndPos <= End &&
6831 "__eh_frame entry length exceeds section size");
6832
6833 uint32_t ID = readNext<uint32_t>(Pos);
6834 if (ID == 0) {
6835 // This is a CIE.
6836
6837 uint32_t Version = readNext<uint8_t>(Pos);
6838
6839 // Parse a null terminated augmentation string
6840 SmallString<8> AugmentationString;
6841 for (uint8_t Char = readNext<uint8_t>(Pos); Char;
6842 Char = readNext<uint8_t>(Pos))
6843 AugmentationString.push_back(Char);
6844
6845 // Optionally parse the EH data if the augmentation string says it's there.
6846 Optional<uint64_t> EHData;
6847 if (StringRef(AugmentationString).count("eh"))
6848 EHData = is64Bit ? readNext<uint64_t>(Pos) : readNext<uint32_t>(Pos);
6849
6850 unsigned ULEBByteCount;
6851 uint64_t CodeAlignmentFactor = decodeULEB128((const uint8_t *)Pos,
6852 &ULEBByteCount);
6853 Pos += ULEBByteCount;
6854
6855 int64_t DataAlignmentFactor = decodeSLEB128((const uint8_t *)Pos,
6856 &ULEBByteCount);
6857 Pos += ULEBByteCount;
6858
6859 uint32_t ReturnAddressRegister = readNext<uint8_t>(Pos);
6860
6861 Optional<uint64_t> AugmentationLength;
6862 Optional<uint32_t> LSDAPointerEncoding;
6863 Optional<uint32_t> PersonalityEncoding;
6864 Optional<uint64_t> Personality;
6865 Optional<uint32_t> FDEPointerEncoding;
6866 if (!AugmentationString.empty() && AugmentationString.front() == 'z') {
6867 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6868 &ULEBByteCount);
6869 Pos += ULEBByteCount;
6870
6871 // Walk the augmentation string to get all the augmentation data.
6872 for (unsigned i = 1, e = AugmentationString.size(); i != e; ++i) {
6873 char Char = AugmentationString[i];
6874 switch (Char) {
6875 case 'e':
6876 assert((i + 1) != e && AugmentationString[i + 1] == 'h' &&
6877 "Expected 'eh' in augmentation string");
6878 break;
6879 case 'L':
6880 assert(!LSDAPointerEncoding && "Duplicate LSDA encoding");
6881 LSDAPointerEncoding = readNext<uint8_t>(Pos);
6882 break;
6883 case 'P': {
6884 assert(!Personality && "Duplicate personality");
6885 PersonalityEncoding = readNext<uint8_t>(Pos);
6886 Personality = readPointer(Pos, is64Bit, *PersonalityEncoding);
6887 break;
6888 }
6889 case 'R':
6890 assert(!FDEPointerEncoding && "Duplicate FDE encoding");
6891 FDEPointerEncoding = readNext<uint8_t>(Pos);
6892 break;
6893 case 'z':
6894 llvm_unreachable("'z' must be first in the augmentation string");
6895 }
6896 }
6897 }
6898
6899 outs() << "CIE:\n";
6900 outs() << " Length: " << Length << "\n";
6901 outs() << " CIE ID: " << ID << "\n";
6902 outs() << " Version: " << Version << "\n";
6903 outs() << " Augmentation String: " << AugmentationString << "\n";
6904 if (EHData)
6905 outs() << " EHData: " << *EHData << "\n";
6906 outs() << " Code Alignment Factor: " << CodeAlignmentFactor << "\n";
6907 outs() << " Data Alignment Factor: " << DataAlignmentFactor << "\n";
6908 outs() << " Return Address Register: " << ReturnAddressRegister << "\n";
6909 if (AugmentationLength) {
6910 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6911 if (LSDAPointerEncoding) {
6912 outs() << " FDE LSDA Pointer Encoding: "
6913 << *LSDAPointerEncoding << "\n";
6914 }
6915 if (Personality) {
6916 outs() << " Personality Encoding: " << *PersonalityEncoding << "\n";
6917 outs() << " Personality: " << *Personality << "\n";
6918 }
6919 if (FDEPointerEncoding) {
6920 outs() << " FDE Address Pointer Encoding: "
6921 << *FDEPointerEncoding << "\n";
6922 }
6923 }
6924 // FIXME: Handle instructions.
6925 // For now just emit some bytes
6926 outs() << " Instructions:\n ";
6927 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
6928 outs());
6929 outs() << "\n";
6930 Pos = EntryEndPos;
6931
6932 // Cache this entry.
6933 uint64_t Offset = EntryStartPos - Contents.data();
6934 CachedCIEs[Offset] = { FDEPointerEncoding, LSDAPointerEncoding,
6935 AugmentationLength.hasValue() };
6936 continue;
6937 }
6938
6939 // This is an FDE.
6940 // The CIE pointer for an FDE is the same location as the ID which we
6941 // already read.
6942 uint32_t CIEPointer = ID;
6943
6944 const char *CIEStart = PosAfterLength - CIEPointer;
6945 assert(CIEStart >= Contents.data() &&
6946 "FDE points to CIE before the __eh_frame start");
6947
6948 uint64_t CIEOffset = CIEStart - Contents.data();
6949 auto CIEIt = CachedCIEs.find(CIEOffset);
6950 if (CIEIt == CachedCIEs.end())
6951 llvm_unreachable("Couldn't find CIE at offset in to __eh_frame section");
6952
6953 const DecodedCIE &CIE = CIEIt->getSecond();
6954 assert(CIE.FDEPointerEncoding &&
6955 "FDE references CIE which did not set pointer encoding");
6956
6957 uint64_t PCPointerSize = getSizeForEncoding(is64Bit,
6958 *CIE.FDEPointerEncoding);
6959
6960 uint64_t PCBegin = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6961 uint64_t PCRange = readPointer(Pos, is64Bit, *CIE.FDEPointerEncoding);
6962
6963 Optional<uint64_t> AugmentationLength;
6964 uint32_t LSDAPointerSize;
6965 Optional<uint64_t> LSDAPointer;
6966 if (CIE.hasAugmentationLength) {
6967 unsigned ULEBByteCount;
6968 AugmentationLength = decodeULEB128((const uint8_t *)Pos,
6969 &ULEBByteCount);
6970 Pos += ULEBByteCount;
6971
6972 // Decode the LSDA if the CIE augmentation string said we should.
6973 if (CIE.LSDAPointerEncoding) {
6974 LSDAPointerSize = getSizeForEncoding(is64Bit, *CIE.LSDAPointerEncoding);
6975 LSDAPointer = readPointer(Pos, is64Bit, *CIE.LSDAPointerEncoding);
6976 }
6977 }
6978
6979 outs() << "FDE:\n";
6980 outs() << " Length: " << Length << "\n";
6981 outs() << " CIE Offset: " << CIEOffset << "\n";
6982
6983 if (PCPointerSize == 8) {
6984 outs() << format(" PC Begin: %016" PRIx64, PCBegin) << "\n";
6985 outs() << format(" PC Range: %016" PRIx64, PCRange) << "\n";
6986 } else {
6987 outs() << format(" PC Begin: %08" PRIx64, PCBegin) << "\n";
6988 outs() << format(" PC Range: %08" PRIx64, PCRange) << "\n";
6989 }
6990 if (AugmentationLength) {
6991 outs() << " Augmentation Data Length: " << *AugmentationLength << "\n";
6992 if (LSDAPointer) {
6993 if (LSDAPointerSize == 8)
6994 outs() << format(" LSDA Pointer: %016\n" PRIx64, *LSDAPointer);
6995 else
6996 outs() << format(" LSDA Pointer: %08\n" PRIx64, *LSDAPointer);
6997 }
6998 }
6999
7000 // FIXME: Handle instructions.
7001 // For now just emit some bytes
7002 outs() << " Instructions:\n ";
7003 dumpBytes(makeArrayRef((const uint8_t*)Pos, (const uint8_t*)EntryEndPos),
7004 outs());
7005 outs() << "\n";
7006 Pos = EntryEndPos;
7007 }
7008}
7009
Tim Northover4bd286a2014-08-01 13:07:19 +00007010void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7011 std::map<uint64_t, SymbolRef> Symbols;
7012 for (const SymbolRef &SymRef : Obj->symbols()) {
7013 // Discard any undefined or absolute symbols. They're not going to take part
7014 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00007015 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00007016 if (Section == Obj->section_end())
7017 continue;
7018
Rafael Espindoladea00162015-07-03 17:44:18 +00007019 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007020 Symbols.insert(std::make_pair(Addr, SymRef));
7021 }
7022
7023 for (const SectionRef &Section : Obj->sections()) {
7024 StringRef SectName;
7025 Section.getName(SectName);
7026 if (SectName == "__compact_unwind")
7027 printMachOCompactUnwindSection(Obj, Symbols, Section);
7028 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007029 printMachOUnwindInfoSection(Obj, Symbols, Section);
Pete Cooper98052532015-12-18 19:45:38 +00007030 else if (SectName == "__eh_frame")
7031 printMachOEHFrameSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007032 }
7033}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007034
7035static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7036 uint32_t cpusubtype, uint32_t filetype,
7037 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7038 bool verbose) {
7039 outs() << "Mach header\n";
7040 outs() << " magic cputype cpusubtype caps filetype ncmds "
7041 "sizeofcmds flags\n";
7042 if (verbose) {
7043 if (magic == MachO::MH_MAGIC)
7044 outs() << " MH_MAGIC";
7045 else if (magic == MachO::MH_MAGIC_64)
7046 outs() << "MH_MAGIC_64";
7047 else
7048 outs() << format(" 0x%08" PRIx32, magic);
7049 switch (cputype) {
7050 case MachO::CPU_TYPE_I386:
7051 outs() << " I386";
7052 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7053 case MachO::CPU_SUBTYPE_I386_ALL:
7054 outs() << " ALL";
7055 break;
7056 default:
7057 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7058 break;
7059 }
7060 break;
7061 case MachO::CPU_TYPE_X86_64:
7062 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007063 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7064 case MachO::CPU_SUBTYPE_X86_64_ALL:
7065 outs() << " ALL";
7066 break;
7067 case MachO::CPU_SUBTYPE_X86_64_H:
7068 outs() << " Haswell";
7069 break;
7070 default:
7071 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7072 break;
7073 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007074 break;
7075 case MachO::CPU_TYPE_ARM:
7076 outs() << " ARM";
7077 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7078 case MachO::CPU_SUBTYPE_ARM_ALL:
7079 outs() << " ALL";
7080 break;
7081 case MachO::CPU_SUBTYPE_ARM_V4T:
7082 outs() << " V4T";
7083 break;
7084 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7085 outs() << " V5TEJ";
7086 break;
7087 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7088 outs() << " XSCALE";
7089 break;
7090 case MachO::CPU_SUBTYPE_ARM_V6:
7091 outs() << " V6";
7092 break;
7093 case MachO::CPU_SUBTYPE_ARM_V6M:
7094 outs() << " V6M";
7095 break;
7096 case MachO::CPU_SUBTYPE_ARM_V7:
7097 outs() << " V7";
7098 break;
7099 case MachO::CPU_SUBTYPE_ARM_V7EM:
7100 outs() << " V7EM";
7101 break;
7102 case MachO::CPU_SUBTYPE_ARM_V7K:
7103 outs() << " V7K";
7104 break;
7105 case MachO::CPU_SUBTYPE_ARM_V7M:
7106 outs() << " V7M";
7107 break;
7108 case MachO::CPU_SUBTYPE_ARM_V7S:
7109 outs() << " V7S";
7110 break;
7111 default:
7112 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7113 break;
7114 }
7115 break;
7116 case MachO::CPU_TYPE_ARM64:
7117 outs() << " ARM64";
7118 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7119 case MachO::CPU_SUBTYPE_ARM64_ALL:
7120 outs() << " ALL";
7121 break;
7122 default:
7123 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7124 break;
7125 }
7126 break;
7127 case MachO::CPU_TYPE_POWERPC:
7128 outs() << " PPC";
7129 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7130 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7131 outs() << " ALL";
7132 break;
7133 default:
7134 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7135 break;
7136 }
7137 break;
7138 case MachO::CPU_TYPE_POWERPC64:
7139 outs() << " PPC64";
7140 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7141 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7142 outs() << " ALL";
7143 break;
7144 default:
7145 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7146 break;
7147 }
7148 break;
7149 }
7150 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007151 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007152 } else {
7153 outs() << format(" 0x%02" PRIx32,
7154 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7155 }
7156 switch (filetype) {
7157 case MachO::MH_OBJECT:
7158 outs() << " OBJECT";
7159 break;
7160 case MachO::MH_EXECUTE:
7161 outs() << " EXECUTE";
7162 break;
7163 case MachO::MH_FVMLIB:
7164 outs() << " FVMLIB";
7165 break;
7166 case MachO::MH_CORE:
7167 outs() << " CORE";
7168 break;
7169 case MachO::MH_PRELOAD:
7170 outs() << " PRELOAD";
7171 break;
7172 case MachO::MH_DYLIB:
7173 outs() << " DYLIB";
7174 break;
7175 case MachO::MH_DYLIB_STUB:
7176 outs() << " DYLIB_STUB";
7177 break;
7178 case MachO::MH_DYLINKER:
7179 outs() << " DYLINKER";
7180 break;
7181 case MachO::MH_BUNDLE:
7182 outs() << " BUNDLE";
7183 break;
7184 case MachO::MH_DSYM:
7185 outs() << " DSYM";
7186 break;
7187 case MachO::MH_KEXT_BUNDLE:
7188 outs() << " KEXTBUNDLE";
7189 break;
7190 default:
7191 outs() << format(" %10u", filetype);
7192 break;
7193 }
7194 outs() << format(" %5u", ncmds);
7195 outs() << format(" %10u", sizeofcmds);
7196 uint32_t f = flags;
7197 if (f & MachO::MH_NOUNDEFS) {
7198 outs() << " NOUNDEFS";
7199 f &= ~MachO::MH_NOUNDEFS;
7200 }
7201 if (f & MachO::MH_INCRLINK) {
7202 outs() << " INCRLINK";
7203 f &= ~MachO::MH_INCRLINK;
7204 }
7205 if (f & MachO::MH_DYLDLINK) {
7206 outs() << " DYLDLINK";
7207 f &= ~MachO::MH_DYLDLINK;
7208 }
7209 if (f & MachO::MH_BINDATLOAD) {
7210 outs() << " BINDATLOAD";
7211 f &= ~MachO::MH_BINDATLOAD;
7212 }
7213 if (f & MachO::MH_PREBOUND) {
7214 outs() << " PREBOUND";
7215 f &= ~MachO::MH_PREBOUND;
7216 }
7217 if (f & MachO::MH_SPLIT_SEGS) {
7218 outs() << " SPLIT_SEGS";
7219 f &= ~MachO::MH_SPLIT_SEGS;
7220 }
7221 if (f & MachO::MH_LAZY_INIT) {
7222 outs() << " LAZY_INIT";
7223 f &= ~MachO::MH_LAZY_INIT;
7224 }
7225 if (f & MachO::MH_TWOLEVEL) {
7226 outs() << " TWOLEVEL";
7227 f &= ~MachO::MH_TWOLEVEL;
7228 }
7229 if (f & MachO::MH_FORCE_FLAT) {
7230 outs() << " FORCE_FLAT";
7231 f &= ~MachO::MH_FORCE_FLAT;
7232 }
7233 if (f & MachO::MH_NOMULTIDEFS) {
7234 outs() << " NOMULTIDEFS";
7235 f &= ~MachO::MH_NOMULTIDEFS;
7236 }
7237 if (f & MachO::MH_NOFIXPREBINDING) {
7238 outs() << " NOFIXPREBINDING";
7239 f &= ~MachO::MH_NOFIXPREBINDING;
7240 }
7241 if (f & MachO::MH_PREBINDABLE) {
7242 outs() << " PREBINDABLE";
7243 f &= ~MachO::MH_PREBINDABLE;
7244 }
7245 if (f & MachO::MH_ALLMODSBOUND) {
7246 outs() << " ALLMODSBOUND";
7247 f &= ~MachO::MH_ALLMODSBOUND;
7248 }
7249 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7250 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7251 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7252 }
7253 if (f & MachO::MH_CANONICAL) {
7254 outs() << " CANONICAL";
7255 f &= ~MachO::MH_CANONICAL;
7256 }
7257 if (f & MachO::MH_WEAK_DEFINES) {
7258 outs() << " WEAK_DEFINES";
7259 f &= ~MachO::MH_WEAK_DEFINES;
7260 }
7261 if (f & MachO::MH_BINDS_TO_WEAK) {
7262 outs() << " BINDS_TO_WEAK";
7263 f &= ~MachO::MH_BINDS_TO_WEAK;
7264 }
7265 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7266 outs() << " ALLOW_STACK_EXECUTION";
7267 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7268 }
7269 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7270 outs() << " DEAD_STRIPPABLE_DYLIB";
7271 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7272 }
7273 if (f & MachO::MH_PIE) {
7274 outs() << " PIE";
7275 f &= ~MachO::MH_PIE;
7276 }
7277 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7278 outs() << " NO_REEXPORTED_DYLIBS";
7279 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7280 }
7281 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7282 outs() << " MH_HAS_TLV_DESCRIPTORS";
7283 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7284 }
7285 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7286 outs() << " MH_NO_HEAP_EXECUTION";
7287 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7288 }
7289 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7290 outs() << " APP_EXTENSION_SAFE";
7291 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7292 }
7293 if (f != 0 || flags == 0)
7294 outs() << format(" 0x%08" PRIx32, f);
7295 } else {
7296 outs() << format(" 0x%08" PRIx32, magic);
7297 outs() << format(" %7d", cputype);
7298 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7299 outs() << format(" 0x%02" PRIx32,
7300 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7301 outs() << format(" %10u", filetype);
7302 outs() << format(" %5u", ncmds);
7303 outs() << format(" %10u", sizeofcmds);
7304 outs() << format(" 0x%08" PRIx32, flags);
7305 }
7306 outs() << "\n";
7307}
7308
Kevin Enderby956366c2014-08-29 22:30:52 +00007309static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7310 StringRef SegName, uint64_t vmaddr,
7311 uint64_t vmsize, uint64_t fileoff,
7312 uint64_t filesize, uint32_t maxprot,
7313 uint32_t initprot, uint32_t nsects,
7314 uint32_t flags, uint32_t object_size,
7315 bool verbose) {
7316 uint64_t expected_cmdsize;
7317 if (cmd == MachO::LC_SEGMENT) {
7318 outs() << " cmd LC_SEGMENT\n";
7319 expected_cmdsize = nsects;
7320 expected_cmdsize *= sizeof(struct MachO::section);
7321 expected_cmdsize += sizeof(struct MachO::segment_command);
7322 } else {
7323 outs() << " cmd LC_SEGMENT_64\n";
7324 expected_cmdsize = nsects;
7325 expected_cmdsize *= sizeof(struct MachO::section_64);
7326 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7327 }
7328 outs() << " cmdsize " << cmdsize;
7329 if (cmdsize != expected_cmdsize)
7330 outs() << " Inconsistent size\n";
7331 else
7332 outs() << "\n";
7333 outs() << " segname " << SegName << "\n";
7334 if (cmd == MachO::LC_SEGMENT_64) {
7335 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7336 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7337 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007338 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7339 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007340 }
7341 outs() << " fileoff " << fileoff;
7342 if (fileoff > object_size)
7343 outs() << " (past end of file)\n";
7344 else
7345 outs() << "\n";
7346 outs() << " filesize " << filesize;
7347 if (fileoff + filesize > object_size)
7348 outs() << " (past end of file)\n";
7349 else
7350 outs() << "\n";
7351 if (verbose) {
7352 if ((maxprot &
7353 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7354 MachO::VM_PROT_EXECUTE)) != 0)
7355 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7356 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007357 outs() << " maxprot ";
7358 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7359 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7360 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007361 }
7362 if ((initprot &
7363 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7364 MachO::VM_PROT_EXECUTE)) != 0)
7365 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7366 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007367 outs() << " initprot ";
7368 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7369 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7370 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007371 }
7372 } else {
7373 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7374 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7375 }
7376 outs() << " nsects " << nsects << "\n";
7377 if (verbose) {
7378 outs() << " flags";
7379 if (flags == 0)
7380 outs() << " (none)\n";
7381 else {
7382 if (flags & MachO::SG_HIGHVM) {
7383 outs() << " HIGHVM";
7384 flags &= ~MachO::SG_HIGHVM;
7385 }
7386 if (flags & MachO::SG_FVMLIB) {
7387 outs() << " FVMLIB";
7388 flags &= ~MachO::SG_FVMLIB;
7389 }
7390 if (flags & MachO::SG_NORELOC) {
7391 outs() << " NORELOC";
7392 flags &= ~MachO::SG_NORELOC;
7393 }
7394 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7395 outs() << " PROTECTED_VERSION_1";
7396 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7397 }
7398 if (flags)
7399 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7400 else
7401 outs() << "\n";
7402 }
7403 } else {
7404 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7405 }
7406}
7407
7408static void PrintSection(const char *sectname, const char *segname,
7409 uint64_t addr, uint64_t size, uint32_t offset,
7410 uint32_t align, uint32_t reloff, uint32_t nreloc,
7411 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7412 uint32_t cmd, const char *sg_segname,
7413 uint32_t filetype, uint32_t object_size,
7414 bool verbose) {
7415 outs() << "Section\n";
7416 outs() << " sectname " << format("%.16s\n", sectname);
7417 outs() << " segname " << format("%.16s", segname);
7418 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7419 outs() << " (does not match segment)\n";
7420 else
7421 outs() << "\n";
7422 if (cmd == MachO::LC_SEGMENT_64) {
7423 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7424 outs() << " size " << format("0x%016" PRIx64, size);
7425 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007426 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7427 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007428 }
7429 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7430 outs() << " (past end of file)\n";
7431 else
7432 outs() << "\n";
7433 outs() << " offset " << offset;
7434 if (offset > object_size)
7435 outs() << " (past end of file)\n";
7436 else
7437 outs() << "\n";
7438 uint32_t align_shifted = 1 << align;
7439 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7440 outs() << " reloff " << reloff;
7441 if (reloff > object_size)
7442 outs() << " (past end of file)\n";
7443 else
7444 outs() << "\n";
7445 outs() << " nreloc " << nreloc;
7446 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7447 outs() << " (past end of file)\n";
7448 else
7449 outs() << "\n";
7450 uint32_t section_type = flags & MachO::SECTION_TYPE;
7451 if (verbose) {
7452 outs() << " type";
7453 if (section_type == MachO::S_REGULAR)
7454 outs() << " S_REGULAR\n";
7455 else if (section_type == MachO::S_ZEROFILL)
7456 outs() << " S_ZEROFILL\n";
7457 else if (section_type == MachO::S_CSTRING_LITERALS)
7458 outs() << " S_CSTRING_LITERALS\n";
7459 else if (section_type == MachO::S_4BYTE_LITERALS)
7460 outs() << " S_4BYTE_LITERALS\n";
7461 else if (section_type == MachO::S_8BYTE_LITERALS)
7462 outs() << " S_8BYTE_LITERALS\n";
7463 else if (section_type == MachO::S_16BYTE_LITERALS)
7464 outs() << " S_16BYTE_LITERALS\n";
7465 else if (section_type == MachO::S_LITERAL_POINTERS)
7466 outs() << " S_LITERAL_POINTERS\n";
7467 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7468 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7469 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7470 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7471 else if (section_type == MachO::S_SYMBOL_STUBS)
7472 outs() << " S_SYMBOL_STUBS\n";
7473 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7474 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7475 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7476 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7477 else if (section_type == MachO::S_COALESCED)
7478 outs() << " S_COALESCED\n";
7479 else if (section_type == MachO::S_INTERPOSING)
7480 outs() << " S_INTERPOSING\n";
7481 else if (section_type == MachO::S_DTRACE_DOF)
7482 outs() << " S_DTRACE_DOF\n";
7483 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7484 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7485 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7486 outs() << " S_THREAD_LOCAL_REGULAR\n";
7487 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7488 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7489 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7490 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7491 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7492 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7493 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7494 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7495 else
7496 outs() << format("0x%08" PRIx32, section_type) << "\n";
7497 outs() << "attributes";
7498 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7499 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7500 outs() << " PURE_INSTRUCTIONS";
7501 if (section_attributes & MachO::S_ATTR_NO_TOC)
7502 outs() << " NO_TOC";
7503 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7504 outs() << " STRIP_STATIC_SYMS";
7505 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7506 outs() << " NO_DEAD_STRIP";
7507 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7508 outs() << " LIVE_SUPPORT";
7509 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7510 outs() << " SELF_MODIFYING_CODE";
7511 if (section_attributes & MachO::S_ATTR_DEBUG)
7512 outs() << " DEBUG";
7513 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7514 outs() << " SOME_INSTRUCTIONS";
7515 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7516 outs() << " EXT_RELOC";
7517 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7518 outs() << " LOC_RELOC";
7519 if (section_attributes == 0)
7520 outs() << " (none)";
7521 outs() << "\n";
7522 } else
7523 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7524 outs() << " reserved1 " << reserved1;
7525 if (section_type == MachO::S_SYMBOL_STUBS ||
7526 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7527 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7528 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7529 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7530 outs() << " (index into indirect symbol table)\n";
7531 else
7532 outs() << "\n";
7533 outs() << " reserved2 " << reserved2;
7534 if (section_type == MachO::S_SYMBOL_STUBS)
7535 outs() << " (size of stubs)\n";
7536 else
7537 outs() << "\n";
7538}
7539
David Majnemer73cc6ff2014-11-13 19:48:56 +00007540static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007541 uint32_t object_size) {
7542 outs() << " cmd LC_SYMTAB\n";
7543 outs() << " cmdsize " << st.cmdsize;
7544 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7545 outs() << " Incorrect size\n";
7546 else
7547 outs() << "\n";
7548 outs() << " symoff " << st.symoff;
7549 if (st.symoff > object_size)
7550 outs() << " (past end of file)\n";
7551 else
7552 outs() << "\n";
7553 outs() << " nsyms " << st.nsyms;
7554 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007555 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007556 big_size = st.nsyms;
7557 big_size *= sizeof(struct MachO::nlist_64);
7558 big_size += st.symoff;
7559 if (big_size > object_size)
7560 outs() << " (past end of file)\n";
7561 else
7562 outs() << "\n";
7563 } else {
7564 big_size = st.nsyms;
7565 big_size *= sizeof(struct MachO::nlist);
7566 big_size += st.symoff;
7567 if (big_size > object_size)
7568 outs() << " (past end of file)\n";
7569 else
7570 outs() << "\n";
7571 }
7572 outs() << " stroff " << st.stroff;
7573 if (st.stroff > object_size)
7574 outs() << " (past end of file)\n";
7575 else
7576 outs() << "\n";
7577 outs() << " strsize " << st.strsize;
7578 big_size = st.stroff;
7579 big_size += st.strsize;
7580 if (big_size > object_size)
7581 outs() << " (past end of file)\n";
7582 else
7583 outs() << "\n";
7584}
7585
7586static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7587 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007588 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007589 outs() << " cmd LC_DYSYMTAB\n";
7590 outs() << " cmdsize " << dyst.cmdsize;
7591 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7592 outs() << " Incorrect size\n";
7593 else
7594 outs() << "\n";
7595 outs() << " ilocalsym " << dyst.ilocalsym;
7596 if (dyst.ilocalsym > nsyms)
7597 outs() << " (greater than the number of symbols)\n";
7598 else
7599 outs() << "\n";
7600 outs() << " nlocalsym " << dyst.nlocalsym;
7601 uint64_t big_size;
7602 big_size = dyst.ilocalsym;
7603 big_size += dyst.nlocalsym;
7604 if (big_size > nsyms)
7605 outs() << " (past the end of the symbol table)\n";
7606 else
7607 outs() << "\n";
7608 outs() << " iextdefsym " << dyst.iextdefsym;
7609 if (dyst.iextdefsym > nsyms)
7610 outs() << " (greater than the number of symbols)\n";
7611 else
7612 outs() << "\n";
7613 outs() << " nextdefsym " << dyst.nextdefsym;
7614 big_size = dyst.iextdefsym;
7615 big_size += dyst.nextdefsym;
7616 if (big_size > nsyms)
7617 outs() << " (past the end of the symbol table)\n";
7618 else
7619 outs() << "\n";
7620 outs() << " iundefsym " << dyst.iundefsym;
7621 if (dyst.iundefsym > nsyms)
7622 outs() << " (greater than the number of symbols)\n";
7623 else
7624 outs() << "\n";
7625 outs() << " nundefsym " << dyst.nundefsym;
7626 big_size = dyst.iundefsym;
7627 big_size += dyst.nundefsym;
7628 if (big_size > nsyms)
7629 outs() << " (past the end of the symbol table)\n";
7630 else
7631 outs() << "\n";
7632 outs() << " tocoff " << dyst.tocoff;
7633 if (dyst.tocoff > object_size)
7634 outs() << " (past end of file)\n";
7635 else
7636 outs() << "\n";
7637 outs() << " ntoc " << dyst.ntoc;
7638 big_size = dyst.ntoc;
7639 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7640 big_size += dyst.tocoff;
7641 if (big_size > object_size)
7642 outs() << " (past end of file)\n";
7643 else
7644 outs() << "\n";
7645 outs() << " modtaboff " << dyst.modtaboff;
7646 if (dyst.modtaboff > object_size)
7647 outs() << " (past end of file)\n";
7648 else
7649 outs() << "\n";
7650 outs() << " nmodtab " << dyst.nmodtab;
7651 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007652 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007653 modtabend = dyst.nmodtab;
7654 modtabend *= sizeof(struct MachO::dylib_module_64);
7655 modtabend += dyst.modtaboff;
7656 } else {
7657 modtabend = dyst.nmodtab;
7658 modtabend *= sizeof(struct MachO::dylib_module);
7659 modtabend += dyst.modtaboff;
7660 }
7661 if (modtabend > object_size)
7662 outs() << " (past end of file)\n";
7663 else
7664 outs() << "\n";
7665 outs() << " extrefsymoff " << dyst.extrefsymoff;
7666 if (dyst.extrefsymoff > object_size)
7667 outs() << " (past end of file)\n";
7668 else
7669 outs() << "\n";
7670 outs() << " nextrefsyms " << dyst.nextrefsyms;
7671 big_size = dyst.nextrefsyms;
7672 big_size *= sizeof(struct MachO::dylib_reference);
7673 big_size += dyst.extrefsymoff;
7674 if (big_size > object_size)
7675 outs() << " (past end of file)\n";
7676 else
7677 outs() << "\n";
7678 outs() << " indirectsymoff " << dyst.indirectsymoff;
7679 if (dyst.indirectsymoff > object_size)
7680 outs() << " (past end of file)\n";
7681 else
7682 outs() << "\n";
7683 outs() << " nindirectsyms " << dyst.nindirectsyms;
7684 big_size = dyst.nindirectsyms;
7685 big_size *= sizeof(uint32_t);
7686 big_size += dyst.indirectsymoff;
7687 if (big_size > object_size)
7688 outs() << " (past end of file)\n";
7689 else
7690 outs() << "\n";
7691 outs() << " extreloff " << dyst.extreloff;
7692 if (dyst.extreloff > object_size)
7693 outs() << " (past end of file)\n";
7694 else
7695 outs() << "\n";
7696 outs() << " nextrel " << dyst.nextrel;
7697 big_size = dyst.nextrel;
7698 big_size *= sizeof(struct MachO::relocation_info);
7699 big_size += dyst.extreloff;
7700 if (big_size > object_size)
7701 outs() << " (past end of file)\n";
7702 else
7703 outs() << "\n";
7704 outs() << " locreloff " << dyst.locreloff;
7705 if (dyst.locreloff > object_size)
7706 outs() << " (past end of file)\n";
7707 else
7708 outs() << "\n";
7709 outs() << " nlocrel " << dyst.nlocrel;
7710 big_size = dyst.nlocrel;
7711 big_size *= sizeof(struct MachO::relocation_info);
7712 big_size += dyst.locreloff;
7713 if (big_size > object_size)
7714 outs() << " (past end of file)\n";
7715 else
7716 outs() << "\n";
7717}
7718
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007719static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7720 uint32_t object_size) {
7721 if (dc.cmd == MachO::LC_DYLD_INFO)
7722 outs() << " cmd LC_DYLD_INFO\n";
7723 else
7724 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7725 outs() << " cmdsize " << dc.cmdsize;
7726 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7727 outs() << " Incorrect size\n";
7728 else
7729 outs() << "\n";
7730 outs() << " rebase_off " << dc.rebase_off;
7731 if (dc.rebase_off > object_size)
7732 outs() << " (past end of file)\n";
7733 else
7734 outs() << "\n";
7735 outs() << " rebase_size " << dc.rebase_size;
7736 uint64_t big_size;
7737 big_size = dc.rebase_off;
7738 big_size += dc.rebase_size;
7739 if (big_size > object_size)
7740 outs() << " (past end of file)\n";
7741 else
7742 outs() << "\n";
7743 outs() << " bind_off " << dc.bind_off;
7744 if (dc.bind_off > object_size)
7745 outs() << " (past end of file)\n";
7746 else
7747 outs() << "\n";
7748 outs() << " bind_size " << dc.bind_size;
7749 big_size = dc.bind_off;
7750 big_size += dc.bind_size;
7751 if (big_size > object_size)
7752 outs() << " (past end of file)\n";
7753 else
7754 outs() << "\n";
7755 outs() << " weak_bind_off " << dc.weak_bind_off;
7756 if (dc.weak_bind_off > object_size)
7757 outs() << " (past end of file)\n";
7758 else
7759 outs() << "\n";
7760 outs() << " weak_bind_size " << dc.weak_bind_size;
7761 big_size = dc.weak_bind_off;
7762 big_size += dc.weak_bind_size;
7763 if (big_size > object_size)
7764 outs() << " (past end of file)\n";
7765 else
7766 outs() << "\n";
7767 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7768 if (dc.lazy_bind_off > object_size)
7769 outs() << " (past end of file)\n";
7770 else
7771 outs() << "\n";
7772 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7773 big_size = dc.lazy_bind_off;
7774 big_size += dc.lazy_bind_size;
7775 if (big_size > object_size)
7776 outs() << " (past end of file)\n";
7777 else
7778 outs() << "\n";
7779 outs() << " export_off " << dc.export_off;
7780 if (dc.export_off > object_size)
7781 outs() << " (past end of file)\n";
7782 else
7783 outs() << "\n";
7784 outs() << " export_size " << dc.export_size;
7785 big_size = dc.export_off;
7786 big_size += dc.export_size;
7787 if (big_size > object_size)
7788 outs() << " (past end of file)\n";
7789 else
7790 outs() << "\n";
7791}
7792
7793static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7794 const char *Ptr) {
7795 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7796 outs() << " cmd LC_ID_DYLINKER\n";
7797 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7798 outs() << " cmd LC_LOAD_DYLINKER\n";
7799 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7800 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7801 else
7802 outs() << " cmd ?(" << dyld.cmd << ")\n";
7803 outs() << " cmdsize " << dyld.cmdsize;
7804 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7805 outs() << " Incorrect size\n";
7806 else
7807 outs() << "\n";
7808 if (dyld.name >= dyld.cmdsize)
7809 outs() << " name ?(bad offset " << dyld.name << ")\n";
7810 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007811 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007812 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7813 }
7814}
7815
7816static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7817 outs() << " cmd LC_UUID\n";
7818 outs() << " cmdsize " << uuid.cmdsize;
7819 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7820 outs() << " Incorrect size\n";
7821 else
7822 outs() << "\n";
7823 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007824 for (int i = 0; i < 16; ++i) {
7825 outs() << format("%02" PRIX32, uuid.uuid[i]);
7826 if (i == 3 || i == 5 || i == 7 || i == 9)
7827 outs() << "-";
7828 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007829 outs() << "\n";
7830}
7831
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007832static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007833 outs() << " cmd LC_RPATH\n";
7834 outs() << " cmdsize " << rpath.cmdsize;
7835 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7836 outs() << " Incorrect size\n";
7837 else
7838 outs() << "\n";
7839 if (rpath.path >= rpath.cmdsize)
7840 outs() << " path ?(bad offset " << rpath.path << ")\n";
7841 else {
7842 const char *P = (const char *)(Ptr) + rpath.path;
7843 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7844 }
7845}
7846
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007847static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007848 StringRef LoadCmdName;
7849 switch (vd.cmd) {
7850 case MachO::LC_VERSION_MIN_MACOSX:
7851 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7852 break;
7853 case MachO::LC_VERSION_MIN_IPHONEOS:
7854 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7855 break;
7856 case MachO::LC_VERSION_MIN_TVOS:
7857 LoadCmdName = "LC_VERSION_MIN_TVOS";
7858 break;
7859 case MachO::LC_VERSION_MIN_WATCHOS:
7860 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7861 break;
7862 default:
7863 llvm_unreachable("Unknown version min load command");
7864 }
7865
7866 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007867 outs() << " cmdsize " << vd.cmdsize;
7868 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7869 outs() << " Incorrect size\n";
7870 else
7871 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007872 outs() << " version "
7873 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7874 << MachOObjectFile::getVersionMinMinor(vd, false);
7875 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7876 if (Update != 0)
7877 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007878 outs() << "\n";
7879 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007880 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007881 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007882 outs() << " sdk "
7883 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7884 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007885 }
Davide Italiano56baef32015-08-26 12:26:11 +00007886 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7887 if (Update != 0)
7888 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007889 outs() << "\n";
7890}
7891
7892static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7893 outs() << " cmd LC_SOURCE_VERSION\n";
7894 outs() << " cmdsize " << sd.cmdsize;
7895 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7896 outs() << " Incorrect size\n";
7897 else
7898 outs() << "\n";
7899 uint64_t a = (sd.version >> 40) & 0xffffff;
7900 uint64_t b = (sd.version >> 30) & 0x3ff;
7901 uint64_t c = (sd.version >> 20) & 0x3ff;
7902 uint64_t d = (sd.version >> 10) & 0x3ff;
7903 uint64_t e = sd.version & 0x3ff;
7904 outs() << " version " << a << "." << b;
7905 if (e != 0)
7906 outs() << "." << c << "." << d << "." << e;
7907 else if (d != 0)
7908 outs() << "." << c << "." << d;
7909 else if (c != 0)
7910 outs() << "." << c;
7911 outs() << "\n";
7912}
7913
7914static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7915 outs() << " cmd LC_MAIN\n";
7916 outs() << " cmdsize " << ep.cmdsize;
7917 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7918 outs() << " Incorrect size\n";
7919 else
7920 outs() << "\n";
7921 outs() << " entryoff " << ep.entryoff << "\n";
7922 outs() << " stacksize " << ep.stacksize << "\n";
7923}
7924
Kevin Enderby0804f4672014-12-16 23:25:52 +00007925static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7926 uint32_t object_size) {
7927 outs() << " cmd LC_ENCRYPTION_INFO\n";
7928 outs() << " cmdsize " << ec.cmdsize;
7929 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7930 outs() << " Incorrect size\n";
7931 else
7932 outs() << "\n";
7933 outs() << " cryptoff " << ec.cryptoff;
7934 if (ec.cryptoff > object_size)
7935 outs() << " (past end of file)\n";
7936 else
7937 outs() << "\n";
7938 outs() << " cryptsize " << ec.cryptsize;
7939 if (ec.cryptsize > object_size)
7940 outs() << " (past end of file)\n";
7941 else
7942 outs() << "\n";
7943 outs() << " cryptid " << ec.cryptid << "\n";
7944}
7945
Kevin Enderby57538292014-12-17 01:01:30 +00007946static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007947 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007948 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7949 outs() << " cmdsize " << ec.cmdsize;
7950 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7951 outs() << " Incorrect size\n";
7952 else
7953 outs() << "\n";
7954 outs() << " cryptoff " << ec.cryptoff;
7955 if (ec.cryptoff > object_size)
7956 outs() << " (past end of file)\n";
7957 else
7958 outs() << "\n";
7959 outs() << " cryptsize " << ec.cryptsize;
7960 if (ec.cryptsize > object_size)
7961 outs() << " (past end of file)\n";
7962 else
7963 outs() << "\n";
7964 outs() << " cryptid " << ec.cryptid << "\n";
7965 outs() << " pad " << ec.pad << "\n";
7966}
7967
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007968static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7969 const char *Ptr) {
7970 outs() << " cmd LC_LINKER_OPTION\n";
7971 outs() << " cmdsize " << lo.cmdsize;
7972 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7973 outs() << " Incorrect size\n";
7974 else
7975 outs() << "\n";
7976 outs() << " count " << lo.count << "\n";
7977 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7978 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7979 uint32_t i = 0;
7980 while (left > 0) {
7981 while (*string == '\0' && left > 0) {
7982 string++;
7983 left--;
7984 }
7985 if (left > 0) {
7986 i++;
7987 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007988 uint32_t NullPos = StringRef(string, left).find('\0');
7989 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007990 string += len;
7991 left -= len;
7992 }
7993 }
7994 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007995 outs() << " count " << lo.count << " does not match number of strings "
7996 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007997}
7998
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007999static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8000 const char *Ptr) {
8001 outs() << " cmd LC_SUB_FRAMEWORK\n";
8002 outs() << " cmdsize " << sub.cmdsize;
8003 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8004 outs() << " Incorrect size\n";
8005 else
8006 outs() << "\n";
8007 if (sub.umbrella < sub.cmdsize) {
8008 const char *P = Ptr + sub.umbrella;
8009 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8010 } else {
8011 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8012 }
8013}
8014
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008015static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8016 const char *Ptr) {
8017 outs() << " cmd LC_SUB_UMBRELLA\n";
8018 outs() << " cmdsize " << sub.cmdsize;
8019 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8020 outs() << " Incorrect size\n";
8021 else
8022 outs() << "\n";
8023 if (sub.sub_umbrella < sub.cmdsize) {
8024 const char *P = Ptr + sub.sub_umbrella;
8025 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8026 } else {
8027 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8028 }
8029}
8030
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008031static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008032 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008033 outs() << " cmd LC_SUB_LIBRARY\n";
8034 outs() << " cmdsize " << sub.cmdsize;
8035 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8036 outs() << " Incorrect size\n";
8037 else
8038 outs() << "\n";
8039 if (sub.sub_library < sub.cmdsize) {
8040 const char *P = Ptr + sub.sub_library;
8041 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8042 } else {
8043 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8044 }
8045}
8046
Kevin Enderby186eac32014-12-19 21:06:24 +00008047static void PrintSubClientCommand(MachO::sub_client_command sub,
8048 const char *Ptr) {
8049 outs() << " cmd LC_SUB_CLIENT\n";
8050 outs() << " cmdsize " << sub.cmdsize;
8051 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8052 outs() << " Incorrect size\n";
8053 else
8054 outs() << "\n";
8055 if (sub.client < sub.cmdsize) {
8056 const char *P = Ptr + sub.client;
8057 outs() << " client " << P << " (offset " << sub.client << ")\n";
8058 } else {
8059 outs() << " client ?(bad offset " << sub.client << ")\n";
8060 }
8061}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008062
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008063static void PrintRoutinesCommand(MachO::routines_command r) {
8064 outs() << " cmd LC_ROUTINES\n";
8065 outs() << " cmdsize " << r.cmdsize;
8066 if (r.cmdsize != sizeof(struct MachO::routines_command))
8067 outs() << " Incorrect size\n";
8068 else
8069 outs() << "\n";
8070 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8071 outs() << " init_module " << r.init_module << "\n";
8072 outs() << " reserved1 " << r.reserved1 << "\n";
8073 outs() << " reserved2 " << r.reserved2 << "\n";
8074 outs() << " reserved3 " << r.reserved3 << "\n";
8075 outs() << " reserved4 " << r.reserved4 << "\n";
8076 outs() << " reserved5 " << r.reserved5 << "\n";
8077 outs() << " reserved6 " << r.reserved6 << "\n";
8078}
8079
8080static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8081 outs() << " cmd LC_ROUTINES_64\n";
8082 outs() << " cmdsize " << r.cmdsize;
8083 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8084 outs() << " Incorrect size\n";
8085 else
8086 outs() << "\n";
8087 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8088 outs() << " init_module " << r.init_module << "\n";
8089 outs() << " reserved1 " << r.reserved1 << "\n";
8090 outs() << " reserved2 " << r.reserved2 << "\n";
8091 outs() << " reserved3 " << r.reserved3 << "\n";
8092 outs() << " reserved4 " << r.reserved4 << "\n";
8093 outs() << " reserved5 " << r.reserved5 << "\n";
8094 outs() << " reserved6 " << r.reserved6 << "\n";
8095}
8096
Kevin Enderby48ef5342014-12-23 22:56:39 +00008097static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8098 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8099 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8100 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8101 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8102 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8103 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8104 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8105 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8106 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8107 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8108 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8109 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8110 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8111 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8112 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8113 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8114 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8115 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8116 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8117 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8118 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8119}
8120
Kevin Enderby227df342014-12-23 23:43:59 +00008121static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008122 uint32_t f;
8123 outs() << "\t mmst_reg ";
8124 for (f = 0; f < 10; f++)
8125 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8126 outs() << "\n";
8127 outs() << "\t mmst_rsrv ";
8128 for (f = 0; f < 6; f++)
8129 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8130 outs() << "\n";
8131}
8132
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008133static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008134 uint32_t f;
8135 outs() << "\t xmm_reg ";
8136 for (f = 0; f < 16; f++)
8137 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8138 outs() << "\n";
8139}
8140
8141static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8142 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8143 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8144 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8145 outs() << " denorm " << fpu.fpu_fcw.denorm;
8146 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8147 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8148 outs() << " undfl " << fpu.fpu_fcw.undfl;
8149 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8150 outs() << "\t\t pc ";
8151 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8152 outs() << "FP_PREC_24B ";
8153 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8154 outs() << "FP_PREC_53B ";
8155 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8156 outs() << "FP_PREC_64B ";
8157 else
8158 outs() << fpu.fpu_fcw.pc << " ";
8159 outs() << "rc ";
8160 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8161 outs() << "FP_RND_NEAR ";
8162 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8163 outs() << "FP_RND_DOWN ";
8164 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8165 outs() << "FP_RND_UP ";
8166 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008167 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008168 outs() << "\n";
8169 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8170 outs() << " denorm " << fpu.fpu_fsw.denorm;
8171 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8172 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8173 outs() << " undfl " << fpu.fpu_fsw.undfl;
8174 outs() << " precis " << fpu.fpu_fsw.precis;
8175 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8176 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8177 outs() << " c0 " << fpu.fpu_fsw.c0;
8178 outs() << " c1 " << fpu.fpu_fsw.c1;
8179 outs() << " c2 " << fpu.fpu_fsw.c2;
8180 outs() << " tos " << fpu.fpu_fsw.tos;
8181 outs() << " c3 " << fpu.fpu_fsw.c3;
8182 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8183 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8184 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8185 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8186 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8187 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8188 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8189 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8190 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8191 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8192 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8193 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8194 outs() << "\n";
8195 outs() << "\t fpu_stmm0:\n";
8196 Print_mmst_reg(fpu.fpu_stmm0);
8197 outs() << "\t fpu_stmm1:\n";
8198 Print_mmst_reg(fpu.fpu_stmm1);
8199 outs() << "\t fpu_stmm2:\n";
8200 Print_mmst_reg(fpu.fpu_stmm2);
8201 outs() << "\t fpu_stmm3:\n";
8202 Print_mmst_reg(fpu.fpu_stmm3);
8203 outs() << "\t fpu_stmm4:\n";
8204 Print_mmst_reg(fpu.fpu_stmm4);
8205 outs() << "\t fpu_stmm5:\n";
8206 Print_mmst_reg(fpu.fpu_stmm5);
8207 outs() << "\t fpu_stmm6:\n";
8208 Print_mmst_reg(fpu.fpu_stmm6);
8209 outs() << "\t fpu_stmm7:\n";
8210 Print_mmst_reg(fpu.fpu_stmm7);
8211 outs() << "\t fpu_xmm0:\n";
8212 Print_xmm_reg(fpu.fpu_xmm0);
8213 outs() << "\t fpu_xmm1:\n";
8214 Print_xmm_reg(fpu.fpu_xmm1);
8215 outs() << "\t fpu_xmm2:\n";
8216 Print_xmm_reg(fpu.fpu_xmm2);
8217 outs() << "\t fpu_xmm3:\n";
8218 Print_xmm_reg(fpu.fpu_xmm3);
8219 outs() << "\t fpu_xmm4:\n";
8220 Print_xmm_reg(fpu.fpu_xmm4);
8221 outs() << "\t fpu_xmm5:\n";
8222 Print_xmm_reg(fpu.fpu_xmm5);
8223 outs() << "\t fpu_xmm6:\n";
8224 Print_xmm_reg(fpu.fpu_xmm6);
8225 outs() << "\t fpu_xmm7:\n";
8226 Print_xmm_reg(fpu.fpu_xmm7);
8227 outs() << "\t fpu_xmm8:\n";
8228 Print_xmm_reg(fpu.fpu_xmm8);
8229 outs() << "\t fpu_xmm9:\n";
8230 Print_xmm_reg(fpu.fpu_xmm9);
8231 outs() << "\t fpu_xmm10:\n";
8232 Print_xmm_reg(fpu.fpu_xmm10);
8233 outs() << "\t fpu_xmm11:\n";
8234 Print_xmm_reg(fpu.fpu_xmm11);
8235 outs() << "\t fpu_xmm12:\n";
8236 Print_xmm_reg(fpu.fpu_xmm12);
8237 outs() << "\t fpu_xmm13:\n";
8238 Print_xmm_reg(fpu.fpu_xmm13);
8239 outs() << "\t fpu_xmm14:\n";
8240 Print_xmm_reg(fpu.fpu_xmm14);
8241 outs() << "\t fpu_xmm15:\n";
8242 Print_xmm_reg(fpu.fpu_xmm15);
8243 outs() << "\t fpu_rsrv4:\n";
8244 for (uint32_t f = 0; f < 6; f++) {
8245 outs() << "\t ";
8246 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008247 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008248 outs() << "\n";
8249 }
8250 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8251 outs() << "\n";
8252}
8253
8254static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8255 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8256 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8257 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8258}
8259
8260static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8261 bool isLittleEndian, uint32_t cputype) {
8262 if (t.cmd == MachO::LC_THREAD)
8263 outs() << " cmd LC_THREAD\n";
8264 else if (t.cmd == MachO::LC_UNIXTHREAD)
8265 outs() << " cmd LC_UNIXTHREAD\n";
8266 else
8267 outs() << " cmd " << t.cmd << " (unknown)\n";
8268 outs() << " cmdsize " << t.cmdsize;
8269 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8270 outs() << " Incorrect size\n";
8271 else
8272 outs() << "\n";
8273
8274 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8275 const char *end = Ptr + t.cmdsize;
8276 uint32_t flavor, count, left;
8277 if (cputype == MachO::CPU_TYPE_X86_64) {
8278 while (begin < end) {
8279 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8280 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8281 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008282 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008283 flavor = 0;
8284 begin = end;
8285 }
8286 if (isLittleEndian != sys::IsLittleEndianHost)
8287 sys::swapByteOrder(flavor);
8288 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8289 memcpy((char *)&count, begin, sizeof(uint32_t));
8290 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008291 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008292 count = 0;
8293 begin = end;
8294 }
8295 if (isLittleEndian != sys::IsLittleEndianHost)
8296 sys::swapByteOrder(count);
8297 if (flavor == MachO::x86_THREAD_STATE64) {
8298 outs() << " flavor x86_THREAD_STATE64\n";
8299 if (count == MachO::x86_THREAD_STATE64_COUNT)
8300 outs() << " count x86_THREAD_STATE64_COUNT\n";
8301 else
8302 outs() << " count " << count
8303 << " (not x86_THREAD_STATE64_COUNT)\n";
8304 MachO::x86_thread_state64_t cpu64;
8305 left = end - begin;
8306 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8307 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8308 begin += sizeof(MachO::x86_thread_state64_t);
8309 } else {
8310 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8311 memcpy(&cpu64, begin, left);
8312 begin += left;
8313 }
8314 if (isLittleEndian != sys::IsLittleEndianHost)
8315 swapStruct(cpu64);
8316 Print_x86_thread_state64_t(cpu64);
8317 } else if (flavor == MachO::x86_THREAD_STATE) {
8318 outs() << " flavor x86_THREAD_STATE\n";
8319 if (count == MachO::x86_THREAD_STATE_COUNT)
8320 outs() << " count x86_THREAD_STATE_COUNT\n";
8321 else
8322 outs() << " count " << count
8323 << " (not x86_THREAD_STATE_COUNT)\n";
8324 struct MachO::x86_thread_state_t ts;
8325 left = end - begin;
8326 if (left >= sizeof(MachO::x86_thread_state_t)) {
8327 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8328 begin += sizeof(MachO::x86_thread_state_t);
8329 } else {
8330 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8331 memcpy(&ts, begin, left);
8332 begin += left;
8333 }
8334 if (isLittleEndian != sys::IsLittleEndianHost)
8335 swapStruct(ts);
8336 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8337 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8338 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8339 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8340 else
8341 outs() << "tsh.count " << ts.tsh.count
8342 << " (not x86_THREAD_STATE64_COUNT\n";
8343 Print_x86_thread_state64_t(ts.uts.ts64);
8344 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008345 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8346 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008347 }
8348 } else if (flavor == MachO::x86_FLOAT_STATE) {
8349 outs() << " flavor x86_FLOAT_STATE\n";
8350 if (count == MachO::x86_FLOAT_STATE_COUNT)
8351 outs() << " count x86_FLOAT_STATE_COUNT\n";
8352 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008353 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008354 struct MachO::x86_float_state_t fs;
8355 left = end - begin;
8356 if (left >= sizeof(MachO::x86_float_state_t)) {
8357 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8358 begin += sizeof(MachO::x86_float_state_t);
8359 } else {
8360 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8361 memcpy(&fs, begin, left);
8362 begin += left;
8363 }
8364 if (isLittleEndian != sys::IsLittleEndianHost)
8365 swapStruct(fs);
8366 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8367 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008368 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008369 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8370 else
8371 outs() << "fsh.count " << fs.fsh.count
8372 << " (not x86_FLOAT_STATE64_COUNT\n";
8373 Print_x86_float_state_t(fs.ufs.fs64);
8374 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008375 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8376 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008377 }
8378 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8379 outs() << " flavor x86_EXCEPTION_STATE\n";
8380 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8381 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8382 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008383 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008384 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8385 struct MachO::x86_exception_state_t es;
8386 left = end - begin;
8387 if (left >= sizeof(MachO::x86_exception_state_t)) {
8388 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8389 begin += sizeof(MachO::x86_exception_state_t);
8390 } else {
8391 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8392 memcpy(&es, begin, left);
8393 begin += left;
8394 }
8395 if (isLittleEndian != sys::IsLittleEndianHost)
8396 swapStruct(es);
8397 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8398 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008399 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008400 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8401 else
8402 outs() << "\t esh.count " << es.esh.count
8403 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8404 Print_x86_exception_state_t(es.ues.es64);
8405 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008406 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8407 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008408 }
8409 } else {
8410 outs() << " flavor " << flavor << " (unknown)\n";
8411 outs() << " count " << count << "\n";
8412 outs() << " state (unknown)\n";
8413 begin += count * sizeof(uint32_t);
8414 }
8415 }
8416 } else {
8417 while (begin < end) {
8418 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8419 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8420 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008421 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008422 flavor = 0;
8423 begin = end;
8424 }
8425 if (isLittleEndian != sys::IsLittleEndianHost)
8426 sys::swapByteOrder(flavor);
8427 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8428 memcpy((char *)&count, begin, sizeof(uint32_t));
8429 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008430 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008431 count = 0;
8432 begin = end;
8433 }
8434 if (isLittleEndian != sys::IsLittleEndianHost)
8435 sys::swapByteOrder(count);
8436 outs() << " flavor " << flavor << "\n";
8437 outs() << " count " << count << "\n";
8438 outs() << " state (Unknown cputype/cpusubtype)\n";
8439 begin += count * sizeof(uint32_t);
8440 }
8441 }
8442}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008443
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008444static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8445 if (dl.cmd == MachO::LC_ID_DYLIB)
8446 outs() << " cmd LC_ID_DYLIB\n";
8447 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8448 outs() << " cmd LC_LOAD_DYLIB\n";
8449 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8450 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8451 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8452 outs() << " cmd LC_REEXPORT_DYLIB\n";
8453 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8454 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8455 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8456 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8457 else
8458 outs() << " cmd " << dl.cmd << " (unknown)\n";
8459 outs() << " cmdsize " << dl.cmdsize;
8460 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8461 outs() << " Incorrect size\n";
8462 else
8463 outs() << "\n";
8464 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008465 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008466 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8467 } else {
8468 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8469 }
8470 outs() << " time stamp " << dl.dylib.timestamp << " ";
8471 time_t t = dl.dylib.timestamp;
8472 outs() << ctime(&t);
8473 outs() << " current version ";
8474 if (dl.dylib.current_version == 0xffffffff)
8475 outs() << "n/a\n";
8476 else
8477 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8478 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8479 << (dl.dylib.current_version & 0xff) << "\n";
8480 outs() << "compatibility version ";
8481 if (dl.dylib.compatibility_version == 0xffffffff)
8482 outs() << "n/a\n";
8483 else
8484 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8485 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8486 << (dl.dylib.compatibility_version & 0xff) << "\n";
8487}
8488
8489static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8490 uint32_t object_size) {
8491 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8492 outs() << " cmd LC_FUNCTION_STARTS\n";
8493 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8494 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8495 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8496 outs() << " cmd LC_FUNCTION_STARTS\n";
8497 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8498 outs() << " cmd LC_DATA_IN_CODE\n";
8499 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8500 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8501 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8502 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8503 else
8504 outs() << " cmd " << ld.cmd << " (?)\n";
8505 outs() << " cmdsize " << ld.cmdsize;
8506 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8507 outs() << " Incorrect size\n";
8508 else
8509 outs() << "\n";
8510 outs() << " dataoff " << ld.dataoff;
8511 if (ld.dataoff > object_size)
8512 outs() << " (past end of file)\n";
8513 else
8514 outs() << "\n";
8515 outs() << " datasize " << ld.datasize;
8516 uint64_t big_size = ld.dataoff;
8517 big_size += ld.datasize;
8518 if (big_size > object_size)
8519 outs() << " (past end of file)\n";
8520 else
8521 outs() << "\n";
8522}
8523
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008524static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8525 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008526 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008527 unsigned Index = 0;
8528 for (const auto &Command : Obj->load_commands()) {
8529 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008530 if (Command.C.cmd == MachO::LC_SEGMENT) {
8531 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8532 const char *sg_segname = SLC.segname;
8533 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8534 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8535 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8536 verbose);
8537 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008538 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008539 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8540 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8541 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8542 }
8543 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8544 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8545 const char *sg_segname = SLC_64.segname;
8546 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8547 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8548 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8549 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8550 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8551 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8552 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8553 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8554 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8555 sg_segname, filetype, Buf.size(), verbose);
8556 }
8557 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8558 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008559 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008560 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8561 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8562 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008563 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8564 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008565 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8566 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8567 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8568 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8569 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8570 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8571 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8572 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8573 PrintDyldLoadCommand(Dyld, Command.Ptr);
8574 } else if (Command.C.cmd == MachO::LC_UUID) {
8575 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8576 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008577 } else if (Command.C.cmd == MachO::LC_RPATH) {
8578 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8579 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008580 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008581 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8582 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8583 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008584 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8585 PrintVersionMinLoadCommand(Vd);
8586 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8587 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8588 PrintSourceVersionCommand(Sd);
8589 } else if (Command.C.cmd == MachO::LC_MAIN) {
8590 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8591 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008592 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008593 MachO::encryption_info_command Ei =
8594 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008595 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008596 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008597 MachO::encryption_info_command_64 Ei =
8598 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008599 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008600 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008601 MachO::linker_option_command Lo =
8602 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008603 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008604 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8605 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8606 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008607 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8608 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8609 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008610 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8611 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8612 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008613 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8614 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8615 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008616 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8617 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8618 PrintRoutinesCommand(Rc);
8619 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8620 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8621 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008622 } else if (Command.C.cmd == MachO::LC_THREAD ||
8623 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8624 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8625 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008626 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8627 Command.C.cmd == MachO::LC_ID_DYLIB ||
8628 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8629 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8630 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8631 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008632 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8633 PrintDylibCommand(Dl, Command.Ptr);
8634 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8635 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8636 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8637 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8638 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8639 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8640 MachO::linkedit_data_command Ld =
8641 Obj->getLinkeditDataLoadCommand(Command);
8642 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008643 } else {
8644 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8645 << ")\n";
8646 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8647 // TODO: get and print the raw bytes of the load command.
8648 }
8649 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008650 }
8651}
8652
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008653static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008654 if (Obj->is64Bit()) {
8655 MachO::mach_header_64 H_64;
8656 H_64 = Obj->getHeader64();
8657 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8658 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8659 } else {
8660 MachO::mach_header H;
8661 H = Obj->getHeader();
8662 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8663 H.sizeofcmds, H.flags, verbose);
8664 }
8665}
8666
8667void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8668 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008669 PrintMachHeader(file, !NonVerbose);
8670}
8671
8672void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8673 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008674 uint32_t filetype = 0;
8675 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008676 if (file->is64Bit()) {
8677 MachO::mach_header_64 H_64;
8678 H_64 = file->getHeader64();
8679 filetype = H_64.filetype;
8680 cputype = H_64.cputype;
8681 } else {
8682 MachO::mach_header H;
8683 H = file->getHeader();
8684 filetype = H.filetype;
8685 cputype = H.cputype;
8686 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008687 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008688}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008689
8690//===----------------------------------------------------------------------===//
8691// export trie dumping
8692//===----------------------------------------------------------------------===//
8693
8694void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008695 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8696 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008697 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8698 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8699 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8700 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8701 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8702 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8703 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8704 if (ReExport)
8705 outs() << "[re-export] ";
8706 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008707 outs() << format("0x%08llX ",
8708 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008709 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008710 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008711 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008712 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008713 if (WeakDef) {
8714 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008715 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008716 }
8717 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008718 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008719 outs() << ", ";
8720 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008721 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008722 }
8723 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008724 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008725 outs() << ", ";
8726 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008727 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008728 }
8729 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008730 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008731 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008732 outs() << format("resolver=0x%08llX", Entry.other());
8733 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008734 }
8735 outs() << "]";
8736 }
8737 if (ReExport) {
8738 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008739 int Ordinal = Entry.other() - 1;
8740 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8741 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008742 outs() << " (from " << DylibName << ")";
8743 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008744 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008745 }
8746 outs() << "\n";
8747 }
8748}
Nick Kledzikac431442014-09-12 21:34:15 +00008749
Nick Kledzikac431442014-09-12 21:34:15 +00008750//===----------------------------------------------------------------------===//
8751// rebase table dumping
8752//===----------------------------------------------------------------------===//
8753
8754namespace {
8755class SegInfo {
8756public:
8757 SegInfo(const object::MachOObjectFile *Obj);
8758
8759 StringRef segmentName(uint32_t SegIndex);
8760 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8761 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008762 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008763
8764private:
8765 struct SectionInfo {
8766 uint64_t Address;
8767 uint64_t Size;
8768 StringRef SectionName;
8769 StringRef SegmentName;
8770 uint64_t OffsetInSegment;
8771 uint64_t SegmentStartAddress;
8772 uint32_t SegmentIndex;
8773 };
8774 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8775 SmallVector<SectionInfo, 32> Sections;
8776};
8777}
8778
8779SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8780 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008781 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008782 StringRef CurSegName;
8783 uint64_t CurSegAddress;
8784 for (const SectionRef &Section : Obj->sections()) {
8785 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008786 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008787 Info.Address = Section.getAddress();
8788 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008789 Info.SegmentName =
8790 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8791 if (!Info.SegmentName.equals(CurSegName)) {
8792 ++CurSegIndex;
8793 CurSegName = Info.SegmentName;
8794 CurSegAddress = Info.Address;
8795 }
8796 Info.SegmentIndex = CurSegIndex - 1;
8797 Info.OffsetInSegment = Info.Address - CurSegAddress;
8798 Info.SegmentStartAddress = CurSegAddress;
8799 Sections.push_back(Info);
8800 }
8801}
8802
8803StringRef SegInfo::segmentName(uint32_t SegIndex) {
8804 for (const SectionInfo &SI : Sections) {
8805 if (SI.SegmentIndex == SegIndex)
8806 return SI.SegmentName;
8807 }
8808 llvm_unreachable("invalid segIndex");
8809}
8810
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008811bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8812 uint64_t OffsetInSeg) {
8813 for (const SectionInfo &SI : Sections) {
8814 if (SI.SegmentIndex != SegIndex)
8815 continue;
8816 if (SI.OffsetInSegment > OffsetInSeg)
8817 continue;
8818 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8819 continue;
8820 return true;
8821 }
8822 return false;
8823}
8824
Nick Kledzikac431442014-09-12 21:34:15 +00008825const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8826 uint64_t OffsetInSeg) {
8827 for (const SectionInfo &SI : Sections) {
8828 if (SI.SegmentIndex != SegIndex)
8829 continue;
8830 if (SI.OffsetInSegment > OffsetInSeg)
8831 continue;
8832 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8833 continue;
8834 return SI;
8835 }
8836 llvm_unreachable("segIndex and offset not in any section");
8837}
8838
8839StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8840 return findSection(SegIndex, OffsetInSeg).SectionName;
8841}
8842
8843uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8844 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8845 return SI.SegmentStartAddress + OffsetInSeg;
8846}
8847
8848void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8849 // Build table of sections so names can used in final output.
8850 SegInfo sectionTable(Obj);
8851
8852 outs() << "segment section address type\n";
8853 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8854 uint32_t SegIndex = Entry.segmentIndex();
8855 uint64_t OffsetInSeg = Entry.segmentOffset();
8856 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8857 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8858 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8859
8860 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008861 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8862 SegmentName.str().c_str(), SectionName.str().c_str(),
8863 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008864 }
8865}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008866
8867static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8868 StringRef DylibName;
8869 switch (Ordinal) {
8870 case MachO::BIND_SPECIAL_DYLIB_SELF:
8871 return "this-image";
8872 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8873 return "main-executable";
8874 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8875 return "flat-namespace";
8876 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008877 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008878 std::error_code EC =
8879 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008880 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008881 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008882 return DylibName;
8883 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008884 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008885 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008886}
8887
8888//===----------------------------------------------------------------------===//
8889// bind table dumping
8890//===----------------------------------------------------------------------===//
8891
8892void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8893 // Build table of sections so names can used in final output.
8894 SegInfo sectionTable(Obj);
8895
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008896 outs() << "segment section address type "
8897 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008898 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8899 uint32_t SegIndex = Entry.segmentIndex();
8900 uint64_t OffsetInSeg = Entry.segmentOffset();
8901 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8902 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8903 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8904
8905 // Table lines look like:
8906 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008907 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008908 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008909 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008910 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008911 << left_justify(SectionName, 18) << " "
8912 << format_hex(Address, 10, true) << " "
8913 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008914 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008915 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008916 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008917 }
8918}
8919
8920//===----------------------------------------------------------------------===//
8921// lazy bind table dumping
8922//===----------------------------------------------------------------------===//
8923
8924void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8925 // Build table of sections so names can used in final output.
8926 SegInfo sectionTable(Obj);
8927
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008928 outs() << "segment section address "
8929 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008930 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8931 uint32_t SegIndex = Entry.segmentIndex();
8932 uint64_t OffsetInSeg = Entry.segmentOffset();
8933 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8934 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8935 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8936
8937 // Table lines look like:
8938 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008939 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008940 << left_justify(SectionName, 18) << " "
8941 << format_hex(Address, 10, true) << " "
8942 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008943 << Entry.symbolName() << "\n";
8944 }
8945}
8946
Nick Kledzik56ebef42014-09-16 01:41:51 +00008947//===----------------------------------------------------------------------===//
8948// weak bind table dumping
8949//===----------------------------------------------------------------------===//
8950
8951void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8952 // Build table of sections so names can used in final output.
8953 SegInfo sectionTable(Obj);
8954
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008955 outs() << "segment section address "
8956 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008957 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8958 // Strong symbols don't have a location to update.
8959 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008960 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008961 << Entry.symbolName() << "\n";
8962 continue;
8963 }
8964 uint32_t SegIndex = Entry.segmentIndex();
8965 uint64_t OffsetInSeg = Entry.segmentOffset();
8966 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8967 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8968 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8969
8970 // Table lines look like:
8971 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008972 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008973 << left_justify(SectionName, 18) << " "
8974 << format_hex(Address, 10, true) << " "
8975 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008976 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8977 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008978 }
8979}
8980
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008981// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8982// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8983// information for that address. If the address is found its binding symbol
8984// name is returned. If not nullptr is returned.
8985static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8986 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008987 if (info->bindtable == nullptr) {
8988 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008989 SegInfo sectionTable(info->O);
8990 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8991 uint32_t SegIndex = Entry.segmentIndex();
8992 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008993 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8994 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008995 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8996 const char *SymbolName = nullptr;
8997 StringRef name = Entry.symbolName();
8998 if (!name.empty())
8999 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009000 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009001 }
9002 }
Kevin Enderby078be602014-10-23 19:53:12 +00009003 for (bind_table_iterator BI = info->bindtable->begin(),
9004 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009005 BI != BE; ++BI) {
9006 uint64_t Address = BI->first;
9007 if (ReferenceValue == Address) {
9008 const char *SymbolName = BI->second;
9009 return SymbolName;
9010 }
9011 }
9012 return nullptr;
9013}