blob: e13c30bedd18cb532083508fc21461d7acc516ce [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
Mehdi Aminib550cb12016-04-18 09:17:29 +000014#include "llvm/Object/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000016#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/Triple.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000032#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000033#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000036#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000037#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000038#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000040#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
45#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046#include <algorithm>
47#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000048#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000049
50#if HAVE_CXXABI_H
51#include <cxxabi.h>
52#endif
53
Benjamin Kramer43a772e2011-09-19 17:56:04 +000054using namespace llvm;
55using namespace object;
56
57static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000058 UseDbg("g",
59 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000060
Kevin Enderbyb28ed012014-10-29 21:28:24 +000061static cl::opt<std::string> DSYMFile("dsym",
62 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000063
Kevin Enderbyb28ed012014-10-29 21:28:24 +000064static cl::opt<bool> FullLeadingAddr("full-leading-addr",
65 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000066
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000067static cl::opt<bool> NoLeadingAddr("no-leading-addr",
68 cl::desc("Print no leading address"));
69
Kevin Enderby13023a12015-01-15 23:19:11 +000070cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
73
Kevin Enderby131d1772015-01-09 19:22:37 +000074cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000075 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000078
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000079cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000080 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
84
85cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
89
Kevin Enderby69fe98d2015-01-23 18:52:17 +000090cl::opt<bool>
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
94
Kevin Enderby9a509442015-01-27 21:28:24 +000095cl::opt<bool>
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
99
Kevin Enderbycd66be52015-03-11 22:06:32 +0000100cl::opt<bool>
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
104
Kevin Enderbyf0640752015-03-13 17:56:32 +0000105cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
109
110cl::opt<bool>
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
114
115cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
119
Kevin Enderby0fc11822015-04-01 20:57:01 +0000120cl::opt<bool>
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
124
Kevin Enderby6a221752015-03-17 17:10:57 +0000125cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
128
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000129static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
132
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000133static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
135 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137bool ArchAll = false;
138
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139static std::string ThumbTripleName;
140
141static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000144 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000149 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000150 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 }
152
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000153 // Get the target specific parser.
154 std::string Error;
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 return TheTarget;
158
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
160 if (*ThumbTarget)
161 return TheTarget;
162
163 errs() << "llvm-objdump: error: unable to get target for '";
164 if (!TheTarget)
165 errs() << TripleName;
166 else
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000169 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000170}
171
Owen Andersond9243c42011-10-17 21:37:35 +0000172struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000174 ErrorOr<SymbolRef::Type> ATypeOrErr = A.getType();
175 if (std::error_code EC = ATypeOrErr.getError())
176 report_fatal_error(EC.message());
177 SymbolRef::Type AType = *ATypeOrErr;
178 ErrorOr<SymbolRef::Type> BTypeOrErr = B.getType();
179 if (std::error_code EC = BTypeOrErr.getError())
180 report_fatal_error(EC.message());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000181 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000182 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
183 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000184 return AAddr < BAddr;
185 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000186};
187
Kevin Enderby273ae012013-06-06 17:20:50 +0000188// Types for the storted data in code table that is built before disassembly
189// and the predicate function to sort them.
190typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
191typedef std::vector<DiceTableEntry> DiceTable;
192typedef DiceTable::iterator dice_table_iterator;
193
Kevin Enderby930fdc72014-11-06 19:00:13 +0000194// This is used to search for a data in code table entry for the PC being
195// disassembled. The j parameter has the PC in j.first. A single data in code
196// table entry can cover many bytes for each of its Kind's. So if the offset,
197// aka the i.first value, of the data in code table entry plus its Length
198// covers the PC being searched for this will return true. If not it will
199// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000200static bool compareDiceTableEntries(const DiceTableEntry &i,
201 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000202 uint16_t Length;
203 i.second.getLength(Length);
204
205 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000206}
207
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000208static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000209 unsigned short Kind) {
210 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000211
212 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000213 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000214 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000215 if (Length >= 4) {
216 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000217 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000218 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000219 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000220 Size = 4;
221 } else if (Length >= 2) {
222 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000223 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000224 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000225 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 Size = 2;
227 } else {
228 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000229 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000230 Value = bytes[0];
231 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000232 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000234 if (Kind == MachO::DICE_KIND_DATA)
235 outs() << "\t@ KIND_DATA\n";
236 else
237 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000238 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000239 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000242 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
244 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000245 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000246 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000247 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000248 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000249 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 outs() << "\t.short " << format("%5u", Value & 0xffff)
251 << "\t@ KIND_JUMP_TABLE16\n";
252 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000253 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000254 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
256 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000257 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000258 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000259 outs() << "\t.long " << Value;
260 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
261 outs() << "\t@ KIND_JUMP_TABLE32\n";
262 else
263 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
264 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 break;
266 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268}
269
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000270static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000271 std::vector<SectionRef> &Sections,
272 std::vector<SymbolRef> &Symbols,
273 SmallVectorImpl<uint64_t> &FoundFns,
274 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000275 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000276 Expected<StringRef> SymName = Symbol.getName();
277 if (!SymName) {
278 std::string Buf;
279 raw_string_ostream OS(Buf);
280 logAllUnhandledErrors(SymName.takeError(), OS, "");
281 OS.flush();
282 report_fatal_error(Buf);
283 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000284 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000285 Symbols.push_back(Symbol);
286 }
Owen Andersond9243c42011-10-17 21:37:35 +0000287
Alexey Samsonov48803e52014-03-13 14:37:36 +0000288 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000289 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000290 Section.getName(SectName);
291 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000292 }
293
Kevin Enderby273ae012013-06-06 17:20:50 +0000294 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000295 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000296 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000297 // We found a function starts segment, parse the addresses for later
298 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000299 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000300 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000301
Charles Davis8bdfafd2013-09-01 04:28:48 +0000302 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000303 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
304 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000305 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000306 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000307 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000309 }
310 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000311 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000312}
313
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000314static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
315 uint32_t n, uint32_t count,
316 uint32_t stride, uint64_t addr) {
317 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
318 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
319 if (n > nindirectsyms)
320 outs() << " (entries start past the end of the indirect symbol "
321 "table) (reserved1 field greater than the table size)";
322 else if (n + count > nindirectsyms)
323 outs() << " (entries extends past the end of the indirect symbol "
324 "table)";
325 outs() << "\n";
326 uint32_t cputype = O->getHeader().cputype;
327 if (cputype & MachO::CPU_ARCH_ABI64)
328 outs() << "address index";
329 else
330 outs() << "address index";
331 if (verbose)
332 outs() << " name\n";
333 else
334 outs() << "\n";
335 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
336 if (cputype & MachO::CPU_ARCH_ABI64)
337 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
338 else
339 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
340 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
341 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
342 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
343 outs() << "LOCAL\n";
344 continue;
345 }
346 if (indirect_symbol ==
347 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
348 outs() << "LOCAL ABSOLUTE\n";
349 continue;
350 }
351 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
352 outs() << "ABSOLUTE\n";
353 continue;
354 }
355 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000356 if (verbose) {
357 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
358 if (indirect_symbol < Symtab.nsyms) {
359 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
360 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000361 Expected<StringRef> SymName = Symbol.getName();
362 if (!SymName) {
363 std::string Buf;
364 raw_string_ostream OS(Buf);
365 logAllUnhandledErrors(SymName.takeError(), OS, "");
366 OS.flush();
367 report_fatal_error(Buf);
368 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000369 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000370 } else {
371 outs() << "?";
372 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000373 }
374 outs() << "\n";
375 }
376}
377
378static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000379 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000380 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
381 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
382 for (unsigned J = 0; J < Seg.nsects; ++J) {
383 MachO::section_64 Sec = O->getSection64(Load, J);
384 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
385 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
386 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
387 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
388 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
389 section_type == MachO::S_SYMBOL_STUBS) {
390 uint32_t stride;
391 if (section_type == MachO::S_SYMBOL_STUBS)
392 stride = Sec.reserved2;
393 else
394 stride = 8;
395 if (stride == 0) {
396 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
397 << Sec.sectname << ") "
398 << "(size of stubs in reserved2 field is zero)\n";
399 continue;
400 }
401 uint32_t count = Sec.size / stride;
402 outs() << "Indirect symbols for (" << Sec.segname << ","
403 << Sec.sectname << ") " << count << " entries";
404 uint32_t n = Sec.reserved1;
405 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
406 }
407 }
408 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
409 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
410 for (unsigned J = 0; J < Seg.nsects; ++J) {
411 MachO::section Sec = O->getSection(Load, J);
412 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
413 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
414 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
415 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
416 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
417 section_type == MachO::S_SYMBOL_STUBS) {
418 uint32_t stride;
419 if (section_type == MachO::S_SYMBOL_STUBS)
420 stride = Sec.reserved2;
421 else
422 stride = 4;
423 if (stride == 0) {
424 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
425 << Sec.sectname << ") "
426 << "(size of stubs in reserved2 field is zero)\n";
427 continue;
428 }
429 uint32_t count = Sec.size / stride;
430 outs() << "Indirect symbols for (" << Sec.segname << ","
431 << Sec.sectname << ") " << count << " entries";
432 uint32_t n = Sec.reserved1;
433 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
434 }
435 }
436 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000437 }
438}
439
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000440static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
441 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
442 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
443 outs() << "Data in code table (" << nentries << " entries)\n";
444 outs() << "offset length kind\n";
445 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
446 ++DI) {
447 uint32_t Offset;
448 DI->getOffset(Offset);
449 outs() << format("0x%08" PRIx32, Offset) << " ";
450 uint16_t Length;
451 DI->getLength(Length);
452 outs() << format("%6u", Length) << " ";
453 uint16_t Kind;
454 DI->getKind(Kind);
455 if (verbose) {
456 switch (Kind) {
457 case MachO::DICE_KIND_DATA:
458 outs() << "DATA";
459 break;
460 case MachO::DICE_KIND_JUMP_TABLE8:
461 outs() << "JUMP_TABLE8";
462 break;
463 case MachO::DICE_KIND_JUMP_TABLE16:
464 outs() << "JUMP_TABLE16";
465 break;
466 case MachO::DICE_KIND_JUMP_TABLE32:
467 outs() << "JUMP_TABLE32";
468 break;
469 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
470 outs() << "ABS_JUMP_TABLE32";
471 break;
472 default:
473 outs() << format("0x%04" PRIx32, Kind);
474 break;
475 }
476 } else
477 outs() << format("0x%04" PRIx32, Kind);
478 outs() << "\n";
479 }
480}
481
Kevin Enderby9a509442015-01-27 21:28:24 +0000482static void PrintLinkOptHints(MachOObjectFile *O) {
483 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
484 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
485 uint32_t nloh = LohLC.datasize;
486 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
487 for (uint32_t i = 0; i < nloh;) {
488 unsigned n;
489 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
490 i += n;
491 outs() << " identifier " << identifier << " ";
492 if (i >= nloh)
493 return;
494 switch (identifier) {
495 case 1:
496 outs() << "AdrpAdrp\n";
497 break;
498 case 2:
499 outs() << "AdrpLdr\n";
500 break;
501 case 3:
502 outs() << "AdrpAddLdr\n";
503 break;
504 case 4:
505 outs() << "AdrpLdrGotLdr\n";
506 break;
507 case 5:
508 outs() << "AdrpAddStr\n";
509 break;
510 case 6:
511 outs() << "AdrpLdrGotStr\n";
512 break;
513 case 7:
514 outs() << "AdrpAdd\n";
515 break;
516 case 8:
517 outs() << "AdrpLdrGot\n";
518 break;
519 default:
520 outs() << "Unknown identifier value\n";
521 break;
522 }
523 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
524 i += n;
525 outs() << " narguments " << narguments << "\n";
526 if (i >= nloh)
527 return;
528
529 for (uint32_t j = 0; j < narguments; j++) {
530 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
531 i += n;
532 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
533 if (i >= nloh)
534 return;
535 }
536 }
537}
538
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000539static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000540 unsigned Index = 0;
541 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000542 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
543 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
544 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
545 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
546 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
547 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
548 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
549 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
550 if (dl.dylib.name < dl.cmdsize) {
551 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
552 if (JustId)
553 outs() << p << "\n";
554 else {
555 outs() << "\t" << p;
556 outs() << " (compatibility version "
557 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
558 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
559 << (dl.dylib.compatibility_version & 0xff) << ",";
560 outs() << " current version "
561 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
562 << ((dl.dylib.current_version >> 8) & 0xff) << "."
563 << (dl.dylib.current_version & 0xff) << ")\n";
564 }
565 } else {
566 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
567 if (Load.C.cmd == MachO::LC_ID_DYLIB)
568 outs() << "LC_ID_DYLIB ";
569 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
570 outs() << "LC_LOAD_DYLIB ";
571 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
572 outs() << "LC_LOAD_WEAK_DYLIB ";
573 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
574 outs() << "LC_LAZY_LOAD_DYLIB ";
575 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
576 outs() << "LC_REEXPORT_DYLIB ";
577 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
578 outs() << "LC_LOAD_UPWARD_DYLIB ";
579 else
580 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000581 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000582 }
583 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000584 }
585}
586
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000587typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
588
589static void CreateSymbolAddressMap(MachOObjectFile *O,
590 SymbolAddressMap *AddrMap) {
591 // Create a map of symbol addresses to symbol names.
592 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000593 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
594 if (std::error_code EC = STOrErr.getError())
595 report_fatal_error(EC.message());
596 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000597 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
598 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000599 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000600 Expected<StringRef> SymNameOrErr = Symbol.getName();
601 if (!SymNameOrErr) {
602 std::string Buf;
603 raw_string_ostream OS(Buf);
604 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
605 OS.flush();
606 report_fatal_error(Buf);
607 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000608 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000609 if (!SymName.startswith(".objc"))
610 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000611 }
612 }
613}
614
615// GuessSymbolName is passed the address of what might be a symbol and a
616// pointer to the SymbolAddressMap. It returns the name of a symbol
617// with that address or nullptr if no symbol is found with that address.
618static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
619 const char *SymbolName = nullptr;
620 // A DenseMap can't lookup up some values.
621 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
622 StringRef name = AddrMap->lookup(value);
623 if (!name.empty())
624 SymbolName = name.data();
625 }
626 return SymbolName;
627}
628
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000629static void DumpCstringChar(const char c) {
630 char p[2];
631 p[0] = c;
632 p[1] = '\0';
633 outs().write_escaped(p);
634}
635
Kevin Enderby10ba0412015-02-04 21:38:42 +0000636static void DumpCstringSection(MachOObjectFile *O, const char *sect,
637 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000638 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000639 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000640 if (print_addresses) {
641 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000642 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000643 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000644 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000645 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000646 for (; i < sect_size && sect[i] != '\0'; i++)
647 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000648 if (i < sect_size && sect[i] == '\0')
649 outs() << "\n";
650 }
651}
652
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000653static void DumpLiteral4(uint32_t l, float f) {
654 outs() << format("0x%08" PRIx32, l);
655 if ((l & 0x7f800000) != 0x7f800000)
656 outs() << format(" (%.16e)\n", f);
657 else {
658 if (l == 0x7f800000)
659 outs() << " (+Infinity)\n";
660 else if (l == 0xff800000)
661 outs() << " (-Infinity)\n";
662 else if ((l & 0x00400000) == 0x00400000)
663 outs() << " (non-signaling Not-a-Number)\n";
664 else
665 outs() << " (signaling Not-a-Number)\n";
666 }
667}
668
669static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
670 uint32_t sect_size, uint64_t sect_addr,
671 bool print_addresses) {
672 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
673 if (print_addresses) {
674 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000675 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000676 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000677 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000678 }
679 float f;
680 memcpy(&f, sect + i, sizeof(float));
681 if (O->isLittleEndian() != sys::IsLittleEndianHost)
682 sys::swapByteOrder(f);
683 uint32_t l;
684 memcpy(&l, sect + i, sizeof(uint32_t));
685 if (O->isLittleEndian() != sys::IsLittleEndianHost)
686 sys::swapByteOrder(l);
687 DumpLiteral4(l, f);
688 }
689}
690
691static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
692 double d) {
693 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
694 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000695 Hi = (O->isLittleEndian()) ? l1 : l0;
696 Lo = (O->isLittleEndian()) ? l0 : l1;
697
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000698 // Hi is the high word, so this is equivalent to if(isfinite(d))
699 if ((Hi & 0x7ff00000) != 0x7ff00000)
700 outs() << format(" (%.16e)\n", d);
701 else {
702 if (Hi == 0x7ff00000 && Lo == 0)
703 outs() << " (+Infinity)\n";
704 else if (Hi == 0xfff00000 && Lo == 0)
705 outs() << " (-Infinity)\n";
706 else if ((Hi & 0x00080000) == 0x00080000)
707 outs() << " (non-signaling Not-a-Number)\n";
708 else
709 outs() << " (signaling Not-a-Number)\n";
710 }
711}
712
713static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
714 uint32_t sect_size, uint64_t sect_addr,
715 bool print_addresses) {
716 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
717 if (print_addresses) {
718 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000719 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000720 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000721 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000722 }
723 double d;
724 memcpy(&d, sect + i, sizeof(double));
725 if (O->isLittleEndian() != sys::IsLittleEndianHost)
726 sys::swapByteOrder(d);
727 uint32_t l0, l1;
728 memcpy(&l0, sect + i, sizeof(uint32_t));
729 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
730 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
731 sys::swapByteOrder(l0);
732 sys::swapByteOrder(l1);
733 }
734 DumpLiteral8(O, l0, l1, d);
735 }
736}
737
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000738static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
739 outs() << format("0x%08" PRIx32, l0) << " ";
740 outs() << format("0x%08" PRIx32, l1) << " ";
741 outs() << format("0x%08" PRIx32, l2) << " ";
742 outs() << format("0x%08" PRIx32, l3) << "\n";
743}
744
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000745static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
746 uint32_t sect_size, uint64_t sect_addr,
747 bool print_addresses) {
748 for (uint32_t i = 0; i < sect_size; i += 16) {
749 if (print_addresses) {
750 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000751 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000752 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000753 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000754 }
755 uint32_t l0, l1, l2, l3;
756 memcpy(&l0, sect + i, sizeof(uint32_t));
757 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
758 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
759 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
760 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
761 sys::swapByteOrder(l0);
762 sys::swapByteOrder(l1);
763 sys::swapByteOrder(l2);
764 sys::swapByteOrder(l3);
765 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000766 DumpLiteral16(l0, l1, l2, l3);
767 }
768}
769
770static void DumpLiteralPointerSection(MachOObjectFile *O,
771 const SectionRef &Section,
772 const char *sect, uint32_t sect_size,
773 uint64_t sect_addr,
774 bool print_addresses) {
775 // Collect the literal sections in this Mach-O file.
776 std::vector<SectionRef> LiteralSections;
777 for (const SectionRef &Section : O->sections()) {
778 DataRefImpl Ref = Section.getRawDataRefImpl();
779 uint32_t section_type;
780 if (O->is64Bit()) {
781 const MachO::section_64 Sec = O->getSection64(Ref);
782 section_type = Sec.flags & MachO::SECTION_TYPE;
783 } else {
784 const MachO::section Sec = O->getSection(Ref);
785 section_type = Sec.flags & MachO::SECTION_TYPE;
786 }
787 if (section_type == MachO::S_CSTRING_LITERALS ||
788 section_type == MachO::S_4BYTE_LITERALS ||
789 section_type == MachO::S_8BYTE_LITERALS ||
790 section_type == MachO::S_16BYTE_LITERALS)
791 LiteralSections.push_back(Section);
792 }
793
794 // Set the size of the literal pointer.
795 uint32_t lp_size = O->is64Bit() ? 8 : 4;
796
Eric Christopher572e03a2015-06-19 01:53:21 +0000797 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000798 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
799 for (const RelocationRef &Reloc : Section.relocations()) {
800 DataRefImpl Rel;
801 MachO::any_relocation_info RE;
802 bool isExtern = false;
803 Rel = Reloc.getRawDataRefImpl();
804 RE = O->getRelocation(Rel);
805 isExtern = O->getPlainRelocationExternal(RE);
806 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000807 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000808 symbol_iterator RelocSym = Reloc.getSymbol();
809 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
810 }
811 }
812 array_pod_sort(Relocs.begin(), Relocs.end());
813
814 // Dump each literal pointer.
815 for (uint32_t i = 0; i < sect_size; i += lp_size) {
816 if (print_addresses) {
817 if (O->is64Bit())
818 outs() << format("%016" PRIx64, sect_addr + i) << " ";
819 else
820 outs() << format("%08" PRIx64, sect_addr + i) << " ";
821 }
822 uint64_t lp;
823 if (O->is64Bit()) {
824 memcpy(&lp, sect + i, sizeof(uint64_t));
825 if (O->isLittleEndian() != sys::IsLittleEndianHost)
826 sys::swapByteOrder(lp);
827 } else {
828 uint32_t li;
829 memcpy(&li, sect + i, sizeof(uint32_t));
830 if (O->isLittleEndian() != sys::IsLittleEndianHost)
831 sys::swapByteOrder(li);
832 lp = li;
833 }
834
835 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000836 auto Reloc = std::find_if(
837 Relocs.begin(), Relocs.end(),
838 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
839 if (Reloc != Relocs.end()) {
840 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000841 Expected<StringRef> SymName = RelocSym->getName();
842 if (!SymName) {
843 std::string Buf;
844 raw_string_ostream OS(Buf);
845 logAllUnhandledErrors(SymName.takeError(), OS, "");
846 OS.flush();
847 report_fatal_error(Buf);
848 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000849 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000850 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000851 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000852
853 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000854 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
855 [&](const SectionRef &R) {
856 return lp >= R.getAddress() &&
857 lp < R.getAddress() + R.getSize();
858 });
859 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000860 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000861 continue;
862 }
863
864 uint64_t SectAddress = Sect->getAddress();
865 uint64_t SectSize = Sect->getSize();
866
867 StringRef SectName;
868 Sect->getName(SectName);
869 DataRefImpl Ref = Sect->getRawDataRefImpl();
870 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
871 outs() << SegmentName << ":" << SectName << ":";
872
873 uint32_t section_type;
874 if (O->is64Bit()) {
875 const MachO::section_64 Sec = O->getSection64(Ref);
876 section_type = Sec.flags & MachO::SECTION_TYPE;
877 } else {
878 const MachO::section Sec = O->getSection(Ref);
879 section_type = Sec.flags & MachO::SECTION_TYPE;
880 }
881
882 StringRef BytesStr;
883 Sect->getContents(BytesStr);
884 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
885
886 switch (section_type) {
887 case MachO::S_CSTRING_LITERALS:
888 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
889 i++) {
890 DumpCstringChar(Contents[i]);
891 }
892 outs() << "\n";
893 break;
894 case MachO::S_4BYTE_LITERALS:
895 float f;
896 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
897 uint32_t l;
898 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(f);
901 sys::swapByteOrder(l);
902 }
903 DumpLiteral4(l, f);
904 break;
905 case MachO::S_8BYTE_LITERALS: {
906 double d;
907 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
908 uint32_t l0, l1;
909 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
910 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
911 sizeof(uint32_t));
912 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
913 sys::swapByteOrder(f);
914 sys::swapByteOrder(l0);
915 sys::swapByteOrder(l1);
916 }
917 DumpLiteral8(O, l0, l1, d);
918 break;
919 }
920 case MachO::S_16BYTE_LITERALS: {
921 uint32_t l0, l1, l2, l3;
922 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
923 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
924 sizeof(uint32_t));
925 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
926 sizeof(uint32_t));
927 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
928 sizeof(uint32_t));
929 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
930 sys::swapByteOrder(l0);
931 sys::swapByteOrder(l1);
932 sys::swapByteOrder(l2);
933 sys::swapByteOrder(l3);
934 }
935 DumpLiteral16(l0, l1, l2, l3);
936 break;
937 }
938 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000939 }
940}
941
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000942static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
943 uint32_t sect_size, uint64_t sect_addr,
944 SymbolAddressMap *AddrMap,
945 bool verbose) {
946 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000947 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000948 for (uint32_t i = 0; i < sect_size; i += stride) {
949 const char *SymbolName = nullptr;
950 if (O->is64Bit()) {
951 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
952 uint64_t pointer_value;
953 memcpy(&pointer_value, sect + i, stride);
954 if (O->isLittleEndian() != sys::IsLittleEndianHost)
955 sys::swapByteOrder(pointer_value);
956 outs() << format("0x%016" PRIx64, pointer_value);
957 if (verbose)
958 SymbolName = GuessSymbolName(pointer_value, AddrMap);
959 } else {
960 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
961 uint32_t pointer_value;
962 memcpy(&pointer_value, sect + i, stride);
963 if (O->isLittleEndian() != sys::IsLittleEndianHost)
964 sys::swapByteOrder(pointer_value);
965 outs() << format("0x%08" PRIx32, pointer_value);
966 if (verbose)
967 SymbolName = GuessSymbolName(pointer_value, AddrMap);
968 }
969 if (SymbolName)
970 outs() << " " << SymbolName;
971 outs() << "\n";
972 }
973}
974
975static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
976 uint32_t size, uint64_t addr) {
977 uint32_t cputype = O->getHeader().cputype;
978 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
979 uint32_t j;
980 for (uint32_t i = 0; i < size; i += j, addr += j) {
981 if (O->is64Bit())
982 outs() << format("%016" PRIx64, addr) << "\t";
983 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000984 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000985 for (j = 0; j < 16 && i + j < size; j++) {
986 uint8_t byte_word = *(sect + i + j);
987 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
988 }
989 outs() << "\n";
990 }
991 } else {
992 uint32_t j;
993 for (uint32_t i = 0; i < size; i += j, addr += j) {
994 if (O->is64Bit())
995 outs() << format("%016" PRIx64, addr) << "\t";
996 else
997 outs() << format("%08" PRIx64, sect) << "\t";
998 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
999 j += sizeof(int32_t)) {
1000 if (i + j + sizeof(int32_t) < size) {
1001 uint32_t long_word;
1002 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1003 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1004 sys::swapByteOrder(long_word);
1005 outs() << format("%08" PRIx32, long_word) << " ";
1006 } else {
1007 for (uint32_t k = 0; i + j + k < size; k++) {
1008 uint8_t byte_word = *(sect + i + j);
1009 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1010 }
1011 }
1012 }
1013 outs() << "\n";
1014 }
1015 }
1016}
1017
Kevin Enderby95df54c2015-02-04 01:01:38 +00001018static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1019 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001020static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1021 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001022
1023static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1024 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001025 SymbolAddressMap AddrMap;
1026 if (verbose)
1027 CreateSymbolAddressMap(O, &AddrMap);
1028
Colin LeMahieufcc32762015-07-29 19:08:10 +00001029 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1030 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001031 std::pair<StringRef, StringRef> DumpSegSectName;
1032 DumpSegSectName = DumpSection.split(',');
1033 StringRef DumpSegName, DumpSectName;
1034 if (DumpSegSectName.second.size()) {
1035 DumpSegName = DumpSegSectName.first;
1036 DumpSectName = DumpSegSectName.second;
1037 } else {
1038 DumpSegName = "";
1039 DumpSectName = DumpSegSectName.first;
1040 }
1041 for (const SectionRef &Section : O->sections()) {
1042 StringRef SectName;
1043 Section.getName(SectName);
1044 DataRefImpl Ref = Section.getRawDataRefImpl();
1045 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1046 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1047 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001048
Kevin Enderby95df54c2015-02-04 01:01:38 +00001049 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001050 if (O->is64Bit()) {
1051 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001052 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001053
1054 } else {
1055 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001056 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001057 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001058 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001059
1060 StringRef BytesStr;
1061 Section.getContents(BytesStr);
1062 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1063 uint32_t sect_size = BytesStr.size();
1064 uint64_t sect_addr = Section.getAddress();
1065
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001066 outs() << "Contents of (" << SegName << "," << SectName
1067 << ") section\n";
1068
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001069 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001070 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1071 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1072 DisassembleMachO(Filename, O, SegName, SectName);
1073 continue;
1074 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001075 if (SegName == "__TEXT" && SectName == "__info_plist") {
1076 outs() << sect;
1077 continue;
1078 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001079 if (SegName == "__OBJC" && SectName == "__protocol") {
1080 DumpProtocolSection(O, sect, sect_size, sect_addr);
1081 continue;
1082 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001083 switch (section_type) {
1084 case MachO::S_REGULAR:
1085 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1086 break;
1087 case MachO::S_ZEROFILL:
1088 outs() << "zerofill section and has no contents in the file\n";
1089 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001090 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001091 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001092 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001093 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001094 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001095 break;
1096 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001097 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001098 break;
1099 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001100 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1101 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001102 case MachO::S_LITERAL_POINTERS:
1103 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001104 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001105 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001106 case MachO::S_MOD_INIT_FUNC_POINTERS:
1107 case MachO::S_MOD_TERM_FUNC_POINTERS:
1108 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1109 verbose);
1110 break;
1111 default:
1112 outs() << "Unknown section type ("
1113 << format("0x%08" PRIx32, section_type) << ")\n";
1114 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1115 break;
1116 }
1117 } else {
1118 if (section_type == MachO::S_ZEROFILL)
1119 outs() << "zerofill section and has no contents in the file\n";
1120 else
1121 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1122 }
1123 }
1124 }
1125 }
1126}
1127
Kevin Enderbycd66be52015-03-11 22:06:32 +00001128static void DumpInfoPlistSectionContents(StringRef Filename,
1129 MachOObjectFile *O) {
1130 for (const SectionRef &Section : O->sections()) {
1131 StringRef SectName;
1132 Section.getName(SectName);
1133 DataRefImpl Ref = Section.getRawDataRefImpl();
1134 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1135 if (SegName == "__TEXT" && SectName == "__info_plist") {
1136 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1137 StringRef BytesStr;
1138 Section.getContents(BytesStr);
1139 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1140 outs() << sect;
1141 return;
1142 }
1143 }
1144}
1145
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001146// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1147// and if it is and there is a list of architecture flags is specified then
1148// check to make sure this Mach-O file is one of those architectures or all
1149// architectures were specified. If not then an error is generated and this
1150// routine returns false. Else it returns true.
1151static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1152 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1153 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1154 bool ArchFound = false;
1155 MachO::mach_header H;
1156 MachO::mach_header_64 H_64;
1157 Triple T;
1158 if (MachO->is64Bit()) {
1159 H_64 = MachO->MachOObjectFile::getHeader64();
1160 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1161 } else {
1162 H = MachO->MachOObjectFile::getHeader();
1163 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1164 }
1165 unsigned i;
1166 for (i = 0; i < ArchFlags.size(); ++i) {
1167 if (ArchFlags[i] == T.getArchName())
1168 ArchFound = true;
1169 break;
1170 }
1171 if (!ArchFound) {
1172 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1173 << "architecture: " + ArchFlags[i] + "\n";
1174 return false;
1175 }
1176 }
1177 return true;
1178}
1179
Kevin Enderby0fc11822015-04-01 20:57:01 +00001180static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1181
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001182// ProcessMachO() is passed a single opened Mach-O file, which may be an
1183// archive member and or in a slice of a universal file. It prints the
1184// the file name and header info and then processes it according to the
1185// command line options.
1186static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1187 StringRef ArchiveMemberName = StringRef(),
1188 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001189 // If we are doing some processing here on the Mach-O file print the header
1190 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001191 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001192 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001193 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001194 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001195 outs() << Filename;
1196 if (!ArchiveMemberName.empty())
1197 outs() << '(' << ArchiveMemberName << ')';
1198 if (!ArchitectureName.empty())
1199 outs() << " (architecture " << ArchitectureName << ")";
1200 outs() << ":\n";
1201 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001202
1203 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001204 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001205 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001206 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001207 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001208 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001209 if (LinkOptHints)
1210 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001211 if (Relocations)
1212 PrintRelocations(MachOOF);
1213 if (SectionHeaders)
1214 PrintSectionHeaders(MachOOF);
1215 if (SectionContents)
1216 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001217 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001218 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001219 if (InfoPlist)
1220 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001221 if (DylibsUsed)
1222 PrintDylibs(MachOOF, false);
1223 if (DylibId)
1224 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001225 if (SymbolTable)
1226 PrintSymbolTable(MachOOF);
1227 if (UnwindInfo)
1228 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001229 if (PrivateHeaders) {
1230 printMachOFileHeader(MachOOF);
1231 printMachOLoadCommands(MachOOF);
1232 }
1233 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001234 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001235 if (ObjcMetaData)
1236 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001237 if (ExportsTrie)
1238 printExportsTrie(MachOOF);
1239 if (Rebase)
1240 printRebaseTable(MachOOF);
1241 if (Bind)
1242 printBindTable(MachOOF);
1243 if (LazyBind)
1244 printLazyBindTable(MachOOF);
1245 if (WeakBind)
1246 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001247
1248 if (DwarfDumpType != DIDT_Null) {
1249 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1250 // Dump the complete DWARF structure.
1251 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1252 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001253}
1254
Kevin Enderby131d1772015-01-09 19:22:37 +00001255// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1256static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1257 outs() << " cputype (" << cputype << ")\n";
1258 outs() << " cpusubtype (" << cpusubtype << ")\n";
1259}
1260
1261// printCPUType() helps print_fat_headers by printing the cputype and
1262// pusubtype (symbolically for the one's it knows about).
1263static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1264 switch (cputype) {
1265 case MachO::CPU_TYPE_I386:
1266 switch (cpusubtype) {
1267 case MachO::CPU_SUBTYPE_I386_ALL:
1268 outs() << " cputype CPU_TYPE_I386\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1270 break;
1271 default:
1272 printUnknownCPUType(cputype, cpusubtype);
1273 break;
1274 }
1275 break;
1276 case MachO::CPU_TYPE_X86_64:
1277 switch (cpusubtype) {
1278 case MachO::CPU_SUBTYPE_X86_64_ALL:
1279 outs() << " cputype CPU_TYPE_X86_64\n";
1280 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1281 break;
1282 case MachO::CPU_SUBTYPE_X86_64_H:
1283 outs() << " cputype CPU_TYPE_X86_64\n";
1284 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1285 break;
1286 default:
1287 printUnknownCPUType(cputype, cpusubtype);
1288 break;
1289 }
1290 break;
1291 case MachO::CPU_TYPE_ARM:
1292 switch (cpusubtype) {
1293 case MachO::CPU_SUBTYPE_ARM_ALL:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1296 break;
1297 case MachO::CPU_SUBTYPE_ARM_V4T:
1298 outs() << " cputype CPU_TYPE_ARM\n";
1299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1300 break;
1301 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1302 outs() << " cputype CPU_TYPE_ARM\n";
1303 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1304 break;
1305 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1306 outs() << " cputype CPU_TYPE_ARM\n";
1307 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1308 break;
1309 case MachO::CPU_SUBTYPE_ARM_V6:
1310 outs() << " cputype CPU_TYPE_ARM\n";
1311 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1312 break;
1313 case MachO::CPU_SUBTYPE_ARM_V6M:
1314 outs() << " cputype CPU_TYPE_ARM\n";
1315 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1316 break;
1317 case MachO::CPU_SUBTYPE_ARM_V7:
1318 outs() << " cputype CPU_TYPE_ARM\n";
1319 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1320 break;
1321 case MachO::CPU_SUBTYPE_ARM_V7EM:
1322 outs() << " cputype CPU_TYPE_ARM\n";
1323 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1324 break;
1325 case MachO::CPU_SUBTYPE_ARM_V7K:
1326 outs() << " cputype CPU_TYPE_ARM\n";
1327 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1328 break;
1329 case MachO::CPU_SUBTYPE_ARM_V7M:
1330 outs() << " cputype CPU_TYPE_ARM\n";
1331 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1332 break;
1333 case MachO::CPU_SUBTYPE_ARM_V7S:
1334 outs() << " cputype CPU_TYPE_ARM\n";
1335 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1336 break;
1337 default:
1338 printUnknownCPUType(cputype, cpusubtype);
1339 break;
1340 }
1341 break;
1342 case MachO::CPU_TYPE_ARM64:
1343 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1344 case MachO::CPU_SUBTYPE_ARM64_ALL:
1345 outs() << " cputype CPU_TYPE_ARM64\n";
1346 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1347 break;
1348 default:
1349 printUnknownCPUType(cputype, cpusubtype);
1350 break;
1351 }
1352 break;
1353 default:
1354 printUnknownCPUType(cputype, cpusubtype);
1355 break;
1356 }
1357}
1358
1359static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1360 bool verbose) {
1361 outs() << "Fat headers\n";
1362 if (verbose)
1363 outs() << "fat_magic FAT_MAGIC\n";
1364 else
1365 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1366
1367 uint32_t nfat_arch = UB->getNumberOfObjects();
1368 StringRef Buf = UB->getData();
1369 uint64_t size = Buf.size();
1370 uint64_t big_size = sizeof(struct MachO::fat_header) +
1371 nfat_arch * sizeof(struct MachO::fat_arch);
1372 outs() << "nfat_arch " << UB->getNumberOfObjects();
1373 if (nfat_arch == 0)
1374 outs() << " (malformed, contains zero architecture types)\n";
1375 else if (big_size > size)
1376 outs() << " (malformed, architectures past end of file)\n";
1377 else
1378 outs() << "\n";
1379
1380 for (uint32_t i = 0; i < nfat_arch; ++i) {
1381 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1382 uint32_t cputype = OFA.getCPUType();
1383 uint32_t cpusubtype = OFA.getCPUSubType();
1384 outs() << "architecture ";
1385 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1386 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1387 uint32_t other_cputype = other_OFA.getCPUType();
1388 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001389 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001390 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001391 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001392 outs() << "(illegal duplicate architecture) ";
1393 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001394 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001395 }
1396 if (verbose) {
1397 outs() << OFA.getArchTypeName() << "\n";
1398 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1399 } else {
1400 outs() << i << "\n";
1401 outs() << " cputype " << cputype << "\n";
1402 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1403 << "\n";
1404 }
1405 if (verbose &&
1406 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1407 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1408 else
1409 outs() << " capabilities "
1410 << format("0x%" PRIx32,
1411 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1412 outs() << " offset " << OFA.getOffset();
1413 if (OFA.getOffset() > size)
1414 outs() << " (past end of file)";
1415 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1416 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1417 outs() << "\n";
1418 outs() << " size " << OFA.getSize();
1419 big_size = OFA.getOffset() + OFA.getSize();
1420 if (big_size > size)
1421 outs() << " (past end of file)";
1422 outs() << "\n";
1423 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1424 << ")\n";
1425 }
1426}
1427
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001428static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001429 bool print_offset) {
1430 if (print_offset)
1431 outs() << C.getChildOffset() << "\t";
1432 sys::fs::perms Mode = C.getAccessMode();
1433 if (verbose) {
1434 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1435 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1436 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001437 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1438 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1439 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1440 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1441 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1442 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1443 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1444 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1445 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001446 } else {
1447 outs() << format("0%o ", Mode);
1448 }
1449
1450 unsigned UID = C.getUID();
1451 outs() << format("%3d/", UID);
1452 unsigned GID = C.getGID();
1453 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001454 ErrorOr<uint64_t> Size = C.getRawSize();
1455 if (std::error_code EC = Size.getError())
1456 report_fatal_error(EC.message());
1457 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001458
1459 StringRef RawLastModified = C.getRawLastModified();
1460 if (verbose) {
1461 unsigned Seconds;
1462 if (RawLastModified.getAsInteger(10, Seconds))
1463 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1464 else {
1465 // Since cime(3) returns a 26 character string of the form:
1466 // "Sun Sep 16 01:03:52 1973\n\0"
1467 // just print 24 characters.
1468 time_t t = Seconds;
1469 outs() << format("%.24s ", ctime(&t));
1470 }
1471 } else {
1472 outs() << RawLastModified << " ";
1473 }
1474
1475 if (verbose) {
1476 ErrorOr<StringRef> NameOrErr = C.getName();
1477 if (NameOrErr.getError()) {
1478 StringRef RawName = C.getRawName();
1479 outs() << RawName << "\n";
1480 } else {
1481 StringRef Name = NameOrErr.get();
1482 outs() << Name << "\n";
1483 }
1484 } else {
1485 StringRef RawName = C.getRawName();
1486 outs() << RawName << "\n";
1487 }
1488}
1489
1490static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001491 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1492 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001493 if (std::error_code EC = I->getError())
1494 report_fatal_error(EC.message());
1495 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001496 printArchiveChild(C, verbose, print_offset);
1497 }
1498}
1499
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001500// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1501// -arch flags selecting just those slices as specified by them and also parses
1502// archive files. Then for each individual Mach-O file ProcessMachO() is
1503// called to process the file based on the command line options.
1504void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001505 // Check for -arch all and verifiy the -arch flags are valid.
1506 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1507 if (ArchFlags[i] == "all") {
1508 ArchAll = true;
1509 } else {
1510 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1511 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1512 "'for the -arch option\n";
1513 return;
1514 }
1515 }
1516 }
1517
1518 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001519 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1520 if (!BinaryOrErr)
1521 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001522 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001523
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001524 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1525 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001526 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001527 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001528 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1529 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001530 if (std::error_code EC = I->getError())
1531 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001532 auto &C = I->get();
1533 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001534 if (ChildOrErr.getError())
1535 continue;
1536 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1537 if (!checkMachOAndArchFlags(O, Filename))
1538 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001539 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001540 }
1541 }
1542 return;
1543 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001544 if (UniversalHeaders) {
1545 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001546 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001547 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001548 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1549 // If we have a list of architecture flags specified dump only those.
1550 if (!ArchAll && ArchFlags.size() != 0) {
1551 // Look for a slice in the universal binary that matches each ArchFlag.
1552 bool ArchFound;
1553 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1554 ArchFound = false;
1555 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1556 E = UB->end_objects();
1557 I != E; ++I) {
1558 if (ArchFlags[i] == I->getArchTypeName()) {
1559 ArchFound = true;
1560 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1561 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001562 std::string ArchitectureName = "";
1563 if (ArchFlags.size() > 1)
1564 ArchitectureName = I->getArchTypeName();
1565 if (ObjOrErr) {
1566 ObjectFile &O = *ObjOrErr.get();
1567 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001568 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001569 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1570 I->getAsArchive()) {
1571 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001572 outs() << "Archive : " << Filename;
1573 if (!ArchitectureName.empty())
1574 outs() << " (architecture " << ArchitectureName << ")";
1575 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001576 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001577 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001578 for (Archive::child_iterator AI = A->child_begin(),
1579 AE = A->child_end();
1580 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001581 if (std::error_code EC = AI->getError())
1582 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001583 auto &C = AI->get();
1584 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001585 if (ChildOrErr.getError())
1586 continue;
1587 if (MachOObjectFile *O =
1588 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001589 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001590 }
1591 }
1592 }
1593 }
1594 if (!ArchFound) {
1595 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1596 << "architecture: " + ArchFlags[i] + "\n";
1597 return;
1598 }
1599 }
1600 return;
1601 }
1602 // No architecture flags were specified so if this contains a slice that
1603 // matches the host architecture dump only that.
1604 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1606 E = UB->end_objects();
1607 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001608 if (MachOObjectFile::getHostArch().getArchName() ==
1609 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001610 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001611 std::string ArchiveName;
1612 ArchiveName.clear();
1613 if (ObjOrErr) {
1614 ObjectFile &O = *ObjOrErr.get();
1615 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001616 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001617 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1618 I->getAsArchive()) {
1619 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001620 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001621 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001622 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001623 for (Archive::child_iterator AI = A->child_begin(),
1624 AE = A->child_end();
1625 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001626 if (std::error_code EC = AI->getError())
1627 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001628 auto &C = AI->get();
1629 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001630 if (ChildOrErr.getError())
1631 continue;
1632 if (MachOObjectFile *O =
1633 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001634 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 }
1636 }
1637 return;
1638 }
1639 }
1640 }
1641 // Either all architectures have been specified or none have been specified
1642 // and this does not contain the host architecture so dump all the slices.
1643 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1644 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1645 E = UB->end_objects();
1646 I != E; ++I) {
1647 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001648 std::string ArchitectureName = "";
1649 if (moreThanOneArch)
1650 ArchitectureName = I->getArchTypeName();
1651 if (ObjOrErr) {
1652 ObjectFile &Obj = *ObjOrErr.get();
1653 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001655 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1656 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001657 outs() << "Archive : " << Filename;
1658 if (!ArchitectureName.empty())
1659 outs() << " (architecture " << ArchitectureName << ")";
1660 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001661 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001662 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001663 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1664 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001665 if (std::error_code EC = AI->getError())
1666 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001667 auto &C = AI->get();
1668 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001669 if (ChildOrErr.getError())
1670 continue;
1671 if (MachOObjectFile *O =
1672 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1673 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001674 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1675 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001676 }
1677 }
1678 }
1679 }
1680 return;
1681 }
1682 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1683 if (!checkMachOAndArchFlags(O, Filename))
1684 return;
1685 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001686 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001687 } else
1688 errs() << "llvm-objdump: '" << Filename << "': "
1689 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001690 return;
1691 }
1692 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001693}
1694
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001695typedef std::pair<uint64_t, const char *> BindInfoEntry;
1696typedef std::vector<BindInfoEntry> BindTable;
1697typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001698
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001699// The block of info used by the Symbolizer call backs.
1700struct DisassembleInfo {
1701 bool verbose;
1702 MachOObjectFile *O;
1703 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001704 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001705 std::vector<SectionRef> *Sections;
1706 const char *class_name;
1707 const char *selector_name;
1708 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001709 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001710 uint64_t adrp_addr;
1711 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001712 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001713 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001714};
1715
1716// SymbolizerGetOpInfo() is the operand information call back function.
1717// This is called to get the symbolic information for operand(s) of an
1718// instruction when it is being done. This routine does this from
1719// the relocation information, symbol table, etc. That block of information
1720// is a pointer to the struct DisassembleInfo that was passed when the
1721// disassembler context was created and passed to back to here when
1722// called back by the disassembler for instruction operands that could have
1723// relocation information. The address of the instruction containing operand is
1724// at the Pc parameter. The immediate value the operand has is passed in
1725// op_info->Value and is at Offset past the start of the instruction and has a
1726// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1727// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1728// names and addends of the symbolic expression to add for the operand. The
1729// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1730// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001731static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1732 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001733 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1734 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001735 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001736
1737 // Make sure all fields returned are zero if we don't set them.
1738 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1739 op_info->Value = value;
1740
1741 // If the TagType is not the value 1 which it code knows about or if no
1742 // verbose symbolic information is wanted then just return 0, indicating no
1743 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001744 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001745 return 0;
1746
1747 unsigned int Arch = info->O->getArch();
1748 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001749 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1750 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001751 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1752 // TODO:
1753 // Search the external relocation entries of a fully linked image
1754 // (if any) for an entry that matches this segment offset.
1755 // uint32_t seg_offset = (Pc + Offset);
1756 return 0;
1757 }
1758 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1759 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001760 uint32_t sect_addr = info->S.getAddress();
1761 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1762 bool reloc_found = false;
1763 DataRefImpl Rel;
1764 MachO::any_relocation_info RE;
1765 bool isExtern = false;
1766 SymbolRef Symbol;
1767 bool r_scattered = false;
1768 uint32_t r_value, pair_r_value, r_type;
1769 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001770 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001771 if (RelocOffset == sect_offset) {
1772 Rel = Reloc.getRawDataRefImpl();
1773 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001774 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001775 r_scattered = info->O->isRelocationScattered(RE);
1776 if (r_scattered) {
1777 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001778 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1779 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1780 DataRefImpl RelNext = Rel;
1781 info->O->moveRelocationNext(RelNext);
1782 MachO::any_relocation_info RENext;
1783 RENext = info->O->getRelocation(RelNext);
1784 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001785 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001786 else
1787 return 0;
1788 }
1789 } else {
1790 isExtern = info->O->getPlainRelocationExternal(RE);
1791 if (isExtern) {
1792 symbol_iterator RelocSym = Reloc.getSymbol();
1793 Symbol = *RelocSym;
1794 }
1795 }
1796 reloc_found = true;
1797 break;
1798 }
1799 }
1800 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001801 Expected<StringRef> SymName = Symbol.getName();
1802 if (!SymName) {
1803 std::string Buf;
1804 raw_string_ostream OS(Buf);
1805 logAllUnhandledErrors(SymName.takeError(), OS, "");
1806 OS.flush();
1807 report_fatal_error(Buf);
1808 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001809 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001810 op_info->AddSymbol.Present = 1;
1811 op_info->AddSymbol.Name = name;
1812 // For i386 extern relocation entries the value in the instruction is
1813 // the offset from the symbol, and value is already set in op_info->Value.
1814 return 1;
1815 }
1816 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1817 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001818 const char *add = GuessSymbolName(r_value, info->AddrMap);
1819 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001820 uint32_t offset = value - (r_value - pair_r_value);
1821 op_info->AddSymbol.Present = 1;
1822 if (add != nullptr)
1823 op_info->AddSymbol.Name = add;
1824 else
1825 op_info->AddSymbol.Value = r_value;
1826 op_info->SubtractSymbol.Present = 1;
1827 if (sub != nullptr)
1828 op_info->SubtractSymbol.Name = sub;
1829 else
1830 op_info->SubtractSymbol.Value = pair_r_value;
1831 op_info->Value = offset;
1832 return 1;
1833 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001834 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001835 }
1836 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001837 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1838 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001839 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1840 // TODO:
1841 // Search the external relocation entries of a fully linked image
1842 // (if any) for an entry that matches this segment offset.
1843 // uint64_t seg_offset = (Pc + Offset);
1844 return 0;
1845 }
1846 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1847 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001848 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001849 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1850 bool reloc_found = false;
1851 DataRefImpl Rel;
1852 MachO::any_relocation_info RE;
1853 bool isExtern = false;
1854 SymbolRef Symbol;
1855 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001856 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001857 if (RelocOffset == sect_offset) {
1858 Rel = Reloc.getRawDataRefImpl();
1859 RE = info->O->getRelocation(Rel);
1860 // NOTE: Scattered relocations don't exist on x86_64.
1861 isExtern = info->O->getPlainRelocationExternal(RE);
1862 if (isExtern) {
1863 symbol_iterator RelocSym = Reloc.getSymbol();
1864 Symbol = *RelocSym;
1865 }
1866 reloc_found = true;
1867 break;
1868 }
1869 }
1870 if (reloc_found && isExtern) {
1871 // The Value passed in will be adjusted by the Pc if the instruction
1872 // adds the Pc. But for x86_64 external relocation entries the Value
1873 // is the offset from the external symbol.
1874 if (info->O->getAnyRelocationPCRel(RE))
1875 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001876 Expected<StringRef> SymName = Symbol.getName();
1877 if (!SymName) {
1878 std::string Buf;
1879 raw_string_ostream OS(Buf);
1880 logAllUnhandledErrors(SymName.takeError(), OS, "");
1881 OS.flush();
1882 report_fatal_error(Buf);
1883 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001884 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001885 unsigned Type = info->O->getAnyRelocationType(RE);
1886 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1887 DataRefImpl RelNext = Rel;
1888 info->O->moveRelocationNext(RelNext);
1889 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1890 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1891 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1892 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1893 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1894 op_info->SubtractSymbol.Present = 1;
1895 op_info->SubtractSymbol.Name = name;
1896 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1897 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001898 Expected<StringRef> SymNameNext = Symbol.getName();
1899 if (!SymNameNext) {
1900 std::string Buf;
1901 raw_string_ostream OS(Buf);
1902 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1903 OS.flush();
1904 report_fatal_error(Buf);
1905 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001906 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001907 }
1908 }
1909 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1910 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1911 op_info->AddSymbol.Present = 1;
1912 op_info->AddSymbol.Name = name;
1913 return 1;
1914 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001915 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001916 }
1917 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001918 if (Offset != 0 || (Size != 4 && Size != 2))
1919 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001920 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1921 // TODO:
1922 // Search the external relocation entries of a fully linked image
1923 // (if any) for an entry that matches this segment offset.
1924 // uint32_t seg_offset = (Pc + Offset);
1925 return 0;
1926 }
1927 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1928 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001929 uint32_t sect_addr = info->S.getAddress();
1930 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001931 DataRefImpl Rel;
1932 MachO::any_relocation_info RE;
1933 bool isExtern = false;
1934 SymbolRef Symbol;
1935 bool r_scattered = false;
1936 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001937 auto Reloc =
1938 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1939 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001940 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001941 return RelocOffset == sect_offset;
1942 });
1943
1944 if (Reloc == info->S.relocations().end())
1945 return 0;
1946
1947 Rel = Reloc->getRawDataRefImpl();
1948 RE = info->O->getRelocation(Rel);
1949 r_length = info->O->getAnyRelocationLength(RE);
1950 r_scattered = info->O->isRelocationScattered(RE);
1951 if (r_scattered) {
1952 r_value = info->O->getScatteredRelocationValue(RE);
1953 r_type = info->O->getScatteredRelocationType(RE);
1954 } else {
1955 r_type = info->O->getAnyRelocationType(RE);
1956 isExtern = info->O->getPlainRelocationExternal(RE);
1957 if (isExtern) {
1958 symbol_iterator RelocSym = Reloc->getSymbol();
1959 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001960 }
1961 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001962 if (r_type == MachO::ARM_RELOC_HALF ||
1963 r_type == MachO::ARM_RELOC_SECTDIFF ||
1964 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1965 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1966 DataRefImpl RelNext = Rel;
1967 info->O->moveRelocationNext(RelNext);
1968 MachO::any_relocation_info RENext;
1969 RENext = info->O->getRelocation(RelNext);
1970 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1971 if (info->O->isRelocationScattered(RENext))
1972 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1973 }
1974
1975 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001976 Expected<StringRef> SymName = Symbol.getName();
1977 if (!SymName) {
1978 std::string Buf;
1979 raw_string_ostream OS(Buf);
1980 logAllUnhandledErrors(SymName.takeError(), OS, "");
1981 OS.flush();
1982 report_fatal_error(Buf);
1983 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001984 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00001985 op_info->AddSymbol.Present = 1;
1986 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001987 switch (r_type) {
1988 case MachO::ARM_RELOC_HALF:
1989 if ((r_length & 0x1) == 1) {
1990 op_info->Value = value << 16 | other_half;
1991 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1992 } else {
1993 op_info->Value = other_half << 16 | value;
1994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00001995 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00001996 break;
1997 default:
1998 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001999 }
2000 return 1;
2001 }
2002 // If we have a branch that is not an external relocation entry then
2003 // return 0 so the code in tryAddingSymbolicOperand() can use the
2004 // SymbolLookUp call back with the branch target address to look up the
2005 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002006 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2007 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002008 return 0;
2009
2010 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002011 if (r_type == MachO::ARM_RELOC_HALF ||
2012 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2013 if ((r_length & 0x1) == 1)
2014 value = value << 16 | other_half;
2015 else
2016 value = other_half << 16 | value;
2017 }
2018 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2019 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2020 offset = value - r_value;
2021 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002022 }
2023
David Blaikie33dd45d02015-03-23 18:39:02 +00002024 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002025 if ((r_length & 0x1) == 1)
2026 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2027 else
2028 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002029 const char *add = GuessSymbolName(r_value, info->AddrMap);
2030 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002031 int32_t offset = value - (r_value - pair_r_value);
2032 op_info->AddSymbol.Present = 1;
2033 if (add != nullptr)
2034 op_info->AddSymbol.Name = add;
2035 else
2036 op_info->AddSymbol.Value = r_value;
2037 op_info->SubtractSymbol.Present = 1;
2038 if (sub != nullptr)
2039 op_info->SubtractSymbol.Name = sub;
2040 else
2041 op_info->SubtractSymbol.Value = pair_r_value;
2042 op_info->Value = offset;
2043 return 1;
2044 }
2045
Kevin Enderby930fdc72014-11-06 19:00:13 +00002046 op_info->AddSymbol.Present = 1;
2047 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002048 if (r_type == MachO::ARM_RELOC_HALF) {
2049 if ((r_length & 0x1) == 1)
2050 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2051 else
2052 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002053 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002054 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002055 if (add != nullptr) {
2056 op_info->AddSymbol.Name = add;
2057 return 1;
2058 }
2059 op_info->AddSymbol.Value = value;
2060 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002061 }
2062 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002063 if (Offset != 0 || Size != 4)
2064 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002065 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2066 // TODO:
2067 // Search the external relocation entries of a fully linked image
2068 // (if any) for an entry that matches this segment offset.
2069 // uint64_t seg_offset = (Pc + Offset);
2070 return 0;
2071 }
2072 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2073 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002074 uint64_t sect_addr = info->S.getAddress();
2075 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002076 auto Reloc =
2077 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2078 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002079 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002080 return RelocOffset == sect_offset;
2081 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002082
David Blaikie33dd45d02015-03-23 18:39:02 +00002083 if (Reloc == info->S.relocations().end())
2084 return 0;
2085
2086 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2087 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2088 uint32_t r_type = info->O->getAnyRelocationType(RE);
2089 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2090 DataRefImpl RelNext = Rel;
2091 info->O->moveRelocationNext(RelNext);
2092 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2093 if (value == 0) {
2094 value = info->O->getPlainRelocationSymbolNum(RENext);
2095 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002096 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002097 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002098 // NOTE: Scattered relocations don't exist on arm64.
2099 if (!info->O->getPlainRelocationExternal(RE))
2100 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002101 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2102 if (!SymName) {
2103 std::string Buf;
2104 raw_string_ostream OS(Buf);
2105 logAllUnhandledErrors(SymName.takeError(), OS, "");
2106 OS.flush();
2107 report_fatal_error(Buf);
2108 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002109 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002110 op_info->AddSymbol.Present = 1;
2111 op_info->AddSymbol.Name = name;
2112
2113 switch (r_type) {
2114 case MachO::ARM64_RELOC_PAGE21:
2115 /* @page */
2116 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2117 break;
2118 case MachO::ARM64_RELOC_PAGEOFF12:
2119 /* @pageoff */
2120 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2121 break;
2122 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2123 /* @gotpage */
2124 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2125 break;
2126 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2127 /* @gotpageoff */
2128 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2129 break;
2130 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2131 /* @tvlppage is not implemented in llvm-mc */
2132 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2133 break;
2134 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2135 /* @tvlppageoff is not implemented in llvm-mc */
2136 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2137 break;
2138 default:
2139 case MachO::ARM64_RELOC_BRANCH26:
2140 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2141 break;
2142 }
2143 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002144 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002145 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002146}
2147
Kevin Enderbybf246f52014-09-24 23:08:22 +00002148// GuessCstringPointer is passed the address of what might be a pointer to a
2149// literal string in a cstring section. If that address is in a cstring section
2150// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002151static const char *GuessCstringPointer(uint64_t ReferenceValue,
2152 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002153 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002154 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2155 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2156 for (unsigned J = 0; J < Seg.nsects; ++J) {
2157 MachO::section_64 Sec = info->O->getSection64(Load, J);
2158 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2159 if (section_type == MachO::S_CSTRING_LITERALS &&
2160 ReferenceValue >= Sec.addr &&
2161 ReferenceValue < Sec.addr + Sec.size) {
2162 uint64_t sect_offset = ReferenceValue - Sec.addr;
2163 uint64_t object_offset = Sec.offset + sect_offset;
2164 StringRef MachOContents = info->O->getData();
2165 uint64_t object_size = MachOContents.size();
2166 const char *object_addr = (const char *)MachOContents.data();
2167 if (object_offset < object_size) {
2168 const char *name = object_addr + object_offset;
2169 return name;
2170 } else {
2171 return nullptr;
2172 }
2173 }
2174 }
2175 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2176 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2177 for (unsigned J = 0; J < Seg.nsects; ++J) {
2178 MachO::section Sec = info->O->getSection(Load, J);
2179 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2180 if (section_type == MachO::S_CSTRING_LITERALS &&
2181 ReferenceValue >= Sec.addr &&
2182 ReferenceValue < Sec.addr + Sec.size) {
2183 uint64_t sect_offset = ReferenceValue - Sec.addr;
2184 uint64_t object_offset = Sec.offset + sect_offset;
2185 StringRef MachOContents = info->O->getData();
2186 uint64_t object_size = MachOContents.size();
2187 const char *object_addr = (const char *)MachOContents.data();
2188 if (object_offset < object_size) {
2189 const char *name = object_addr + object_offset;
2190 return name;
2191 } else {
2192 return nullptr;
2193 }
2194 }
2195 }
2196 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002197 }
2198 return nullptr;
2199}
2200
Kevin Enderby85974882014-09-26 22:20:44 +00002201// GuessIndirectSymbol returns the name of the indirect symbol for the
2202// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2203// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2204// symbol name being referenced by the stub or pointer.
2205static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2206 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002207 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2208 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002209 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002210 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2211 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2212 for (unsigned J = 0; J < Seg.nsects; ++J) {
2213 MachO::section_64 Sec = info->O->getSection64(Load, J);
2214 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2215 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2216 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2217 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2218 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2219 section_type == MachO::S_SYMBOL_STUBS) &&
2220 ReferenceValue >= Sec.addr &&
2221 ReferenceValue < Sec.addr + Sec.size) {
2222 uint32_t stride;
2223 if (section_type == MachO::S_SYMBOL_STUBS)
2224 stride = Sec.reserved2;
2225 else
2226 stride = 8;
2227 if (stride == 0)
2228 return nullptr;
2229 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2230 if (index < Dysymtab.nindirectsyms) {
2231 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002232 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002233 if (indirect_symbol < Symtab.nsyms) {
2234 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2235 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002236 Expected<StringRef> SymName = Symbol.getName();
2237 if (!SymName) {
2238 std::string Buf;
2239 raw_string_ostream OS(Buf);
2240 logAllUnhandledErrors(SymName.takeError(), OS, "");
2241 OS.flush();
2242 report_fatal_error(Buf);
2243 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002244 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002245 return name;
2246 }
2247 }
2248 }
2249 }
2250 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2251 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2252 for (unsigned J = 0; J < Seg.nsects; ++J) {
2253 MachO::section Sec = info->O->getSection(Load, J);
2254 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2255 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2256 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2257 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2258 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2259 section_type == MachO::S_SYMBOL_STUBS) &&
2260 ReferenceValue >= Sec.addr &&
2261 ReferenceValue < Sec.addr + Sec.size) {
2262 uint32_t stride;
2263 if (section_type == MachO::S_SYMBOL_STUBS)
2264 stride = Sec.reserved2;
2265 else
2266 stride = 4;
2267 if (stride == 0)
2268 return nullptr;
2269 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2270 if (index < Dysymtab.nindirectsyms) {
2271 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002272 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002273 if (indirect_symbol < Symtab.nsyms) {
2274 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2275 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002276 Expected<StringRef> SymName = Symbol.getName();
2277 if (!SymName) {
2278 std::string Buf;
2279 raw_string_ostream OS(Buf);
2280 logAllUnhandledErrors(SymName.takeError(), OS, "");
2281 OS.flush();
2282 report_fatal_error(Buf);
2283 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002284 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002285 return name;
2286 }
2287 }
2288 }
2289 }
2290 }
Kevin Enderby85974882014-09-26 22:20:44 +00002291 }
2292 return nullptr;
2293}
2294
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002295// method_reference() is called passing it the ReferenceName that might be
2296// a reference it to an Objective-C method call. If so then it allocates and
2297// assembles a method call string with the values last seen and saved in
2298// the DisassembleInfo's class_name and selector_name fields. This is saved
2299// into the method field of the info and any previous string is free'ed.
2300// Then the class_name field in the info is set to nullptr. The method call
2301// string is set into ReferenceName and ReferenceType is set to
2302// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2303// then both ReferenceType and ReferenceName are left unchanged.
2304static void method_reference(struct DisassembleInfo *info,
2305 uint64_t *ReferenceType,
2306 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002307 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002308 if (*ReferenceName != nullptr) {
2309 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002310 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002311 if (info->method != nullptr)
2312 free(info->method);
2313 if (info->class_name != nullptr) {
2314 info->method = (char *)malloc(5 + strlen(info->class_name) +
2315 strlen(info->selector_name));
2316 if (info->method != nullptr) {
2317 strcpy(info->method, "+[");
2318 strcat(info->method, info->class_name);
2319 strcat(info->method, " ");
2320 strcat(info->method, info->selector_name);
2321 strcat(info->method, "]");
2322 *ReferenceName = info->method;
2323 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2324 }
2325 } else {
2326 info->method = (char *)malloc(9 + strlen(info->selector_name));
2327 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002328 if (Arch == Triple::x86_64)
2329 strcpy(info->method, "-[%rdi ");
2330 else if (Arch == Triple::aarch64)
2331 strcpy(info->method, "-[x0 ");
2332 else
2333 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002334 strcat(info->method, info->selector_name);
2335 strcat(info->method, "]");
2336 *ReferenceName = info->method;
2337 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2338 }
2339 }
2340 info->class_name = nullptr;
2341 }
2342 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002343 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002344 if (info->method != nullptr)
2345 free(info->method);
2346 info->method = (char *)malloc(17 + strlen(info->selector_name));
2347 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002348 if (Arch == Triple::x86_64)
2349 strcpy(info->method, "-[[%rdi super] ");
2350 else if (Arch == Triple::aarch64)
2351 strcpy(info->method, "-[[x0 super] ");
2352 else
2353 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002354 strcat(info->method, info->selector_name);
2355 strcat(info->method, "]");
2356 *ReferenceName = info->method;
2357 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2358 }
2359 info->class_name = nullptr;
2360 }
2361 }
2362 }
2363}
2364
2365// GuessPointerPointer() is passed the address of what might be a pointer to
2366// a reference to an Objective-C class, selector, message ref or cfstring.
2367// If so the value of the pointer is returned and one of the booleans are set
2368// to true. If not zero is returned and all the booleans are set to false.
2369static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2370 struct DisassembleInfo *info,
2371 bool &classref, bool &selref, bool &msgref,
2372 bool &cfstring) {
2373 classref = false;
2374 selref = false;
2375 msgref = false;
2376 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002377 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002378 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2379 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2380 for (unsigned J = 0; J < Seg.nsects; ++J) {
2381 MachO::section_64 Sec = info->O->getSection64(Load, J);
2382 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2383 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2384 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2385 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2386 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2387 ReferenceValue >= Sec.addr &&
2388 ReferenceValue < Sec.addr + Sec.size) {
2389 uint64_t sect_offset = ReferenceValue - Sec.addr;
2390 uint64_t object_offset = Sec.offset + sect_offset;
2391 StringRef MachOContents = info->O->getData();
2392 uint64_t object_size = MachOContents.size();
2393 const char *object_addr = (const char *)MachOContents.data();
2394 if (object_offset < object_size) {
2395 uint64_t pointer_value;
2396 memcpy(&pointer_value, object_addr + object_offset,
2397 sizeof(uint64_t));
2398 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2399 sys::swapByteOrder(pointer_value);
2400 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2401 selref = true;
2402 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2403 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2404 classref = true;
2405 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2406 ReferenceValue + 8 < Sec.addr + Sec.size) {
2407 msgref = true;
2408 memcpy(&pointer_value, object_addr + object_offset + 8,
2409 sizeof(uint64_t));
2410 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2411 sys::swapByteOrder(pointer_value);
2412 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2413 cfstring = true;
2414 return pointer_value;
2415 } else {
2416 return 0;
2417 }
2418 }
2419 }
2420 }
2421 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002422 }
2423 return 0;
2424}
2425
2426// get_pointer_64 returns a pointer to the bytes in the object file at the
2427// Address from a section in the Mach-O file. And indirectly returns the
2428// offset into the section, number of bytes left in the section past the offset
2429// and which section is was being referenced. If the Address is not in a
2430// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002431static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2432 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002433 DisassembleInfo *info,
2434 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002435 offset = 0;
2436 left = 0;
2437 S = SectionRef();
2438 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2439 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2440 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002441 if (SectSize == 0)
2442 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002443 if (objc_only) {
2444 StringRef SectName;
2445 ((*(info->Sections))[SectIdx]).getName(SectName);
2446 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2447 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2448 if (SegName != "__OBJC" && SectName != "__cstring")
2449 continue;
2450 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002451 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2452 S = (*(info->Sections))[SectIdx];
2453 offset = Address - SectAddress;
2454 left = SectSize - offset;
2455 StringRef SectContents;
2456 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2457 return SectContents.data() + offset;
2458 }
2459 }
2460 return nullptr;
2461}
2462
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002463static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2464 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002465 DisassembleInfo *info,
2466 bool objc_only = false) {
2467 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002468}
2469
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002470// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2471// the symbol indirectly through n_value. Based on the relocation information
2472// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002473// If no relocation information is found and a non-zero ReferenceValue for the
2474// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002475static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2476 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002477 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002478 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002479 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002480 return nullptr;
2481
2482 // See if there is an external relocation entry at the sect_offset.
2483 bool reloc_found = false;
2484 DataRefImpl Rel;
2485 MachO::any_relocation_info RE;
2486 bool isExtern = false;
2487 SymbolRef Symbol;
2488 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002489 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002490 if (RelocOffset == sect_offset) {
2491 Rel = Reloc.getRawDataRefImpl();
2492 RE = info->O->getRelocation(Rel);
2493 if (info->O->isRelocationScattered(RE))
2494 continue;
2495 isExtern = info->O->getPlainRelocationExternal(RE);
2496 if (isExtern) {
2497 symbol_iterator RelocSym = Reloc.getSymbol();
2498 Symbol = *RelocSym;
2499 }
2500 reloc_found = true;
2501 break;
2502 }
2503 }
2504 // If there is an external relocation entry for a symbol in this section
2505 // at this section_offset then use that symbol's value for the n_value
2506 // and return its name.
2507 const char *SymbolName = nullptr;
2508 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002509 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002510 Expected<StringRef> NameOrError = Symbol.getName();
2511 if (!NameOrError) {
2512 std::string Buf;
2513 raw_string_ostream OS(Buf);
2514 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2515 OS.flush();
2516 report_fatal_error(Buf);
2517 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002518 StringRef Name = *NameOrError;
2519 if (!Name.empty()) {
2520 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002521 return SymbolName;
2522 }
2523 }
2524
2525 // TODO: For fully linked images, look through the external relocation
2526 // entries off the dynamic symtab command. For these the r_offset is from the
2527 // start of the first writeable segment in the Mach-O file. So the offset
2528 // to this section from that segment is passed to this routine by the caller,
2529 // as the database_offset. Which is the difference of the section's starting
2530 // address and the first writable segment.
2531 //
2532 // NOTE: need add passing the database_offset to this routine.
2533
Kevin Enderby0fc11822015-04-01 20:57:01 +00002534 // We did not find an external relocation entry so look up the ReferenceValue
2535 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002536 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002537
2538 return SymbolName;
2539}
2540
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002541static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2542 DisassembleInfo *info,
2543 uint32_t ReferenceValue) {
2544 uint64_t n_value64;
2545 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2546}
2547
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002548// These are structs in the Objective-C meta data and read to produce the
2549// comments for disassembly. While these are part of the ABI they are no
2550// public defintions. So the are here not in include/llvm/Support/MachO.h .
2551
2552// The cfstring object in a 64-bit Mach-O file.
2553struct cfstring64_t {
2554 uint64_t isa; // class64_t * (64-bit pointer)
2555 uint64_t flags; // flag bits
2556 uint64_t characters; // char * (64-bit pointer)
2557 uint64_t length; // number of non-NULL characters in above
2558};
2559
2560// The class object in a 64-bit Mach-O file.
2561struct class64_t {
2562 uint64_t isa; // class64_t * (64-bit pointer)
2563 uint64_t superclass; // class64_t * (64-bit pointer)
2564 uint64_t cache; // Cache (64-bit pointer)
2565 uint64_t vtable; // IMP * (64-bit pointer)
2566 uint64_t data; // class_ro64_t * (64-bit pointer)
2567};
2568
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002569struct class32_t {
2570 uint32_t isa; /* class32_t * (32-bit pointer) */
2571 uint32_t superclass; /* class32_t * (32-bit pointer) */
2572 uint32_t cache; /* Cache (32-bit pointer) */
2573 uint32_t vtable; /* IMP * (32-bit pointer) */
2574 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2575};
2576
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002577struct class_ro64_t {
2578 uint32_t flags;
2579 uint32_t instanceStart;
2580 uint32_t instanceSize;
2581 uint32_t reserved;
2582 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2583 uint64_t name; // const char * (64-bit pointer)
2584 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2585 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2586 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2587 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2588 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2589};
2590
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002591struct class_ro32_t {
2592 uint32_t flags;
2593 uint32_t instanceStart;
2594 uint32_t instanceSize;
2595 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2596 uint32_t name; /* const char * (32-bit pointer) */
2597 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2598 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2599 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2600 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2601 uint32_t baseProperties; /* const struct objc_property_list *
2602 (32-bit pointer) */
2603};
2604
2605/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002606#define RO_META (1 << 0)
2607#define RO_ROOT (1 << 1)
2608#define RO_HAS_CXX_STRUCTORS (1 << 2)
2609
2610struct method_list64_t {
2611 uint32_t entsize;
2612 uint32_t count;
2613 /* struct method64_t first; These structures follow inline */
2614};
2615
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002616struct method_list32_t {
2617 uint32_t entsize;
2618 uint32_t count;
2619 /* struct method32_t first; These structures follow inline */
2620};
2621
Kevin Enderby0fc11822015-04-01 20:57:01 +00002622struct method64_t {
2623 uint64_t name; /* SEL (64-bit pointer) */
2624 uint64_t types; /* const char * (64-bit pointer) */
2625 uint64_t imp; /* IMP (64-bit pointer) */
2626};
2627
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002628struct method32_t {
2629 uint32_t name; /* SEL (32-bit pointer) */
2630 uint32_t types; /* const char * (32-bit pointer) */
2631 uint32_t imp; /* IMP (32-bit pointer) */
2632};
2633
Kevin Enderby0fc11822015-04-01 20:57:01 +00002634struct protocol_list64_t {
2635 uint64_t count; /* uintptr_t (a 64-bit value) */
2636 /* struct protocol64_t * list[0]; These pointers follow inline */
2637};
2638
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002639struct protocol_list32_t {
2640 uint32_t count; /* uintptr_t (a 32-bit value) */
2641 /* struct protocol32_t * list[0]; These pointers follow inline */
2642};
2643
Kevin Enderby0fc11822015-04-01 20:57:01 +00002644struct protocol64_t {
2645 uint64_t isa; /* id * (64-bit pointer) */
2646 uint64_t name; /* const char * (64-bit pointer) */
2647 uint64_t protocols; /* struct protocol_list64_t *
2648 (64-bit pointer) */
2649 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2650 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2651 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2652 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2653 uint64_t instanceProperties; /* struct objc_property_list *
2654 (64-bit pointer) */
2655};
2656
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002657struct protocol32_t {
2658 uint32_t isa; /* id * (32-bit pointer) */
2659 uint32_t name; /* const char * (32-bit pointer) */
2660 uint32_t protocols; /* struct protocol_list_t *
2661 (32-bit pointer) */
2662 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2663 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2664 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2665 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2666 uint32_t instanceProperties; /* struct objc_property_list *
2667 (32-bit pointer) */
2668};
2669
Kevin Enderby0fc11822015-04-01 20:57:01 +00002670struct ivar_list64_t {
2671 uint32_t entsize;
2672 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002673 /* struct ivar64_t first; These structures follow inline */
2674};
2675
2676struct ivar_list32_t {
2677 uint32_t entsize;
2678 uint32_t count;
2679 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002680};
2681
2682struct ivar64_t {
2683 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2684 uint64_t name; /* const char * (64-bit pointer) */
2685 uint64_t type; /* const char * (64-bit pointer) */
2686 uint32_t alignment;
2687 uint32_t size;
2688};
2689
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002690struct ivar32_t {
2691 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2692 uint32_t name; /* const char * (32-bit pointer) */
2693 uint32_t type; /* const char * (32-bit pointer) */
2694 uint32_t alignment;
2695 uint32_t size;
2696};
2697
Kevin Enderby0fc11822015-04-01 20:57:01 +00002698struct objc_property_list64 {
2699 uint32_t entsize;
2700 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002701 /* struct objc_property64 first; These structures follow inline */
2702};
2703
2704struct objc_property_list32 {
2705 uint32_t entsize;
2706 uint32_t count;
2707 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002708};
2709
2710struct objc_property64 {
2711 uint64_t name; /* const char * (64-bit pointer) */
2712 uint64_t attributes; /* const char * (64-bit pointer) */
2713};
2714
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002715struct objc_property32 {
2716 uint32_t name; /* const char * (32-bit pointer) */
2717 uint32_t attributes; /* const char * (32-bit pointer) */
2718};
2719
Kevin Enderby0fc11822015-04-01 20:57:01 +00002720struct category64_t {
2721 uint64_t name; /* const char * (64-bit pointer) */
2722 uint64_t cls; /* struct class_t * (64-bit pointer) */
2723 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2724 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2725 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2726 uint64_t instanceProperties; /* struct objc_property_list *
2727 (64-bit pointer) */
2728};
2729
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002730struct category32_t {
2731 uint32_t name; /* const char * (32-bit pointer) */
2732 uint32_t cls; /* struct class_t * (32-bit pointer) */
2733 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2734 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2735 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2736 uint32_t instanceProperties; /* struct objc_property_list *
2737 (32-bit pointer) */
2738};
2739
Kevin Enderby0fc11822015-04-01 20:57:01 +00002740struct objc_image_info64 {
2741 uint32_t version;
2742 uint32_t flags;
2743};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002744struct objc_image_info32 {
2745 uint32_t version;
2746 uint32_t flags;
2747};
Kevin Enderby846c0002015-04-16 17:19:59 +00002748struct imageInfo_t {
2749 uint32_t version;
2750 uint32_t flags;
2751};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002752/* masks for objc_image_info.flags */
2753#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2754#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2755
2756struct message_ref64 {
2757 uint64_t imp; /* IMP (64-bit pointer) */
2758 uint64_t sel; /* SEL (64-bit pointer) */
2759};
2760
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002761struct message_ref32 {
2762 uint32_t imp; /* IMP (32-bit pointer) */
2763 uint32_t sel; /* SEL (32-bit pointer) */
2764};
2765
Kevin Enderby846c0002015-04-16 17:19:59 +00002766// Objective-C 1 (32-bit only) meta data structs.
2767
2768struct objc_module_t {
2769 uint32_t version;
2770 uint32_t size;
2771 uint32_t name; /* char * (32-bit pointer) */
2772 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2773};
2774
2775struct objc_symtab_t {
2776 uint32_t sel_ref_cnt;
2777 uint32_t refs; /* SEL * (32-bit pointer) */
2778 uint16_t cls_def_cnt;
2779 uint16_t cat_def_cnt;
2780 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2781};
2782
2783struct objc_class_t {
2784 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2785 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2786 uint32_t name; /* const char * (32-bit pointer) */
2787 int32_t version;
2788 int32_t info;
2789 int32_t instance_size;
2790 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2791 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2792 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2793 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2794};
2795
2796#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2797// class is not a metaclass
2798#define CLS_CLASS 0x1
2799// class is a metaclass
2800#define CLS_META 0x2
2801
2802struct objc_category_t {
2803 uint32_t category_name; /* char * (32-bit pointer) */
2804 uint32_t class_name; /* char * (32-bit pointer) */
2805 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2806 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2807 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2808};
2809
2810struct objc_ivar_t {
2811 uint32_t ivar_name; /* char * (32-bit pointer) */
2812 uint32_t ivar_type; /* char * (32-bit pointer) */
2813 int32_t ivar_offset;
2814};
2815
2816struct objc_ivar_list_t {
2817 int32_t ivar_count;
2818 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2819};
2820
2821struct objc_method_list_t {
2822 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2823 int32_t method_count;
2824 // struct objc_method_t method_list[1]; /* variable length structure */
2825};
2826
2827struct objc_method_t {
2828 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2829 uint32_t method_types; /* char * (32-bit pointer) */
2830 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2831 (32-bit pointer) */
2832};
2833
2834struct objc_protocol_list_t {
2835 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2836 int32_t count;
2837 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2838 // (32-bit pointer) */
2839};
2840
2841struct objc_protocol_t {
2842 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2843 uint32_t protocol_name; /* char * (32-bit pointer) */
2844 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2845 uint32_t instance_methods; /* struct objc_method_description_list *
2846 (32-bit pointer) */
2847 uint32_t class_methods; /* struct objc_method_description_list *
2848 (32-bit pointer) */
2849};
2850
2851struct objc_method_description_list_t {
2852 int32_t count;
2853 // struct objc_method_description_t list[1];
2854};
2855
2856struct objc_method_description_t {
2857 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2858 uint32_t types; /* char * (32-bit pointer) */
2859};
2860
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002861inline void swapStruct(struct cfstring64_t &cfs) {
2862 sys::swapByteOrder(cfs.isa);
2863 sys::swapByteOrder(cfs.flags);
2864 sys::swapByteOrder(cfs.characters);
2865 sys::swapByteOrder(cfs.length);
2866}
2867
2868inline void swapStruct(struct class64_t &c) {
2869 sys::swapByteOrder(c.isa);
2870 sys::swapByteOrder(c.superclass);
2871 sys::swapByteOrder(c.cache);
2872 sys::swapByteOrder(c.vtable);
2873 sys::swapByteOrder(c.data);
2874}
2875
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002876inline void swapStruct(struct class32_t &c) {
2877 sys::swapByteOrder(c.isa);
2878 sys::swapByteOrder(c.superclass);
2879 sys::swapByteOrder(c.cache);
2880 sys::swapByteOrder(c.vtable);
2881 sys::swapByteOrder(c.data);
2882}
2883
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002884inline void swapStruct(struct class_ro64_t &cro) {
2885 sys::swapByteOrder(cro.flags);
2886 sys::swapByteOrder(cro.instanceStart);
2887 sys::swapByteOrder(cro.instanceSize);
2888 sys::swapByteOrder(cro.reserved);
2889 sys::swapByteOrder(cro.ivarLayout);
2890 sys::swapByteOrder(cro.name);
2891 sys::swapByteOrder(cro.baseMethods);
2892 sys::swapByteOrder(cro.baseProtocols);
2893 sys::swapByteOrder(cro.ivars);
2894 sys::swapByteOrder(cro.weakIvarLayout);
2895 sys::swapByteOrder(cro.baseProperties);
2896}
2897
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002898inline void swapStruct(struct class_ro32_t &cro) {
2899 sys::swapByteOrder(cro.flags);
2900 sys::swapByteOrder(cro.instanceStart);
2901 sys::swapByteOrder(cro.instanceSize);
2902 sys::swapByteOrder(cro.ivarLayout);
2903 sys::swapByteOrder(cro.name);
2904 sys::swapByteOrder(cro.baseMethods);
2905 sys::swapByteOrder(cro.baseProtocols);
2906 sys::swapByteOrder(cro.ivars);
2907 sys::swapByteOrder(cro.weakIvarLayout);
2908 sys::swapByteOrder(cro.baseProperties);
2909}
2910
Kevin Enderby0fc11822015-04-01 20:57:01 +00002911inline void swapStruct(struct method_list64_t &ml) {
2912 sys::swapByteOrder(ml.entsize);
2913 sys::swapByteOrder(ml.count);
2914}
2915
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002916inline void swapStruct(struct method_list32_t &ml) {
2917 sys::swapByteOrder(ml.entsize);
2918 sys::swapByteOrder(ml.count);
2919}
2920
Kevin Enderby0fc11822015-04-01 20:57:01 +00002921inline void swapStruct(struct method64_t &m) {
2922 sys::swapByteOrder(m.name);
2923 sys::swapByteOrder(m.types);
2924 sys::swapByteOrder(m.imp);
2925}
2926
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002927inline void swapStruct(struct method32_t &m) {
2928 sys::swapByteOrder(m.name);
2929 sys::swapByteOrder(m.types);
2930 sys::swapByteOrder(m.imp);
2931}
2932
Kevin Enderby0fc11822015-04-01 20:57:01 +00002933inline void swapStruct(struct protocol_list64_t &pl) {
2934 sys::swapByteOrder(pl.count);
2935}
2936
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002937inline void swapStruct(struct protocol_list32_t &pl) {
2938 sys::swapByteOrder(pl.count);
2939}
2940
Kevin Enderby0fc11822015-04-01 20:57:01 +00002941inline void swapStruct(struct protocol64_t &p) {
2942 sys::swapByteOrder(p.isa);
2943 sys::swapByteOrder(p.name);
2944 sys::swapByteOrder(p.protocols);
2945 sys::swapByteOrder(p.instanceMethods);
2946 sys::swapByteOrder(p.classMethods);
2947 sys::swapByteOrder(p.optionalInstanceMethods);
2948 sys::swapByteOrder(p.optionalClassMethods);
2949 sys::swapByteOrder(p.instanceProperties);
2950}
2951
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002952inline void swapStruct(struct protocol32_t &p) {
2953 sys::swapByteOrder(p.isa);
2954 sys::swapByteOrder(p.name);
2955 sys::swapByteOrder(p.protocols);
2956 sys::swapByteOrder(p.instanceMethods);
2957 sys::swapByteOrder(p.classMethods);
2958 sys::swapByteOrder(p.optionalInstanceMethods);
2959 sys::swapByteOrder(p.optionalClassMethods);
2960 sys::swapByteOrder(p.instanceProperties);
2961}
2962
Kevin Enderby0fc11822015-04-01 20:57:01 +00002963inline void swapStruct(struct ivar_list64_t &il) {
2964 sys::swapByteOrder(il.entsize);
2965 sys::swapByteOrder(il.count);
2966}
2967
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002968inline void swapStruct(struct ivar_list32_t &il) {
2969 sys::swapByteOrder(il.entsize);
2970 sys::swapByteOrder(il.count);
2971}
2972
Kevin Enderby0fc11822015-04-01 20:57:01 +00002973inline void swapStruct(struct ivar64_t &i) {
2974 sys::swapByteOrder(i.offset);
2975 sys::swapByteOrder(i.name);
2976 sys::swapByteOrder(i.type);
2977 sys::swapByteOrder(i.alignment);
2978 sys::swapByteOrder(i.size);
2979}
2980
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002981inline void swapStruct(struct ivar32_t &i) {
2982 sys::swapByteOrder(i.offset);
2983 sys::swapByteOrder(i.name);
2984 sys::swapByteOrder(i.type);
2985 sys::swapByteOrder(i.alignment);
2986 sys::swapByteOrder(i.size);
2987}
2988
Kevin Enderby0fc11822015-04-01 20:57:01 +00002989inline void swapStruct(struct objc_property_list64 &pl) {
2990 sys::swapByteOrder(pl.entsize);
2991 sys::swapByteOrder(pl.count);
2992}
2993
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002994inline void swapStruct(struct objc_property_list32 &pl) {
2995 sys::swapByteOrder(pl.entsize);
2996 sys::swapByteOrder(pl.count);
2997}
2998
Kevin Enderby0fc11822015-04-01 20:57:01 +00002999inline void swapStruct(struct objc_property64 &op) {
3000 sys::swapByteOrder(op.name);
3001 sys::swapByteOrder(op.attributes);
3002}
3003
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003004inline void swapStruct(struct objc_property32 &op) {
3005 sys::swapByteOrder(op.name);
3006 sys::swapByteOrder(op.attributes);
3007}
3008
Kevin Enderby0fc11822015-04-01 20:57:01 +00003009inline void swapStruct(struct category64_t &c) {
3010 sys::swapByteOrder(c.name);
3011 sys::swapByteOrder(c.cls);
3012 sys::swapByteOrder(c.instanceMethods);
3013 sys::swapByteOrder(c.classMethods);
3014 sys::swapByteOrder(c.protocols);
3015 sys::swapByteOrder(c.instanceProperties);
3016}
3017
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003018inline void swapStruct(struct category32_t &c) {
3019 sys::swapByteOrder(c.name);
3020 sys::swapByteOrder(c.cls);
3021 sys::swapByteOrder(c.instanceMethods);
3022 sys::swapByteOrder(c.classMethods);
3023 sys::swapByteOrder(c.protocols);
3024 sys::swapByteOrder(c.instanceProperties);
3025}
3026
Kevin Enderby0fc11822015-04-01 20:57:01 +00003027inline void swapStruct(struct objc_image_info64 &o) {
3028 sys::swapByteOrder(o.version);
3029 sys::swapByteOrder(o.flags);
3030}
3031
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003032inline void swapStruct(struct objc_image_info32 &o) {
3033 sys::swapByteOrder(o.version);
3034 sys::swapByteOrder(o.flags);
3035}
3036
Kevin Enderby846c0002015-04-16 17:19:59 +00003037inline void swapStruct(struct imageInfo_t &o) {
3038 sys::swapByteOrder(o.version);
3039 sys::swapByteOrder(o.flags);
3040}
3041
Kevin Enderby0fc11822015-04-01 20:57:01 +00003042inline void swapStruct(struct message_ref64 &mr) {
3043 sys::swapByteOrder(mr.imp);
3044 sys::swapByteOrder(mr.sel);
3045}
3046
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003047inline void swapStruct(struct message_ref32 &mr) {
3048 sys::swapByteOrder(mr.imp);
3049 sys::swapByteOrder(mr.sel);
3050}
3051
Kevin Enderby846c0002015-04-16 17:19:59 +00003052inline void swapStruct(struct objc_module_t &module) {
3053 sys::swapByteOrder(module.version);
3054 sys::swapByteOrder(module.size);
3055 sys::swapByteOrder(module.name);
3056 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003057}
Kevin Enderby846c0002015-04-16 17:19:59 +00003058
3059inline void swapStruct(struct objc_symtab_t &symtab) {
3060 sys::swapByteOrder(symtab.sel_ref_cnt);
3061 sys::swapByteOrder(symtab.refs);
3062 sys::swapByteOrder(symtab.cls_def_cnt);
3063 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003064}
Kevin Enderby846c0002015-04-16 17:19:59 +00003065
3066inline void swapStruct(struct objc_class_t &objc_class) {
3067 sys::swapByteOrder(objc_class.isa);
3068 sys::swapByteOrder(objc_class.super_class);
3069 sys::swapByteOrder(objc_class.name);
3070 sys::swapByteOrder(objc_class.version);
3071 sys::swapByteOrder(objc_class.info);
3072 sys::swapByteOrder(objc_class.instance_size);
3073 sys::swapByteOrder(objc_class.ivars);
3074 sys::swapByteOrder(objc_class.methodLists);
3075 sys::swapByteOrder(objc_class.cache);
3076 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003077}
Kevin Enderby846c0002015-04-16 17:19:59 +00003078
3079inline void swapStruct(struct objc_category_t &objc_category) {
3080 sys::swapByteOrder(objc_category.category_name);
3081 sys::swapByteOrder(objc_category.class_name);
3082 sys::swapByteOrder(objc_category.instance_methods);
3083 sys::swapByteOrder(objc_category.class_methods);
3084 sys::swapByteOrder(objc_category.protocols);
3085}
3086
3087inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3088 sys::swapByteOrder(objc_ivar_list.ivar_count);
3089}
3090
3091inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3092 sys::swapByteOrder(objc_ivar.ivar_name);
3093 sys::swapByteOrder(objc_ivar.ivar_type);
3094 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003095}
Kevin Enderby846c0002015-04-16 17:19:59 +00003096
3097inline void swapStruct(struct objc_method_list_t &method_list) {
3098 sys::swapByteOrder(method_list.obsolete);
3099 sys::swapByteOrder(method_list.method_count);
3100}
3101
3102inline void swapStruct(struct objc_method_t &method) {
3103 sys::swapByteOrder(method.method_name);
3104 sys::swapByteOrder(method.method_types);
3105 sys::swapByteOrder(method.method_imp);
3106}
3107
3108inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3109 sys::swapByteOrder(protocol_list.next);
3110 sys::swapByteOrder(protocol_list.count);
3111}
3112
3113inline void swapStruct(struct objc_protocol_t &protocol) {
3114 sys::swapByteOrder(protocol.isa);
3115 sys::swapByteOrder(protocol.protocol_name);
3116 sys::swapByteOrder(protocol.protocol_list);
3117 sys::swapByteOrder(protocol.instance_methods);
3118 sys::swapByteOrder(protocol.class_methods);
3119}
3120
3121inline void swapStruct(struct objc_method_description_list_t &mdl) {
3122 sys::swapByteOrder(mdl.count);
3123}
3124
3125inline void swapStruct(struct objc_method_description_t &md) {
3126 sys::swapByteOrder(md.name);
3127 sys::swapByteOrder(md.types);
3128}
3129
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003130static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3131 struct DisassembleInfo *info);
3132
3133// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3134// to an Objective-C class and returns the class name. It is also passed the
3135// address of the pointer, so when the pointer is zero as it can be in an .o
3136// file, that is used to look for an external relocation entry with a symbol
3137// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003138static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3139 uint64_t ReferenceValue,
3140 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003141 const char *r;
3142 uint32_t offset, left;
3143 SectionRef S;
3144
3145 // The pointer_value can be 0 in an object file and have a relocation
3146 // entry for the class symbol at the ReferenceValue (the address of the
3147 // pointer).
3148 if (pointer_value == 0) {
3149 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3150 if (r == nullptr || left < sizeof(uint64_t))
3151 return nullptr;
3152 uint64_t n_value;
3153 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3154 if (symbol_name == nullptr)
3155 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003156 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003157 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3158 return class_name + 2;
3159 else
3160 return nullptr;
3161 }
3162
3163 // The case were the pointer_value is non-zero and points to a class defined
3164 // in this Mach-O file.
3165 r = get_pointer_64(pointer_value, offset, left, S, info);
3166 if (r == nullptr || left < sizeof(struct class64_t))
3167 return nullptr;
3168 struct class64_t c;
3169 memcpy(&c, r, sizeof(struct class64_t));
3170 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3171 swapStruct(c);
3172 if (c.data == 0)
3173 return nullptr;
3174 r = get_pointer_64(c.data, offset, left, S, info);
3175 if (r == nullptr || left < sizeof(struct class_ro64_t))
3176 return nullptr;
3177 struct class_ro64_t cro;
3178 memcpy(&cro, r, sizeof(struct class_ro64_t));
3179 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3180 swapStruct(cro);
3181 if (cro.name == 0)
3182 return nullptr;
3183 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3184 return name;
3185}
3186
3187// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3188// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003189static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3190 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003191 const char *r, *name;
3192 uint32_t offset, left;
3193 SectionRef S;
3194 struct cfstring64_t cfs;
3195 uint64_t cfs_characters;
3196
3197 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3198 if (r == nullptr || left < sizeof(struct cfstring64_t))
3199 return nullptr;
3200 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3201 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3202 swapStruct(cfs);
3203 if (cfs.characters == 0) {
3204 uint64_t n_value;
3205 const char *symbol_name = get_symbol_64(
3206 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3207 if (symbol_name == nullptr)
3208 return nullptr;
3209 cfs_characters = n_value;
3210 } else
3211 cfs_characters = cfs.characters;
3212 name = get_pointer_64(cfs_characters, offset, left, S, info);
3213
3214 return name;
3215}
3216
3217// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3218// of a pointer to an Objective-C selector reference when the pointer value is
3219// zero as in a .o file and is likely to have a external relocation entry with
3220// who's symbol's n_value is the real pointer to the selector name. If that is
3221// the case the real pointer to the selector name is returned else 0 is
3222// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003223static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3224 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003225 uint32_t offset, left;
3226 SectionRef S;
3227
3228 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3229 if (r == nullptr || left < sizeof(uint64_t))
3230 return 0;
3231 uint64_t n_value;
3232 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3233 if (symbol_name == nullptr)
3234 return 0;
3235 return n_value;
3236}
3237
Kevin Enderby0fc11822015-04-01 20:57:01 +00003238static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3239 const char *sectname) {
3240 for (const SectionRef &Section : O->sections()) {
3241 StringRef SectName;
3242 Section.getName(SectName);
3243 DataRefImpl Ref = Section.getRawDataRefImpl();
3244 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3245 if (SegName == segname && SectName == sectname)
3246 return Section;
3247 }
3248 return SectionRef();
3249}
3250
3251static void
3252walk_pointer_list_64(const char *listname, const SectionRef S,
3253 MachOObjectFile *O, struct DisassembleInfo *info,
3254 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3255 if (S == SectionRef())
3256 return;
3257
3258 StringRef SectName;
3259 S.getName(SectName);
3260 DataRefImpl Ref = S.getRawDataRefImpl();
3261 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3262 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3263
3264 StringRef BytesStr;
3265 S.getContents(BytesStr);
3266 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3267
3268 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3269 uint32_t left = S.getSize() - i;
3270 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3271 uint64_t p = 0;
3272 memcpy(&p, Contents + i, size);
3273 if (i + sizeof(uint64_t) > S.getSize())
3274 outs() << listname << " list pointer extends past end of (" << SegName
3275 << "," << SectName << ") section\n";
3276 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3277
3278 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3279 sys::swapByteOrder(p);
3280
3281 uint64_t n_value = 0;
3282 const char *name = get_symbol_64(i, S, info, n_value, p);
3283 if (name == nullptr)
3284 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3285
3286 if (n_value != 0) {
3287 outs() << format("0x%" PRIx64, n_value);
3288 if (p != 0)
3289 outs() << " + " << format("0x%" PRIx64, p);
3290 } else
3291 outs() << format("0x%" PRIx64, p);
3292 if (name != nullptr)
3293 outs() << " " << name;
3294 outs() << "\n";
3295
3296 p += n_value;
3297 if (func)
3298 func(p, info);
3299 }
3300}
3301
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003302static void
3303walk_pointer_list_32(const char *listname, const SectionRef S,
3304 MachOObjectFile *O, struct DisassembleInfo *info,
3305 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3306 if (S == SectionRef())
3307 return;
3308
3309 StringRef SectName;
3310 S.getName(SectName);
3311 DataRefImpl Ref = S.getRawDataRefImpl();
3312 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3313 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3314
3315 StringRef BytesStr;
3316 S.getContents(BytesStr);
3317 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3318
3319 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3320 uint32_t left = S.getSize() - i;
3321 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3322 uint32_t p = 0;
3323 memcpy(&p, Contents + i, size);
3324 if (i + sizeof(uint32_t) > S.getSize())
3325 outs() << listname << " list pointer extends past end of (" << SegName
3326 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003327 uint32_t Address = S.getAddress() + i;
3328 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003329
3330 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3331 sys::swapByteOrder(p);
3332 outs() << format("0x%" PRIx32, p);
3333
3334 const char *name = get_symbol_32(i, S, info, p);
3335 if (name != nullptr)
3336 outs() << " " << name;
3337 outs() << "\n";
3338
3339 if (func)
3340 func(p, info);
3341 }
3342}
3343
3344static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003345 if (layout_map == nullptr)
3346 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003347 outs() << " layout map: ";
3348 do {
3349 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3350 left--;
3351 layout_map++;
3352 } while (*layout_map != '\0' && left != 0);
3353 outs() << "\n";
3354}
3355
Kevin Enderby0fc11822015-04-01 20:57:01 +00003356static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3357 uint32_t offset, left;
3358 SectionRef S;
3359 const char *layout_map;
3360
3361 if (p == 0)
3362 return;
3363 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003364 print_layout_map(layout_map, left);
3365}
3366
3367static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3368 uint32_t offset, left;
3369 SectionRef S;
3370 const char *layout_map;
3371
3372 if (p == 0)
3373 return;
3374 layout_map = get_pointer_32(p, offset, left, S, info);
3375 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003376}
3377
3378static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3379 const char *indent) {
3380 struct method_list64_t ml;
3381 struct method64_t m;
3382 const char *r;
3383 uint32_t offset, xoffset, left, i;
3384 SectionRef S, xS;
3385 const char *name, *sym_name;
3386 uint64_t n_value;
3387
3388 r = get_pointer_64(p, offset, left, S, info);
3389 if (r == nullptr)
3390 return;
3391 memset(&ml, '\0', sizeof(struct method_list64_t));
3392 if (left < sizeof(struct method_list64_t)) {
3393 memcpy(&ml, r, left);
3394 outs() << " (method_list_t entends past the end of the section)\n";
3395 } else
3396 memcpy(&ml, r, sizeof(struct method_list64_t));
3397 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3398 swapStruct(ml);
3399 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3400 outs() << indent << "\t\t count " << ml.count << "\n";
3401
3402 p += sizeof(struct method_list64_t);
3403 offset += sizeof(struct method_list64_t);
3404 for (i = 0; i < ml.count; i++) {
3405 r = get_pointer_64(p, offset, left, S, info);
3406 if (r == nullptr)
3407 return;
3408 memset(&m, '\0', sizeof(struct method64_t));
3409 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003410 memcpy(&m, r, left);
3411 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003412 } else
3413 memcpy(&m, r, sizeof(struct method64_t));
3414 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3415 swapStruct(m);
3416
3417 outs() << indent << "\t\t name ";
3418 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3419 info, n_value, m.name);
3420 if (n_value != 0) {
3421 if (info->verbose && sym_name != nullptr)
3422 outs() << sym_name;
3423 else
3424 outs() << format("0x%" PRIx64, n_value);
3425 if (m.name != 0)
3426 outs() << " + " << format("0x%" PRIx64, m.name);
3427 } else
3428 outs() << format("0x%" PRIx64, m.name);
3429 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3430 if (name != nullptr)
3431 outs() << format(" %.*s", left, name);
3432 outs() << "\n";
3433
3434 outs() << indent << "\t\t types ";
3435 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3436 info, n_value, m.types);
3437 if (n_value != 0) {
3438 if (info->verbose && sym_name != nullptr)
3439 outs() << sym_name;
3440 else
3441 outs() << format("0x%" PRIx64, n_value);
3442 if (m.types != 0)
3443 outs() << " + " << format("0x%" PRIx64, m.types);
3444 } else
3445 outs() << format("0x%" PRIx64, m.types);
3446 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3447 if (name != nullptr)
3448 outs() << format(" %.*s", left, name);
3449 outs() << "\n";
3450
3451 outs() << indent << "\t\t imp ";
3452 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3453 n_value, m.imp);
3454 if (info->verbose && name == nullptr) {
3455 if (n_value != 0) {
3456 outs() << format("0x%" PRIx64, n_value) << " ";
3457 if (m.imp != 0)
3458 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3459 } else
3460 outs() << format("0x%" PRIx64, m.imp) << " ";
3461 }
3462 if (name != nullptr)
3463 outs() << name;
3464 outs() << "\n";
3465
3466 p += sizeof(struct method64_t);
3467 offset += sizeof(struct method64_t);
3468 }
3469}
3470
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003471static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3472 const char *indent) {
3473 struct method_list32_t ml;
3474 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003475 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003476 uint32_t offset, xoffset, left, i;
3477 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003478
3479 r = get_pointer_32(p, offset, left, S, info);
3480 if (r == nullptr)
3481 return;
3482 memset(&ml, '\0', sizeof(struct method_list32_t));
3483 if (left < sizeof(struct method_list32_t)) {
3484 memcpy(&ml, r, left);
3485 outs() << " (method_list_t entends past the end of the section)\n";
3486 } else
3487 memcpy(&ml, r, sizeof(struct method_list32_t));
3488 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3489 swapStruct(ml);
3490 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3491 outs() << indent << "\t\t count " << ml.count << "\n";
3492
3493 p += sizeof(struct method_list32_t);
3494 offset += sizeof(struct method_list32_t);
3495 for (i = 0; i < ml.count; i++) {
3496 r = get_pointer_32(p, offset, left, S, info);
3497 if (r == nullptr)
3498 return;
3499 memset(&m, '\0', sizeof(struct method32_t));
3500 if (left < sizeof(struct method32_t)) {
3501 memcpy(&ml, r, left);
3502 outs() << indent << " (method_t entends past the end of the section)\n";
3503 } else
3504 memcpy(&m, r, sizeof(struct method32_t));
3505 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3506 swapStruct(m);
3507
3508 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3509 name = get_pointer_32(m.name, xoffset, left, xS, info);
3510 if (name != nullptr)
3511 outs() << format(" %.*s", left, name);
3512 outs() << "\n";
3513
3514 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3515 name = get_pointer_32(m.types, xoffset, left, xS, info);
3516 if (name != nullptr)
3517 outs() << format(" %.*s", left, name);
3518 outs() << "\n";
3519
3520 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3521 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3522 m.imp);
3523 if (name != nullptr)
3524 outs() << " " << name;
3525 outs() << "\n";
3526
3527 p += sizeof(struct method32_t);
3528 offset += sizeof(struct method32_t);
3529 }
3530}
3531
Kevin Enderby846c0002015-04-16 17:19:59 +00003532static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3533 uint32_t offset, left, xleft;
3534 SectionRef S;
3535 struct objc_method_list_t method_list;
3536 struct objc_method_t method;
3537 const char *r, *methods, *name, *SymbolName;
3538 int32_t i;
3539
3540 r = get_pointer_32(p, offset, left, S, info, true);
3541 if (r == nullptr)
3542 return true;
3543
3544 outs() << "\n";
3545 if (left > sizeof(struct objc_method_list_t)) {
3546 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3547 } else {
3548 outs() << "\t\t objc_method_list extends past end of the section\n";
3549 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3550 memcpy(&method_list, r, left);
3551 }
3552 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3553 swapStruct(method_list);
3554
3555 outs() << "\t\t obsolete "
3556 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3557 outs() << "\t\t method_count " << method_list.method_count << "\n";
3558
3559 methods = r + sizeof(struct objc_method_list_t);
3560 for (i = 0; i < method_list.method_count; i++) {
3561 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3562 outs() << "\t\t remaining method's extend past the of the section\n";
3563 break;
3564 }
3565 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3566 sizeof(struct objc_method_t));
3567 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3568 swapStruct(method);
3569
3570 outs() << "\t\t method_name "
3571 << format("0x%08" PRIx32, method.method_name);
3572 if (info->verbose) {
3573 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3574 if (name != nullptr)
3575 outs() << format(" %.*s", xleft, name);
3576 else
3577 outs() << " (not in an __OBJC section)";
3578 }
3579 outs() << "\n";
3580
3581 outs() << "\t\t method_types "
3582 << format("0x%08" PRIx32, method.method_types);
3583 if (info->verbose) {
3584 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3585 if (name != nullptr)
3586 outs() << format(" %.*s", xleft, name);
3587 else
3588 outs() << " (not in an __OBJC section)";
3589 }
3590 outs() << "\n";
3591
3592 outs() << "\t\t method_imp "
3593 << format("0x%08" PRIx32, method.method_imp) << " ";
3594 if (info->verbose) {
3595 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3596 if (SymbolName != nullptr)
3597 outs() << SymbolName;
3598 }
3599 outs() << "\n";
3600 }
3601 return false;
3602}
3603
Kevin Enderby0fc11822015-04-01 20:57:01 +00003604static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3605 struct protocol_list64_t pl;
3606 uint64_t q, n_value;
3607 struct protocol64_t pc;
3608 const char *r;
3609 uint32_t offset, xoffset, left, i;
3610 SectionRef S, xS;
3611 const char *name, *sym_name;
3612
3613 r = get_pointer_64(p, offset, left, S, info);
3614 if (r == nullptr)
3615 return;
3616 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3617 if (left < sizeof(struct protocol_list64_t)) {
3618 memcpy(&pl, r, left);
3619 outs() << " (protocol_list_t entends past the end of the section)\n";
3620 } else
3621 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3622 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3623 swapStruct(pl);
3624 outs() << " count " << pl.count << "\n";
3625
3626 p += sizeof(struct protocol_list64_t);
3627 offset += sizeof(struct protocol_list64_t);
3628 for (i = 0; i < pl.count; i++) {
3629 r = get_pointer_64(p, offset, left, S, info);
3630 if (r == nullptr)
3631 return;
3632 q = 0;
3633 if (left < sizeof(uint64_t)) {
3634 memcpy(&q, r, left);
3635 outs() << " (protocol_t * entends past the end of the section)\n";
3636 } else
3637 memcpy(&q, r, sizeof(uint64_t));
3638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3639 sys::swapByteOrder(q);
3640
3641 outs() << "\t\t list[" << i << "] ";
3642 sym_name = get_symbol_64(offset, S, info, n_value, q);
3643 if (n_value != 0) {
3644 if (info->verbose && sym_name != nullptr)
3645 outs() << sym_name;
3646 else
3647 outs() << format("0x%" PRIx64, n_value);
3648 if (q != 0)
3649 outs() << " + " << format("0x%" PRIx64, q);
3650 } else
3651 outs() << format("0x%" PRIx64, q);
3652 outs() << " (struct protocol_t *)\n";
3653
3654 r = get_pointer_64(q + n_value, offset, left, S, info);
3655 if (r == nullptr)
3656 return;
3657 memset(&pc, '\0', sizeof(struct protocol64_t));
3658 if (left < sizeof(struct protocol64_t)) {
3659 memcpy(&pc, r, left);
3660 outs() << " (protocol_t entends past the end of the section)\n";
3661 } else
3662 memcpy(&pc, r, sizeof(struct protocol64_t));
3663 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3664 swapStruct(pc);
3665
3666 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3667
3668 outs() << "\t\t\t name ";
3669 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3670 info, n_value, pc.name);
3671 if (n_value != 0) {
3672 if (info->verbose && sym_name != nullptr)
3673 outs() << sym_name;
3674 else
3675 outs() << format("0x%" PRIx64, n_value);
3676 if (pc.name != 0)
3677 outs() << " + " << format("0x%" PRIx64, pc.name);
3678 } else
3679 outs() << format("0x%" PRIx64, pc.name);
3680 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3681 if (name != nullptr)
3682 outs() << format(" %.*s", left, name);
3683 outs() << "\n";
3684
3685 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3686
3687 outs() << "\t\t instanceMethods ";
3688 sym_name =
3689 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3690 S, info, n_value, pc.instanceMethods);
3691 if (n_value != 0) {
3692 if (info->verbose && sym_name != nullptr)
3693 outs() << sym_name;
3694 else
3695 outs() << format("0x%" PRIx64, n_value);
3696 if (pc.instanceMethods != 0)
3697 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3698 } else
3699 outs() << format("0x%" PRIx64, pc.instanceMethods);
3700 outs() << " (struct method_list_t *)\n";
3701 if (pc.instanceMethods + n_value != 0)
3702 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3703
3704 outs() << "\t\t classMethods ";
3705 sym_name =
3706 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3707 info, n_value, pc.classMethods);
3708 if (n_value != 0) {
3709 if (info->verbose && sym_name != nullptr)
3710 outs() << sym_name;
3711 else
3712 outs() << format("0x%" PRIx64, n_value);
3713 if (pc.classMethods != 0)
3714 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3715 } else
3716 outs() << format("0x%" PRIx64, pc.classMethods);
3717 outs() << " (struct method_list_t *)\n";
3718 if (pc.classMethods + n_value != 0)
3719 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3720
3721 outs() << "\t optionalInstanceMethods "
3722 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3723 outs() << "\t optionalClassMethods "
3724 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3725 outs() << "\t instanceProperties "
3726 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3727
3728 p += sizeof(uint64_t);
3729 offset += sizeof(uint64_t);
3730 }
3731}
3732
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003733static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3734 struct protocol_list32_t pl;
3735 uint32_t q;
3736 struct protocol32_t pc;
3737 const char *r;
3738 uint32_t offset, xoffset, left, i;
3739 SectionRef S, xS;
3740 const char *name;
3741
3742 r = get_pointer_32(p, offset, left, S, info);
3743 if (r == nullptr)
3744 return;
3745 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3746 if (left < sizeof(struct protocol_list32_t)) {
3747 memcpy(&pl, r, left);
3748 outs() << " (protocol_list_t entends past the end of the section)\n";
3749 } else
3750 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3751 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3752 swapStruct(pl);
3753 outs() << " count " << pl.count << "\n";
3754
3755 p += sizeof(struct protocol_list32_t);
3756 offset += sizeof(struct protocol_list32_t);
3757 for (i = 0; i < pl.count; i++) {
3758 r = get_pointer_32(p, offset, left, S, info);
3759 if (r == nullptr)
3760 return;
3761 q = 0;
3762 if (left < sizeof(uint32_t)) {
3763 memcpy(&q, r, left);
3764 outs() << " (protocol_t * entends past the end of the section)\n";
3765 } else
3766 memcpy(&q, r, sizeof(uint32_t));
3767 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3768 sys::swapByteOrder(q);
3769 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3770 << " (struct protocol_t *)\n";
3771 r = get_pointer_32(q, offset, left, S, info);
3772 if (r == nullptr)
3773 return;
3774 memset(&pc, '\0', sizeof(struct protocol32_t));
3775 if (left < sizeof(struct protocol32_t)) {
3776 memcpy(&pc, r, left);
3777 outs() << " (protocol_t entends past the end of the section)\n";
3778 } else
3779 memcpy(&pc, r, sizeof(struct protocol32_t));
3780 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3781 swapStruct(pc);
3782 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3783 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3784 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3785 if (name != nullptr)
3786 outs() << format(" %.*s", left, name);
3787 outs() << "\n";
3788 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3789 outs() << "\t\t instanceMethods "
3790 << format("0x%" PRIx32, pc.instanceMethods)
3791 << " (struct method_list_t *)\n";
3792 if (pc.instanceMethods != 0)
3793 print_method_list32_t(pc.instanceMethods, info, "\t");
3794 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3795 << " (struct method_list_t *)\n";
3796 if (pc.classMethods != 0)
3797 print_method_list32_t(pc.classMethods, info, "\t");
3798 outs() << "\t optionalInstanceMethods "
3799 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3800 outs() << "\t optionalClassMethods "
3801 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3802 outs() << "\t instanceProperties "
3803 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3804 p += sizeof(uint32_t);
3805 offset += sizeof(uint32_t);
3806 }
3807}
3808
Kevin Enderby846c0002015-04-16 17:19:59 +00003809static void print_indent(uint32_t indent) {
3810 for (uint32_t i = 0; i < indent;) {
3811 if (indent - i >= 8) {
3812 outs() << "\t";
3813 i += 8;
3814 } else {
3815 for (uint32_t j = i; j < indent; j++)
3816 outs() << " ";
3817 return;
3818 }
3819 }
3820}
3821
3822static bool print_method_description_list(uint32_t p, uint32_t indent,
3823 struct DisassembleInfo *info) {
3824 uint32_t offset, left, xleft;
3825 SectionRef S;
3826 struct objc_method_description_list_t mdl;
3827 struct objc_method_description_t md;
3828 const char *r, *list, *name;
3829 int32_t i;
3830
3831 r = get_pointer_32(p, offset, left, S, info, true);
3832 if (r == nullptr)
3833 return true;
3834
3835 outs() << "\n";
3836 if (left > sizeof(struct objc_method_description_list_t)) {
3837 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3838 } else {
3839 print_indent(indent);
3840 outs() << " objc_method_description_list extends past end of the section\n";
3841 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3842 memcpy(&mdl, r, left);
3843 }
3844 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3845 swapStruct(mdl);
3846
3847 print_indent(indent);
3848 outs() << " count " << mdl.count << "\n";
3849
3850 list = r + sizeof(struct objc_method_description_list_t);
3851 for (i = 0; i < mdl.count; i++) {
3852 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3853 print_indent(indent);
3854 outs() << " remaining list entries extend past the of the section\n";
3855 break;
3856 }
3857 print_indent(indent);
3858 outs() << " list[" << i << "]\n";
3859 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3860 sizeof(struct objc_method_description_t));
3861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3862 swapStruct(md);
3863
3864 print_indent(indent);
3865 outs() << " name " << format("0x%08" PRIx32, md.name);
3866 if (info->verbose) {
3867 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3868 if (name != nullptr)
3869 outs() << format(" %.*s", xleft, name);
3870 else
3871 outs() << " (not in an __OBJC section)";
3872 }
3873 outs() << "\n";
3874
3875 print_indent(indent);
3876 outs() << " types " << format("0x%08" PRIx32, md.types);
3877 if (info->verbose) {
3878 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3879 if (name != nullptr)
3880 outs() << format(" %.*s", xleft, name);
3881 else
3882 outs() << " (not in an __OBJC section)";
3883 }
3884 outs() << "\n";
3885 }
3886 return false;
3887}
3888
3889static bool print_protocol_list(uint32_t p, uint32_t indent,
3890 struct DisassembleInfo *info);
3891
3892static bool print_protocol(uint32_t p, uint32_t indent,
3893 struct DisassembleInfo *info) {
3894 uint32_t offset, left;
3895 SectionRef S;
3896 struct objc_protocol_t protocol;
3897 const char *r, *name;
3898
3899 r = get_pointer_32(p, offset, left, S, info, true);
3900 if (r == nullptr)
3901 return true;
3902
3903 outs() << "\n";
3904 if (left >= sizeof(struct objc_protocol_t)) {
3905 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3906 } else {
3907 print_indent(indent);
3908 outs() << " Protocol extends past end of the section\n";
3909 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3910 memcpy(&protocol, r, left);
3911 }
3912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3913 swapStruct(protocol);
3914
3915 print_indent(indent);
3916 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3917 << "\n";
3918
3919 print_indent(indent);
3920 outs() << " protocol_name "
3921 << format("0x%08" PRIx32, protocol.protocol_name);
3922 if (info->verbose) {
3923 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3924 if (name != nullptr)
3925 outs() << format(" %.*s", left, name);
3926 else
3927 outs() << " (not in an __OBJC section)";
3928 }
3929 outs() << "\n";
3930
3931 print_indent(indent);
3932 outs() << " protocol_list "
3933 << format("0x%08" PRIx32, protocol.protocol_list);
3934 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3935 outs() << " (not in an __OBJC section)\n";
3936
3937 print_indent(indent);
3938 outs() << " instance_methods "
3939 << format("0x%08" PRIx32, protocol.instance_methods);
3940 if (print_method_description_list(protocol.instance_methods, indent, info))
3941 outs() << " (not in an __OBJC section)\n";
3942
3943 print_indent(indent);
3944 outs() << " class_methods "
3945 << format("0x%08" PRIx32, protocol.class_methods);
3946 if (print_method_description_list(protocol.class_methods, indent, info))
3947 outs() << " (not in an __OBJC section)\n";
3948
3949 return false;
3950}
3951
3952static bool print_protocol_list(uint32_t p, uint32_t indent,
3953 struct DisassembleInfo *info) {
3954 uint32_t offset, left, l;
3955 SectionRef S;
3956 struct objc_protocol_list_t protocol_list;
3957 const char *r, *list;
3958 int32_t i;
3959
3960 r = get_pointer_32(p, offset, left, S, info, true);
3961 if (r == nullptr)
3962 return true;
3963
3964 outs() << "\n";
3965 if (left > sizeof(struct objc_protocol_list_t)) {
3966 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3967 } else {
3968 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3969 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3970 memcpy(&protocol_list, r, left);
3971 }
3972 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3973 swapStruct(protocol_list);
3974
3975 print_indent(indent);
3976 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3977 << "\n";
3978 print_indent(indent);
3979 outs() << " count " << protocol_list.count << "\n";
3980
3981 list = r + sizeof(struct objc_protocol_list_t);
3982 for (i = 0; i < protocol_list.count; i++) {
3983 if ((i + 1) * sizeof(uint32_t) > left) {
3984 outs() << "\t\t remaining list entries extend past the of the section\n";
3985 break;
3986 }
3987 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
3988 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3989 sys::swapByteOrder(l);
3990
3991 print_indent(indent);
3992 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
3993 if (print_protocol(l, indent, info))
3994 outs() << "(not in an __OBJC section)\n";
3995 }
3996 return false;
3997}
3998
Kevin Enderby0fc11822015-04-01 20:57:01 +00003999static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4000 struct ivar_list64_t il;
4001 struct ivar64_t i;
4002 const char *r;
4003 uint32_t offset, xoffset, left, j;
4004 SectionRef S, xS;
4005 const char *name, *sym_name, *ivar_offset_p;
4006 uint64_t ivar_offset, n_value;
4007
4008 r = get_pointer_64(p, offset, left, S, info);
4009 if (r == nullptr)
4010 return;
4011 memset(&il, '\0', sizeof(struct ivar_list64_t));
4012 if (left < sizeof(struct ivar_list64_t)) {
4013 memcpy(&il, r, left);
4014 outs() << " (ivar_list_t entends past the end of the section)\n";
4015 } else
4016 memcpy(&il, r, sizeof(struct ivar_list64_t));
4017 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4018 swapStruct(il);
4019 outs() << " entsize " << il.entsize << "\n";
4020 outs() << " count " << il.count << "\n";
4021
4022 p += sizeof(struct ivar_list64_t);
4023 offset += sizeof(struct ivar_list64_t);
4024 for (j = 0; j < il.count; j++) {
4025 r = get_pointer_64(p, offset, left, S, info);
4026 if (r == nullptr)
4027 return;
4028 memset(&i, '\0', sizeof(struct ivar64_t));
4029 if (left < sizeof(struct ivar64_t)) {
4030 memcpy(&i, r, left);
4031 outs() << " (ivar_t entends past the end of the section)\n";
4032 } else
4033 memcpy(&i, r, sizeof(struct ivar64_t));
4034 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4035 swapStruct(i);
4036
4037 outs() << "\t\t\t offset ";
4038 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4039 info, n_value, i.offset);
4040 if (n_value != 0) {
4041 if (info->verbose && sym_name != nullptr)
4042 outs() << sym_name;
4043 else
4044 outs() << format("0x%" PRIx64, n_value);
4045 if (i.offset != 0)
4046 outs() << " + " << format("0x%" PRIx64, i.offset);
4047 } else
4048 outs() << format("0x%" PRIx64, i.offset);
4049 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4050 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4051 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4052 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4053 sys::swapByteOrder(ivar_offset);
4054 outs() << " " << ivar_offset << "\n";
4055 } else
4056 outs() << "\n";
4057
4058 outs() << "\t\t\t name ";
4059 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4060 n_value, i.name);
4061 if (n_value != 0) {
4062 if (info->verbose && sym_name != nullptr)
4063 outs() << sym_name;
4064 else
4065 outs() << format("0x%" PRIx64, n_value);
4066 if (i.name != 0)
4067 outs() << " + " << format("0x%" PRIx64, i.name);
4068 } else
4069 outs() << format("0x%" PRIx64, i.name);
4070 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4071 if (name != nullptr)
4072 outs() << format(" %.*s", left, name);
4073 outs() << "\n";
4074
4075 outs() << "\t\t\t type ";
4076 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4077 n_value, i.name);
4078 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4079 if (n_value != 0) {
4080 if (info->verbose && sym_name != nullptr)
4081 outs() << sym_name;
4082 else
4083 outs() << format("0x%" PRIx64, n_value);
4084 if (i.type != 0)
4085 outs() << " + " << format("0x%" PRIx64, i.type);
4086 } else
4087 outs() << format("0x%" PRIx64, i.type);
4088 if (name != nullptr)
4089 outs() << format(" %.*s", left, name);
4090 outs() << "\n";
4091
4092 outs() << "\t\t\talignment " << i.alignment << "\n";
4093 outs() << "\t\t\t size " << i.size << "\n";
4094
4095 p += sizeof(struct ivar64_t);
4096 offset += sizeof(struct ivar64_t);
4097 }
4098}
4099
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004100static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4101 struct ivar_list32_t il;
4102 struct ivar32_t i;
4103 const char *r;
4104 uint32_t offset, xoffset, left, j;
4105 SectionRef S, xS;
4106 const char *name, *ivar_offset_p;
4107 uint32_t ivar_offset;
4108
4109 r = get_pointer_32(p, offset, left, S, info);
4110 if (r == nullptr)
4111 return;
4112 memset(&il, '\0', sizeof(struct ivar_list32_t));
4113 if (left < sizeof(struct ivar_list32_t)) {
4114 memcpy(&il, r, left);
4115 outs() << " (ivar_list_t entends past the end of the section)\n";
4116 } else
4117 memcpy(&il, r, sizeof(struct ivar_list32_t));
4118 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4119 swapStruct(il);
4120 outs() << " entsize " << il.entsize << "\n";
4121 outs() << " count " << il.count << "\n";
4122
4123 p += sizeof(struct ivar_list32_t);
4124 offset += sizeof(struct ivar_list32_t);
4125 for (j = 0; j < il.count; j++) {
4126 r = get_pointer_32(p, offset, left, S, info);
4127 if (r == nullptr)
4128 return;
4129 memset(&i, '\0', sizeof(struct ivar32_t));
4130 if (left < sizeof(struct ivar32_t)) {
4131 memcpy(&i, r, left);
4132 outs() << " (ivar_t entends past the end of the section)\n";
4133 } else
4134 memcpy(&i, r, sizeof(struct ivar32_t));
4135 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4136 swapStruct(i);
4137
4138 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4139 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4140 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4141 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4142 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4143 sys::swapByteOrder(ivar_offset);
4144 outs() << " " << ivar_offset << "\n";
4145 } else
4146 outs() << "\n";
4147
4148 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4149 name = get_pointer_32(i.name, xoffset, left, xS, info);
4150 if (name != nullptr)
4151 outs() << format(" %.*s", left, name);
4152 outs() << "\n";
4153
4154 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4155 name = get_pointer_32(i.type, xoffset, left, xS, info);
4156 if (name != nullptr)
4157 outs() << format(" %.*s", left, name);
4158 outs() << "\n";
4159
4160 outs() << "\t\t\talignment " << i.alignment << "\n";
4161 outs() << "\t\t\t size " << i.size << "\n";
4162
4163 p += sizeof(struct ivar32_t);
4164 offset += sizeof(struct ivar32_t);
4165 }
4166}
4167
Kevin Enderby0fc11822015-04-01 20:57:01 +00004168static void print_objc_property_list64(uint64_t p,
4169 struct DisassembleInfo *info) {
4170 struct objc_property_list64 opl;
4171 struct objc_property64 op;
4172 const char *r;
4173 uint32_t offset, xoffset, left, j;
4174 SectionRef S, xS;
4175 const char *name, *sym_name;
4176 uint64_t n_value;
4177
4178 r = get_pointer_64(p, offset, left, S, info);
4179 if (r == nullptr)
4180 return;
4181 memset(&opl, '\0', sizeof(struct objc_property_list64));
4182 if (left < sizeof(struct objc_property_list64)) {
4183 memcpy(&opl, r, left);
4184 outs() << " (objc_property_list entends past the end of the section)\n";
4185 } else
4186 memcpy(&opl, r, sizeof(struct objc_property_list64));
4187 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4188 swapStruct(opl);
4189 outs() << " entsize " << opl.entsize << "\n";
4190 outs() << " count " << opl.count << "\n";
4191
4192 p += sizeof(struct objc_property_list64);
4193 offset += sizeof(struct objc_property_list64);
4194 for (j = 0; j < opl.count; j++) {
4195 r = get_pointer_64(p, offset, left, S, info);
4196 if (r == nullptr)
4197 return;
4198 memset(&op, '\0', sizeof(struct objc_property64));
4199 if (left < sizeof(struct objc_property64)) {
4200 memcpy(&op, r, left);
4201 outs() << " (objc_property entends past the end of the section)\n";
4202 } else
4203 memcpy(&op, r, sizeof(struct objc_property64));
4204 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4205 swapStruct(op);
4206
4207 outs() << "\t\t\t name ";
4208 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4209 info, n_value, op.name);
4210 if (n_value != 0) {
4211 if (info->verbose && sym_name != nullptr)
4212 outs() << sym_name;
4213 else
4214 outs() << format("0x%" PRIx64, n_value);
4215 if (op.name != 0)
4216 outs() << " + " << format("0x%" PRIx64, op.name);
4217 } else
4218 outs() << format("0x%" PRIx64, op.name);
4219 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4220 if (name != nullptr)
4221 outs() << format(" %.*s", left, name);
4222 outs() << "\n";
4223
4224 outs() << "\t\t\tattributes ";
4225 sym_name =
4226 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4227 info, n_value, op.attributes);
4228 if (n_value != 0) {
4229 if (info->verbose && sym_name != nullptr)
4230 outs() << sym_name;
4231 else
4232 outs() << format("0x%" PRIx64, n_value);
4233 if (op.attributes != 0)
4234 outs() << " + " << format("0x%" PRIx64, op.attributes);
4235 } else
4236 outs() << format("0x%" PRIx64, op.attributes);
4237 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4238 if (name != nullptr)
4239 outs() << format(" %.*s", left, name);
4240 outs() << "\n";
4241
4242 p += sizeof(struct objc_property64);
4243 offset += sizeof(struct objc_property64);
4244 }
4245}
4246
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004247static void print_objc_property_list32(uint32_t p,
4248 struct DisassembleInfo *info) {
4249 struct objc_property_list32 opl;
4250 struct objc_property32 op;
4251 const char *r;
4252 uint32_t offset, xoffset, left, j;
4253 SectionRef S, xS;
4254 const char *name;
4255
4256 r = get_pointer_32(p, offset, left, S, info);
4257 if (r == nullptr)
4258 return;
4259 memset(&opl, '\0', sizeof(struct objc_property_list32));
4260 if (left < sizeof(struct objc_property_list32)) {
4261 memcpy(&opl, r, left);
4262 outs() << " (objc_property_list entends past the end of the section)\n";
4263 } else
4264 memcpy(&opl, r, sizeof(struct objc_property_list32));
4265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4266 swapStruct(opl);
4267 outs() << " entsize " << opl.entsize << "\n";
4268 outs() << " count " << opl.count << "\n";
4269
4270 p += sizeof(struct objc_property_list32);
4271 offset += sizeof(struct objc_property_list32);
4272 for (j = 0; j < opl.count; j++) {
4273 r = get_pointer_32(p, offset, left, S, info);
4274 if (r == nullptr)
4275 return;
4276 memset(&op, '\0', sizeof(struct objc_property32));
4277 if (left < sizeof(struct objc_property32)) {
4278 memcpy(&op, r, left);
4279 outs() << " (objc_property entends past the end of the section)\n";
4280 } else
4281 memcpy(&op, r, sizeof(struct objc_property32));
4282 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4283 swapStruct(op);
4284
4285 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4286 name = get_pointer_32(op.name, xoffset, left, xS, info);
4287 if (name != nullptr)
4288 outs() << format(" %.*s", left, name);
4289 outs() << "\n";
4290
4291 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4292 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4293 if (name != nullptr)
4294 outs() << format(" %.*s", left, name);
4295 outs() << "\n";
4296
4297 p += sizeof(struct objc_property32);
4298 offset += sizeof(struct objc_property32);
4299 }
4300}
4301
Richard Smith81ff44d2015-10-09 22:09:56 +00004302static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004303 bool &is_meta_class) {
4304 struct class_ro64_t cro;
4305 const char *r;
4306 uint32_t offset, xoffset, left;
4307 SectionRef S, xS;
4308 const char *name, *sym_name;
4309 uint64_t n_value;
4310
4311 r = get_pointer_64(p, offset, left, S, info);
4312 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004313 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004314 memset(&cro, '\0', sizeof(struct class_ro64_t));
4315 if (left < sizeof(struct class_ro64_t)) {
4316 memcpy(&cro, r, left);
4317 outs() << " (class_ro_t entends past the end of the section)\n";
4318 } else
4319 memcpy(&cro, r, sizeof(struct class_ro64_t));
4320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4321 swapStruct(cro);
4322 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4323 if (cro.flags & RO_META)
4324 outs() << " RO_META";
4325 if (cro.flags & RO_ROOT)
4326 outs() << " RO_ROOT";
4327 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4328 outs() << " RO_HAS_CXX_STRUCTORS";
4329 outs() << "\n";
4330 outs() << " instanceStart " << cro.instanceStart << "\n";
4331 outs() << " instanceSize " << cro.instanceSize << "\n";
4332 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4333 << "\n";
4334 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4335 << "\n";
4336 print_layout_map64(cro.ivarLayout, info);
4337
4338 outs() << " name ";
4339 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4340 info, n_value, cro.name);
4341 if (n_value != 0) {
4342 if (info->verbose && sym_name != nullptr)
4343 outs() << sym_name;
4344 else
4345 outs() << format("0x%" PRIx64, n_value);
4346 if (cro.name != 0)
4347 outs() << " + " << format("0x%" PRIx64, cro.name);
4348 } else
4349 outs() << format("0x%" PRIx64, cro.name);
4350 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4351 if (name != nullptr)
4352 outs() << format(" %.*s", left, name);
4353 outs() << "\n";
4354
4355 outs() << " baseMethods ";
4356 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4357 S, info, n_value, cro.baseMethods);
4358 if (n_value != 0) {
4359 if (info->verbose && sym_name != nullptr)
4360 outs() << sym_name;
4361 else
4362 outs() << format("0x%" PRIx64, n_value);
4363 if (cro.baseMethods != 0)
4364 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4365 } else
4366 outs() << format("0x%" PRIx64, cro.baseMethods);
4367 outs() << " (struct method_list_t *)\n";
4368 if (cro.baseMethods + n_value != 0)
4369 print_method_list64_t(cro.baseMethods + n_value, info, "");
4370
4371 outs() << " baseProtocols ";
4372 sym_name =
4373 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4374 info, n_value, cro.baseProtocols);
4375 if (n_value != 0) {
4376 if (info->verbose && sym_name != nullptr)
4377 outs() << sym_name;
4378 else
4379 outs() << format("0x%" PRIx64, n_value);
4380 if (cro.baseProtocols != 0)
4381 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4382 } else
4383 outs() << format("0x%" PRIx64, cro.baseProtocols);
4384 outs() << "\n";
4385 if (cro.baseProtocols + n_value != 0)
4386 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4387
4388 outs() << " ivars ";
4389 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004390 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004391 if (n_value != 0) {
4392 if (info->verbose && sym_name != nullptr)
4393 outs() << sym_name;
4394 else
4395 outs() << format("0x%" PRIx64, n_value);
4396 if (cro.ivars != 0)
4397 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4398 } else
4399 outs() << format("0x%" PRIx64, cro.ivars);
4400 outs() << "\n";
4401 if (cro.ivars + n_value != 0)
4402 print_ivar_list64_t(cro.ivars + n_value, info);
4403
4404 outs() << " weakIvarLayout ";
4405 sym_name =
4406 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4407 info, n_value, cro.weakIvarLayout);
4408 if (n_value != 0) {
4409 if (info->verbose && sym_name != nullptr)
4410 outs() << sym_name;
4411 else
4412 outs() << format("0x%" PRIx64, n_value);
4413 if (cro.weakIvarLayout != 0)
4414 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4415 } else
4416 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4417 outs() << "\n";
4418 print_layout_map64(cro.weakIvarLayout + n_value, info);
4419
4420 outs() << " baseProperties ";
4421 sym_name =
4422 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4423 info, n_value, cro.baseProperties);
4424 if (n_value != 0) {
4425 if (info->verbose && sym_name != nullptr)
4426 outs() << sym_name;
4427 else
4428 outs() << format("0x%" PRIx64, n_value);
4429 if (cro.baseProperties != 0)
4430 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4431 } else
4432 outs() << format("0x%" PRIx64, cro.baseProperties);
4433 outs() << "\n";
4434 if (cro.baseProperties + n_value != 0)
4435 print_objc_property_list64(cro.baseProperties + n_value, info);
4436
Rafael Espindolab9091322015-10-24 23:19:10 +00004437 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004438 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004439}
4440
Richard Smith81ff44d2015-10-09 22:09:56 +00004441static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004442 bool &is_meta_class) {
4443 struct class_ro32_t cro;
4444 const char *r;
4445 uint32_t offset, xoffset, left;
4446 SectionRef S, xS;
4447 const char *name;
4448
4449 r = get_pointer_32(p, offset, left, S, info);
4450 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004451 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004452 memset(&cro, '\0', sizeof(struct class_ro32_t));
4453 if (left < sizeof(struct class_ro32_t)) {
4454 memcpy(&cro, r, left);
4455 outs() << " (class_ro_t entends past the end of the section)\n";
4456 } else
4457 memcpy(&cro, r, sizeof(struct class_ro32_t));
4458 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4459 swapStruct(cro);
4460 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4461 if (cro.flags & RO_META)
4462 outs() << " RO_META";
4463 if (cro.flags & RO_ROOT)
4464 outs() << " RO_ROOT";
4465 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4466 outs() << " RO_HAS_CXX_STRUCTORS";
4467 outs() << "\n";
4468 outs() << " instanceStart " << cro.instanceStart << "\n";
4469 outs() << " instanceSize " << cro.instanceSize << "\n";
4470 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4471 << "\n";
4472 print_layout_map32(cro.ivarLayout, info);
4473
4474 outs() << " name " << format("0x%" PRIx32, cro.name);
4475 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4476 if (name != nullptr)
4477 outs() << format(" %.*s", left, name);
4478 outs() << "\n";
4479
4480 outs() << " baseMethods "
4481 << format("0x%" PRIx32, cro.baseMethods)
4482 << " (struct method_list_t *)\n";
4483 if (cro.baseMethods != 0)
4484 print_method_list32_t(cro.baseMethods, info, "");
4485
4486 outs() << " baseProtocols "
4487 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4488 if (cro.baseProtocols != 0)
4489 print_protocol_list32_t(cro.baseProtocols, info);
4490 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4491 << "\n";
4492 if (cro.ivars != 0)
4493 print_ivar_list32_t(cro.ivars, info);
4494 outs() << " weakIvarLayout "
4495 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4496 print_layout_map32(cro.weakIvarLayout, info);
4497 outs() << " baseProperties "
4498 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4499 if (cro.baseProperties != 0)
4500 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004501 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004502 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004503}
4504
Kevin Enderby0fc11822015-04-01 20:57:01 +00004505static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4506 struct class64_t c;
4507 const char *r;
4508 uint32_t offset, left;
4509 SectionRef S;
4510 const char *name;
4511 uint64_t isa_n_value, n_value;
4512
4513 r = get_pointer_64(p, offset, left, S, info);
4514 if (r == nullptr || left < sizeof(struct class64_t))
4515 return;
4516 memset(&c, '\0', sizeof(struct class64_t));
4517 if (left < sizeof(struct class64_t)) {
4518 memcpy(&c, r, left);
4519 outs() << " (class_t entends past the end of the section)\n";
4520 } else
4521 memcpy(&c, r, sizeof(struct class64_t));
4522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4523 swapStruct(c);
4524
4525 outs() << " isa " << format("0x%" PRIx64, c.isa);
4526 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4527 isa_n_value, c.isa);
4528 if (name != nullptr)
4529 outs() << " " << name;
4530 outs() << "\n";
4531
4532 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4533 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4534 n_value, c.superclass);
4535 if (name != nullptr)
4536 outs() << " " << name;
4537 outs() << "\n";
4538
4539 outs() << " cache " << format("0x%" PRIx64, c.cache);
4540 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4541 n_value, c.cache);
4542 if (name != nullptr)
4543 outs() << " " << name;
4544 outs() << "\n";
4545
4546 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4547 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4548 n_value, c.vtable);
4549 if (name != nullptr)
4550 outs() << " " << name;
4551 outs() << "\n";
4552
4553 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4554 n_value, c.data);
4555 outs() << " data ";
4556 if (n_value != 0) {
4557 if (info->verbose && name != nullptr)
4558 outs() << name;
4559 else
4560 outs() << format("0x%" PRIx64, n_value);
4561 if (c.data != 0)
4562 outs() << " + " << format("0x%" PRIx64, c.data);
4563 } else
4564 outs() << format("0x%" PRIx64, c.data);
4565 outs() << " (struct class_ro_t *)";
4566
4567 // This is a Swift class if some of the low bits of the pointer are set.
4568 if ((c.data + n_value) & 0x7)
4569 outs() << " Swift class";
4570 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004571 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004572 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4573 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004574
Kevin Enderbyaac75382015-10-08 16:56:35 +00004575 if (!is_meta_class &&
4576 c.isa + isa_n_value != p &&
4577 c.isa + isa_n_value != 0 &&
4578 info->depth < 100) {
4579 info->depth++;
4580 outs() << "Meta Class\n";
4581 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004582 }
4583}
4584
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004585static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4586 struct class32_t c;
4587 const char *r;
4588 uint32_t offset, left;
4589 SectionRef S;
4590 const char *name;
4591
4592 r = get_pointer_32(p, offset, left, S, info);
4593 if (r == nullptr)
4594 return;
4595 memset(&c, '\0', sizeof(struct class32_t));
4596 if (left < sizeof(struct class32_t)) {
4597 memcpy(&c, r, left);
4598 outs() << " (class_t entends past the end of the section)\n";
4599 } else
4600 memcpy(&c, r, sizeof(struct class32_t));
4601 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4602 swapStruct(c);
4603
4604 outs() << " isa " << format("0x%" PRIx32, c.isa);
4605 name =
4606 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4607 if (name != nullptr)
4608 outs() << " " << name;
4609 outs() << "\n";
4610
4611 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4612 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4613 c.superclass);
4614 if (name != nullptr)
4615 outs() << " " << name;
4616 outs() << "\n";
4617
4618 outs() << " cache " << format("0x%" PRIx32, c.cache);
4619 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4620 c.cache);
4621 if (name != nullptr)
4622 outs() << " " << name;
4623 outs() << "\n";
4624
4625 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4626 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4627 c.vtable);
4628 if (name != nullptr)
4629 outs() << " " << name;
4630 outs() << "\n";
4631
4632 name =
4633 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4634 outs() << " data " << format("0x%" PRIx32, c.data)
4635 << " (struct class_ro_t *)";
4636
4637 // This is a Swift class if some of the low bits of the pointer are set.
4638 if (c.data & 0x3)
4639 outs() << " Swift class";
4640 outs() << "\n";
4641 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004642 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4643 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004644
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004645 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004646 outs() << "Meta Class\n";
4647 print_class32_t(c.isa, info);
4648 }
4649}
4650
Kevin Enderby846c0002015-04-16 17:19:59 +00004651static void print_objc_class_t(struct objc_class_t *objc_class,
4652 struct DisassembleInfo *info) {
4653 uint32_t offset, left, xleft;
4654 const char *name, *p, *ivar_list;
4655 SectionRef S;
4656 int32_t i;
4657 struct objc_ivar_list_t objc_ivar_list;
4658 struct objc_ivar_t ivar;
4659
4660 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4661 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4662 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4663 if (name != nullptr)
4664 outs() << format(" %.*s", left, name);
4665 else
4666 outs() << " (not in an __OBJC section)";
4667 }
4668 outs() << "\n";
4669
4670 outs() << "\t super_class "
4671 << format("0x%08" PRIx32, objc_class->super_class);
4672 if (info->verbose) {
4673 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4674 if (name != nullptr)
4675 outs() << format(" %.*s", left, name);
4676 else
4677 outs() << " (not in an __OBJC section)";
4678 }
4679 outs() << "\n";
4680
4681 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4682 if (info->verbose) {
4683 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4684 if (name != nullptr)
4685 outs() << format(" %.*s", left, name);
4686 else
4687 outs() << " (not in an __OBJC section)";
4688 }
4689 outs() << "\n";
4690
4691 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4692 << "\n";
4693
4694 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4695 if (info->verbose) {
4696 if (CLS_GETINFO(objc_class, CLS_CLASS))
4697 outs() << " CLS_CLASS";
4698 else if (CLS_GETINFO(objc_class, CLS_META))
4699 outs() << " CLS_META";
4700 }
4701 outs() << "\n";
4702
4703 outs() << "\t instance_size "
4704 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4705
4706 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4707 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4708 if (p != nullptr) {
4709 if (left > sizeof(struct objc_ivar_list_t)) {
4710 outs() << "\n";
4711 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4712 } else {
4713 outs() << " (entends past the end of the section)\n";
4714 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4715 memcpy(&objc_ivar_list, p, left);
4716 }
4717 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4718 swapStruct(objc_ivar_list);
4719 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4720 ivar_list = p + sizeof(struct objc_ivar_list_t);
4721 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4722 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4723 outs() << "\t\t remaining ivar's extend past the of the section\n";
4724 break;
4725 }
4726 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4727 sizeof(struct objc_ivar_t));
4728 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4729 swapStruct(ivar);
4730
4731 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4732 if (info->verbose) {
4733 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", xleft, name);
4736 else
4737 outs() << " (not in an __OBJC section)";
4738 }
4739 outs() << "\n";
4740
4741 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4742 if (info->verbose) {
4743 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4744 if (name != nullptr)
4745 outs() << format(" %.*s", xleft, name);
4746 else
4747 outs() << " (not in an __OBJC section)";
4748 }
4749 outs() << "\n";
4750
4751 outs() << "\t\t ivar_offset "
4752 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4753 }
4754 } else {
4755 outs() << " (not in an __OBJC section)\n";
4756 }
4757
4758 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4759 if (print_method_list(objc_class->methodLists, info))
4760 outs() << " (not in an __OBJC section)\n";
4761
4762 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4763 << "\n";
4764
4765 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4766 if (print_protocol_list(objc_class->protocols, 16, info))
4767 outs() << " (not in an __OBJC section)\n";
4768}
4769
4770static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4771 struct DisassembleInfo *info) {
4772 uint32_t offset, left;
4773 const char *name;
4774 SectionRef S;
4775
4776 outs() << "\t category name "
4777 << format("0x%08" PRIx32, objc_category->category_name);
4778 if (info->verbose) {
4779 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4780 true);
4781 if (name != nullptr)
4782 outs() << format(" %.*s", left, name);
4783 else
4784 outs() << " (not in an __OBJC section)";
4785 }
4786 outs() << "\n";
4787
4788 outs() << "\t\t class name "
4789 << format("0x%08" PRIx32, objc_category->class_name);
4790 if (info->verbose) {
4791 name =
4792 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4793 if (name != nullptr)
4794 outs() << format(" %.*s", left, name);
4795 else
4796 outs() << " (not in an __OBJC section)";
4797 }
4798 outs() << "\n";
4799
4800 outs() << "\t instance methods "
4801 << format("0x%08" PRIx32, objc_category->instance_methods);
4802 if (print_method_list(objc_category->instance_methods, info))
4803 outs() << " (not in an __OBJC section)\n";
4804
4805 outs() << "\t class methods "
4806 << format("0x%08" PRIx32, objc_category->class_methods);
4807 if (print_method_list(objc_category->class_methods, info))
4808 outs() << " (not in an __OBJC section)\n";
4809}
4810
Kevin Enderby0fc11822015-04-01 20:57:01 +00004811static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4812 struct category64_t c;
4813 const char *r;
4814 uint32_t offset, xoffset, left;
4815 SectionRef S, xS;
4816 const char *name, *sym_name;
4817 uint64_t n_value;
4818
4819 r = get_pointer_64(p, offset, left, S, info);
4820 if (r == nullptr)
4821 return;
4822 memset(&c, '\0', sizeof(struct category64_t));
4823 if (left < sizeof(struct category64_t)) {
4824 memcpy(&c, r, left);
4825 outs() << " (category_t entends past the end of the section)\n";
4826 } else
4827 memcpy(&c, r, sizeof(struct category64_t));
4828 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4829 swapStruct(c);
4830
4831 outs() << " name ";
4832 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4833 info, n_value, c.name);
4834 if (n_value != 0) {
4835 if (info->verbose && sym_name != nullptr)
4836 outs() << sym_name;
4837 else
4838 outs() << format("0x%" PRIx64, n_value);
4839 if (c.name != 0)
4840 outs() << " + " << format("0x%" PRIx64, c.name);
4841 } else
4842 outs() << format("0x%" PRIx64, c.name);
4843 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4844 if (name != nullptr)
4845 outs() << format(" %.*s", left, name);
4846 outs() << "\n";
4847
4848 outs() << " cls ";
4849 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4850 n_value, c.cls);
4851 if (n_value != 0) {
4852 if (info->verbose && sym_name != nullptr)
4853 outs() << sym_name;
4854 else
4855 outs() << format("0x%" PRIx64, n_value);
4856 if (c.cls != 0)
4857 outs() << " + " << format("0x%" PRIx64, c.cls);
4858 } else
4859 outs() << format("0x%" PRIx64, c.cls);
4860 outs() << "\n";
4861 if (c.cls + n_value != 0)
4862 print_class64_t(c.cls + n_value, info);
4863
4864 outs() << " instanceMethods ";
4865 sym_name =
4866 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4867 info, n_value, c.instanceMethods);
4868 if (n_value != 0) {
4869 if (info->verbose && sym_name != nullptr)
4870 outs() << sym_name;
4871 else
4872 outs() << format("0x%" PRIx64, n_value);
4873 if (c.instanceMethods != 0)
4874 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4875 } else
4876 outs() << format("0x%" PRIx64, c.instanceMethods);
4877 outs() << "\n";
4878 if (c.instanceMethods + n_value != 0)
4879 print_method_list64_t(c.instanceMethods + n_value, info, "");
4880
4881 outs() << " classMethods ";
4882 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4883 S, info, n_value, c.classMethods);
4884 if (n_value != 0) {
4885 if (info->verbose && sym_name != nullptr)
4886 outs() << sym_name;
4887 else
4888 outs() << format("0x%" PRIx64, n_value);
4889 if (c.classMethods != 0)
4890 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4891 } else
4892 outs() << format("0x%" PRIx64, c.classMethods);
4893 outs() << "\n";
4894 if (c.classMethods + n_value != 0)
4895 print_method_list64_t(c.classMethods + n_value, info, "");
4896
4897 outs() << " protocols ";
4898 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4899 info, n_value, c.protocols);
4900 if (n_value != 0) {
4901 if (info->verbose && sym_name != nullptr)
4902 outs() << sym_name;
4903 else
4904 outs() << format("0x%" PRIx64, n_value);
4905 if (c.protocols != 0)
4906 outs() << " + " << format("0x%" PRIx64, c.protocols);
4907 } else
4908 outs() << format("0x%" PRIx64, c.protocols);
4909 outs() << "\n";
4910 if (c.protocols + n_value != 0)
4911 print_protocol_list64_t(c.protocols + n_value, info);
4912
4913 outs() << "instanceProperties ";
4914 sym_name =
4915 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4916 S, info, n_value, c.instanceProperties);
4917 if (n_value != 0) {
4918 if (info->verbose && sym_name != nullptr)
4919 outs() << sym_name;
4920 else
4921 outs() << format("0x%" PRIx64, n_value);
4922 if (c.instanceProperties != 0)
4923 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4924 } else
4925 outs() << format("0x%" PRIx64, c.instanceProperties);
4926 outs() << "\n";
4927 if (c.instanceProperties + n_value != 0)
4928 print_objc_property_list64(c.instanceProperties + n_value, info);
4929}
4930
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004931static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4932 struct category32_t c;
4933 const char *r;
4934 uint32_t offset, left;
4935 SectionRef S, xS;
4936 const char *name;
4937
4938 r = get_pointer_32(p, offset, left, S, info);
4939 if (r == nullptr)
4940 return;
4941 memset(&c, '\0', sizeof(struct category32_t));
4942 if (left < sizeof(struct category32_t)) {
4943 memcpy(&c, r, left);
4944 outs() << " (category_t entends past the end of the section)\n";
4945 } else
4946 memcpy(&c, r, sizeof(struct category32_t));
4947 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4948 swapStruct(c);
4949
4950 outs() << " name " << format("0x%" PRIx32, c.name);
4951 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4952 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004953 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004954 outs() << " " << name;
4955 outs() << "\n";
4956
4957 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4958 if (c.cls != 0)
4959 print_class32_t(c.cls, info);
4960 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4961 << "\n";
4962 if (c.instanceMethods != 0)
4963 print_method_list32_t(c.instanceMethods, info, "");
4964 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4965 << "\n";
4966 if (c.classMethods != 0)
4967 print_method_list32_t(c.classMethods, info, "");
4968 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4969 if (c.protocols != 0)
4970 print_protocol_list32_t(c.protocols, info);
4971 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4972 << "\n";
4973 if (c.instanceProperties != 0)
4974 print_objc_property_list32(c.instanceProperties, info);
4975}
4976
Kevin Enderby0fc11822015-04-01 20:57:01 +00004977static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
4978 uint32_t i, left, offset, xoffset;
4979 uint64_t p, n_value;
4980 struct message_ref64 mr;
4981 const char *name, *sym_name;
4982 const char *r;
4983 SectionRef xS;
4984
4985 if (S == SectionRef())
4986 return;
4987
4988 StringRef SectName;
4989 S.getName(SectName);
4990 DataRefImpl Ref = S.getRawDataRefImpl();
4991 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
4992 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4993 offset = 0;
4994 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
4995 p = S.getAddress() + i;
4996 r = get_pointer_64(p, offset, left, S, info);
4997 if (r == nullptr)
4998 return;
4999 memset(&mr, '\0', sizeof(struct message_ref64));
5000 if (left < sizeof(struct message_ref64)) {
5001 memcpy(&mr, r, left);
5002 outs() << " (message_ref entends past the end of the section)\n";
5003 } else
5004 memcpy(&mr, r, sizeof(struct message_ref64));
5005 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5006 swapStruct(mr);
5007
5008 outs() << " imp ";
5009 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5010 n_value, mr.imp);
5011 if (n_value != 0) {
5012 outs() << format("0x%" PRIx64, n_value) << " ";
5013 if (mr.imp != 0)
5014 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5015 } else
5016 outs() << format("0x%" PRIx64, mr.imp) << " ";
5017 if (name != nullptr)
5018 outs() << " " << name;
5019 outs() << "\n";
5020
5021 outs() << " sel ";
5022 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5023 info, n_value, mr.sel);
5024 if (n_value != 0) {
5025 if (info->verbose && sym_name != nullptr)
5026 outs() << sym_name;
5027 else
5028 outs() << format("0x%" PRIx64, n_value);
5029 if (mr.sel != 0)
5030 outs() << " + " << format("0x%" PRIx64, mr.sel);
5031 } else
5032 outs() << format("0x%" PRIx64, mr.sel);
5033 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5034 if (name != nullptr)
5035 outs() << format(" %.*s", left, name);
5036 outs() << "\n";
5037
5038 offset += sizeof(struct message_ref64);
5039 }
5040}
5041
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005042static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5043 uint32_t i, left, offset, xoffset, p;
5044 struct message_ref32 mr;
5045 const char *name, *r;
5046 SectionRef xS;
5047
5048 if (S == SectionRef())
5049 return;
5050
5051 StringRef SectName;
5052 S.getName(SectName);
5053 DataRefImpl Ref = S.getRawDataRefImpl();
5054 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5055 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5056 offset = 0;
5057 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5058 p = S.getAddress() + i;
5059 r = get_pointer_32(p, offset, left, S, info);
5060 if (r == nullptr)
5061 return;
5062 memset(&mr, '\0', sizeof(struct message_ref32));
5063 if (left < sizeof(struct message_ref32)) {
5064 memcpy(&mr, r, left);
5065 outs() << " (message_ref entends past the end of the section)\n";
5066 } else
5067 memcpy(&mr, r, sizeof(struct message_ref32));
5068 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5069 swapStruct(mr);
5070
5071 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5072 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5073 mr.imp);
5074 if (name != nullptr)
5075 outs() << " " << name;
5076 outs() << "\n";
5077
5078 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5079 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5080 if (name != nullptr)
5081 outs() << " " << name;
5082 outs() << "\n";
5083
5084 offset += sizeof(struct message_ref32);
5085 }
5086}
5087
Kevin Enderby0fc11822015-04-01 20:57:01 +00005088static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5089 uint32_t left, offset, swift_version;
5090 uint64_t p;
5091 struct objc_image_info64 o;
5092 const char *r;
5093
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005094 if (S == SectionRef())
5095 return;
5096
Kevin Enderby0fc11822015-04-01 20:57:01 +00005097 StringRef SectName;
5098 S.getName(SectName);
5099 DataRefImpl Ref = S.getRawDataRefImpl();
5100 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5101 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5102 p = S.getAddress();
5103 r = get_pointer_64(p, offset, left, S, info);
5104 if (r == nullptr)
5105 return;
5106 memset(&o, '\0', sizeof(struct objc_image_info64));
5107 if (left < sizeof(struct objc_image_info64)) {
5108 memcpy(&o, r, left);
5109 outs() << " (objc_image_info entends past the end of the section)\n";
5110 } else
5111 memcpy(&o, r, sizeof(struct objc_image_info64));
5112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5113 swapStruct(o);
5114 outs() << " version " << o.version << "\n";
5115 outs() << " flags " << format("0x%" PRIx32, o.flags);
5116 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5117 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5118 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5119 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5120 swift_version = (o.flags >> 8) & 0xff;
5121 if (swift_version != 0) {
5122 if (swift_version == 1)
5123 outs() << " Swift 1.0";
5124 else if (swift_version == 2)
5125 outs() << " Swift 1.1";
5126 else
5127 outs() << " unknown future Swift version (" << swift_version << ")";
5128 }
5129 outs() << "\n";
5130}
5131
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005132static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5133 uint32_t left, offset, swift_version, p;
5134 struct objc_image_info32 o;
5135 const char *r;
5136
5137 StringRef SectName;
5138 S.getName(SectName);
5139 DataRefImpl Ref = S.getRawDataRefImpl();
5140 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5141 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5142 p = S.getAddress();
5143 r = get_pointer_32(p, offset, left, S, info);
5144 if (r == nullptr)
5145 return;
5146 memset(&o, '\0', sizeof(struct objc_image_info32));
5147 if (left < sizeof(struct objc_image_info32)) {
5148 memcpy(&o, r, left);
5149 outs() << " (objc_image_info entends past the end of the section)\n";
5150 } else
5151 memcpy(&o, r, sizeof(struct objc_image_info32));
5152 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5153 swapStruct(o);
5154 outs() << " version " << o.version << "\n";
5155 outs() << " flags " << format("0x%" PRIx32, o.flags);
5156 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5157 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5158 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5159 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5160 swift_version = (o.flags >> 8) & 0xff;
5161 if (swift_version != 0) {
5162 if (swift_version == 1)
5163 outs() << " Swift 1.0";
5164 else if (swift_version == 2)
5165 outs() << " Swift 1.1";
5166 else
5167 outs() << " unknown future Swift version (" << swift_version << ")";
5168 }
5169 outs() << "\n";
5170}
5171
Kevin Enderby846c0002015-04-16 17:19:59 +00005172static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5173 uint32_t left, offset, p;
5174 struct imageInfo_t o;
5175 const char *r;
5176
5177 StringRef SectName;
5178 S.getName(SectName);
5179 DataRefImpl Ref = S.getRawDataRefImpl();
5180 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5181 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5182 p = S.getAddress();
5183 r = get_pointer_32(p, offset, left, S, info);
5184 if (r == nullptr)
5185 return;
5186 memset(&o, '\0', sizeof(struct imageInfo_t));
5187 if (left < sizeof(struct imageInfo_t)) {
5188 memcpy(&o, r, left);
5189 outs() << " (imageInfo entends past the end of the section)\n";
5190 } else
5191 memcpy(&o, r, sizeof(struct imageInfo_t));
5192 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5193 swapStruct(o);
5194 outs() << " version " << o.version << "\n";
5195 outs() << " flags " << format("0x%" PRIx32, o.flags);
5196 if (o.flags & 0x1)
5197 outs() << " F&C";
5198 if (o.flags & 0x2)
5199 outs() << " GC";
5200 if (o.flags & 0x4)
5201 outs() << " GC-only";
5202 else
5203 outs() << " RR";
5204 outs() << "\n";
5205}
5206
Kevin Enderby0fc11822015-04-01 20:57:01 +00005207static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5208 SymbolAddressMap AddrMap;
5209 if (verbose)
5210 CreateSymbolAddressMap(O, &AddrMap);
5211
5212 std::vector<SectionRef> Sections;
5213 for (const SectionRef &Section : O->sections()) {
5214 StringRef SectName;
5215 Section.getName(SectName);
5216 Sections.push_back(Section);
5217 }
5218
5219 struct DisassembleInfo info;
5220 // Set up the block of info used by the Symbolizer call backs.
5221 info.verbose = verbose;
5222 info.O = O;
5223 info.AddrMap = &AddrMap;
5224 info.Sections = &Sections;
5225 info.class_name = nullptr;
5226 info.selector_name = nullptr;
5227 info.method = nullptr;
5228 info.demangled_name = nullptr;
5229 info.bindtable = nullptr;
5230 info.adrp_addr = 0;
5231 info.adrp_inst = 0;
5232
Kevin Enderbyaac75382015-10-08 16:56:35 +00005233 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005234 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5235 if (CL == SectionRef())
5236 CL = get_section(O, "__DATA", "__objc_classlist");
5237 info.S = CL;
5238 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005239
Davide Italiano62507042015-12-11 22:27:59 +00005240 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5241 if (CR == SectionRef())
5242 CR = get_section(O, "__DATA", "__objc_classrefs");
5243 info.S = CR;
5244 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005245
Davide Italiano62507042015-12-11 22:27:59 +00005246 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5247 if (SR == SectionRef())
5248 SR = get_section(O, "__DATA", "__objc_superrefs");
5249 info.S = SR;
5250 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005251
Davide Italiano62507042015-12-11 22:27:59 +00005252 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5253 if (CA == SectionRef())
5254 CA = get_section(O, "__DATA", "__objc_catlist");
5255 info.S = CA;
5256 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005257
Davide Italiano62507042015-12-11 22:27:59 +00005258 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5259 if (PL == SectionRef())
5260 PL = get_section(O, "__DATA", "__objc_protolist");
5261 info.S = PL;
5262 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005263
Davide Italiano62507042015-12-11 22:27:59 +00005264 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5265 if (MR == SectionRef())
5266 MR = get_section(O, "__DATA", "__objc_msgrefs");
5267 info.S = MR;
5268 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005269
Davide Italiano62507042015-12-11 22:27:59 +00005270 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5271 if (II == SectionRef())
5272 II = get_section(O, "__DATA", "__objc_imageinfo");
5273 info.S = II;
5274 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005275
5276 if (info.bindtable != nullptr)
5277 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005278}
5279
5280static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005281 SymbolAddressMap AddrMap;
5282 if (verbose)
5283 CreateSymbolAddressMap(O, &AddrMap);
5284
5285 std::vector<SectionRef> Sections;
5286 for (const SectionRef &Section : O->sections()) {
5287 StringRef SectName;
5288 Section.getName(SectName);
5289 Sections.push_back(Section);
5290 }
5291
5292 struct DisassembleInfo info;
5293 // Set up the block of info used by the Symbolizer call backs.
5294 info.verbose = verbose;
5295 info.O = O;
5296 info.AddrMap = &AddrMap;
5297 info.Sections = &Sections;
5298 info.class_name = nullptr;
5299 info.selector_name = nullptr;
5300 info.method = nullptr;
5301 info.demangled_name = nullptr;
5302 info.bindtable = nullptr;
5303 info.adrp_addr = 0;
5304 info.adrp_inst = 0;
5305
5306 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5307 if (CL != SectionRef()) {
5308 info.S = CL;
5309 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5310 } else {
5311 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5312 info.S = CL;
5313 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5314 }
5315
5316 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5317 if (CR != SectionRef()) {
5318 info.S = CR;
5319 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5320 } else {
5321 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5322 info.S = CR;
5323 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5324 }
5325
5326 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5327 if (SR != SectionRef()) {
5328 info.S = SR;
5329 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5330 } else {
5331 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5332 info.S = SR;
5333 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5334 }
5335
5336 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5337 if (CA != SectionRef()) {
5338 info.S = CA;
5339 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5340 } else {
5341 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5342 info.S = CA;
5343 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5344 }
5345
5346 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5347 if (PL != SectionRef()) {
5348 info.S = PL;
5349 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5350 } else {
5351 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5352 info.S = PL;
5353 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5354 }
5355
5356 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5357 if (MR != SectionRef()) {
5358 info.S = MR;
5359 print_message_refs32(MR, &info);
5360 } else {
5361 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5362 info.S = MR;
5363 print_message_refs32(MR, &info);
5364 }
5365
5366 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5367 if (II != SectionRef()) {
5368 info.S = II;
5369 print_image_info32(II, &info);
5370 } else {
5371 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5372 info.S = II;
5373 print_image_info32(II, &info);
5374 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005375}
5376
5377static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005378 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5379 const char *r, *name, *defs;
5380 struct objc_module_t module;
5381 SectionRef S, xS;
5382 struct objc_symtab_t symtab;
5383 struct objc_class_t objc_class;
5384 struct objc_category_t objc_category;
5385
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005386 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005387 S = get_section(O, "__OBJC", "__module_info");
5388 if (S == SectionRef())
5389 return false;
5390
5391 SymbolAddressMap AddrMap;
5392 if (verbose)
5393 CreateSymbolAddressMap(O, &AddrMap);
5394
5395 std::vector<SectionRef> Sections;
5396 for (const SectionRef &Section : O->sections()) {
5397 StringRef SectName;
5398 Section.getName(SectName);
5399 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005400 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005401
5402 struct DisassembleInfo info;
5403 // Set up the block of info used by the Symbolizer call backs.
5404 info.verbose = verbose;
5405 info.O = O;
5406 info.AddrMap = &AddrMap;
5407 info.Sections = &Sections;
5408 info.class_name = nullptr;
5409 info.selector_name = nullptr;
5410 info.method = nullptr;
5411 info.demangled_name = nullptr;
5412 info.bindtable = nullptr;
5413 info.adrp_addr = 0;
5414 info.adrp_inst = 0;
5415
5416 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5417 p = S.getAddress() + i;
5418 r = get_pointer_32(p, offset, left, S, &info, true);
5419 if (r == nullptr)
5420 return true;
5421 memset(&module, '\0', sizeof(struct objc_module_t));
5422 if (left < sizeof(struct objc_module_t)) {
5423 memcpy(&module, r, left);
5424 outs() << " (module extends past end of __module_info section)\n";
5425 } else
5426 memcpy(&module, r, sizeof(struct objc_module_t));
5427 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5428 swapStruct(module);
5429
5430 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5431 outs() << " version " << module.version << "\n";
5432 outs() << " size " << module.size << "\n";
5433 outs() << " name ";
5434 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5435 if (name != nullptr)
5436 outs() << format("%.*s", left, name);
5437 else
5438 outs() << format("0x%08" PRIx32, module.name)
5439 << "(not in an __OBJC section)";
5440 outs() << "\n";
5441
5442 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5443 if (module.symtab == 0 || r == nullptr) {
5444 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5445 << " (not in an __OBJC section)\n";
5446 continue;
5447 }
5448 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5449 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5450 defs_left = 0;
5451 defs = nullptr;
5452 if (left < sizeof(struct objc_symtab_t)) {
5453 memcpy(&symtab, r, left);
5454 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5455 } else {
5456 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5457 if (left > sizeof(struct objc_symtab_t)) {
5458 defs_left = left - sizeof(struct objc_symtab_t);
5459 defs = r + sizeof(struct objc_symtab_t);
5460 }
5461 }
5462 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5463 swapStruct(symtab);
5464
5465 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5466 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5467 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5468 if (r == nullptr)
5469 outs() << " (not in an __OBJC section)";
5470 outs() << "\n";
5471 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5472 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5473 if (symtab.cls_def_cnt > 0)
5474 outs() << "\tClass Definitions\n";
5475 for (j = 0; j < symtab.cls_def_cnt; j++) {
5476 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5477 outs() << "\t(remaining class defs entries entends past the end of the "
5478 << "section)\n";
5479 break;
5480 }
5481 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5482 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5483 sys::swapByteOrder(def);
5484
5485 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5486 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5487 if (r != nullptr) {
5488 if (left > sizeof(struct objc_class_t)) {
5489 outs() << "\n";
5490 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5491 } else {
5492 outs() << " (entends past the end of the section)\n";
5493 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5494 memcpy(&objc_class, r, left);
5495 }
5496 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5497 swapStruct(objc_class);
5498 print_objc_class_t(&objc_class, &info);
5499 } else {
5500 outs() << "(not in an __OBJC section)\n";
5501 }
5502
5503 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5504 outs() << "\tMeta Class";
5505 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5506 if (r != nullptr) {
5507 if (left > sizeof(struct objc_class_t)) {
5508 outs() << "\n";
5509 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5510 } else {
5511 outs() << " (entends past the end of the section)\n";
5512 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5513 memcpy(&objc_class, r, left);
5514 }
5515 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5516 swapStruct(objc_class);
5517 print_objc_class_t(&objc_class, &info);
5518 } else {
5519 outs() << "(not in an __OBJC section)\n";
5520 }
5521 }
5522 }
5523 if (symtab.cat_def_cnt > 0)
5524 outs() << "\tCategory Definitions\n";
5525 for (j = 0; j < symtab.cat_def_cnt; j++) {
5526 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5527 outs() << "\t(remaining category defs entries entends past the end of "
5528 << "the section)\n";
5529 break;
5530 }
5531 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5532 sizeof(uint32_t));
5533 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5534 sys::swapByteOrder(def);
5535
5536 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5537 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5538 << format("0x%08" PRIx32, def);
5539 if (r != nullptr) {
5540 if (left > sizeof(struct objc_category_t)) {
5541 outs() << "\n";
5542 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5543 } else {
5544 outs() << " (entends past the end of the section)\n";
5545 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5546 memcpy(&objc_category, r, left);
5547 }
5548 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5549 swapStruct(objc_category);
5550 print_objc_objc_category_t(&objc_category, &info);
5551 } else {
5552 outs() << "(not in an __OBJC section)\n";
5553 }
5554 }
5555 }
5556 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5557 if (II != SectionRef())
5558 print_image_info(II, &info);
5559
5560 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005561}
5562
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005563static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5564 uint32_t size, uint32_t addr) {
5565 SymbolAddressMap AddrMap;
5566 CreateSymbolAddressMap(O, &AddrMap);
5567
5568 std::vector<SectionRef> Sections;
5569 for (const SectionRef &Section : O->sections()) {
5570 StringRef SectName;
5571 Section.getName(SectName);
5572 Sections.push_back(Section);
5573 }
5574
5575 struct DisassembleInfo info;
5576 // Set up the block of info used by the Symbolizer call backs.
5577 info.verbose = true;
5578 info.O = O;
5579 info.AddrMap = &AddrMap;
5580 info.Sections = &Sections;
5581 info.class_name = nullptr;
5582 info.selector_name = nullptr;
5583 info.method = nullptr;
5584 info.demangled_name = nullptr;
5585 info.bindtable = nullptr;
5586 info.adrp_addr = 0;
5587 info.adrp_inst = 0;
5588
5589 const char *p;
5590 struct objc_protocol_t protocol;
5591 uint32_t left, paddr;
5592 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5593 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5594 left = size - (p - sect);
5595 if (left < sizeof(struct objc_protocol_t)) {
5596 outs() << "Protocol extends past end of __protocol section\n";
5597 memcpy(&protocol, p, left);
5598 } else
5599 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5600 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5601 swapStruct(protocol);
5602 paddr = addr + (p - sect);
5603 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5604 if (print_protocol(paddr, 0, &info))
5605 outs() << "(not in an __OBJC section)\n";
5606 }
5607}
5608
Kevin Enderby0fc11822015-04-01 20:57:01 +00005609static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5610 if (O->is64Bit())
5611 printObjc2_64bit_MetaData(O, verbose);
5612 else {
5613 MachO::mach_header H;
5614 H = O->getHeader();
5615 if (H.cputype == MachO::CPU_TYPE_ARM)
5616 printObjc2_32bit_MetaData(O, verbose);
5617 else {
5618 // This is the 32-bit non-arm cputype case. Which is normally
5619 // the first Objective-C ABI. But it may be the case of a
5620 // binary for the iOS simulator which is the second Objective-C
5621 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5622 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005623 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005624 printObjc2_32bit_MetaData(O, verbose);
5625 }
5626 }
5627}
5628
Kevin Enderbybf246f52014-09-24 23:08:22 +00005629// GuessLiteralPointer returns a string which for the item in the Mach-O file
5630// for the address passed in as ReferenceValue for printing as a comment with
5631// the instruction and also returns the corresponding type of that item
5632// indirectly through ReferenceType.
5633//
5634// If ReferenceValue is an address of literal cstring then a pointer to the
5635// cstring is returned and ReferenceType is set to
5636// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5637//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005638// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5639// Class ref that name is returned and the ReferenceType is set accordingly.
5640//
5641// Lastly, literals which are Symbol address in a literal pool are looked for
5642// and if found the symbol name is returned and ReferenceType is set to
5643// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5644//
5645// If there is no item in the Mach-O file for the address passed in as
5646// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005647static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5648 uint64_t ReferencePC,
5649 uint64_t *ReferenceType,
5650 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005651 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005652 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5653 uint64_t sect_addr = info->S.getAddress();
5654 uint64_t sect_offset = ReferencePC - sect_addr;
5655 bool reloc_found = false;
5656 DataRefImpl Rel;
5657 MachO::any_relocation_info RE;
5658 bool isExtern = false;
5659 SymbolRef Symbol;
5660 for (const RelocationRef &Reloc : info->S.relocations()) {
5661 uint64_t RelocOffset = Reloc.getOffset();
5662 if (RelocOffset == sect_offset) {
5663 Rel = Reloc.getRawDataRefImpl();
5664 RE = info->O->getRelocation(Rel);
5665 if (info->O->isRelocationScattered(RE))
5666 continue;
5667 isExtern = info->O->getPlainRelocationExternal(RE);
5668 if (isExtern) {
5669 symbol_iterator RelocSym = Reloc.getSymbol();
5670 Symbol = *RelocSym;
5671 }
5672 reloc_found = true;
5673 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005674 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005675 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005676 // If there is an external relocation entry for a symbol in a section
5677 // then used that symbol's value for the value of the reference.
5678 if (reloc_found && isExtern) {
5679 if (info->O->getAnyRelocationPCRel(RE)) {
5680 unsigned Type = info->O->getAnyRelocationType(RE);
5681 if (Type == MachO::X86_64_RELOC_SIGNED) {
5682 ReferenceValue = Symbol.getValue();
5683 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005684 }
5685 }
5686 }
5687
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005688 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5689 // Message refs and Class refs.
5690 bool classref, selref, msgref, cfstring;
5691 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5692 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005693 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005694 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5695 // And the pointer_value in that section is typically zero as it will be
5696 // set by dyld as part of the "bind information".
5697 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5698 if (name != nullptr) {
5699 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005700 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005701 if (class_name != nullptr && class_name[1] == '_' &&
5702 class_name[2] != '\0') {
5703 info->class_name = class_name + 2;
5704 return name;
5705 }
5706 }
5707 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005708
David Blaikie33dd45d02015-03-23 18:39:02 +00005709 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005710 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5711 const char *name =
5712 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5713 if (name != nullptr)
5714 info->class_name = name;
5715 else
5716 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005717 return name;
5718 }
5719
David Blaikie33dd45d02015-03-23 18:39:02 +00005720 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005721 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5722 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5723 return name;
5724 }
5725
David Blaikie33dd45d02015-03-23 18:39:02 +00005726 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005727 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5728
5729 if (pointer_value != 0)
5730 ReferenceValue = pointer_value;
5731
5732 const char *name = GuessCstringPointer(ReferenceValue, info);
5733 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005734 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005735 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5736 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005737 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005738 info->class_name = nullptr;
5739 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5740 info->selector_name = name;
5741 } else
5742 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5743 return name;
5744 }
5745
5746 // Lastly look for an indirect symbol with this ReferenceValue which is in
5747 // a literal pool. If found return that symbol name.
5748 name = GuessIndirectSymbol(ReferenceValue, info);
5749 if (name) {
5750 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5751 return name;
5752 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005753
5754 return nullptr;
5755}
5756
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005757// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005758// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005759// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5760// is created and returns the symbol name that matches the ReferenceValue or
5761// nullptr if none. The ReferenceType is passed in for the IN type of
5762// reference the instruction is making from the values in defined in the header
5763// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5764// Out type and the ReferenceName will also be set which is added as a comment
5765// to the disassembled instruction.
5766//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005767#if HAVE_CXXABI_H
5768// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005769// returned through ReferenceName and ReferenceType is set to
5770// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005771#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005772//
5773// When this is called to get a symbol name for a branch target then the
5774// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5775// SymbolValue will be looked for in the indirect symbol table to determine if
5776// it is an address for a symbol stub. If so then the symbol name for that
5777// stub is returned indirectly through ReferenceName and then ReferenceType is
5778// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5779//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005780// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005781// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5782// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5783// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005784// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005785static const char *SymbolizerSymbolLookUp(void *DisInfo,
5786 uint64_t ReferenceValue,
5787 uint64_t *ReferenceType,
5788 uint64_t ReferencePC,
5789 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005790 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005791 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005792 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005793 *ReferenceName = nullptr;
5794 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005795 return nullptr;
5796 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005797
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005798 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005799
Kevin Enderby85974882014-09-26 22:20:44 +00005800 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5801 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005802 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005803 method_reference(info, ReferenceType, ReferenceName);
5804 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5805 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5806 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005807#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005808 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005809 if (info->demangled_name != nullptr)
5810 free(info->demangled_name);
5811 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005812 info->demangled_name =
5813 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005814 if (info->demangled_name != nullptr) {
5815 *ReferenceName = info->demangled_name;
5816 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5817 } else
5818 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5819 } else
5820#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005821 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5822 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5823 *ReferenceName =
5824 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005825 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005826 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005827 else
5828 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005829 // If this is arm64 and the reference is an adrp instruction save the
5830 // instruction, passed in ReferenceValue and the address of the instruction
5831 // for use later if we see and add immediate instruction.
5832 } else if (info->O->getArch() == Triple::aarch64 &&
5833 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5834 info->adrp_inst = ReferenceValue;
5835 info->adrp_addr = ReferencePC;
5836 SymbolName = nullptr;
5837 *ReferenceName = nullptr;
5838 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5839 // If this is arm64 and reference is an add immediate instruction and we
5840 // have
5841 // seen an adrp instruction just before it and the adrp's Xd register
5842 // matches
5843 // this add's Xn register reconstruct the value being referenced and look to
5844 // see if it is a literal pointer. Note the add immediate instruction is
5845 // passed in ReferenceValue.
5846 } else if (info->O->getArch() == Triple::aarch64 &&
5847 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5848 ReferencePC - 4 == info->adrp_addr &&
5849 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5850 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5851 uint32_t addxri_inst;
5852 uint64_t adrp_imm, addxri_imm;
5853
5854 adrp_imm =
5855 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5856 if (info->adrp_inst & 0x0200000)
5857 adrp_imm |= 0xfffffffffc000000LL;
5858
5859 addxri_inst = ReferenceValue;
5860 addxri_imm = (addxri_inst >> 10) & 0xfff;
5861 if (((addxri_inst >> 22) & 0x3) == 1)
5862 addxri_imm <<= 12;
5863
5864 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5865 (adrp_imm << 12) + addxri_imm;
5866
5867 *ReferenceName =
5868 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5869 if (*ReferenceName == nullptr)
5870 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5871 // If this is arm64 and the reference is a load register instruction and we
5872 // have seen an adrp instruction just before it and the adrp's Xd register
5873 // matches this add's Xn register reconstruct the value being referenced and
5874 // look to see if it is a literal pointer. Note the load register
5875 // instruction is passed in ReferenceValue.
5876 } else if (info->O->getArch() == Triple::aarch64 &&
5877 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5878 ReferencePC - 4 == info->adrp_addr &&
5879 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5880 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5881 uint32_t ldrxui_inst;
5882 uint64_t adrp_imm, ldrxui_imm;
5883
5884 adrp_imm =
5885 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5886 if (info->adrp_inst & 0x0200000)
5887 adrp_imm |= 0xfffffffffc000000LL;
5888
5889 ldrxui_inst = ReferenceValue;
5890 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5891
5892 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5893 (adrp_imm << 12) + (ldrxui_imm << 3);
5894
5895 *ReferenceName =
5896 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5897 if (*ReferenceName == nullptr)
5898 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5899 }
5900 // If this arm64 and is an load register (PC-relative) instruction the
5901 // ReferenceValue is the PC plus the immediate value.
5902 else if (info->O->getArch() == Triple::aarch64 &&
5903 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5904 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5905 *ReferenceName =
5906 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5907 if (*ReferenceName == nullptr)
5908 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005909 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005910#if HAVE_CXXABI_H
5911 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5912 if (info->demangled_name != nullptr)
5913 free(info->demangled_name);
5914 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005915 info->demangled_name =
5916 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005917 if (info->demangled_name != nullptr) {
5918 *ReferenceName = info->demangled_name;
5919 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5920 }
5921 }
5922#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005923 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005924 *ReferenceName = nullptr;
5925 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5926 }
5927
5928 return SymbolName;
5929}
5930
Kevin Enderbybf246f52014-09-24 23:08:22 +00005931/// \brief Emits the comments that are stored in the CommentStream.
5932/// Each comment in the CommentStream must end with a newline.
5933static void emitComments(raw_svector_ostream &CommentStream,
5934 SmallString<128> &CommentsToEmit,
5935 formatted_raw_ostream &FormattedOS,
5936 const MCAsmInfo &MAI) {
5937 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005938 StringRef Comments = CommentsToEmit.str();
5939 // Get the default information for printing a comment.
5940 const char *CommentBegin = MAI.getCommentString();
5941 unsigned CommentColumn = MAI.getCommentColumn();
5942 bool IsFirst = true;
5943 while (!Comments.empty()) {
5944 if (!IsFirst)
5945 FormattedOS << '\n';
5946 // Emit a line of comments.
5947 FormattedOS.PadToColumn(CommentColumn);
5948 size_t Position = Comments.find('\n');
5949 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5950 // Move after the newline character.
5951 Comments = Comments.substr(Position + 1);
5952 IsFirst = false;
5953 }
5954 FormattedOS.flush();
5955
5956 // Tell the comment stream that the vector changed underneath it.
5957 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005958}
5959
Kevin Enderby95df54c2015-02-04 01:01:38 +00005960static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5961 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005962 const char *McpuDefault = nullptr;
5963 const Target *ThumbTarget = nullptr;
5964 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005965 if (!TheTarget) {
5966 // GetTarget prints out stuff.
5967 return;
5968 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005969 if (MCPU.empty() && McpuDefault)
5970 MCPU = McpuDefault;
5971
Ahmed Charles56440fd2014-03-06 05:51:42 +00005972 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005973 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005974 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005975 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005976
Kevin Enderbyc9595622014-08-06 23:24:41 +00005977 // Package up features to be passed to target/subtarget
5978 std::string FeaturesStr;
5979 if (MAttrs.size()) {
5980 SubtargetFeatures Features;
5981 for (unsigned i = 0; i != MAttrs.size(); ++i)
5982 Features.AddFeature(MAttrs[i]);
5983 FeaturesStr = Features.getString();
5984 }
5985
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005986 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00005987 std::unique_ptr<const MCRegisterInfo> MRI(
5988 TheTarget->createMCRegInfo(TripleName));
5989 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00005990 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00005991 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00005992 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00005993 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005994 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005995 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005996 std::unique_ptr<MCSymbolizer> Symbolizer;
5997 struct DisassembleInfo SymbolizerInfo;
5998 std::unique_ptr<MCRelocationInfo> RelInfo(
5999 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6000 if (RelInfo) {
6001 Symbolizer.reset(TheTarget->createMCSymbolizer(
6002 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006003 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006004 DisAsm->setSymbolizer(std::move(Symbolizer));
6005 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006006 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006007 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006008 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006009 // Set the display preference for hex vs. decimal immediates.
6010 IP->setPrintImmHex(PrintImmHex);
6011 // Comment stream and backing vector.
6012 SmallString<128> CommentsToEmit;
6013 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006014 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6015 // if it is done then arm64 comments for string literals don't get printed
6016 // and some constant get printed instead and not setting it causes intel
6017 // (32-bit and 64-bit) comments printed with different spacing before the
6018 // comment causing different diffs with the 'C' disassembler library API.
6019 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006020
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006021 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006022 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006023 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006024 return;
6025 }
6026
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006027 // Set up thumb disassembler.
6028 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6029 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6030 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006031 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006032 std::unique_ptr<MCInstPrinter> ThumbIP;
6033 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006034 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6035 struct DisassembleInfo ThumbSymbolizerInfo;
6036 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006037 if (ThumbTarget) {
6038 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6039 ThumbAsmInfo.reset(
6040 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6041 ThumbSTI.reset(
6042 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6043 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6044 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006045 MCContext *PtrThumbCtx = ThumbCtx.get();
6046 ThumbRelInfo.reset(
6047 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6048 if (ThumbRelInfo) {
6049 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6050 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006051 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006052 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6053 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006054 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6055 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006056 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6057 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006058 // Set the display preference for hex vs. decimal immediates.
6059 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006060 }
6061
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006062 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006063 errs() << "error: couldn't initialize disassembler for target "
6064 << ThumbTripleName << '\n';
6065 return;
6066 }
6067
Charles Davis8bdfafd2013-09-01 04:28:48 +00006068 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006069
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006070 // FIXME: Using the -cfg command line option, this code used to be able to
6071 // annotate relocations with the referenced symbol's name, and if this was
6072 // inside a __[cf]string section, the data it points to. This is now replaced
6073 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006074 std::vector<SectionRef> Sections;
6075 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006076 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006077 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006078
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006079 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006080 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006081
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006082 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006083 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006084
Kevin Enderby273ae012013-06-06 17:20:50 +00006085 // Build a data in code table that is sorted on by the address of each entry.
6086 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006087 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006088 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006089 else
6090 BaseAddress = BaseSegmentAddress;
6091 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006092 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006093 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006094 uint32_t Offset;
6095 DI->getOffset(Offset);
6096 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6097 }
6098 array_pod_sort(Dices.begin(), Dices.end());
6099
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006100#ifndef NDEBUG
6101 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6102#else
6103 raw_ostream &DebugOut = nulls();
6104#endif
6105
Ahmed Charles56440fd2014-03-06 05:51:42 +00006106 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006107 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006108 // Try to find debug info and set up the DIContext for it.
6109 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006110 // A separate DSym file path was specified, parse it as a macho file,
6111 // get the sections and supply it to the section name parsing machinery.
6112 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006113 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006114 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006115 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006116 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006117 return;
6118 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006119 DbgObj =
6120 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6121 .get()
6122 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006123 }
6124
Eric Christopher7370b552012-11-12 21:40:38 +00006125 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006126 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006127 }
6128
Colin LeMahieufcc32762015-07-29 19:08:10 +00006129 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006130 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006131
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006132 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006133 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006134 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6135 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006136
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006137 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006138
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006139 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006140 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006141 continue;
6142
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006143 StringRef BytesStr;
6144 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006145 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6146 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006147 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006148
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006149 bool symbolTableWorked = false;
6150
Kevin Enderbybf246f52014-09-24 23:08:22 +00006151 // Create a map of symbol addresses to symbol names for use by
6152 // the SymbolizerSymbolLookUp() routine.
6153 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006154 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006155 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006156 ErrorOr<SymbolRef::Type> STOrErr = Symbol.getType();
6157 if (std::error_code EC = STOrErr.getError())
6158 report_fatal_error(EC.message());
6159 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006160 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6161 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006162 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006163 Expected<StringRef> SymNameOrErr = Symbol.getName();
6164 if (!SymNameOrErr) {
6165 std::string Buf;
6166 raw_string_ostream OS(Buf);
6167 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6168 OS.flush();
6169 report_fatal_error(Buf);
6170 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006171 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006172 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006173 if (!DisSymName.empty() && DisSymName == SymName)
6174 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006175 }
6176 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006177 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006178 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6179 return;
6180 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006181 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006182 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006183 SymbolizerInfo.O = MachOOF;
6184 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006185 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006186 SymbolizerInfo.Sections = &Sections;
6187 SymbolizerInfo.class_name = nullptr;
6188 SymbolizerInfo.selector_name = nullptr;
6189 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006190 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006191 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006192 SymbolizerInfo.adrp_addr = 0;
6193 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006194 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006195 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006196 ThumbSymbolizerInfo.O = MachOOF;
6197 ThumbSymbolizerInfo.S = Sections[SectIdx];
6198 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6199 ThumbSymbolizerInfo.Sections = &Sections;
6200 ThumbSymbolizerInfo.class_name = nullptr;
6201 ThumbSymbolizerInfo.selector_name = nullptr;
6202 ThumbSymbolizerInfo.method = nullptr;
6203 ThumbSymbolizerInfo.demangled_name = nullptr;
6204 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006205 ThumbSymbolizerInfo.adrp_addr = 0;
6206 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006207
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006208 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006209 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006210 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6211 if (!SymNameOrErr) {
6212 std::string Buf;
6213 raw_string_ostream OS(Buf);
6214 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6215 OS.flush();
6216 report_fatal_error(Buf);
6217 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006218 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006219
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006220 ErrorOr<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6221 if (std::error_code EC = STOrErr.getError())
6222 report_fatal_error(EC.message());
6223 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006224 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006225 continue;
6226
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006227 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006228 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006229 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006230 continue;
6231
Kevin Enderby6a221752015-03-17 17:10:57 +00006232 // If we are only disassembling one symbol see if this is that symbol.
6233 if (!DisSymName.empty() && DisSymName != SymName)
6234 continue;
6235
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006236 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006237 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006238 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006239 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006240
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006241 // Stop disassembling either at the beginning of the next symbol or at
6242 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006243 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006244 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006245 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006246 while (Symbols.size() > NextSymIdx) {
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006247 ErrorOr<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6248 if (std::error_code EC = STOrErr.getError())
6249 report_fatal_error(EC.message());
6250 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006251 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006252 containsNextSym =
6253 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006254 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006255 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006256 break;
6257 }
6258 ++NextSymIdx;
6259 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006260
Rafael Espindola80291272014-10-08 15:28:58 +00006261 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006262 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006263 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006264
6265 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006266
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006267 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6268 bool isThumb =
6269 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
6270
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006271 outs() << SymName << ":\n";
6272 DILineInfo lastLine;
6273 for (uint64_t Index = Start; Index < End; Index += Size) {
6274 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006275
Kevin Enderbybf246f52014-09-24 23:08:22 +00006276 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006277 if (!NoLeadingAddr) {
6278 if (FullLeadingAddr) {
6279 if (MachOOF->is64Bit())
6280 outs() << format("%016" PRIx64, PC);
6281 else
6282 outs() << format("%08" PRIx64, PC);
6283 } else {
6284 outs() << format("%8" PRIx64 ":", PC);
6285 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006286 }
6287 if (!NoShowRawInsn)
6288 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006289
6290 // Check the data in code table here to see if this is data not an
6291 // instruction to be disassembled.
6292 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006293 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006294 dice_table_iterator DTI =
6295 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6296 compareDiceTableEntries);
6297 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006298 uint16_t Length;
6299 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006300 uint16_t Kind;
6301 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006302 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006303 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6304 (PC == (DTI->first + Length - 1)) && (Length & 1))
6305 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006306 continue;
6307 }
6308
Kevin Enderbybf246f52014-09-24 23:08:22 +00006309 SmallVector<char, 64> AnnotationsBytes;
6310 raw_svector_ostream Annotations(AnnotationsBytes);
6311
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006312 bool gotInst;
6313 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006314 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006315 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006316 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006317 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006318 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006319 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006320 if (!NoShowRawInsn) {
Craig Topper0013be12015-09-21 05:32:41 +00006321 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006322 }
6323 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006324 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006325 if (isThumb)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006326 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006327 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006328 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006329 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006330
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006331 // Print debug info.
6332 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006333 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006334 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006335 if (dli != lastLine && dli.Line != 0)
6336 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6337 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006338 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006339 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006340 outs() << "\n";
6341 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006342 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006343 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006344 outs() << format("\t.byte 0x%02x #bad opcode\n",
6345 *(Bytes.data() + Index) & 0xff);
6346 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006347 } else if (Arch == Triple::aarch64) {
6348 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6349 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6350 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6351 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6352 outs() << format("\t.long\t0x%08x\n", opcode);
6353 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006354 } else {
6355 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6356 if (Size == 0)
6357 Size = 1; // skip illegible bytes
6358 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006359 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006360 }
6361 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006362 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006363 // Reading the symbol table didn't work, disassemble the whole section.
6364 uint64_t SectAddress = Sections[SectIdx].getAddress();
6365 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006366 uint64_t InstSize;
6367 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006368 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006369
Kevin Enderbybf246f52014-09-24 23:08:22 +00006370 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006371 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6372 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006373 if (!NoLeadingAddr) {
6374 if (FullLeadingAddr) {
6375 if (MachOOF->is64Bit())
6376 outs() << format("%016" PRIx64, PC);
6377 else
6378 outs() << format("%08" PRIx64, PC);
6379 } else {
6380 outs() << format("%8" PRIx64 ":", PC);
6381 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006382 }
6383 if (!NoShowRawInsn) {
6384 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006385 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006386 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006387 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006388 outs() << "\n";
6389 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006390 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006391 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006392 outs() << format("\t.byte 0x%02x #bad opcode\n",
6393 *(Bytes.data() + Index) & 0xff);
6394 InstSize = 1; // skip exactly one illegible byte and move on.
6395 } else {
6396 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6397 if (InstSize == 0)
6398 InstSize = 1; // skip illegible bytes
6399 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006400 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006401 }
6402 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006403 // The TripleName's need to be reset if we are called again for a different
6404 // archtecture.
6405 TripleName = "";
6406 ThumbTripleName = "";
6407
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006408 if (SymbolizerInfo.method != nullptr)
6409 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006410 if (SymbolizerInfo.demangled_name != nullptr)
6411 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006412 if (SymbolizerInfo.bindtable != nullptr)
6413 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006414 if (ThumbSymbolizerInfo.method != nullptr)
6415 free(ThumbSymbolizerInfo.method);
6416 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6417 free(ThumbSymbolizerInfo.demangled_name);
6418 if (ThumbSymbolizerInfo.bindtable != nullptr)
6419 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006420 }
6421}
Tim Northover4bd286a2014-08-01 13:07:19 +00006422
Tim Northover39c70bb2014-08-12 11:52:59 +00006423//===----------------------------------------------------------------------===//
6424// __compact_unwind section dumping
6425//===----------------------------------------------------------------------===//
6426
Tim Northover4bd286a2014-08-01 13:07:19 +00006427namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006428
6429template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006430 using llvm::support::little;
6431 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006432
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006433 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6434 Buf += sizeof(T);
6435 return Val;
6436}
Tim Northover39c70bb2014-08-12 11:52:59 +00006437
Tim Northover4bd286a2014-08-01 13:07:19 +00006438struct CompactUnwindEntry {
6439 uint32_t OffsetInSection;
6440
6441 uint64_t FunctionAddr;
6442 uint32_t Length;
6443 uint32_t CompactEncoding;
6444 uint64_t PersonalityAddr;
6445 uint64_t LSDAAddr;
6446
6447 RelocationRef FunctionReloc;
6448 RelocationRef PersonalityReloc;
6449 RelocationRef LSDAReloc;
6450
6451 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006452 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006453 if (Is64)
6454 read<uint64_t>(Contents.data() + Offset);
6455 else
6456 read<uint32_t>(Contents.data() + Offset);
6457 }
6458
6459private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006460 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006461 FunctionAddr = readNext<UIntPtr>(Buf);
6462 Length = readNext<uint32_t>(Buf);
6463 CompactEncoding = readNext<uint32_t>(Buf);
6464 PersonalityAddr = readNext<UIntPtr>(Buf);
6465 LSDAAddr = readNext<UIntPtr>(Buf);
6466 }
6467};
6468}
6469
6470/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6471/// and data being relocated, determine the best base Name and Addend to use for
6472/// display purposes.
6473///
6474/// 1. An Extern relocation will directly reference a symbol (and the data is
6475/// then already an addend), so use that.
6476/// 2. Otherwise the data is an offset in the object file's layout; try to find
6477// a symbol before it in the same section, and use the offset from there.
6478/// 3. Finally, if all that fails, fall back to an offset from the start of the
6479/// referenced section.
6480static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6481 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006482 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006483 StringRef &Name, uint64_t &Addend) {
6484 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006485 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6486 if (!NameOrErr) {
6487 std::string Buf;
6488 raw_string_ostream OS(Buf);
6489 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6490 OS.flush();
6491 report_fatal_error(Buf);
6492 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006493 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006494 Addend = Addr;
6495 return;
6496 }
6497
6498 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006499 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006500
Rafael Espindola80291272014-10-08 15:28:58 +00006501 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006502
6503 auto Sym = Symbols.upper_bound(Addr);
6504 if (Sym == Symbols.begin()) {
6505 // The first symbol in the object is after this reference, the best we can
6506 // do is section-relative notation.
6507 RelocSection.getName(Name);
6508 Addend = Addr - SectionAddr;
6509 return;
6510 }
6511
6512 // Go back one so that SymbolAddress <= Addr.
6513 --Sym;
6514
Rafael Espindola8bab8892015-08-07 23:27:14 +00006515 section_iterator SymSection = *Sym->second.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006516 if (RelocSection == *SymSection) {
6517 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006518 Expected<StringRef> NameOrErr = Sym->second.getName();
6519 if (!NameOrErr) {
6520 std::string Buf;
6521 raw_string_ostream OS(Buf);
6522 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6523 OS.flush();
6524 report_fatal_error(Buf);
6525 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006526 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006527 Addend = Addr - Sym->first;
6528 return;
6529 }
6530
6531 // There is a symbol before this reference, but it's in a different
6532 // section. Probably not helpful to mention it, so use the section name.
6533 RelocSection.getName(Name);
6534 Addend = Addr - SectionAddr;
6535}
6536
6537static void printUnwindRelocDest(const MachOObjectFile *Obj,
6538 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006539 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006540 StringRef Name;
6541 uint64_t Addend;
6542
Rafael Espindola854038e2015-06-26 14:51:16 +00006543 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006544 return;
6545
Tim Northover4bd286a2014-08-01 13:07:19 +00006546 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6547
6548 outs() << Name;
6549 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006550 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006551}
6552
6553static void
6554printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6555 std::map<uint64_t, SymbolRef> &Symbols,
6556 const SectionRef &CompactUnwind) {
6557
6558 assert(Obj->isLittleEndian() &&
6559 "There should not be a big-endian .o with __compact_unwind");
6560
6561 bool Is64 = Obj->is64Bit();
6562 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6563 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6564
6565 StringRef Contents;
6566 CompactUnwind.getContents(Contents);
6567
6568 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6569
6570 // First populate the initial raw offsets, encodings and so on from the entry.
6571 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6572 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6573 CompactUnwinds.push_back(Entry);
6574 }
6575
6576 // Next we need to look at the relocations to find out what objects are
6577 // actually being referred to.
6578 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006579 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006580
6581 uint32_t EntryIdx = RelocAddress / EntrySize;
6582 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6583 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6584
6585 if (OffsetInEntry == 0)
6586 Entry.FunctionReloc = Reloc;
6587 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6588 Entry.PersonalityReloc = Reloc;
6589 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6590 Entry.LSDAReloc = Reloc;
6591 else
6592 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6593 }
6594
6595 // Finally, we're ready to print the data we've gathered.
6596 outs() << "Contents of __compact_unwind section:\n";
6597 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006598 outs() << " Entry at offset "
6599 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006600
6601 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006602 outs() << " start: " << format("0x%" PRIx64,
6603 Entry.FunctionAddr) << ' ';
6604 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006605 outs() << '\n';
6606
6607 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006608 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6609 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006610 // 3. The 32-bit compact encoding.
6611 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006612 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006613
6614 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006615 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006616 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006617 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006618 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6619 Entry.PersonalityAddr);
6620 outs() << '\n';
6621 }
6622
6623 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006624 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006625 outs() << " LSDA: " << format("0x%" PRIx64,
6626 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006627 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6628 outs() << '\n';
6629 }
6630 }
6631}
6632
Tim Northover39c70bb2014-08-12 11:52:59 +00006633//===----------------------------------------------------------------------===//
6634// __unwind_info section dumping
6635//===----------------------------------------------------------------------===//
6636
6637static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6638 const char *Pos = PageStart;
6639 uint32_t Kind = readNext<uint32_t>(Pos);
6640 (void)Kind;
6641 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6642
6643 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6644 uint16_t NumEntries = readNext<uint16_t>(Pos);
6645
6646 Pos = PageStart + EntriesStart;
6647 for (unsigned i = 0; i < NumEntries; ++i) {
6648 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6649 uint32_t Encoding = readNext<uint32_t>(Pos);
6650
6651 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006652 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6653 << ", "
6654 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006655 }
6656}
6657
6658static void printCompressedSecondLevelUnwindPage(
6659 const char *PageStart, uint32_t FunctionBase,
6660 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6661 const char *Pos = PageStart;
6662 uint32_t Kind = readNext<uint32_t>(Pos);
6663 (void)Kind;
6664 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6665
6666 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6667 uint16_t NumEntries = readNext<uint16_t>(Pos);
6668
6669 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6670 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006671 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6672 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006673
6674 Pos = PageStart + EntriesStart;
6675 for (unsigned i = 0; i < NumEntries; ++i) {
6676 uint32_t Entry = readNext<uint32_t>(Pos);
6677 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6678 uint32_t EncodingIdx = Entry >> 24;
6679
6680 uint32_t Encoding;
6681 if (EncodingIdx < CommonEncodings.size())
6682 Encoding = CommonEncodings[EncodingIdx];
6683 else
6684 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6685
6686 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006687 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6688 << ", "
6689 << "encoding[" << EncodingIdx
6690 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006691 }
6692}
6693
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006694static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6695 std::map<uint64_t, SymbolRef> &Symbols,
6696 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006697
6698 assert(Obj->isLittleEndian() &&
6699 "There should not be a big-endian .o with __unwind_info");
6700
6701 outs() << "Contents of __unwind_info section:\n";
6702
6703 StringRef Contents;
6704 UnwindInfo.getContents(Contents);
6705 const char *Pos = Contents.data();
6706
6707 //===----------------------------------
6708 // Section header
6709 //===----------------------------------
6710
6711 uint32_t Version = readNext<uint32_t>(Pos);
6712 outs() << " Version: "
6713 << format("0x%" PRIx32, Version) << '\n';
6714 assert(Version == 1 && "only understand version 1");
6715
6716 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6717 outs() << " Common encodings array section offset: "
6718 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6719 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6720 outs() << " Number of common encodings in array: "
6721 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6722
6723 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6724 outs() << " Personality function array section offset: "
6725 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6726 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6727 outs() << " Number of personality functions in array: "
6728 << format("0x%" PRIx32, NumPersonalities) << '\n';
6729
6730 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6731 outs() << " Index array section offset: "
6732 << format("0x%" PRIx32, IndicesStart) << '\n';
6733 uint32_t NumIndices = readNext<uint32_t>(Pos);
6734 outs() << " Number of indices in array: "
6735 << format("0x%" PRIx32, NumIndices) << '\n';
6736
6737 //===----------------------------------
6738 // A shared list of common encodings
6739 //===----------------------------------
6740
6741 // These occupy indices in the range [0, N] whenever an encoding is referenced
6742 // from a compressed 2nd level index table. In practice the linker only
6743 // creates ~128 of these, so that indices are available to embed encodings in
6744 // the 2nd level index.
6745
6746 SmallVector<uint32_t, 64> CommonEncodings;
6747 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6748 Pos = Contents.data() + CommonEncodingsStart;
6749 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6750 uint32_t Encoding = readNext<uint32_t>(Pos);
6751 CommonEncodings.push_back(Encoding);
6752
6753 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6754 << '\n';
6755 }
6756
Tim Northover39c70bb2014-08-12 11:52:59 +00006757 //===----------------------------------
6758 // Personality functions used in this executable
6759 //===----------------------------------
6760
6761 // There should be only a handful of these (one per source language,
6762 // roughly). Particularly since they only get 2 bits in the compact encoding.
6763
6764 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6765 Pos = Contents.data() + PersonalitiesStart;
6766 for (unsigned i = 0; i < NumPersonalities; ++i) {
6767 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6768 outs() << " personality[" << i + 1
6769 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6770 }
6771
6772 //===----------------------------------
6773 // The level 1 index entries
6774 //===----------------------------------
6775
6776 // These specify an approximate place to start searching for the more detailed
6777 // information, sorted by PC.
6778
6779 struct IndexEntry {
6780 uint32_t FunctionOffset;
6781 uint32_t SecondLevelPageStart;
6782 uint32_t LSDAStart;
6783 };
6784
6785 SmallVector<IndexEntry, 4> IndexEntries;
6786
6787 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6788 Pos = Contents.data() + IndicesStart;
6789 for (unsigned i = 0; i < NumIndices; ++i) {
6790 IndexEntry Entry;
6791
6792 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6793 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6794 Entry.LSDAStart = readNext<uint32_t>(Pos);
6795 IndexEntries.push_back(Entry);
6796
6797 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006798 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6799 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006800 << "2nd level page offset="
6801 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006802 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006803 }
6804
Tim Northover39c70bb2014-08-12 11:52:59 +00006805 //===----------------------------------
6806 // Next come the LSDA tables
6807 //===----------------------------------
6808
6809 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6810 // the first top-level index's LSDAOffset to the last (sentinel).
6811
6812 outs() << " LSDA descriptors:\n";
6813 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6814 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6815 (2 * sizeof(uint32_t));
6816 for (int i = 0; i < NumLSDAs; ++i) {
6817 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6818 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6819 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006820 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6821 << ", "
6822 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006823 }
6824
6825 //===----------------------------------
6826 // Finally, the 2nd level indices
6827 //===----------------------------------
6828
6829 // Generally these are 4K in size, and have 2 possible forms:
6830 // + Regular stores up to 511 entries with disparate encodings
6831 // + Compressed stores up to 1021 entries if few enough compact encoding
6832 // values are used.
6833 outs() << " Second level indices:\n";
6834 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6835 // The final sentinel top-level index has no associated 2nd level page
6836 if (IndexEntries[i].SecondLevelPageStart == 0)
6837 break;
6838
6839 outs() << " Second level index[" << i << "]: "
6840 << "offset in section="
6841 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6842 << ", "
6843 << "base function offset="
6844 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6845
6846 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006847 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006848 if (Kind == 2)
6849 printRegularSecondLevelUnwindPage(Pos);
6850 else if (Kind == 3)
6851 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6852 CommonEncodings);
6853 else
6854 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006855 }
6856}
6857
Tim Northover4bd286a2014-08-01 13:07:19 +00006858void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6859 std::map<uint64_t, SymbolRef> Symbols;
6860 for (const SymbolRef &SymRef : Obj->symbols()) {
6861 // Discard any undefined or absolute symbols. They're not going to take part
6862 // in the convenience lookup for unwind info and just take up resources.
Rafael Espindola8bab8892015-08-07 23:27:14 +00006863 section_iterator Section = *SymRef.getSection();
Tim Northover4bd286a2014-08-01 13:07:19 +00006864 if (Section == Obj->section_end())
6865 continue;
6866
Rafael Espindoladea00162015-07-03 17:44:18 +00006867 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006868 Symbols.insert(std::make_pair(Addr, SymRef));
6869 }
6870
6871 for (const SectionRef &Section : Obj->sections()) {
6872 StringRef SectName;
6873 Section.getName(SectName);
6874 if (SectName == "__compact_unwind")
6875 printMachOCompactUnwindSection(Obj, Symbols, Section);
6876 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006877 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006878 }
6879}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006880
6881static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6882 uint32_t cpusubtype, uint32_t filetype,
6883 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6884 bool verbose) {
6885 outs() << "Mach header\n";
6886 outs() << " magic cputype cpusubtype caps filetype ncmds "
6887 "sizeofcmds flags\n";
6888 if (verbose) {
6889 if (magic == MachO::MH_MAGIC)
6890 outs() << " MH_MAGIC";
6891 else if (magic == MachO::MH_MAGIC_64)
6892 outs() << "MH_MAGIC_64";
6893 else
6894 outs() << format(" 0x%08" PRIx32, magic);
6895 switch (cputype) {
6896 case MachO::CPU_TYPE_I386:
6897 outs() << " I386";
6898 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6899 case MachO::CPU_SUBTYPE_I386_ALL:
6900 outs() << " ALL";
6901 break;
6902 default:
6903 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6904 break;
6905 }
6906 break;
6907 case MachO::CPU_TYPE_X86_64:
6908 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006909 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6910 case MachO::CPU_SUBTYPE_X86_64_ALL:
6911 outs() << " ALL";
6912 break;
6913 case MachO::CPU_SUBTYPE_X86_64_H:
6914 outs() << " Haswell";
6915 break;
6916 default:
6917 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6918 break;
6919 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006920 break;
6921 case MachO::CPU_TYPE_ARM:
6922 outs() << " ARM";
6923 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6924 case MachO::CPU_SUBTYPE_ARM_ALL:
6925 outs() << " ALL";
6926 break;
6927 case MachO::CPU_SUBTYPE_ARM_V4T:
6928 outs() << " V4T";
6929 break;
6930 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6931 outs() << " V5TEJ";
6932 break;
6933 case MachO::CPU_SUBTYPE_ARM_XSCALE:
6934 outs() << " XSCALE";
6935 break;
6936 case MachO::CPU_SUBTYPE_ARM_V6:
6937 outs() << " V6";
6938 break;
6939 case MachO::CPU_SUBTYPE_ARM_V6M:
6940 outs() << " V6M";
6941 break;
6942 case MachO::CPU_SUBTYPE_ARM_V7:
6943 outs() << " V7";
6944 break;
6945 case MachO::CPU_SUBTYPE_ARM_V7EM:
6946 outs() << " V7EM";
6947 break;
6948 case MachO::CPU_SUBTYPE_ARM_V7K:
6949 outs() << " V7K";
6950 break;
6951 case MachO::CPU_SUBTYPE_ARM_V7M:
6952 outs() << " V7M";
6953 break;
6954 case MachO::CPU_SUBTYPE_ARM_V7S:
6955 outs() << " V7S";
6956 break;
6957 default:
6958 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6959 break;
6960 }
6961 break;
6962 case MachO::CPU_TYPE_ARM64:
6963 outs() << " ARM64";
6964 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6965 case MachO::CPU_SUBTYPE_ARM64_ALL:
6966 outs() << " ALL";
6967 break;
6968 default:
6969 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6970 break;
6971 }
6972 break;
6973 case MachO::CPU_TYPE_POWERPC:
6974 outs() << " PPC";
6975 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6976 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6977 outs() << " ALL";
6978 break;
6979 default:
6980 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6981 break;
6982 }
6983 break;
6984 case MachO::CPU_TYPE_POWERPC64:
6985 outs() << " PPC64";
6986 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6987 case MachO::CPU_SUBTYPE_POWERPC_ALL:
6988 outs() << " ALL";
6989 break;
6990 default:
6991 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6992 break;
6993 }
6994 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00006995 default:
6996 outs() << format(" %7d", cputype);
6997 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6998 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006999 }
7000 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007001 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007002 } else {
7003 outs() << format(" 0x%02" PRIx32,
7004 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7005 }
7006 switch (filetype) {
7007 case MachO::MH_OBJECT:
7008 outs() << " OBJECT";
7009 break;
7010 case MachO::MH_EXECUTE:
7011 outs() << " EXECUTE";
7012 break;
7013 case MachO::MH_FVMLIB:
7014 outs() << " FVMLIB";
7015 break;
7016 case MachO::MH_CORE:
7017 outs() << " CORE";
7018 break;
7019 case MachO::MH_PRELOAD:
7020 outs() << " PRELOAD";
7021 break;
7022 case MachO::MH_DYLIB:
7023 outs() << " DYLIB";
7024 break;
7025 case MachO::MH_DYLIB_STUB:
7026 outs() << " DYLIB_STUB";
7027 break;
7028 case MachO::MH_DYLINKER:
7029 outs() << " DYLINKER";
7030 break;
7031 case MachO::MH_BUNDLE:
7032 outs() << " BUNDLE";
7033 break;
7034 case MachO::MH_DSYM:
7035 outs() << " DSYM";
7036 break;
7037 case MachO::MH_KEXT_BUNDLE:
7038 outs() << " KEXTBUNDLE";
7039 break;
7040 default:
7041 outs() << format(" %10u", filetype);
7042 break;
7043 }
7044 outs() << format(" %5u", ncmds);
7045 outs() << format(" %10u", sizeofcmds);
7046 uint32_t f = flags;
7047 if (f & MachO::MH_NOUNDEFS) {
7048 outs() << " NOUNDEFS";
7049 f &= ~MachO::MH_NOUNDEFS;
7050 }
7051 if (f & MachO::MH_INCRLINK) {
7052 outs() << " INCRLINK";
7053 f &= ~MachO::MH_INCRLINK;
7054 }
7055 if (f & MachO::MH_DYLDLINK) {
7056 outs() << " DYLDLINK";
7057 f &= ~MachO::MH_DYLDLINK;
7058 }
7059 if (f & MachO::MH_BINDATLOAD) {
7060 outs() << " BINDATLOAD";
7061 f &= ~MachO::MH_BINDATLOAD;
7062 }
7063 if (f & MachO::MH_PREBOUND) {
7064 outs() << " PREBOUND";
7065 f &= ~MachO::MH_PREBOUND;
7066 }
7067 if (f & MachO::MH_SPLIT_SEGS) {
7068 outs() << " SPLIT_SEGS";
7069 f &= ~MachO::MH_SPLIT_SEGS;
7070 }
7071 if (f & MachO::MH_LAZY_INIT) {
7072 outs() << " LAZY_INIT";
7073 f &= ~MachO::MH_LAZY_INIT;
7074 }
7075 if (f & MachO::MH_TWOLEVEL) {
7076 outs() << " TWOLEVEL";
7077 f &= ~MachO::MH_TWOLEVEL;
7078 }
7079 if (f & MachO::MH_FORCE_FLAT) {
7080 outs() << " FORCE_FLAT";
7081 f &= ~MachO::MH_FORCE_FLAT;
7082 }
7083 if (f & MachO::MH_NOMULTIDEFS) {
7084 outs() << " NOMULTIDEFS";
7085 f &= ~MachO::MH_NOMULTIDEFS;
7086 }
7087 if (f & MachO::MH_NOFIXPREBINDING) {
7088 outs() << " NOFIXPREBINDING";
7089 f &= ~MachO::MH_NOFIXPREBINDING;
7090 }
7091 if (f & MachO::MH_PREBINDABLE) {
7092 outs() << " PREBINDABLE";
7093 f &= ~MachO::MH_PREBINDABLE;
7094 }
7095 if (f & MachO::MH_ALLMODSBOUND) {
7096 outs() << " ALLMODSBOUND";
7097 f &= ~MachO::MH_ALLMODSBOUND;
7098 }
7099 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7100 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7101 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7102 }
7103 if (f & MachO::MH_CANONICAL) {
7104 outs() << " CANONICAL";
7105 f &= ~MachO::MH_CANONICAL;
7106 }
7107 if (f & MachO::MH_WEAK_DEFINES) {
7108 outs() << " WEAK_DEFINES";
7109 f &= ~MachO::MH_WEAK_DEFINES;
7110 }
7111 if (f & MachO::MH_BINDS_TO_WEAK) {
7112 outs() << " BINDS_TO_WEAK";
7113 f &= ~MachO::MH_BINDS_TO_WEAK;
7114 }
7115 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7116 outs() << " ALLOW_STACK_EXECUTION";
7117 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7118 }
7119 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7120 outs() << " DEAD_STRIPPABLE_DYLIB";
7121 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7122 }
7123 if (f & MachO::MH_PIE) {
7124 outs() << " PIE";
7125 f &= ~MachO::MH_PIE;
7126 }
7127 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7128 outs() << " NO_REEXPORTED_DYLIBS";
7129 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7130 }
7131 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7132 outs() << " MH_HAS_TLV_DESCRIPTORS";
7133 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7134 }
7135 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7136 outs() << " MH_NO_HEAP_EXECUTION";
7137 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7138 }
7139 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7140 outs() << " APP_EXTENSION_SAFE";
7141 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7142 }
7143 if (f != 0 || flags == 0)
7144 outs() << format(" 0x%08" PRIx32, f);
7145 } else {
7146 outs() << format(" 0x%08" PRIx32, magic);
7147 outs() << format(" %7d", cputype);
7148 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7149 outs() << format(" 0x%02" PRIx32,
7150 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7151 outs() << format(" %10u", filetype);
7152 outs() << format(" %5u", ncmds);
7153 outs() << format(" %10u", sizeofcmds);
7154 outs() << format(" 0x%08" PRIx32, flags);
7155 }
7156 outs() << "\n";
7157}
7158
Kevin Enderby956366c2014-08-29 22:30:52 +00007159static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7160 StringRef SegName, uint64_t vmaddr,
7161 uint64_t vmsize, uint64_t fileoff,
7162 uint64_t filesize, uint32_t maxprot,
7163 uint32_t initprot, uint32_t nsects,
7164 uint32_t flags, uint32_t object_size,
7165 bool verbose) {
7166 uint64_t expected_cmdsize;
7167 if (cmd == MachO::LC_SEGMENT) {
7168 outs() << " cmd LC_SEGMENT\n";
7169 expected_cmdsize = nsects;
7170 expected_cmdsize *= sizeof(struct MachO::section);
7171 expected_cmdsize += sizeof(struct MachO::segment_command);
7172 } else {
7173 outs() << " cmd LC_SEGMENT_64\n";
7174 expected_cmdsize = nsects;
7175 expected_cmdsize *= sizeof(struct MachO::section_64);
7176 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7177 }
7178 outs() << " cmdsize " << cmdsize;
7179 if (cmdsize != expected_cmdsize)
7180 outs() << " Inconsistent size\n";
7181 else
7182 outs() << "\n";
7183 outs() << " segname " << SegName << "\n";
7184 if (cmd == MachO::LC_SEGMENT_64) {
7185 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7186 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7187 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007188 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7189 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007190 }
7191 outs() << " fileoff " << fileoff;
7192 if (fileoff > object_size)
7193 outs() << " (past end of file)\n";
7194 else
7195 outs() << "\n";
7196 outs() << " filesize " << filesize;
7197 if (fileoff + filesize > object_size)
7198 outs() << " (past end of file)\n";
7199 else
7200 outs() << "\n";
7201 if (verbose) {
7202 if ((maxprot &
7203 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7204 MachO::VM_PROT_EXECUTE)) != 0)
7205 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7206 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007207 outs() << " maxprot ";
7208 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7209 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7210 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007211 }
7212 if ((initprot &
7213 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7214 MachO::VM_PROT_EXECUTE)) != 0)
7215 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7216 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007217 outs() << " initprot ";
7218 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7219 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7220 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007221 }
7222 } else {
7223 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7224 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7225 }
7226 outs() << " nsects " << nsects << "\n";
7227 if (verbose) {
7228 outs() << " flags";
7229 if (flags == 0)
7230 outs() << " (none)\n";
7231 else {
7232 if (flags & MachO::SG_HIGHVM) {
7233 outs() << " HIGHVM";
7234 flags &= ~MachO::SG_HIGHVM;
7235 }
7236 if (flags & MachO::SG_FVMLIB) {
7237 outs() << " FVMLIB";
7238 flags &= ~MachO::SG_FVMLIB;
7239 }
7240 if (flags & MachO::SG_NORELOC) {
7241 outs() << " NORELOC";
7242 flags &= ~MachO::SG_NORELOC;
7243 }
7244 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7245 outs() << " PROTECTED_VERSION_1";
7246 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7247 }
7248 if (flags)
7249 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7250 else
7251 outs() << "\n";
7252 }
7253 } else {
7254 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7255 }
7256}
7257
7258static void PrintSection(const char *sectname, const char *segname,
7259 uint64_t addr, uint64_t size, uint32_t offset,
7260 uint32_t align, uint32_t reloff, uint32_t nreloc,
7261 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7262 uint32_t cmd, const char *sg_segname,
7263 uint32_t filetype, uint32_t object_size,
7264 bool verbose) {
7265 outs() << "Section\n";
7266 outs() << " sectname " << format("%.16s\n", sectname);
7267 outs() << " segname " << format("%.16s", segname);
7268 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7269 outs() << " (does not match segment)\n";
7270 else
7271 outs() << "\n";
7272 if (cmd == MachO::LC_SEGMENT_64) {
7273 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7274 outs() << " size " << format("0x%016" PRIx64, size);
7275 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007276 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7277 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007278 }
7279 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7280 outs() << " (past end of file)\n";
7281 else
7282 outs() << "\n";
7283 outs() << " offset " << offset;
7284 if (offset > object_size)
7285 outs() << " (past end of file)\n";
7286 else
7287 outs() << "\n";
7288 uint32_t align_shifted = 1 << align;
7289 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7290 outs() << " reloff " << reloff;
7291 if (reloff > object_size)
7292 outs() << " (past end of file)\n";
7293 else
7294 outs() << "\n";
7295 outs() << " nreloc " << nreloc;
7296 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7297 outs() << " (past end of file)\n";
7298 else
7299 outs() << "\n";
7300 uint32_t section_type = flags & MachO::SECTION_TYPE;
7301 if (verbose) {
7302 outs() << " type";
7303 if (section_type == MachO::S_REGULAR)
7304 outs() << " S_REGULAR\n";
7305 else if (section_type == MachO::S_ZEROFILL)
7306 outs() << " S_ZEROFILL\n";
7307 else if (section_type == MachO::S_CSTRING_LITERALS)
7308 outs() << " S_CSTRING_LITERALS\n";
7309 else if (section_type == MachO::S_4BYTE_LITERALS)
7310 outs() << " S_4BYTE_LITERALS\n";
7311 else if (section_type == MachO::S_8BYTE_LITERALS)
7312 outs() << " S_8BYTE_LITERALS\n";
7313 else if (section_type == MachO::S_16BYTE_LITERALS)
7314 outs() << " S_16BYTE_LITERALS\n";
7315 else if (section_type == MachO::S_LITERAL_POINTERS)
7316 outs() << " S_LITERAL_POINTERS\n";
7317 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7318 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7319 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7320 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7321 else if (section_type == MachO::S_SYMBOL_STUBS)
7322 outs() << " S_SYMBOL_STUBS\n";
7323 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7324 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7325 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7326 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7327 else if (section_type == MachO::S_COALESCED)
7328 outs() << " S_COALESCED\n";
7329 else if (section_type == MachO::S_INTERPOSING)
7330 outs() << " S_INTERPOSING\n";
7331 else if (section_type == MachO::S_DTRACE_DOF)
7332 outs() << " S_DTRACE_DOF\n";
7333 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7334 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7335 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7336 outs() << " S_THREAD_LOCAL_REGULAR\n";
7337 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7338 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7339 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7340 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7341 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7342 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7343 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7344 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7345 else
7346 outs() << format("0x%08" PRIx32, section_type) << "\n";
7347 outs() << "attributes";
7348 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7349 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7350 outs() << " PURE_INSTRUCTIONS";
7351 if (section_attributes & MachO::S_ATTR_NO_TOC)
7352 outs() << " NO_TOC";
7353 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7354 outs() << " STRIP_STATIC_SYMS";
7355 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7356 outs() << " NO_DEAD_STRIP";
7357 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7358 outs() << " LIVE_SUPPORT";
7359 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7360 outs() << " SELF_MODIFYING_CODE";
7361 if (section_attributes & MachO::S_ATTR_DEBUG)
7362 outs() << " DEBUG";
7363 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7364 outs() << " SOME_INSTRUCTIONS";
7365 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7366 outs() << " EXT_RELOC";
7367 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7368 outs() << " LOC_RELOC";
7369 if (section_attributes == 0)
7370 outs() << " (none)";
7371 outs() << "\n";
7372 } else
7373 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7374 outs() << " reserved1 " << reserved1;
7375 if (section_type == MachO::S_SYMBOL_STUBS ||
7376 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7377 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7378 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7379 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7380 outs() << " (index into indirect symbol table)\n";
7381 else
7382 outs() << "\n";
7383 outs() << " reserved2 " << reserved2;
7384 if (section_type == MachO::S_SYMBOL_STUBS)
7385 outs() << " (size of stubs)\n";
7386 else
7387 outs() << "\n";
7388}
7389
David Majnemer73cc6ff2014-11-13 19:48:56 +00007390static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007391 uint32_t object_size) {
7392 outs() << " cmd LC_SYMTAB\n";
7393 outs() << " cmdsize " << st.cmdsize;
7394 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7395 outs() << " Incorrect size\n";
7396 else
7397 outs() << "\n";
7398 outs() << " symoff " << st.symoff;
7399 if (st.symoff > object_size)
7400 outs() << " (past end of file)\n";
7401 else
7402 outs() << "\n";
7403 outs() << " nsyms " << st.nsyms;
7404 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007405 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007406 big_size = st.nsyms;
7407 big_size *= sizeof(struct MachO::nlist_64);
7408 big_size += st.symoff;
7409 if (big_size > object_size)
7410 outs() << " (past end of file)\n";
7411 else
7412 outs() << "\n";
7413 } else {
7414 big_size = st.nsyms;
7415 big_size *= sizeof(struct MachO::nlist);
7416 big_size += st.symoff;
7417 if (big_size > object_size)
7418 outs() << " (past end of file)\n";
7419 else
7420 outs() << "\n";
7421 }
7422 outs() << " stroff " << st.stroff;
7423 if (st.stroff > object_size)
7424 outs() << " (past end of file)\n";
7425 else
7426 outs() << "\n";
7427 outs() << " strsize " << st.strsize;
7428 big_size = st.stroff;
7429 big_size += st.strsize;
7430 if (big_size > object_size)
7431 outs() << " (past end of file)\n";
7432 else
7433 outs() << "\n";
7434}
7435
7436static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7437 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007438 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007439 outs() << " cmd LC_DYSYMTAB\n";
7440 outs() << " cmdsize " << dyst.cmdsize;
7441 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7442 outs() << " Incorrect size\n";
7443 else
7444 outs() << "\n";
7445 outs() << " ilocalsym " << dyst.ilocalsym;
7446 if (dyst.ilocalsym > nsyms)
7447 outs() << " (greater than the number of symbols)\n";
7448 else
7449 outs() << "\n";
7450 outs() << " nlocalsym " << dyst.nlocalsym;
7451 uint64_t big_size;
7452 big_size = dyst.ilocalsym;
7453 big_size += dyst.nlocalsym;
7454 if (big_size > nsyms)
7455 outs() << " (past the end of the symbol table)\n";
7456 else
7457 outs() << "\n";
7458 outs() << " iextdefsym " << dyst.iextdefsym;
7459 if (dyst.iextdefsym > nsyms)
7460 outs() << " (greater than the number of symbols)\n";
7461 else
7462 outs() << "\n";
7463 outs() << " nextdefsym " << dyst.nextdefsym;
7464 big_size = dyst.iextdefsym;
7465 big_size += dyst.nextdefsym;
7466 if (big_size > nsyms)
7467 outs() << " (past the end of the symbol table)\n";
7468 else
7469 outs() << "\n";
7470 outs() << " iundefsym " << dyst.iundefsym;
7471 if (dyst.iundefsym > nsyms)
7472 outs() << " (greater than the number of symbols)\n";
7473 else
7474 outs() << "\n";
7475 outs() << " nundefsym " << dyst.nundefsym;
7476 big_size = dyst.iundefsym;
7477 big_size += dyst.nundefsym;
7478 if (big_size > nsyms)
7479 outs() << " (past the end of the symbol table)\n";
7480 else
7481 outs() << "\n";
7482 outs() << " tocoff " << dyst.tocoff;
7483 if (dyst.tocoff > object_size)
7484 outs() << " (past end of file)\n";
7485 else
7486 outs() << "\n";
7487 outs() << " ntoc " << dyst.ntoc;
7488 big_size = dyst.ntoc;
7489 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7490 big_size += dyst.tocoff;
7491 if (big_size > object_size)
7492 outs() << " (past end of file)\n";
7493 else
7494 outs() << "\n";
7495 outs() << " modtaboff " << dyst.modtaboff;
7496 if (dyst.modtaboff > object_size)
7497 outs() << " (past end of file)\n";
7498 else
7499 outs() << "\n";
7500 outs() << " nmodtab " << dyst.nmodtab;
7501 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007502 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007503 modtabend = dyst.nmodtab;
7504 modtabend *= sizeof(struct MachO::dylib_module_64);
7505 modtabend += dyst.modtaboff;
7506 } else {
7507 modtabend = dyst.nmodtab;
7508 modtabend *= sizeof(struct MachO::dylib_module);
7509 modtabend += dyst.modtaboff;
7510 }
7511 if (modtabend > object_size)
7512 outs() << " (past end of file)\n";
7513 else
7514 outs() << "\n";
7515 outs() << " extrefsymoff " << dyst.extrefsymoff;
7516 if (dyst.extrefsymoff > object_size)
7517 outs() << " (past end of file)\n";
7518 else
7519 outs() << "\n";
7520 outs() << " nextrefsyms " << dyst.nextrefsyms;
7521 big_size = dyst.nextrefsyms;
7522 big_size *= sizeof(struct MachO::dylib_reference);
7523 big_size += dyst.extrefsymoff;
7524 if (big_size > object_size)
7525 outs() << " (past end of file)\n";
7526 else
7527 outs() << "\n";
7528 outs() << " indirectsymoff " << dyst.indirectsymoff;
7529 if (dyst.indirectsymoff > object_size)
7530 outs() << " (past end of file)\n";
7531 else
7532 outs() << "\n";
7533 outs() << " nindirectsyms " << dyst.nindirectsyms;
7534 big_size = dyst.nindirectsyms;
7535 big_size *= sizeof(uint32_t);
7536 big_size += dyst.indirectsymoff;
7537 if (big_size > object_size)
7538 outs() << " (past end of file)\n";
7539 else
7540 outs() << "\n";
7541 outs() << " extreloff " << dyst.extreloff;
7542 if (dyst.extreloff > object_size)
7543 outs() << " (past end of file)\n";
7544 else
7545 outs() << "\n";
7546 outs() << " nextrel " << dyst.nextrel;
7547 big_size = dyst.nextrel;
7548 big_size *= sizeof(struct MachO::relocation_info);
7549 big_size += dyst.extreloff;
7550 if (big_size > object_size)
7551 outs() << " (past end of file)\n";
7552 else
7553 outs() << "\n";
7554 outs() << " locreloff " << dyst.locreloff;
7555 if (dyst.locreloff > object_size)
7556 outs() << " (past end of file)\n";
7557 else
7558 outs() << "\n";
7559 outs() << " nlocrel " << dyst.nlocrel;
7560 big_size = dyst.nlocrel;
7561 big_size *= sizeof(struct MachO::relocation_info);
7562 big_size += dyst.locreloff;
7563 if (big_size > object_size)
7564 outs() << " (past end of file)\n";
7565 else
7566 outs() << "\n";
7567}
7568
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007569static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7570 uint32_t object_size) {
7571 if (dc.cmd == MachO::LC_DYLD_INFO)
7572 outs() << " cmd LC_DYLD_INFO\n";
7573 else
7574 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7575 outs() << " cmdsize " << dc.cmdsize;
7576 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7577 outs() << " Incorrect size\n";
7578 else
7579 outs() << "\n";
7580 outs() << " rebase_off " << dc.rebase_off;
7581 if (dc.rebase_off > object_size)
7582 outs() << " (past end of file)\n";
7583 else
7584 outs() << "\n";
7585 outs() << " rebase_size " << dc.rebase_size;
7586 uint64_t big_size;
7587 big_size = dc.rebase_off;
7588 big_size += dc.rebase_size;
7589 if (big_size > object_size)
7590 outs() << " (past end of file)\n";
7591 else
7592 outs() << "\n";
7593 outs() << " bind_off " << dc.bind_off;
7594 if (dc.bind_off > object_size)
7595 outs() << " (past end of file)\n";
7596 else
7597 outs() << "\n";
7598 outs() << " bind_size " << dc.bind_size;
7599 big_size = dc.bind_off;
7600 big_size += dc.bind_size;
7601 if (big_size > object_size)
7602 outs() << " (past end of file)\n";
7603 else
7604 outs() << "\n";
7605 outs() << " weak_bind_off " << dc.weak_bind_off;
7606 if (dc.weak_bind_off > object_size)
7607 outs() << " (past end of file)\n";
7608 else
7609 outs() << "\n";
7610 outs() << " weak_bind_size " << dc.weak_bind_size;
7611 big_size = dc.weak_bind_off;
7612 big_size += dc.weak_bind_size;
7613 if (big_size > object_size)
7614 outs() << " (past end of file)\n";
7615 else
7616 outs() << "\n";
7617 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7618 if (dc.lazy_bind_off > object_size)
7619 outs() << " (past end of file)\n";
7620 else
7621 outs() << "\n";
7622 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7623 big_size = dc.lazy_bind_off;
7624 big_size += dc.lazy_bind_size;
7625 if (big_size > object_size)
7626 outs() << " (past end of file)\n";
7627 else
7628 outs() << "\n";
7629 outs() << " export_off " << dc.export_off;
7630 if (dc.export_off > object_size)
7631 outs() << " (past end of file)\n";
7632 else
7633 outs() << "\n";
7634 outs() << " export_size " << dc.export_size;
7635 big_size = dc.export_off;
7636 big_size += dc.export_size;
7637 if (big_size > object_size)
7638 outs() << " (past end of file)\n";
7639 else
7640 outs() << "\n";
7641}
7642
7643static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7644 const char *Ptr) {
7645 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7646 outs() << " cmd LC_ID_DYLINKER\n";
7647 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7648 outs() << " cmd LC_LOAD_DYLINKER\n";
7649 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7650 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7651 else
7652 outs() << " cmd ?(" << dyld.cmd << ")\n";
7653 outs() << " cmdsize " << dyld.cmdsize;
7654 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7655 outs() << " Incorrect size\n";
7656 else
7657 outs() << "\n";
7658 if (dyld.name >= dyld.cmdsize)
7659 outs() << " name ?(bad offset " << dyld.name << ")\n";
7660 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007661 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007662 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7663 }
7664}
7665
7666static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7667 outs() << " cmd LC_UUID\n";
7668 outs() << " cmdsize " << uuid.cmdsize;
7669 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7670 outs() << " Incorrect size\n";
7671 else
7672 outs() << "\n";
7673 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007674 for (int i = 0; i < 16; ++i) {
7675 outs() << format("%02" PRIX32, uuid.uuid[i]);
7676 if (i == 3 || i == 5 || i == 7 || i == 9)
7677 outs() << "-";
7678 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007679 outs() << "\n";
7680}
7681
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007682static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007683 outs() << " cmd LC_RPATH\n";
7684 outs() << " cmdsize " << rpath.cmdsize;
7685 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7686 outs() << " Incorrect size\n";
7687 else
7688 outs() << "\n";
7689 if (rpath.path >= rpath.cmdsize)
7690 outs() << " path ?(bad offset " << rpath.path << ")\n";
7691 else {
7692 const char *P = (const char *)(Ptr) + rpath.path;
7693 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7694 }
7695}
7696
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007697static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007698 StringRef LoadCmdName;
7699 switch (vd.cmd) {
7700 case MachO::LC_VERSION_MIN_MACOSX:
7701 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7702 break;
7703 case MachO::LC_VERSION_MIN_IPHONEOS:
7704 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7705 break;
7706 case MachO::LC_VERSION_MIN_TVOS:
7707 LoadCmdName = "LC_VERSION_MIN_TVOS";
7708 break;
7709 case MachO::LC_VERSION_MIN_WATCHOS:
7710 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7711 break;
7712 default:
7713 llvm_unreachable("Unknown version min load command");
7714 }
7715
7716 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007717 outs() << " cmdsize " << vd.cmdsize;
7718 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7719 outs() << " Incorrect size\n";
7720 else
7721 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007722 outs() << " version "
7723 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7724 << MachOObjectFile::getVersionMinMinor(vd, false);
7725 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7726 if (Update != 0)
7727 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007728 outs() << "\n";
7729 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007730 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007731 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007732 outs() << " sdk "
7733 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7734 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007735 }
Davide Italiano56baef32015-08-26 12:26:11 +00007736 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7737 if (Update != 0)
7738 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007739 outs() << "\n";
7740}
7741
7742static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7743 outs() << " cmd LC_SOURCE_VERSION\n";
7744 outs() << " cmdsize " << sd.cmdsize;
7745 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7746 outs() << " Incorrect size\n";
7747 else
7748 outs() << "\n";
7749 uint64_t a = (sd.version >> 40) & 0xffffff;
7750 uint64_t b = (sd.version >> 30) & 0x3ff;
7751 uint64_t c = (sd.version >> 20) & 0x3ff;
7752 uint64_t d = (sd.version >> 10) & 0x3ff;
7753 uint64_t e = sd.version & 0x3ff;
7754 outs() << " version " << a << "." << b;
7755 if (e != 0)
7756 outs() << "." << c << "." << d << "." << e;
7757 else if (d != 0)
7758 outs() << "." << c << "." << d;
7759 else if (c != 0)
7760 outs() << "." << c;
7761 outs() << "\n";
7762}
7763
7764static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7765 outs() << " cmd LC_MAIN\n";
7766 outs() << " cmdsize " << ep.cmdsize;
7767 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7768 outs() << " Incorrect size\n";
7769 else
7770 outs() << "\n";
7771 outs() << " entryoff " << ep.entryoff << "\n";
7772 outs() << " stacksize " << ep.stacksize << "\n";
7773}
7774
Kevin Enderby0804f4672014-12-16 23:25:52 +00007775static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7776 uint32_t object_size) {
7777 outs() << " cmd LC_ENCRYPTION_INFO\n";
7778 outs() << " cmdsize " << ec.cmdsize;
7779 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7780 outs() << " Incorrect size\n";
7781 else
7782 outs() << "\n";
7783 outs() << " cryptoff " << ec.cryptoff;
7784 if (ec.cryptoff > object_size)
7785 outs() << " (past end of file)\n";
7786 else
7787 outs() << "\n";
7788 outs() << " cryptsize " << ec.cryptsize;
7789 if (ec.cryptsize > object_size)
7790 outs() << " (past end of file)\n";
7791 else
7792 outs() << "\n";
7793 outs() << " cryptid " << ec.cryptid << "\n";
7794}
7795
Kevin Enderby57538292014-12-17 01:01:30 +00007796static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007797 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007798 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7799 outs() << " cmdsize " << ec.cmdsize;
7800 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7801 outs() << " Incorrect size\n";
7802 else
7803 outs() << "\n";
7804 outs() << " cryptoff " << ec.cryptoff;
7805 if (ec.cryptoff > object_size)
7806 outs() << " (past end of file)\n";
7807 else
7808 outs() << "\n";
7809 outs() << " cryptsize " << ec.cryptsize;
7810 if (ec.cryptsize > object_size)
7811 outs() << " (past end of file)\n";
7812 else
7813 outs() << "\n";
7814 outs() << " cryptid " << ec.cryptid << "\n";
7815 outs() << " pad " << ec.pad << "\n";
7816}
7817
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007818static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7819 const char *Ptr) {
7820 outs() << " cmd LC_LINKER_OPTION\n";
7821 outs() << " cmdsize " << lo.cmdsize;
7822 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7823 outs() << " Incorrect size\n";
7824 else
7825 outs() << "\n";
7826 outs() << " count " << lo.count << "\n";
7827 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7828 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7829 uint32_t i = 0;
7830 while (left > 0) {
7831 while (*string == '\0' && left > 0) {
7832 string++;
7833 left--;
7834 }
7835 if (left > 0) {
7836 i++;
7837 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007838 uint32_t NullPos = StringRef(string, left).find('\0');
7839 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007840 string += len;
7841 left -= len;
7842 }
7843 }
7844 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007845 outs() << " count " << lo.count << " does not match number of strings "
7846 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007847}
7848
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007849static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7850 const char *Ptr) {
7851 outs() << " cmd LC_SUB_FRAMEWORK\n";
7852 outs() << " cmdsize " << sub.cmdsize;
7853 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7854 outs() << " Incorrect size\n";
7855 else
7856 outs() << "\n";
7857 if (sub.umbrella < sub.cmdsize) {
7858 const char *P = Ptr + sub.umbrella;
7859 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7860 } else {
7861 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7862 }
7863}
7864
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007865static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7866 const char *Ptr) {
7867 outs() << " cmd LC_SUB_UMBRELLA\n";
7868 outs() << " cmdsize " << sub.cmdsize;
7869 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7870 outs() << " Incorrect size\n";
7871 else
7872 outs() << "\n";
7873 if (sub.sub_umbrella < sub.cmdsize) {
7874 const char *P = Ptr + sub.sub_umbrella;
7875 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7876 } else {
7877 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7878 }
7879}
7880
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007881static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007882 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007883 outs() << " cmd LC_SUB_LIBRARY\n";
7884 outs() << " cmdsize " << sub.cmdsize;
7885 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7886 outs() << " Incorrect size\n";
7887 else
7888 outs() << "\n";
7889 if (sub.sub_library < sub.cmdsize) {
7890 const char *P = Ptr + sub.sub_library;
7891 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7892 } else {
7893 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7894 }
7895}
7896
Kevin Enderby186eac32014-12-19 21:06:24 +00007897static void PrintSubClientCommand(MachO::sub_client_command sub,
7898 const char *Ptr) {
7899 outs() << " cmd LC_SUB_CLIENT\n";
7900 outs() << " cmdsize " << sub.cmdsize;
7901 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7902 outs() << " Incorrect size\n";
7903 else
7904 outs() << "\n";
7905 if (sub.client < sub.cmdsize) {
7906 const char *P = Ptr + sub.client;
7907 outs() << " client " << P << " (offset " << sub.client << ")\n";
7908 } else {
7909 outs() << " client ?(bad offset " << sub.client << ")\n";
7910 }
7911}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007912
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007913static void PrintRoutinesCommand(MachO::routines_command r) {
7914 outs() << " cmd LC_ROUTINES\n";
7915 outs() << " cmdsize " << r.cmdsize;
7916 if (r.cmdsize != sizeof(struct MachO::routines_command))
7917 outs() << " Incorrect size\n";
7918 else
7919 outs() << "\n";
7920 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7921 outs() << " init_module " << r.init_module << "\n";
7922 outs() << " reserved1 " << r.reserved1 << "\n";
7923 outs() << " reserved2 " << r.reserved2 << "\n";
7924 outs() << " reserved3 " << r.reserved3 << "\n";
7925 outs() << " reserved4 " << r.reserved4 << "\n";
7926 outs() << " reserved5 " << r.reserved5 << "\n";
7927 outs() << " reserved6 " << r.reserved6 << "\n";
7928}
7929
7930static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7931 outs() << " cmd LC_ROUTINES_64\n";
7932 outs() << " cmdsize " << r.cmdsize;
7933 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
7934 outs() << " Incorrect size\n";
7935 else
7936 outs() << "\n";
7937 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
7938 outs() << " init_module " << r.init_module << "\n";
7939 outs() << " reserved1 " << r.reserved1 << "\n";
7940 outs() << " reserved2 " << r.reserved2 << "\n";
7941 outs() << " reserved3 " << r.reserved3 << "\n";
7942 outs() << " reserved4 " << r.reserved4 << "\n";
7943 outs() << " reserved5 " << r.reserved5 << "\n";
7944 outs() << " reserved6 " << r.reserved6 << "\n";
7945}
7946
Kevin Enderby48ef5342014-12-23 22:56:39 +00007947static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
7948 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
7949 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
7950 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
7951 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
7952 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
7953 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
7954 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
7955 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
7956 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
7957 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
7958 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
7959 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
7960 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
7961 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
7962 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
7963 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
7964 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
7965 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
7966 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
7967 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
7968 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
7969}
7970
Kevin Enderby227df342014-12-23 23:43:59 +00007971static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007972 uint32_t f;
7973 outs() << "\t mmst_reg ";
7974 for (f = 0; f < 10; f++)
7975 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
7976 outs() << "\n";
7977 outs() << "\t mmst_rsrv ";
7978 for (f = 0; f < 6; f++)
7979 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
7980 outs() << "\n";
7981}
7982
Kevin Enderbyaefb0032014-12-24 00:16:51 +00007983static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00007984 uint32_t f;
7985 outs() << "\t xmm_reg ";
7986 for (f = 0; f < 16; f++)
7987 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
7988 outs() << "\n";
7989}
7990
7991static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
7992 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
7993 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
7994 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
7995 outs() << " denorm " << fpu.fpu_fcw.denorm;
7996 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
7997 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
7998 outs() << " undfl " << fpu.fpu_fcw.undfl;
7999 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8000 outs() << "\t\t pc ";
8001 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8002 outs() << "FP_PREC_24B ";
8003 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8004 outs() << "FP_PREC_53B ";
8005 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8006 outs() << "FP_PREC_64B ";
8007 else
8008 outs() << fpu.fpu_fcw.pc << " ";
8009 outs() << "rc ";
8010 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8011 outs() << "FP_RND_NEAR ";
8012 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8013 outs() << "FP_RND_DOWN ";
8014 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8015 outs() << "FP_RND_UP ";
8016 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008017 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008018 outs() << "\n";
8019 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8020 outs() << " denorm " << fpu.fpu_fsw.denorm;
8021 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8022 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8023 outs() << " undfl " << fpu.fpu_fsw.undfl;
8024 outs() << " precis " << fpu.fpu_fsw.precis;
8025 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8026 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8027 outs() << " c0 " << fpu.fpu_fsw.c0;
8028 outs() << " c1 " << fpu.fpu_fsw.c1;
8029 outs() << " c2 " << fpu.fpu_fsw.c2;
8030 outs() << " tos " << fpu.fpu_fsw.tos;
8031 outs() << " c3 " << fpu.fpu_fsw.c3;
8032 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8033 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8034 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8035 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8036 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8037 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8038 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8039 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8040 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8041 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8042 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8043 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8044 outs() << "\n";
8045 outs() << "\t fpu_stmm0:\n";
8046 Print_mmst_reg(fpu.fpu_stmm0);
8047 outs() << "\t fpu_stmm1:\n";
8048 Print_mmst_reg(fpu.fpu_stmm1);
8049 outs() << "\t fpu_stmm2:\n";
8050 Print_mmst_reg(fpu.fpu_stmm2);
8051 outs() << "\t fpu_stmm3:\n";
8052 Print_mmst_reg(fpu.fpu_stmm3);
8053 outs() << "\t fpu_stmm4:\n";
8054 Print_mmst_reg(fpu.fpu_stmm4);
8055 outs() << "\t fpu_stmm5:\n";
8056 Print_mmst_reg(fpu.fpu_stmm5);
8057 outs() << "\t fpu_stmm6:\n";
8058 Print_mmst_reg(fpu.fpu_stmm6);
8059 outs() << "\t fpu_stmm7:\n";
8060 Print_mmst_reg(fpu.fpu_stmm7);
8061 outs() << "\t fpu_xmm0:\n";
8062 Print_xmm_reg(fpu.fpu_xmm0);
8063 outs() << "\t fpu_xmm1:\n";
8064 Print_xmm_reg(fpu.fpu_xmm1);
8065 outs() << "\t fpu_xmm2:\n";
8066 Print_xmm_reg(fpu.fpu_xmm2);
8067 outs() << "\t fpu_xmm3:\n";
8068 Print_xmm_reg(fpu.fpu_xmm3);
8069 outs() << "\t fpu_xmm4:\n";
8070 Print_xmm_reg(fpu.fpu_xmm4);
8071 outs() << "\t fpu_xmm5:\n";
8072 Print_xmm_reg(fpu.fpu_xmm5);
8073 outs() << "\t fpu_xmm6:\n";
8074 Print_xmm_reg(fpu.fpu_xmm6);
8075 outs() << "\t fpu_xmm7:\n";
8076 Print_xmm_reg(fpu.fpu_xmm7);
8077 outs() << "\t fpu_xmm8:\n";
8078 Print_xmm_reg(fpu.fpu_xmm8);
8079 outs() << "\t fpu_xmm9:\n";
8080 Print_xmm_reg(fpu.fpu_xmm9);
8081 outs() << "\t fpu_xmm10:\n";
8082 Print_xmm_reg(fpu.fpu_xmm10);
8083 outs() << "\t fpu_xmm11:\n";
8084 Print_xmm_reg(fpu.fpu_xmm11);
8085 outs() << "\t fpu_xmm12:\n";
8086 Print_xmm_reg(fpu.fpu_xmm12);
8087 outs() << "\t fpu_xmm13:\n";
8088 Print_xmm_reg(fpu.fpu_xmm13);
8089 outs() << "\t fpu_xmm14:\n";
8090 Print_xmm_reg(fpu.fpu_xmm14);
8091 outs() << "\t fpu_xmm15:\n";
8092 Print_xmm_reg(fpu.fpu_xmm15);
8093 outs() << "\t fpu_rsrv4:\n";
8094 for (uint32_t f = 0; f < 6; f++) {
8095 outs() << "\t ";
8096 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008097 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008098 outs() << "\n";
8099 }
8100 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8101 outs() << "\n";
8102}
8103
8104static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8105 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8106 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8107 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8108}
8109
8110static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8111 bool isLittleEndian, uint32_t cputype) {
8112 if (t.cmd == MachO::LC_THREAD)
8113 outs() << " cmd LC_THREAD\n";
8114 else if (t.cmd == MachO::LC_UNIXTHREAD)
8115 outs() << " cmd LC_UNIXTHREAD\n";
8116 else
8117 outs() << " cmd " << t.cmd << " (unknown)\n";
8118 outs() << " cmdsize " << t.cmdsize;
8119 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8120 outs() << " Incorrect size\n";
8121 else
8122 outs() << "\n";
8123
8124 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8125 const char *end = Ptr + t.cmdsize;
8126 uint32_t flavor, count, left;
8127 if (cputype == MachO::CPU_TYPE_X86_64) {
8128 while (begin < end) {
8129 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8130 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8131 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008132 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008133 flavor = 0;
8134 begin = end;
8135 }
8136 if (isLittleEndian != sys::IsLittleEndianHost)
8137 sys::swapByteOrder(flavor);
8138 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8139 memcpy((char *)&count, begin, sizeof(uint32_t));
8140 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008141 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008142 count = 0;
8143 begin = end;
8144 }
8145 if (isLittleEndian != sys::IsLittleEndianHost)
8146 sys::swapByteOrder(count);
8147 if (flavor == MachO::x86_THREAD_STATE64) {
8148 outs() << " flavor x86_THREAD_STATE64\n";
8149 if (count == MachO::x86_THREAD_STATE64_COUNT)
8150 outs() << " count x86_THREAD_STATE64_COUNT\n";
8151 else
8152 outs() << " count " << count
8153 << " (not x86_THREAD_STATE64_COUNT)\n";
8154 MachO::x86_thread_state64_t cpu64;
8155 left = end - begin;
8156 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8157 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8158 begin += sizeof(MachO::x86_thread_state64_t);
8159 } else {
8160 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8161 memcpy(&cpu64, begin, left);
8162 begin += left;
8163 }
8164 if (isLittleEndian != sys::IsLittleEndianHost)
8165 swapStruct(cpu64);
8166 Print_x86_thread_state64_t(cpu64);
8167 } else if (flavor == MachO::x86_THREAD_STATE) {
8168 outs() << " flavor x86_THREAD_STATE\n";
8169 if (count == MachO::x86_THREAD_STATE_COUNT)
8170 outs() << " count x86_THREAD_STATE_COUNT\n";
8171 else
8172 outs() << " count " << count
8173 << " (not x86_THREAD_STATE_COUNT)\n";
8174 struct MachO::x86_thread_state_t ts;
8175 left = end - begin;
8176 if (left >= sizeof(MachO::x86_thread_state_t)) {
8177 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8178 begin += sizeof(MachO::x86_thread_state_t);
8179 } else {
8180 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8181 memcpy(&ts, begin, left);
8182 begin += left;
8183 }
8184 if (isLittleEndian != sys::IsLittleEndianHost)
8185 swapStruct(ts);
8186 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8187 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8188 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8189 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8190 else
8191 outs() << "tsh.count " << ts.tsh.count
8192 << " (not x86_THREAD_STATE64_COUNT\n";
8193 Print_x86_thread_state64_t(ts.uts.ts64);
8194 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008195 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8196 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008197 }
8198 } else if (flavor == MachO::x86_FLOAT_STATE) {
8199 outs() << " flavor x86_FLOAT_STATE\n";
8200 if (count == MachO::x86_FLOAT_STATE_COUNT)
8201 outs() << " count x86_FLOAT_STATE_COUNT\n";
8202 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008203 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008204 struct MachO::x86_float_state_t fs;
8205 left = end - begin;
8206 if (left >= sizeof(MachO::x86_float_state_t)) {
8207 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8208 begin += sizeof(MachO::x86_float_state_t);
8209 } else {
8210 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8211 memcpy(&fs, begin, left);
8212 begin += left;
8213 }
8214 if (isLittleEndian != sys::IsLittleEndianHost)
8215 swapStruct(fs);
8216 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8217 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008218 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008219 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8220 else
8221 outs() << "fsh.count " << fs.fsh.count
8222 << " (not x86_FLOAT_STATE64_COUNT\n";
8223 Print_x86_float_state_t(fs.ufs.fs64);
8224 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008225 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8226 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008227 }
8228 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8229 outs() << " flavor x86_EXCEPTION_STATE\n";
8230 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8231 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8232 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008233 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008234 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8235 struct MachO::x86_exception_state_t es;
8236 left = end - begin;
8237 if (left >= sizeof(MachO::x86_exception_state_t)) {
8238 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8239 begin += sizeof(MachO::x86_exception_state_t);
8240 } else {
8241 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8242 memcpy(&es, begin, left);
8243 begin += left;
8244 }
8245 if (isLittleEndian != sys::IsLittleEndianHost)
8246 swapStruct(es);
8247 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8248 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008249 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008250 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8251 else
8252 outs() << "\t esh.count " << es.esh.count
8253 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8254 Print_x86_exception_state_t(es.ues.es64);
8255 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008256 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8257 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008258 }
8259 } else {
8260 outs() << " flavor " << flavor << " (unknown)\n";
8261 outs() << " count " << count << "\n";
8262 outs() << " state (unknown)\n";
8263 begin += count * sizeof(uint32_t);
8264 }
8265 }
8266 } else {
8267 while (begin < end) {
8268 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8269 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8270 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008271 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008272 flavor = 0;
8273 begin = end;
8274 }
8275 if (isLittleEndian != sys::IsLittleEndianHost)
8276 sys::swapByteOrder(flavor);
8277 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8278 memcpy((char *)&count, begin, sizeof(uint32_t));
8279 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008280 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008281 count = 0;
8282 begin = end;
8283 }
8284 if (isLittleEndian != sys::IsLittleEndianHost)
8285 sys::swapByteOrder(count);
8286 outs() << " flavor " << flavor << "\n";
8287 outs() << " count " << count << "\n";
8288 outs() << " state (Unknown cputype/cpusubtype)\n";
8289 begin += count * sizeof(uint32_t);
8290 }
8291 }
8292}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008293
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008294static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8295 if (dl.cmd == MachO::LC_ID_DYLIB)
8296 outs() << " cmd LC_ID_DYLIB\n";
8297 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8298 outs() << " cmd LC_LOAD_DYLIB\n";
8299 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8300 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8301 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8302 outs() << " cmd LC_REEXPORT_DYLIB\n";
8303 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8304 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8305 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8306 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8307 else
8308 outs() << " cmd " << dl.cmd << " (unknown)\n";
8309 outs() << " cmdsize " << dl.cmdsize;
8310 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8311 outs() << " Incorrect size\n";
8312 else
8313 outs() << "\n";
8314 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008315 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008316 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8317 } else {
8318 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8319 }
8320 outs() << " time stamp " << dl.dylib.timestamp << " ";
8321 time_t t = dl.dylib.timestamp;
8322 outs() << ctime(&t);
8323 outs() << " current version ";
8324 if (dl.dylib.current_version == 0xffffffff)
8325 outs() << "n/a\n";
8326 else
8327 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8328 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8329 << (dl.dylib.current_version & 0xff) << "\n";
8330 outs() << "compatibility version ";
8331 if (dl.dylib.compatibility_version == 0xffffffff)
8332 outs() << "n/a\n";
8333 else
8334 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8335 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8336 << (dl.dylib.compatibility_version & 0xff) << "\n";
8337}
8338
8339static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8340 uint32_t object_size) {
8341 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
8342 outs() << " cmd LC_FUNCTION_STARTS\n";
8343 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8344 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8345 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8346 outs() << " cmd LC_FUNCTION_STARTS\n";
8347 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8348 outs() << " cmd LC_DATA_IN_CODE\n";
8349 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8350 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8351 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8352 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8353 else
8354 outs() << " cmd " << ld.cmd << " (?)\n";
8355 outs() << " cmdsize " << ld.cmdsize;
8356 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8357 outs() << " Incorrect size\n";
8358 else
8359 outs() << "\n";
8360 outs() << " dataoff " << ld.dataoff;
8361 if (ld.dataoff > object_size)
8362 outs() << " (past end of file)\n";
8363 else
8364 outs() << "\n";
8365 outs() << " datasize " << ld.datasize;
8366 uint64_t big_size = ld.dataoff;
8367 big_size += ld.datasize;
8368 if (big_size > object_size)
8369 outs() << " (past end of file)\n";
8370 else
8371 outs() << "\n";
8372}
8373
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008374static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8375 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008376 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008377 unsigned Index = 0;
8378 for (const auto &Command : Obj->load_commands()) {
8379 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008380 if (Command.C.cmd == MachO::LC_SEGMENT) {
8381 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8382 const char *sg_segname = SLC.segname;
8383 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8384 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8385 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8386 verbose);
8387 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008388 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008389 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8390 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8391 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8392 }
8393 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8394 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8395 const char *sg_segname = SLC_64.segname;
8396 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8397 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8398 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8399 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8400 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8401 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8402 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8403 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8404 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8405 sg_segname, filetype, Buf.size(), verbose);
8406 }
8407 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8408 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008409 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008410 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8411 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8412 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008413 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8414 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008415 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8416 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8417 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8418 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8419 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8420 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8421 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8422 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8423 PrintDyldLoadCommand(Dyld, Command.Ptr);
8424 } else if (Command.C.cmd == MachO::LC_UUID) {
8425 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8426 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008427 } else if (Command.C.cmd == MachO::LC_RPATH) {
8428 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8429 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008430 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008431 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8432 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8433 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008434 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8435 PrintVersionMinLoadCommand(Vd);
8436 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8437 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8438 PrintSourceVersionCommand(Sd);
8439 } else if (Command.C.cmd == MachO::LC_MAIN) {
8440 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8441 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008442 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008443 MachO::encryption_info_command Ei =
8444 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008445 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008446 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008447 MachO::encryption_info_command_64 Ei =
8448 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008449 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008450 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008451 MachO::linker_option_command Lo =
8452 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008453 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008454 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8455 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8456 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008457 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8458 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8459 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008460 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8461 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8462 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008463 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8464 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8465 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008466 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8467 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8468 PrintRoutinesCommand(Rc);
8469 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8470 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8471 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008472 } else if (Command.C.cmd == MachO::LC_THREAD ||
8473 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8474 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8475 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008476 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8477 Command.C.cmd == MachO::LC_ID_DYLIB ||
8478 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8479 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8480 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8481 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008482 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8483 PrintDylibCommand(Dl, Command.Ptr);
8484 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8485 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8486 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8487 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8488 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8489 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8490 MachO::linkedit_data_command Ld =
8491 Obj->getLinkeditDataLoadCommand(Command);
8492 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008493 } else {
8494 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8495 << ")\n";
8496 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8497 // TODO: get and print the raw bytes of the load command.
8498 }
8499 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008500 }
8501}
8502
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008503static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008504 if (Obj->is64Bit()) {
8505 MachO::mach_header_64 H_64;
8506 H_64 = Obj->getHeader64();
8507 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8508 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8509 } else {
8510 MachO::mach_header H;
8511 H = Obj->getHeader();
8512 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8513 H.sizeofcmds, H.flags, verbose);
8514 }
8515}
8516
8517void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8518 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008519 PrintMachHeader(file, !NonVerbose);
8520}
8521
8522void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8523 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008524 uint32_t filetype = 0;
8525 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008526 if (file->is64Bit()) {
8527 MachO::mach_header_64 H_64;
8528 H_64 = file->getHeader64();
8529 filetype = H_64.filetype;
8530 cputype = H_64.cputype;
8531 } else {
8532 MachO::mach_header H;
8533 H = file->getHeader();
8534 filetype = H.filetype;
8535 cputype = H.cputype;
8536 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008537 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008538}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008539
8540//===----------------------------------------------------------------------===//
8541// export trie dumping
8542//===----------------------------------------------------------------------===//
8543
8544void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008545 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8546 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008547 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8548 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8549 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8550 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8551 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8552 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8553 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8554 if (ReExport)
8555 outs() << "[re-export] ";
8556 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008557 outs() << format("0x%08llX ",
8558 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008559 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008560 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008561 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008562 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008563 if (WeakDef) {
8564 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008565 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008566 }
8567 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008568 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008569 outs() << ", ";
8570 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008571 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008572 }
8573 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008574 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008575 outs() << ", ";
8576 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008577 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008578 }
8579 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008580 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008581 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008582 outs() << format("resolver=0x%08llX", Entry.other());
8583 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008584 }
8585 outs() << "]";
8586 }
8587 if (ReExport) {
8588 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008589 int Ordinal = Entry.other() - 1;
8590 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8591 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008592 outs() << " (from " << DylibName << ")";
8593 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008594 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008595 }
8596 outs() << "\n";
8597 }
8598}
Nick Kledzikac431442014-09-12 21:34:15 +00008599
Nick Kledzikac431442014-09-12 21:34:15 +00008600//===----------------------------------------------------------------------===//
8601// rebase table dumping
8602//===----------------------------------------------------------------------===//
8603
8604namespace {
8605class SegInfo {
8606public:
8607 SegInfo(const object::MachOObjectFile *Obj);
8608
8609 StringRef segmentName(uint32_t SegIndex);
8610 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8611 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008612 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008613
8614private:
8615 struct SectionInfo {
8616 uint64_t Address;
8617 uint64_t Size;
8618 StringRef SectionName;
8619 StringRef SegmentName;
8620 uint64_t OffsetInSegment;
8621 uint64_t SegmentStartAddress;
8622 uint32_t SegmentIndex;
8623 };
8624 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8625 SmallVector<SectionInfo, 32> Sections;
8626};
8627}
8628
8629SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8630 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008631 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008632 StringRef CurSegName;
8633 uint64_t CurSegAddress;
8634 for (const SectionRef &Section : Obj->sections()) {
8635 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008636 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008637 Info.Address = Section.getAddress();
8638 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008639 Info.SegmentName =
8640 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8641 if (!Info.SegmentName.equals(CurSegName)) {
8642 ++CurSegIndex;
8643 CurSegName = Info.SegmentName;
8644 CurSegAddress = Info.Address;
8645 }
8646 Info.SegmentIndex = CurSegIndex - 1;
8647 Info.OffsetInSegment = Info.Address - CurSegAddress;
8648 Info.SegmentStartAddress = CurSegAddress;
8649 Sections.push_back(Info);
8650 }
8651}
8652
8653StringRef SegInfo::segmentName(uint32_t SegIndex) {
8654 for (const SectionInfo &SI : Sections) {
8655 if (SI.SegmentIndex == SegIndex)
8656 return SI.SegmentName;
8657 }
8658 llvm_unreachable("invalid segIndex");
8659}
8660
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008661bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8662 uint64_t OffsetInSeg) {
8663 for (const SectionInfo &SI : Sections) {
8664 if (SI.SegmentIndex != SegIndex)
8665 continue;
8666 if (SI.OffsetInSegment > OffsetInSeg)
8667 continue;
8668 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8669 continue;
8670 return true;
8671 }
8672 return false;
8673}
8674
Nick Kledzikac431442014-09-12 21:34:15 +00008675const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8676 uint64_t OffsetInSeg) {
8677 for (const SectionInfo &SI : Sections) {
8678 if (SI.SegmentIndex != SegIndex)
8679 continue;
8680 if (SI.OffsetInSegment > OffsetInSeg)
8681 continue;
8682 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8683 continue;
8684 return SI;
8685 }
8686 llvm_unreachable("segIndex and offset not in any section");
8687}
8688
8689StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8690 return findSection(SegIndex, OffsetInSeg).SectionName;
8691}
8692
8693uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8694 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8695 return SI.SegmentStartAddress + OffsetInSeg;
8696}
8697
8698void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8699 // Build table of sections so names can used in final output.
8700 SegInfo sectionTable(Obj);
8701
8702 outs() << "segment section address type\n";
8703 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8704 uint32_t SegIndex = Entry.segmentIndex();
8705 uint64_t OffsetInSeg = Entry.segmentOffset();
8706 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8707 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8708 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8709
8710 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008711 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8712 SegmentName.str().c_str(), SectionName.str().c_str(),
8713 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008714 }
8715}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008716
8717static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8718 StringRef DylibName;
8719 switch (Ordinal) {
8720 case MachO::BIND_SPECIAL_DYLIB_SELF:
8721 return "this-image";
8722 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8723 return "main-executable";
8724 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8725 return "flat-namespace";
8726 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008727 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008728 std::error_code EC =
8729 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008730 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008731 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008732 return DylibName;
8733 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008734 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008735 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008736}
8737
8738//===----------------------------------------------------------------------===//
8739// bind table dumping
8740//===----------------------------------------------------------------------===//
8741
8742void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8743 // Build table of sections so names can used in final output.
8744 SegInfo sectionTable(Obj);
8745
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008746 outs() << "segment section address type "
8747 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008748 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8749 uint32_t SegIndex = Entry.segmentIndex();
8750 uint64_t OffsetInSeg = Entry.segmentOffset();
8751 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8752 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8753 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8754
8755 // Table lines look like:
8756 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008757 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008758 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008759 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008760 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008761 << left_justify(SectionName, 18) << " "
8762 << format_hex(Address, 10, true) << " "
8763 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008764 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008765 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008766 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008767 }
8768}
8769
8770//===----------------------------------------------------------------------===//
8771// lazy bind table dumping
8772//===----------------------------------------------------------------------===//
8773
8774void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8775 // Build table of sections so names can used in final output.
8776 SegInfo sectionTable(Obj);
8777
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008778 outs() << "segment section address "
8779 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008780 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8781 uint32_t SegIndex = Entry.segmentIndex();
8782 uint64_t OffsetInSeg = Entry.segmentOffset();
8783 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8784 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8785 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8786
8787 // Table lines look like:
8788 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008789 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008790 << left_justify(SectionName, 18) << " "
8791 << format_hex(Address, 10, true) << " "
8792 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008793 << Entry.symbolName() << "\n";
8794 }
8795}
8796
Nick Kledzik56ebef42014-09-16 01:41:51 +00008797//===----------------------------------------------------------------------===//
8798// weak bind table dumping
8799//===----------------------------------------------------------------------===//
8800
8801void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8802 // Build table of sections so names can used in final output.
8803 SegInfo sectionTable(Obj);
8804
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008805 outs() << "segment section address "
8806 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008807 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8808 // Strong symbols don't have a location to update.
8809 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008810 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008811 << Entry.symbolName() << "\n";
8812 continue;
8813 }
8814 uint32_t SegIndex = Entry.segmentIndex();
8815 uint64_t OffsetInSeg = Entry.segmentOffset();
8816 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8817 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8818 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8819
8820 // Table lines look like:
8821 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008822 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008823 << left_justify(SectionName, 18) << " "
8824 << format_hex(Address, 10, true) << " "
8825 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008826 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8827 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008828 }
8829}
8830
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008831// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8832// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8833// information for that address. If the address is found its binding symbol
8834// name is returned. If not nullptr is returned.
8835static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8836 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008837 if (info->bindtable == nullptr) {
8838 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008839 SegInfo sectionTable(info->O);
8840 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8841 uint32_t SegIndex = Entry.segmentIndex();
8842 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008843 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8844 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008845 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8846 const char *SymbolName = nullptr;
8847 StringRef name = Entry.symbolName();
8848 if (!name.empty())
8849 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008850 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008851 }
8852 }
Kevin Enderby078be602014-10-23 19:53:12 +00008853 for (bind_table_iterator BI = info->bindtable->begin(),
8854 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008855 BI != BE; ++BI) {
8856 uint64_t Address = BI->first;
8857 if (ReferenceValue == Address) {
8858 const char *SymbolName = BI->second;
8859 return SymbolName;
8860 }
8861 }
8862 return nullptr;
8863}