blob: 232f17f4cd0b780a6fa9fb6bdb35740026e54b8a [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.
Tim Northover9e8eb412016-04-22 23:21:13 +0000145 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000146 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000147 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000148 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 }
150
151 if (TT.getArch() == Triple::arm) {
152 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
153 // that support ARM are also capable of Thumb mode.
154 llvm::Triple ThumbTriple = TT;
155 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
156 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000157 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 }
159
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000160 // Get the target specific parser.
161 std::string Error;
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000163 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 return TheTarget;
165
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
167 if (*ThumbTarget)
168 return TheTarget;
169
170 errs() << "llvm-objdump: error: unable to get target for '";
171 if (!TheTarget)
172 errs() << TripleName;
173 else
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000176 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000177}
178
Owen Andersond9243c42011-10-17 21:37:35 +0000179struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000181 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
182 if (!ATypeOrErr) {
183 std::string Buf;
184 raw_string_ostream OS(Buf);
185 logAllUnhandledErrors(ATypeOrErr.takeError(), OS, "");
186 OS.flush();
187 report_fatal_error(Buf);
188 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000189 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000190 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
191 if (!BTypeOrErr) {
192 std::string Buf;
193 raw_string_ostream OS(Buf);
194 logAllUnhandledErrors(BTypeOrErr.takeError(), OS, "");
195 OS.flush();
196 report_fatal_error(Buf);
197 }
Kevin Enderby74f58d42016-03-23 21:45:21 +0000198 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000199 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
200 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000201 return AAddr < BAddr;
202 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000203};
204
Kevin Enderby273ae012013-06-06 17:20:50 +0000205// Types for the storted data in code table that is built before disassembly
206// and the predicate function to sort them.
207typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
208typedef std::vector<DiceTableEntry> DiceTable;
209typedef DiceTable::iterator dice_table_iterator;
210
Kevin Enderby930fdc72014-11-06 19:00:13 +0000211// This is used to search for a data in code table entry for the PC being
212// disassembled. The j parameter has the PC in j.first. A single data in code
213// table entry can cover many bytes for each of its Kind's. So if the offset,
214// aka the i.first value, of the data in code table entry plus its Length
215// covers the PC being searched for this will return true. If not it will
216// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000217static bool compareDiceTableEntries(const DiceTableEntry &i,
218 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000219 uint16_t Length;
220 i.second.getLength(Length);
221
222 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000223}
224
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000225static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 unsigned short Kind) {
227 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000228
229 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000230 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000231 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000232 if (Length >= 4) {
233 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000234 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000235 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000236 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 Size = 4;
238 } else if (Length >= 2) {
239 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000240 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000241 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000242 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 Size = 2;
244 } else {
245 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000246 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000247 Value = bytes[0];
248 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000249 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000250 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 if (Kind == MachO::DICE_KIND_DATA)
252 outs() << "\t@ KIND_DATA\n";
253 else
254 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000255 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000256 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000257 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000258 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000259 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000260 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
261 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000262 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000263 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000264 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000265 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000266 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 outs() << "\t.short " << format("%5u", Value & 0xffff)
268 << "\t@ KIND_JUMP_TABLE16\n";
269 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000270 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000271 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000272 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
273 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000274 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000275 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000276 outs() << "\t.long " << Value;
277 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
278 outs() << "\t@ KIND_JUMP_TABLE32\n";
279 else
280 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
281 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000282 break;
283 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000284 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000285}
286
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000287static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000288 std::vector<SectionRef> &Sections,
289 std::vector<SymbolRef> &Symbols,
290 SmallVectorImpl<uint64_t> &FoundFns,
291 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000292 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000293 Expected<StringRef> SymName = Symbol.getName();
294 if (!SymName) {
295 std::string Buf;
296 raw_string_ostream OS(Buf);
297 logAllUnhandledErrors(SymName.takeError(), OS, "");
298 OS.flush();
299 report_fatal_error(Buf);
300 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000301 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000302 Symbols.push_back(Symbol);
303 }
Owen Andersond9243c42011-10-17 21:37:35 +0000304
Alexey Samsonov48803e52014-03-13 14:37:36 +0000305 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000306 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000307 Section.getName(SectName);
308 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000309 }
310
Kevin Enderby273ae012013-06-06 17:20:50 +0000311 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000312 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000313 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000314 // We found a function starts segment, parse the addresses for later
315 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000316 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000317 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000318
Charles Davis8bdfafd2013-09-01 04:28:48 +0000319 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000320 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
321 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000322 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000323 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000324 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000325 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000326 }
327 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000328 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000329}
330
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000331static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
332 uint32_t n, uint32_t count,
333 uint32_t stride, uint64_t addr) {
334 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
335 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
336 if (n > nindirectsyms)
337 outs() << " (entries start past the end of the indirect symbol "
338 "table) (reserved1 field greater than the table size)";
339 else if (n + count > nindirectsyms)
340 outs() << " (entries extends past the end of the indirect symbol "
341 "table)";
342 outs() << "\n";
343 uint32_t cputype = O->getHeader().cputype;
344 if (cputype & MachO::CPU_ARCH_ABI64)
345 outs() << "address index";
346 else
347 outs() << "address index";
348 if (verbose)
349 outs() << " name\n";
350 else
351 outs() << "\n";
352 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
353 if (cputype & MachO::CPU_ARCH_ABI64)
354 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
355 else
Tim Northover43978372016-04-26 18:29:16 +0000356 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000357 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
358 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
359 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
360 outs() << "LOCAL\n";
361 continue;
362 }
363 if (indirect_symbol ==
364 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
365 outs() << "LOCAL ABSOLUTE\n";
366 continue;
367 }
368 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
369 outs() << "ABSOLUTE\n";
370 continue;
371 }
372 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000373 if (verbose) {
374 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
375 if (indirect_symbol < Symtab.nsyms) {
376 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
377 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000378 Expected<StringRef> SymName = Symbol.getName();
379 if (!SymName) {
380 std::string Buf;
381 raw_string_ostream OS(Buf);
382 logAllUnhandledErrors(SymName.takeError(), OS, "");
383 OS.flush();
384 report_fatal_error(Buf);
385 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000386 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000387 } else {
388 outs() << "?";
389 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000390 }
391 outs() << "\n";
392 }
393}
394
395static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000396 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000397 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
398 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
399 for (unsigned J = 0; J < Seg.nsects; ++J) {
400 MachO::section_64 Sec = O->getSection64(Load, J);
401 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
402 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
403 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
404 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
405 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
406 section_type == MachO::S_SYMBOL_STUBS) {
407 uint32_t stride;
408 if (section_type == MachO::S_SYMBOL_STUBS)
409 stride = Sec.reserved2;
410 else
411 stride = 8;
412 if (stride == 0) {
413 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
414 << Sec.sectname << ") "
415 << "(size of stubs in reserved2 field is zero)\n";
416 continue;
417 }
418 uint32_t count = Sec.size / stride;
419 outs() << "Indirect symbols for (" << Sec.segname << ","
420 << Sec.sectname << ") " << count << " entries";
421 uint32_t n = Sec.reserved1;
422 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
423 }
424 }
425 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
426 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
427 for (unsigned J = 0; J < Seg.nsects; ++J) {
428 MachO::section Sec = O->getSection(Load, J);
429 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
430 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
431 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
432 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
433 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
434 section_type == MachO::S_SYMBOL_STUBS) {
435 uint32_t stride;
436 if (section_type == MachO::S_SYMBOL_STUBS)
437 stride = Sec.reserved2;
438 else
439 stride = 4;
440 if (stride == 0) {
441 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
442 << Sec.sectname << ") "
443 << "(size of stubs in reserved2 field is zero)\n";
444 continue;
445 }
446 uint32_t count = Sec.size / stride;
447 outs() << "Indirect symbols for (" << Sec.segname << ","
448 << Sec.sectname << ") " << count << " entries";
449 uint32_t n = Sec.reserved1;
450 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
451 }
452 }
453 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000454 }
455}
456
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000457static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
458 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
459 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
460 outs() << "Data in code table (" << nentries << " entries)\n";
461 outs() << "offset length kind\n";
462 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
463 ++DI) {
464 uint32_t Offset;
465 DI->getOffset(Offset);
466 outs() << format("0x%08" PRIx32, Offset) << " ";
467 uint16_t Length;
468 DI->getLength(Length);
469 outs() << format("%6u", Length) << " ";
470 uint16_t Kind;
471 DI->getKind(Kind);
472 if (verbose) {
473 switch (Kind) {
474 case MachO::DICE_KIND_DATA:
475 outs() << "DATA";
476 break;
477 case MachO::DICE_KIND_JUMP_TABLE8:
478 outs() << "JUMP_TABLE8";
479 break;
480 case MachO::DICE_KIND_JUMP_TABLE16:
481 outs() << "JUMP_TABLE16";
482 break;
483 case MachO::DICE_KIND_JUMP_TABLE32:
484 outs() << "JUMP_TABLE32";
485 break;
486 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
487 outs() << "ABS_JUMP_TABLE32";
488 break;
489 default:
490 outs() << format("0x%04" PRIx32, Kind);
491 break;
492 }
493 } else
494 outs() << format("0x%04" PRIx32, Kind);
495 outs() << "\n";
496 }
497}
498
Kevin Enderby9a509442015-01-27 21:28:24 +0000499static void PrintLinkOptHints(MachOObjectFile *O) {
500 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
501 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
502 uint32_t nloh = LohLC.datasize;
503 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
504 for (uint32_t i = 0; i < nloh;) {
505 unsigned n;
506 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
507 i += n;
508 outs() << " identifier " << identifier << " ";
509 if (i >= nloh)
510 return;
511 switch (identifier) {
512 case 1:
513 outs() << "AdrpAdrp\n";
514 break;
515 case 2:
516 outs() << "AdrpLdr\n";
517 break;
518 case 3:
519 outs() << "AdrpAddLdr\n";
520 break;
521 case 4:
522 outs() << "AdrpLdrGotLdr\n";
523 break;
524 case 5:
525 outs() << "AdrpAddStr\n";
526 break;
527 case 6:
528 outs() << "AdrpLdrGotStr\n";
529 break;
530 case 7:
531 outs() << "AdrpAdd\n";
532 break;
533 case 8:
534 outs() << "AdrpLdrGot\n";
535 break;
536 default:
537 outs() << "Unknown identifier value\n";
538 break;
539 }
540 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
541 i += n;
542 outs() << " narguments " << narguments << "\n";
543 if (i >= nloh)
544 return;
545
546 for (uint32_t j = 0; j < narguments; j++) {
547 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
548 i += n;
549 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
550 if (i >= nloh)
551 return;
552 }
553 }
554}
555
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000556static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000557 unsigned Index = 0;
558 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000559 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
560 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
561 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
562 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
563 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
564 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
565 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
566 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
567 if (dl.dylib.name < dl.cmdsize) {
568 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
569 if (JustId)
570 outs() << p << "\n";
571 else {
572 outs() << "\t" << p;
573 outs() << " (compatibility version "
574 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
575 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
576 << (dl.dylib.compatibility_version & 0xff) << ",";
577 outs() << " current version "
578 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
579 << ((dl.dylib.current_version >> 8) & 0xff) << "."
580 << (dl.dylib.current_version & 0xff) << ")\n";
581 }
582 } else {
583 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
584 if (Load.C.cmd == MachO::LC_ID_DYLIB)
585 outs() << "LC_ID_DYLIB ";
586 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
587 outs() << "LC_LOAD_DYLIB ";
588 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
589 outs() << "LC_LOAD_WEAK_DYLIB ";
590 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
591 outs() << "LC_LAZY_LOAD_DYLIB ";
592 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
593 outs() << "LC_REEXPORT_DYLIB ";
594 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
595 outs() << "LC_LOAD_UPWARD_DYLIB ";
596 else
597 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000598 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000599 }
600 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000601 }
602}
603
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000604typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
605
606static void CreateSymbolAddressMap(MachOObjectFile *O,
607 SymbolAddressMap *AddrMap) {
608 // Create a map of symbol addresses to symbol names.
609 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000610 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
611 if (!STOrErr) {
612 std::string Buf;
613 raw_string_ostream OS(Buf);
614 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
615 OS.flush();
616 report_fatal_error(Buf);
617 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000618 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000619 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
620 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000621 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000622 Expected<StringRef> SymNameOrErr = Symbol.getName();
623 if (!SymNameOrErr) {
624 std::string Buf;
625 raw_string_ostream OS(Buf);
626 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
627 OS.flush();
628 report_fatal_error(Buf);
629 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000630 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000631 if (!SymName.startswith(".objc"))
632 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000633 }
634 }
635}
636
637// GuessSymbolName is passed the address of what might be a symbol and a
638// pointer to the SymbolAddressMap. It returns the name of a symbol
639// with that address or nullptr if no symbol is found with that address.
640static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
641 const char *SymbolName = nullptr;
642 // A DenseMap can't lookup up some values.
643 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
644 StringRef name = AddrMap->lookup(value);
645 if (!name.empty())
646 SymbolName = name.data();
647 }
648 return SymbolName;
649}
650
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000651static void DumpCstringChar(const char c) {
652 char p[2];
653 p[0] = c;
654 p[1] = '\0';
655 outs().write_escaped(p);
656}
657
Kevin Enderby10ba0412015-02-04 21:38:42 +0000658static void DumpCstringSection(MachOObjectFile *O, const char *sect,
659 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000660 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000661 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000662 if (print_addresses) {
663 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000664 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000665 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000666 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000667 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000668 for (; i < sect_size && sect[i] != '\0'; i++)
669 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000670 if (i < sect_size && sect[i] == '\0')
671 outs() << "\n";
672 }
673}
674
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000675static void DumpLiteral4(uint32_t l, float f) {
676 outs() << format("0x%08" PRIx32, l);
677 if ((l & 0x7f800000) != 0x7f800000)
678 outs() << format(" (%.16e)\n", f);
679 else {
680 if (l == 0x7f800000)
681 outs() << " (+Infinity)\n";
682 else if (l == 0xff800000)
683 outs() << " (-Infinity)\n";
684 else if ((l & 0x00400000) == 0x00400000)
685 outs() << " (non-signaling Not-a-Number)\n";
686 else
687 outs() << " (signaling Not-a-Number)\n";
688 }
689}
690
691static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
692 uint32_t sect_size, uint64_t sect_addr,
693 bool print_addresses) {
694 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
695 if (print_addresses) {
696 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000697 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000698 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000699 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000700 }
701 float f;
702 memcpy(&f, sect + i, sizeof(float));
703 if (O->isLittleEndian() != sys::IsLittleEndianHost)
704 sys::swapByteOrder(f);
705 uint32_t l;
706 memcpy(&l, sect + i, sizeof(uint32_t));
707 if (O->isLittleEndian() != sys::IsLittleEndianHost)
708 sys::swapByteOrder(l);
709 DumpLiteral4(l, f);
710 }
711}
712
713static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
714 double d) {
715 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
716 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000717 Hi = (O->isLittleEndian()) ? l1 : l0;
718 Lo = (O->isLittleEndian()) ? l0 : l1;
719
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000720 // Hi is the high word, so this is equivalent to if(isfinite(d))
721 if ((Hi & 0x7ff00000) != 0x7ff00000)
722 outs() << format(" (%.16e)\n", d);
723 else {
724 if (Hi == 0x7ff00000 && Lo == 0)
725 outs() << " (+Infinity)\n";
726 else if (Hi == 0xfff00000 && Lo == 0)
727 outs() << " (-Infinity)\n";
728 else if ((Hi & 0x00080000) == 0x00080000)
729 outs() << " (non-signaling Not-a-Number)\n";
730 else
731 outs() << " (signaling Not-a-Number)\n";
732 }
733}
734
735static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
736 uint32_t sect_size, uint64_t sect_addr,
737 bool print_addresses) {
738 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
739 if (print_addresses) {
740 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000741 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000742 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000743 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000744 }
745 double d;
746 memcpy(&d, sect + i, sizeof(double));
747 if (O->isLittleEndian() != sys::IsLittleEndianHost)
748 sys::swapByteOrder(d);
749 uint32_t l0, l1;
750 memcpy(&l0, sect + i, sizeof(uint32_t));
751 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
752 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
753 sys::swapByteOrder(l0);
754 sys::swapByteOrder(l1);
755 }
756 DumpLiteral8(O, l0, l1, d);
757 }
758}
759
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000760static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
761 outs() << format("0x%08" PRIx32, l0) << " ";
762 outs() << format("0x%08" PRIx32, l1) << " ";
763 outs() << format("0x%08" PRIx32, l2) << " ";
764 outs() << format("0x%08" PRIx32, l3) << "\n";
765}
766
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000767static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
768 uint32_t sect_size, uint64_t sect_addr,
769 bool print_addresses) {
770 for (uint32_t i = 0; i < sect_size; i += 16) {
771 if (print_addresses) {
772 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000773 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000774 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000775 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000776 }
777 uint32_t l0, l1, l2, l3;
778 memcpy(&l0, sect + i, sizeof(uint32_t));
779 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
780 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
781 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
782 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
783 sys::swapByteOrder(l0);
784 sys::swapByteOrder(l1);
785 sys::swapByteOrder(l2);
786 sys::swapByteOrder(l3);
787 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000788 DumpLiteral16(l0, l1, l2, l3);
789 }
790}
791
792static void DumpLiteralPointerSection(MachOObjectFile *O,
793 const SectionRef &Section,
794 const char *sect, uint32_t sect_size,
795 uint64_t sect_addr,
796 bool print_addresses) {
797 // Collect the literal sections in this Mach-O file.
798 std::vector<SectionRef> LiteralSections;
799 for (const SectionRef &Section : O->sections()) {
800 DataRefImpl Ref = Section.getRawDataRefImpl();
801 uint32_t section_type;
802 if (O->is64Bit()) {
803 const MachO::section_64 Sec = O->getSection64(Ref);
804 section_type = Sec.flags & MachO::SECTION_TYPE;
805 } else {
806 const MachO::section Sec = O->getSection(Ref);
807 section_type = Sec.flags & MachO::SECTION_TYPE;
808 }
809 if (section_type == MachO::S_CSTRING_LITERALS ||
810 section_type == MachO::S_4BYTE_LITERALS ||
811 section_type == MachO::S_8BYTE_LITERALS ||
812 section_type == MachO::S_16BYTE_LITERALS)
813 LiteralSections.push_back(Section);
814 }
815
816 // Set the size of the literal pointer.
817 uint32_t lp_size = O->is64Bit() ? 8 : 4;
818
Eric Christopher572e03a2015-06-19 01:53:21 +0000819 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000820 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
821 for (const RelocationRef &Reloc : Section.relocations()) {
822 DataRefImpl Rel;
823 MachO::any_relocation_info RE;
824 bool isExtern = false;
825 Rel = Reloc.getRawDataRefImpl();
826 RE = O->getRelocation(Rel);
827 isExtern = O->getPlainRelocationExternal(RE);
828 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000829 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000830 symbol_iterator RelocSym = Reloc.getSymbol();
831 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
832 }
833 }
834 array_pod_sort(Relocs.begin(), Relocs.end());
835
836 // Dump each literal pointer.
837 for (uint32_t i = 0; i < sect_size; i += lp_size) {
838 if (print_addresses) {
839 if (O->is64Bit())
840 outs() << format("%016" PRIx64, sect_addr + i) << " ";
841 else
842 outs() << format("%08" PRIx64, sect_addr + i) << " ";
843 }
844 uint64_t lp;
845 if (O->is64Bit()) {
846 memcpy(&lp, sect + i, sizeof(uint64_t));
847 if (O->isLittleEndian() != sys::IsLittleEndianHost)
848 sys::swapByteOrder(lp);
849 } else {
850 uint32_t li;
851 memcpy(&li, sect + i, sizeof(uint32_t));
852 if (O->isLittleEndian() != sys::IsLittleEndianHost)
853 sys::swapByteOrder(li);
854 lp = li;
855 }
856
857 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000858 auto Reloc = std::find_if(
859 Relocs.begin(), Relocs.end(),
860 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
861 if (Reloc != Relocs.end()) {
862 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000863 Expected<StringRef> SymName = RelocSym->getName();
864 if (!SymName) {
865 std::string Buf;
866 raw_string_ostream OS(Buf);
867 logAllUnhandledErrors(SymName.takeError(), OS, "");
868 OS.flush();
869 report_fatal_error(Buf);
870 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000871 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000872 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000873 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000874
875 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000876 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
877 [&](const SectionRef &R) {
878 return lp >= R.getAddress() &&
879 lp < R.getAddress() + R.getSize();
880 });
881 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000882 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000883 continue;
884 }
885
886 uint64_t SectAddress = Sect->getAddress();
887 uint64_t SectSize = Sect->getSize();
888
889 StringRef SectName;
890 Sect->getName(SectName);
891 DataRefImpl Ref = Sect->getRawDataRefImpl();
892 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
893 outs() << SegmentName << ":" << SectName << ":";
894
895 uint32_t section_type;
896 if (O->is64Bit()) {
897 const MachO::section_64 Sec = O->getSection64(Ref);
898 section_type = Sec.flags & MachO::SECTION_TYPE;
899 } else {
900 const MachO::section Sec = O->getSection(Ref);
901 section_type = Sec.flags & MachO::SECTION_TYPE;
902 }
903
904 StringRef BytesStr;
905 Sect->getContents(BytesStr);
906 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
907
908 switch (section_type) {
909 case MachO::S_CSTRING_LITERALS:
910 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
911 i++) {
912 DumpCstringChar(Contents[i]);
913 }
914 outs() << "\n";
915 break;
916 case MachO::S_4BYTE_LITERALS:
917 float f;
918 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
919 uint32_t l;
920 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
921 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
922 sys::swapByteOrder(f);
923 sys::swapByteOrder(l);
924 }
925 DumpLiteral4(l, f);
926 break;
927 case MachO::S_8BYTE_LITERALS: {
928 double d;
929 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
930 uint32_t l0, l1;
931 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
932 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
933 sizeof(uint32_t));
934 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
935 sys::swapByteOrder(f);
936 sys::swapByteOrder(l0);
937 sys::swapByteOrder(l1);
938 }
939 DumpLiteral8(O, l0, l1, d);
940 break;
941 }
942 case MachO::S_16BYTE_LITERALS: {
943 uint32_t l0, l1, l2, l3;
944 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
945 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
946 sizeof(uint32_t));
947 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
948 sizeof(uint32_t));
949 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
950 sizeof(uint32_t));
951 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
952 sys::swapByteOrder(l0);
953 sys::swapByteOrder(l1);
954 sys::swapByteOrder(l2);
955 sys::swapByteOrder(l3);
956 }
957 DumpLiteral16(l0, l1, l2, l3);
958 break;
959 }
960 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000961 }
962}
963
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000964static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
965 uint32_t sect_size, uint64_t sect_addr,
966 SymbolAddressMap *AddrMap,
967 bool verbose) {
968 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000969 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000970 for (uint32_t i = 0; i < sect_size; i += stride) {
971 const char *SymbolName = nullptr;
972 if (O->is64Bit()) {
973 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
974 uint64_t pointer_value;
975 memcpy(&pointer_value, sect + i, stride);
976 if (O->isLittleEndian() != sys::IsLittleEndianHost)
977 sys::swapByteOrder(pointer_value);
978 outs() << format("0x%016" PRIx64, pointer_value);
979 if (verbose)
980 SymbolName = GuessSymbolName(pointer_value, AddrMap);
981 } else {
982 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
983 uint32_t pointer_value;
984 memcpy(&pointer_value, sect + i, stride);
985 if (O->isLittleEndian() != sys::IsLittleEndianHost)
986 sys::swapByteOrder(pointer_value);
987 outs() << format("0x%08" PRIx32, pointer_value);
988 if (verbose)
989 SymbolName = GuessSymbolName(pointer_value, AddrMap);
990 }
991 if (SymbolName)
992 outs() << " " << SymbolName;
993 outs() << "\n";
994 }
995}
996
997static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
998 uint32_t size, uint64_t addr) {
999 uint32_t cputype = O->getHeader().cputype;
1000 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1001 uint32_t j;
1002 for (uint32_t i = 0; i < size; i += j, addr += j) {
1003 if (O->is64Bit())
1004 outs() << format("%016" PRIx64, addr) << "\t";
1005 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001006 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001007 for (j = 0; j < 16 && i + j < size; j++) {
1008 uint8_t byte_word = *(sect + i + j);
1009 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1010 }
1011 outs() << "\n";
1012 }
1013 } else {
1014 uint32_t j;
1015 for (uint32_t i = 0; i < size; i += j, addr += j) {
1016 if (O->is64Bit())
1017 outs() << format("%016" PRIx64, addr) << "\t";
1018 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001019 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001020 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1021 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001022 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001023 uint32_t long_word;
1024 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1025 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1026 sys::swapByteOrder(long_word);
1027 outs() << format("%08" PRIx32, long_word) << " ";
1028 } else {
1029 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001030 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001031 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1032 }
1033 }
1034 }
1035 outs() << "\n";
1036 }
1037 }
1038}
1039
Kevin Enderby95df54c2015-02-04 01:01:38 +00001040static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1041 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001042static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1043 uint32_t size, uint32_t addr);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001044
1045static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1046 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001047 SymbolAddressMap AddrMap;
1048 if (verbose)
1049 CreateSymbolAddressMap(O, &AddrMap);
1050
Colin LeMahieufcc32762015-07-29 19:08:10 +00001051 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1052 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001053 std::pair<StringRef, StringRef> DumpSegSectName;
1054 DumpSegSectName = DumpSection.split(',');
1055 StringRef DumpSegName, DumpSectName;
1056 if (DumpSegSectName.second.size()) {
1057 DumpSegName = DumpSegSectName.first;
1058 DumpSectName = DumpSegSectName.second;
1059 } else {
1060 DumpSegName = "";
1061 DumpSectName = DumpSegSectName.first;
1062 }
1063 for (const SectionRef &Section : O->sections()) {
1064 StringRef SectName;
1065 Section.getName(SectName);
1066 DataRefImpl Ref = Section.getRawDataRefImpl();
1067 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1068 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1069 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001070
Kevin Enderby95df54c2015-02-04 01:01:38 +00001071 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001072 if (O->is64Bit()) {
1073 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001074 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001075
1076 } else {
1077 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001078 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001079 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001080 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001081
1082 StringRef BytesStr;
1083 Section.getContents(BytesStr);
1084 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1085 uint32_t sect_size = BytesStr.size();
1086 uint64_t sect_addr = Section.getAddress();
1087
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001088 outs() << "Contents of (" << SegName << "," << SectName
1089 << ") section\n";
1090
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001091 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001092 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1093 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1094 DisassembleMachO(Filename, O, SegName, SectName);
1095 continue;
1096 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001097 if (SegName == "__TEXT" && SectName == "__info_plist") {
1098 outs() << sect;
1099 continue;
1100 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001101 if (SegName == "__OBJC" && SectName == "__protocol") {
1102 DumpProtocolSection(O, sect, sect_size, sect_addr);
1103 continue;
1104 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001105 switch (section_type) {
1106 case MachO::S_REGULAR:
1107 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1108 break;
1109 case MachO::S_ZEROFILL:
1110 outs() << "zerofill section and has no contents in the file\n";
1111 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001112 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001113 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001114 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001115 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001116 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001117 break;
1118 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001119 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001120 break;
1121 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001122 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1123 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001124 case MachO::S_LITERAL_POINTERS:
1125 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001126 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001127 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001128 case MachO::S_MOD_INIT_FUNC_POINTERS:
1129 case MachO::S_MOD_TERM_FUNC_POINTERS:
1130 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1131 verbose);
1132 break;
1133 default:
1134 outs() << "Unknown section type ("
1135 << format("0x%08" PRIx32, section_type) << ")\n";
1136 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1137 break;
1138 }
1139 } else {
1140 if (section_type == MachO::S_ZEROFILL)
1141 outs() << "zerofill section and has no contents in the file\n";
1142 else
1143 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1144 }
1145 }
1146 }
1147 }
1148}
1149
Kevin Enderbycd66be52015-03-11 22:06:32 +00001150static void DumpInfoPlistSectionContents(StringRef Filename,
1151 MachOObjectFile *O) {
1152 for (const SectionRef &Section : O->sections()) {
1153 StringRef SectName;
1154 Section.getName(SectName);
1155 DataRefImpl Ref = Section.getRawDataRefImpl();
1156 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1157 if (SegName == "__TEXT" && SectName == "__info_plist") {
1158 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1159 StringRef BytesStr;
1160 Section.getContents(BytesStr);
1161 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1162 outs() << sect;
1163 return;
1164 }
1165 }
1166}
1167
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001168// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1169// and if it is and there is a list of architecture flags is specified then
1170// check to make sure this Mach-O file is one of those architectures or all
1171// architectures were specified. If not then an error is generated and this
1172// routine returns false. Else it returns true.
1173static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1174 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1175 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1176 bool ArchFound = false;
1177 MachO::mach_header H;
1178 MachO::mach_header_64 H_64;
1179 Triple T;
1180 if (MachO->is64Bit()) {
1181 H_64 = MachO->MachOObjectFile::getHeader64();
Tim Northover9e8eb412016-04-22 23:21:13 +00001182 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001183 } else {
1184 H = MachO->MachOObjectFile::getHeader();
Tim Northover9e8eb412016-04-22 23:21:13 +00001185 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001186 }
1187 unsigned i;
1188 for (i = 0; i < ArchFlags.size(); ++i) {
1189 if (ArchFlags[i] == T.getArchName())
1190 ArchFound = true;
1191 break;
1192 }
1193 if (!ArchFound) {
1194 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1195 << "architecture: " + ArchFlags[i] + "\n";
1196 return false;
1197 }
1198 }
1199 return true;
1200}
1201
Kevin Enderby0fc11822015-04-01 20:57:01 +00001202static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1203
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001204// ProcessMachO() is passed a single opened Mach-O file, which may be an
1205// archive member and or in a slice of a universal file. It prints the
1206// the file name and header info and then processes it according to the
1207// command line options.
1208static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1209 StringRef ArchiveMemberName = StringRef(),
1210 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001211 // If we are doing some processing here on the Mach-O file print the header
1212 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001213 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +00001214 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001215 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001216 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001217 outs() << Filename;
1218 if (!ArchiveMemberName.empty())
1219 outs() << '(' << ArchiveMemberName << ')';
1220 if (!ArchitectureName.empty())
1221 outs() << " (architecture " << ArchitectureName << ")";
1222 outs() << ":\n";
1223 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001224
1225 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001226 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001227 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001228 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001229 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001230 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001231 if (LinkOptHints)
1232 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001233 if (Relocations)
1234 PrintRelocations(MachOOF);
1235 if (SectionHeaders)
1236 PrintSectionHeaders(MachOOF);
1237 if (SectionContents)
1238 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001239 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001240 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001241 if (InfoPlist)
1242 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001243 if (DylibsUsed)
1244 PrintDylibs(MachOOF, false);
1245 if (DylibId)
1246 PrintDylibs(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +00001247 if (SymbolTable)
1248 PrintSymbolTable(MachOOF);
1249 if (UnwindInfo)
1250 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001251 if (PrivateHeaders) {
1252 printMachOFileHeader(MachOOF);
1253 printMachOLoadCommands(MachOOF);
1254 }
1255 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001256 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001257 if (ObjcMetaData)
1258 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001259 if (ExportsTrie)
1260 printExportsTrie(MachOOF);
1261 if (Rebase)
1262 printRebaseTable(MachOOF);
1263 if (Bind)
1264 printBindTable(MachOOF);
1265 if (LazyBind)
1266 printLazyBindTable(MachOOF);
1267 if (WeakBind)
1268 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001269
1270 if (DwarfDumpType != DIDT_Null) {
1271 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1272 // Dump the complete DWARF structure.
1273 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1274 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001275}
1276
Kevin Enderby131d1772015-01-09 19:22:37 +00001277// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1278static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1279 outs() << " cputype (" << cputype << ")\n";
1280 outs() << " cpusubtype (" << cpusubtype << ")\n";
1281}
1282
1283// printCPUType() helps print_fat_headers by printing the cputype and
1284// pusubtype (symbolically for the one's it knows about).
1285static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1286 switch (cputype) {
1287 case MachO::CPU_TYPE_I386:
1288 switch (cpusubtype) {
1289 case MachO::CPU_SUBTYPE_I386_ALL:
1290 outs() << " cputype CPU_TYPE_I386\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1292 break;
1293 default:
1294 printUnknownCPUType(cputype, cpusubtype);
1295 break;
1296 }
1297 break;
1298 case MachO::CPU_TYPE_X86_64:
1299 switch (cpusubtype) {
1300 case MachO::CPU_SUBTYPE_X86_64_ALL:
1301 outs() << " cputype CPU_TYPE_X86_64\n";
1302 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1303 break;
1304 case MachO::CPU_SUBTYPE_X86_64_H:
1305 outs() << " cputype CPU_TYPE_X86_64\n";
1306 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1307 break;
1308 default:
1309 printUnknownCPUType(cputype, cpusubtype);
1310 break;
1311 }
1312 break;
1313 case MachO::CPU_TYPE_ARM:
1314 switch (cpusubtype) {
1315 case MachO::CPU_SUBTYPE_ARM_ALL:
1316 outs() << " cputype CPU_TYPE_ARM\n";
1317 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1318 break;
1319 case MachO::CPU_SUBTYPE_ARM_V4T:
1320 outs() << " cputype CPU_TYPE_ARM\n";
1321 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1322 break;
1323 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1324 outs() << " cputype CPU_TYPE_ARM\n";
1325 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1326 break;
1327 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1328 outs() << " cputype CPU_TYPE_ARM\n";
1329 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1330 break;
1331 case MachO::CPU_SUBTYPE_ARM_V6:
1332 outs() << " cputype CPU_TYPE_ARM\n";
1333 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1334 break;
1335 case MachO::CPU_SUBTYPE_ARM_V6M:
1336 outs() << " cputype CPU_TYPE_ARM\n";
1337 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1338 break;
1339 case MachO::CPU_SUBTYPE_ARM_V7:
1340 outs() << " cputype CPU_TYPE_ARM\n";
1341 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1342 break;
1343 case MachO::CPU_SUBTYPE_ARM_V7EM:
1344 outs() << " cputype CPU_TYPE_ARM\n";
1345 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1346 break;
1347 case MachO::CPU_SUBTYPE_ARM_V7K:
1348 outs() << " cputype CPU_TYPE_ARM\n";
1349 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1350 break;
1351 case MachO::CPU_SUBTYPE_ARM_V7M:
1352 outs() << " cputype CPU_TYPE_ARM\n";
1353 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1354 break;
1355 case MachO::CPU_SUBTYPE_ARM_V7S:
1356 outs() << " cputype CPU_TYPE_ARM\n";
1357 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1358 break;
1359 default:
1360 printUnknownCPUType(cputype, cpusubtype);
1361 break;
1362 }
1363 break;
1364 case MachO::CPU_TYPE_ARM64:
1365 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1366 case MachO::CPU_SUBTYPE_ARM64_ALL:
1367 outs() << " cputype CPU_TYPE_ARM64\n";
1368 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1369 break;
1370 default:
1371 printUnknownCPUType(cputype, cpusubtype);
1372 break;
1373 }
1374 break;
1375 default:
1376 printUnknownCPUType(cputype, cpusubtype);
1377 break;
1378 }
1379}
1380
1381static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1382 bool verbose) {
1383 outs() << "Fat headers\n";
1384 if (verbose)
1385 outs() << "fat_magic FAT_MAGIC\n";
1386 else
1387 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1388
1389 uint32_t nfat_arch = UB->getNumberOfObjects();
1390 StringRef Buf = UB->getData();
1391 uint64_t size = Buf.size();
1392 uint64_t big_size = sizeof(struct MachO::fat_header) +
1393 nfat_arch * sizeof(struct MachO::fat_arch);
1394 outs() << "nfat_arch " << UB->getNumberOfObjects();
1395 if (nfat_arch == 0)
1396 outs() << " (malformed, contains zero architecture types)\n";
1397 else if (big_size > size)
1398 outs() << " (malformed, architectures past end of file)\n";
1399 else
1400 outs() << "\n";
1401
1402 for (uint32_t i = 0; i < nfat_arch; ++i) {
1403 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1404 uint32_t cputype = OFA.getCPUType();
1405 uint32_t cpusubtype = OFA.getCPUSubType();
1406 outs() << "architecture ";
1407 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1408 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1409 uint32_t other_cputype = other_OFA.getCPUType();
1410 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001411 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001412 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001413 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001414 outs() << "(illegal duplicate architecture) ";
1415 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001416 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001417 }
1418 if (verbose) {
1419 outs() << OFA.getArchTypeName() << "\n";
1420 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1421 } else {
1422 outs() << i << "\n";
1423 outs() << " cputype " << cputype << "\n";
1424 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1425 << "\n";
1426 }
1427 if (verbose &&
1428 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1429 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1430 else
1431 outs() << " capabilities "
1432 << format("0x%" PRIx32,
1433 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1434 outs() << " offset " << OFA.getOffset();
1435 if (OFA.getOffset() > size)
1436 outs() << " (past end of file)";
1437 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1438 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1439 outs() << "\n";
1440 outs() << " size " << OFA.getSize();
1441 big_size = OFA.getOffset() + OFA.getSize();
1442 if (big_size > size)
1443 outs() << " (past end of file)";
1444 outs() << "\n";
1445 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1446 << ")\n";
1447 }
1448}
1449
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001450static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001451 bool print_offset) {
1452 if (print_offset)
1453 outs() << C.getChildOffset() << "\t";
1454 sys::fs::perms Mode = C.getAccessMode();
1455 if (verbose) {
1456 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1457 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1458 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001459 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1460 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1461 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1462 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1463 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1464 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1465 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1466 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1467 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001468 } else {
1469 outs() << format("0%o ", Mode);
1470 }
1471
1472 unsigned UID = C.getUID();
1473 outs() << format("%3d/", UID);
1474 unsigned GID = C.getGID();
1475 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001476 ErrorOr<uint64_t> Size = C.getRawSize();
1477 if (std::error_code EC = Size.getError())
1478 report_fatal_error(EC.message());
1479 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001480
1481 StringRef RawLastModified = C.getRawLastModified();
1482 if (verbose) {
1483 unsigned Seconds;
1484 if (RawLastModified.getAsInteger(10, Seconds))
1485 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1486 else {
1487 // Since cime(3) returns a 26 character string of the form:
1488 // "Sun Sep 16 01:03:52 1973\n\0"
1489 // just print 24 characters.
1490 time_t t = Seconds;
1491 outs() << format("%.24s ", ctime(&t));
1492 }
1493 } else {
1494 outs() << RawLastModified << " ";
1495 }
1496
1497 if (verbose) {
1498 ErrorOr<StringRef> NameOrErr = C.getName();
1499 if (NameOrErr.getError()) {
1500 StringRef RawName = C.getRawName();
1501 outs() << RawName << "\n";
1502 } else {
1503 StringRef Name = NameOrErr.get();
1504 outs() << Name << "\n";
1505 }
1506 } else {
1507 StringRef RawName = C.getRawName();
1508 outs() << RawName << "\n";
1509 }
1510}
1511
1512static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001513 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1514 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001515 if (std::error_code EC = I->getError())
1516 report_fatal_error(EC.message());
1517 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001518 printArchiveChild(C, verbose, print_offset);
1519 }
1520}
1521
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001522// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1523// -arch flags selecting just those slices as specified by them and also parses
1524// archive files. Then for each individual Mach-O file ProcessMachO() is
1525// called to process the file based on the command line options.
1526void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001527 // Check for -arch all and verifiy the -arch flags are valid.
1528 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1529 if (ArchFlags[i] == "all") {
1530 ArchAll = true;
1531 } else {
1532 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1533 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1534 "'for the -arch option\n";
1535 return;
1536 }
1537 }
1538 }
1539
1540 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001541 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1542 if (!BinaryOrErr)
1543 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001544 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001545
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001546 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1547 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001548 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001549 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001550 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1551 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001552 if (std::error_code EC = I->getError())
1553 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001554 auto &C = I->get();
1555 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001556 if (ChildOrErr.getError())
1557 continue;
1558 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1559 if (!checkMachOAndArchFlags(O, Filename))
1560 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001561 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001562 }
1563 }
1564 return;
1565 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001566 if (UniversalHeaders) {
1567 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001568 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001569 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001570 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1571 // If we have a list of architecture flags specified dump only those.
1572 if (!ArchAll && ArchFlags.size() != 0) {
1573 // Look for a slice in the universal binary that matches each ArchFlag.
1574 bool ArchFound;
1575 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1576 ArchFound = false;
1577 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1578 E = UB->end_objects();
1579 I != E; ++I) {
1580 if (ArchFlags[i] == I->getArchTypeName()) {
1581 ArchFound = true;
1582 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1583 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001584 std::string ArchitectureName = "";
1585 if (ArchFlags.size() > 1)
1586 ArchitectureName = I->getArchTypeName();
1587 if (ObjOrErr) {
1588 ObjectFile &O = *ObjOrErr.get();
1589 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001590 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001591 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1592 I->getAsArchive()) {
1593 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001594 outs() << "Archive : " << Filename;
1595 if (!ArchitectureName.empty())
1596 outs() << " (architecture " << ArchitectureName << ")";
1597 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001598 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001599 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001600 for (Archive::child_iterator AI = A->child_begin(),
1601 AE = A->child_end();
1602 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001603 if (std::error_code EC = AI->getError())
1604 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001605 auto &C = AI->get();
1606 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001607 if (ChildOrErr.getError())
1608 continue;
1609 if (MachOObjectFile *O =
1610 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001611 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 }
1613 }
1614 }
1615 }
1616 if (!ArchFound) {
1617 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1618 << "architecture: " + ArchFlags[i] + "\n";
1619 return;
1620 }
1621 }
1622 return;
1623 }
1624 // No architecture flags were specified so if this contains a slice that
1625 // matches the host architecture dump only that.
1626 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001627 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1628 E = UB->end_objects();
1629 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001630 if (MachOObjectFile::getHostArch().getArchName() ==
1631 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001632 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 std::string ArchiveName;
1634 ArchiveName.clear();
1635 if (ObjOrErr) {
1636 ObjectFile &O = *ObjOrErr.get();
1637 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001638 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001639 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1640 I->getAsArchive()) {
1641 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001643 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001644 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001645 for (Archive::child_iterator AI = A->child_begin(),
1646 AE = A->child_end();
1647 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001648 if (std::error_code EC = AI->getError())
1649 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001650 auto &C = AI->get();
1651 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001652 if (ChildOrErr.getError())
1653 continue;
1654 if (MachOObjectFile *O =
1655 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001656 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001657 }
1658 }
1659 return;
1660 }
1661 }
1662 }
1663 // Either all architectures have been specified or none have been specified
1664 // and this does not contain the host architecture so dump all the slices.
1665 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1666 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1667 E = UB->end_objects();
1668 I != E; ++I) {
1669 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001670 std::string ArchitectureName = "";
1671 if (moreThanOneArch)
1672 ArchitectureName = I->getArchTypeName();
1673 if (ObjOrErr) {
1674 ObjectFile &Obj = *ObjOrErr.get();
1675 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001676 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001677 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1678 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001679 outs() << "Archive : " << Filename;
1680 if (!ArchitectureName.empty())
1681 outs() << " (architecture " << ArchitectureName << ")";
1682 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001683 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001684 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001685 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1686 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001687 if (std::error_code EC = AI->getError())
1688 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001689 auto &C = AI->get();
1690 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001691 if (ChildOrErr.getError())
1692 continue;
1693 if (MachOObjectFile *O =
1694 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1695 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001696 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1697 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001698 }
1699 }
1700 }
1701 }
1702 return;
1703 }
1704 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1705 if (!checkMachOAndArchFlags(O, Filename))
1706 return;
1707 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001708 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001709 } else
1710 errs() << "llvm-objdump: '" << Filename << "': "
1711 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001712 return;
1713 }
1714 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001715}
1716
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001717typedef std::pair<uint64_t, const char *> BindInfoEntry;
1718typedef std::vector<BindInfoEntry> BindTable;
1719typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001720
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001721// The block of info used by the Symbolizer call backs.
1722struct DisassembleInfo {
1723 bool verbose;
1724 MachOObjectFile *O;
1725 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001726 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001727 std::vector<SectionRef> *Sections;
1728 const char *class_name;
1729 const char *selector_name;
1730 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001731 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001732 uint64_t adrp_addr;
1733 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001734 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001735 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001736};
1737
1738// SymbolizerGetOpInfo() is the operand information call back function.
1739// This is called to get the symbolic information for operand(s) of an
1740// instruction when it is being done. This routine does this from
1741// the relocation information, symbol table, etc. That block of information
1742// is a pointer to the struct DisassembleInfo that was passed when the
1743// disassembler context was created and passed to back to here when
1744// called back by the disassembler for instruction operands that could have
1745// relocation information. The address of the instruction containing operand is
1746// at the Pc parameter. The immediate value the operand has is passed in
1747// op_info->Value and is at Offset past the start of the instruction and has a
1748// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1749// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1750// names and addends of the symbolic expression to add for the operand. The
1751// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1752// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001753static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1754 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001755 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1756 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001757 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001758
1759 // Make sure all fields returned are zero if we don't set them.
1760 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1761 op_info->Value = value;
1762
1763 // If the TagType is not the value 1 which it code knows about or if no
1764 // verbose symbolic information is wanted then just return 0, indicating no
1765 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001766 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001767 return 0;
1768
1769 unsigned int Arch = info->O->getArch();
1770 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001771 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1772 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001773 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1774 // TODO:
1775 // Search the external relocation entries of a fully linked image
1776 // (if any) for an entry that matches this segment offset.
1777 // uint32_t seg_offset = (Pc + Offset);
1778 return 0;
1779 }
1780 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1781 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001782 uint32_t sect_addr = info->S.getAddress();
1783 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1784 bool reloc_found = false;
1785 DataRefImpl Rel;
1786 MachO::any_relocation_info RE;
1787 bool isExtern = false;
1788 SymbolRef Symbol;
1789 bool r_scattered = false;
1790 uint32_t r_value, pair_r_value, r_type;
1791 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001792 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001793 if (RelocOffset == sect_offset) {
1794 Rel = Reloc.getRawDataRefImpl();
1795 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001796 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001797 r_scattered = info->O->isRelocationScattered(RE);
1798 if (r_scattered) {
1799 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001800 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1801 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1802 DataRefImpl RelNext = Rel;
1803 info->O->moveRelocationNext(RelNext);
1804 MachO::any_relocation_info RENext;
1805 RENext = info->O->getRelocation(RelNext);
1806 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001807 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001808 else
1809 return 0;
1810 }
1811 } else {
1812 isExtern = info->O->getPlainRelocationExternal(RE);
1813 if (isExtern) {
1814 symbol_iterator RelocSym = Reloc.getSymbol();
1815 Symbol = *RelocSym;
1816 }
1817 }
1818 reloc_found = true;
1819 break;
1820 }
1821 }
1822 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001823 Expected<StringRef> SymName = Symbol.getName();
1824 if (!SymName) {
1825 std::string Buf;
1826 raw_string_ostream OS(Buf);
1827 logAllUnhandledErrors(SymName.takeError(), OS, "");
1828 OS.flush();
1829 report_fatal_error(Buf);
1830 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001831 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001832 op_info->AddSymbol.Present = 1;
1833 op_info->AddSymbol.Name = name;
1834 // For i386 extern relocation entries the value in the instruction is
1835 // the offset from the symbol, and value is already set in op_info->Value.
1836 return 1;
1837 }
1838 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1839 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001840 const char *add = GuessSymbolName(r_value, info->AddrMap);
1841 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001842 uint32_t offset = value - (r_value - pair_r_value);
1843 op_info->AddSymbol.Present = 1;
1844 if (add != nullptr)
1845 op_info->AddSymbol.Name = add;
1846 else
1847 op_info->AddSymbol.Value = r_value;
1848 op_info->SubtractSymbol.Present = 1;
1849 if (sub != nullptr)
1850 op_info->SubtractSymbol.Name = sub;
1851 else
1852 op_info->SubtractSymbol.Value = pair_r_value;
1853 op_info->Value = offset;
1854 return 1;
1855 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001856 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001857 }
1858 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001859 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1860 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001861 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1862 // TODO:
1863 // Search the external relocation entries of a fully linked image
1864 // (if any) for an entry that matches this segment offset.
1865 // uint64_t seg_offset = (Pc + Offset);
1866 return 0;
1867 }
1868 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1869 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001870 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001871 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1872 bool reloc_found = false;
1873 DataRefImpl Rel;
1874 MachO::any_relocation_info RE;
1875 bool isExtern = false;
1876 SymbolRef Symbol;
1877 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001878 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001879 if (RelocOffset == sect_offset) {
1880 Rel = Reloc.getRawDataRefImpl();
1881 RE = info->O->getRelocation(Rel);
1882 // NOTE: Scattered relocations don't exist on x86_64.
1883 isExtern = info->O->getPlainRelocationExternal(RE);
1884 if (isExtern) {
1885 symbol_iterator RelocSym = Reloc.getSymbol();
1886 Symbol = *RelocSym;
1887 }
1888 reloc_found = true;
1889 break;
1890 }
1891 }
1892 if (reloc_found && isExtern) {
1893 // The Value passed in will be adjusted by the Pc if the instruction
1894 // adds the Pc. But for x86_64 external relocation entries the Value
1895 // is the offset from the external symbol.
1896 if (info->O->getAnyRelocationPCRel(RE))
1897 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001898 Expected<StringRef> SymName = Symbol.getName();
1899 if (!SymName) {
1900 std::string Buf;
1901 raw_string_ostream OS(Buf);
1902 logAllUnhandledErrors(SymName.takeError(), OS, "");
1903 OS.flush();
1904 report_fatal_error(Buf);
1905 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001906 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001907 unsigned Type = info->O->getAnyRelocationType(RE);
1908 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1909 DataRefImpl RelNext = Rel;
1910 info->O->moveRelocationNext(RelNext);
1911 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1912 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1913 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1914 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1915 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1916 op_info->SubtractSymbol.Present = 1;
1917 op_info->SubtractSymbol.Name = name;
1918 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1919 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001920 Expected<StringRef> SymNameNext = Symbol.getName();
1921 if (!SymNameNext) {
1922 std::string Buf;
1923 raw_string_ostream OS(Buf);
1924 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1925 OS.flush();
1926 report_fatal_error(Buf);
1927 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001928 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001929 }
1930 }
1931 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1932 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1933 op_info->AddSymbol.Present = 1;
1934 op_info->AddSymbol.Name = name;
1935 return 1;
1936 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001937 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001938 }
1939 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001940 if (Offset != 0 || (Size != 4 && Size != 2))
1941 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001942 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1943 // TODO:
1944 // Search the external relocation entries of a fully linked image
1945 // (if any) for an entry that matches this segment offset.
1946 // uint32_t seg_offset = (Pc + Offset);
1947 return 0;
1948 }
1949 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1950 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001951 uint32_t sect_addr = info->S.getAddress();
1952 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001953 DataRefImpl Rel;
1954 MachO::any_relocation_info RE;
1955 bool isExtern = false;
1956 SymbolRef Symbol;
1957 bool r_scattered = false;
1958 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00001959 auto Reloc =
1960 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1961 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001962 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00001963 return RelocOffset == sect_offset;
1964 });
1965
1966 if (Reloc == info->S.relocations().end())
1967 return 0;
1968
1969 Rel = Reloc->getRawDataRefImpl();
1970 RE = info->O->getRelocation(Rel);
1971 r_length = info->O->getAnyRelocationLength(RE);
1972 r_scattered = info->O->isRelocationScattered(RE);
1973 if (r_scattered) {
1974 r_value = info->O->getScatteredRelocationValue(RE);
1975 r_type = info->O->getScatteredRelocationType(RE);
1976 } else {
1977 r_type = info->O->getAnyRelocationType(RE);
1978 isExtern = info->O->getPlainRelocationExternal(RE);
1979 if (isExtern) {
1980 symbol_iterator RelocSym = Reloc->getSymbol();
1981 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001982 }
1983 }
David Blaikie33dd45d02015-03-23 18:39:02 +00001984 if (r_type == MachO::ARM_RELOC_HALF ||
1985 r_type == MachO::ARM_RELOC_SECTDIFF ||
1986 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1987 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1988 DataRefImpl RelNext = Rel;
1989 info->O->moveRelocationNext(RelNext);
1990 MachO::any_relocation_info RENext;
1991 RENext = info->O->getRelocation(RelNext);
1992 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1993 if (info->O->isRelocationScattered(RENext))
1994 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1995 }
1996
1997 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001998 Expected<StringRef> SymName = Symbol.getName();
1999 if (!SymName) {
2000 std::string Buf;
2001 raw_string_ostream OS(Buf);
2002 logAllUnhandledErrors(SymName.takeError(), OS, "");
2003 OS.flush();
2004 report_fatal_error(Buf);
2005 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002006 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002007 op_info->AddSymbol.Present = 1;
2008 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002009 switch (r_type) {
2010 case MachO::ARM_RELOC_HALF:
2011 if ((r_length & 0x1) == 1) {
2012 op_info->Value = value << 16 | other_half;
2013 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2014 } else {
2015 op_info->Value = other_half << 16 | value;
2016 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002017 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002018 break;
2019 default:
2020 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002021 }
2022 return 1;
2023 }
2024 // If we have a branch that is not an external relocation entry then
2025 // return 0 so the code in tryAddingSymbolicOperand() can use the
2026 // SymbolLookUp call back with the branch target address to look up the
2027 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002028 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2029 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002030 return 0;
2031
2032 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002033 if (r_type == MachO::ARM_RELOC_HALF ||
2034 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2035 if ((r_length & 0x1) == 1)
2036 value = value << 16 | other_half;
2037 else
2038 value = other_half << 16 | value;
2039 }
2040 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2041 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2042 offset = value - r_value;
2043 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002044 }
2045
David Blaikie33dd45d02015-03-23 18:39:02 +00002046 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002047 if ((r_length & 0x1) == 1)
2048 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2049 else
2050 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002051 const char *add = GuessSymbolName(r_value, info->AddrMap);
2052 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002053 int32_t offset = value - (r_value - pair_r_value);
2054 op_info->AddSymbol.Present = 1;
2055 if (add != nullptr)
2056 op_info->AddSymbol.Name = add;
2057 else
2058 op_info->AddSymbol.Value = r_value;
2059 op_info->SubtractSymbol.Present = 1;
2060 if (sub != nullptr)
2061 op_info->SubtractSymbol.Name = sub;
2062 else
2063 op_info->SubtractSymbol.Value = pair_r_value;
2064 op_info->Value = offset;
2065 return 1;
2066 }
2067
Kevin Enderby930fdc72014-11-06 19:00:13 +00002068 op_info->AddSymbol.Present = 1;
2069 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002070 if (r_type == MachO::ARM_RELOC_HALF) {
2071 if ((r_length & 0x1) == 1)
2072 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2073 else
2074 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002075 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002076 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002077 if (add != nullptr) {
2078 op_info->AddSymbol.Name = add;
2079 return 1;
2080 }
2081 op_info->AddSymbol.Value = value;
2082 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002083 }
2084 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002085 if (Offset != 0 || Size != 4)
2086 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002087 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2088 // TODO:
2089 // Search the external relocation entries of a fully linked image
2090 // (if any) for an entry that matches this segment offset.
2091 // uint64_t seg_offset = (Pc + Offset);
2092 return 0;
2093 }
2094 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2095 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002096 uint64_t sect_addr = info->S.getAddress();
2097 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002098 auto Reloc =
2099 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2100 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002101 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002102 return RelocOffset == sect_offset;
2103 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002104
David Blaikie33dd45d02015-03-23 18:39:02 +00002105 if (Reloc == info->S.relocations().end())
2106 return 0;
2107
2108 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2109 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2110 uint32_t r_type = info->O->getAnyRelocationType(RE);
2111 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2112 DataRefImpl RelNext = Rel;
2113 info->O->moveRelocationNext(RelNext);
2114 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2115 if (value == 0) {
2116 value = info->O->getPlainRelocationSymbolNum(RENext);
2117 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002118 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002119 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002120 // NOTE: Scattered relocations don't exist on arm64.
2121 if (!info->O->getPlainRelocationExternal(RE))
2122 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002123 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2124 if (!SymName) {
2125 std::string Buf;
2126 raw_string_ostream OS(Buf);
2127 logAllUnhandledErrors(SymName.takeError(), OS, "");
2128 OS.flush();
2129 report_fatal_error(Buf);
2130 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002131 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002132 op_info->AddSymbol.Present = 1;
2133 op_info->AddSymbol.Name = name;
2134
2135 switch (r_type) {
2136 case MachO::ARM64_RELOC_PAGE21:
2137 /* @page */
2138 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2139 break;
2140 case MachO::ARM64_RELOC_PAGEOFF12:
2141 /* @pageoff */
2142 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2143 break;
2144 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2145 /* @gotpage */
2146 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2147 break;
2148 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2149 /* @gotpageoff */
2150 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2151 break;
2152 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2153 /* @tvlppage is not implemented in llvm-mc */
2154 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2155 break;
2156 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2157 /* @tvlppageoff is not implemented in llvm-mc */
2158 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2159 break;
2160 default:
2161 case MachO::ARM64_RELOC_BRANCH26:
2162 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2163 break;
2164 }
2165 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002166 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002167 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002168}
2169
Kevin Enderbybf246f52014-09-24 23:08:22 +00002170// GuessCstringPointer is passed the address of what might be a pointer to a
2171// literal string in a cstring section. If that address is in a cstring section
2172// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002173static const char *GuessCstringPointer(uint64_t ReferenceValue,
2174 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002175 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002176 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2177 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2178 for (unsigned J = 0; J < Seg.nsects; ++J) {
2179 MachO::section_64 Sec = info->O->getSection64(Load, J);
2180 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2181 if (section_type == MachO::S_CSTRING_LITERALS &&
2182 ReferenceValue >= Sec.addr &&
2183 ReferenceValue < Sec.addr + Sec.size) {
2184 uint64_t sect_offset = ReferenceValue - Sec.addr;
2185 uint64_t object_offset = Sec.offset + sect_offset;
2186 StringRef MachOContents = info->O->getData();
2187 uint64_t object_size = MachOContents.size();
2188 const char *object_addr = (const char *)MachOContents.data();
2189 if (object_offset < object_size) {
2190 const char *name = object_addr + object_offset;
2191 return name;
2192 } else {
2193 return nullptr;
2194 }
2195 }
2196 }
2197 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2198 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2199 for (unsigned J = 0; J < Seg.nsects; ++J) {
2200 MachO::section Sec = info->O->getSection(Load, J);
2201 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2202 if (section_type == MachO::S_CSTRING_LITERALS &&
2203 ReferenceValue >= Sec.addr &&
2204 ReferenceValue < Sec.addr + Sec.size) {
2205 uint64_t sect_offset = ReferenceValue - Sec.addr;
2206 uint64_t object_offset = Sec.offset + sect_offset;
2207 StringRef MachOContents = info->O->getData();
2208 uint64_t object_size = MachOContents.size();
2209 const char *object_addr = (const char *)MachOContents.data();
2210 if (object_offset < object_size) {
2211 const char *name = object_addr + object_offset;
2212 return name;
2213 } else {
2214 return nullptr;
2215 }
2216 }
2217 }
2218 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002219 }
2220 return nullptr;
2221}
2222
Kevin Enderby85974882014-09-26 22:20:44 +00002223// GuessIndirectSymbol returns the name of the indirect symbol for the
2224// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2225// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2226// symbol name being referenced by the stub or pointer.
2227static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2228 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002229 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2230 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002231 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002232 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2233 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2234 for (unsigned J = 0; J < Seg.nsects; ++J) {
2235 MachO::section_64 Sec = info->O->getSection64(Load, J);
2236 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2237 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2238 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2239 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2240 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2241 section_type == MachO::S_SYMBOL_STUBS) &&
2242 ReferenceValue >= Sec.addr &&
2243 ReferenceValue < Sec.addr + Sec.size) {
2244 uint32_t stride;
2245 if (section_type == MachO::S_SYMBOL_STUBS)
2246 stride = Sec.reserved2;
2247 else
2248 stride = 8;
2249 if (stride == 0)
2250 return nullptr;
2251 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2252 if (index < Dysymtab.nindirectsyms) {
2253 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002254 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002255 if (indirect_symbol < Symtab.nsyms) {
2256 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2257 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002258 Expected<StringRef> SymName = Symbol.getName();
2259 if (!SymName) {
2260 std::string Buf;
2261 raw_string_ostream OS(Buf);
2262 logAllUnhandledErrors(SymName.takeError(), OS, "");
2263 OS.flush();
2264 report_fatal_error(Buf);
2265 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002266 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002267 return name;
2268 }
2269 }
2270 }
2271 }
2272 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2273 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2274 for (unsigned J = 0; J < Seg.nsects; ++J) {
2275 MachO::section Sec = info->O->getSection(Load, J);
2276 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2277 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2278 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2279 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2280 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2281 section_type == MachO::S_SYMBOL_STUBS) &&
2282 ReferenceValue >= Sec.addr &&
2283 ReferenceValue < Sec.addr + Sec.size) {
2284 uint32_t stride;
2285 if (section_type == MachO::S_SYMBOL_STUBS)
2286 stride = Sec.reserved2;
2287 else
2288 stride = 4;
2289 if (stride == 0)
2290 return nullptr;
2291 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2292 if (index < Dysymtab.nindirectsyms) {
2293 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002294 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002295 if (indirect_symbol < Symtab.nsyms) {
2296 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2297 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002298 Expected<StringRef> SymName = Symbol.getName();
2299 if (!SymName) {
2300 std::string Buf;
2301 raw_string_ostream OS(Buf);
2302 logAllUnhandledErrors(SymName.takeError(), OS, "");
2303 OS.flush();
2304 report_fatal_error(Buf);
2305 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002306 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002307 return name;
2308 }
2309 }
2310 }
2311 }
2312 }
Kevin Enderby85974882014-09-26 22:20:44 +00002313 }
2314 return nullptr;
2315}
2316
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002317// method_reference() is called passing it the ReferenceName that might be
2318// a reference it to an Objective-C method call. If so then it allocates and
2319// assembles a method call string with the values last seen and saved in
2320// the DisassembleInfo's class_name and selector_name fields. This is saved
2321// into the method field of the info and any previous string is free'ed.
2322// Then the class_name field in the info is set to nullptr. The method call
2323// string is set into ReferenceName and ReferenceType is set to
2324// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2325// then both ReferenceType and ReferenceName are left unchanged.
2326static void method_reference(struct DisassembleInfo *info,
2327 uint64_t *ReferenceType,
2328 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002329 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002330 if (*ReferenceName != nullptr) {
2331 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002332 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002333 if (info->method != nullptr)
2334 free(info->method);
2335 if (info->class_name != nullptr) {
2336 info->method = (char *)malloc(5 + strlen(info->class_name) +
2337 strlen(info->selector_name));
2338 if (info->method != nullptr) {
2339 strcpy(info->method, "+[");
2340 strcat(info->method, info->class_name);
2341 strcat(info->method, " ");
2342 strcat(info->method, info->selector_name);
2343 strcat(info->method, "]");
2344 *ReferenceName = info->method;
2345 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2346 }
2347 } else {
2348 info->method = (char *)malloc(9 + strlen(info->selector_name));
2349 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002350 if (Arch == Triple::x86_64)
2351 strcpy(info->method, "-[%rdi ");
2352 else if (Arch == Triple::aarch64)
2353 strcpy(info->method, "-[x0 ");
2354 else
2355 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002356 strcat(info->method, info->selector_name);
2357 strcat(info->method, "]");
2358 *ReferenceName = info->method;
2359 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2360 }
2361 }
2362 info->class_name = nullptr;
2363 }
2364 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002365 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002366 if (info->method != nullptr)
2367 free(info->method);
2368 info->method = (char *)malloc(17 + strlen(info->selector_name));
2369 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002370 if (Arch == Triple::x86_64)
2371 strcpy(info->method, "-[[%rdi super] ");
2372 else if (Arch == Triple::aarch64)
2373 strcpy(info->method, "-[[x0 super] ");
2374 else
2375 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002376 strcat(info->method, info->selector_name);
2377 strcat(info->method, "]");
2378 *ReferenceName = info->method;
2379 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2380 }
2381 info->class_name = nullptr;
2382 }
2383 }
2384 }
2385}
2386
2387// GuessPointerPointer() is passed the address of what might be a pointer to
2388// a reference to an Objective-C class, selector, message ref or cfstring.
2389// If so the value of the pointer is returned and one of the booleans are set
2390// to true. If not zero is returned and all the booleans are set to false.
2391static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2392 struct DisassembleInfo *info,
2393 bool &classref, bool &selref, bool &msgref,
2394 bool &cfstring) {
2395 classref = false;
2396 selref = false;
2397 msgref = false;
2398 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002399 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002400 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2401 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2402 for (unsigned J = 0; J < Seg.nsects; ++J) {
2403 MachO::section_64 Sec = info->O->getSection64(Load, J);
2404 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2405 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2406 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2407 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2408 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2409 ReferenceValue >= Sec.addr &&
2410 ReferenceValue < Sec.addr + Sec.size) {
2411 uint64_t sect_offset = ReferenceValue - Sec.addr;
2412 uint64_t object_offset = Sec.offset + sect_offset;
2413 StringRef MachOContents = info->O->getData();
2414 uint64_t object_size = MachOContents.size();
2415 const char *object_addr = (const char *)MachOContents.data();
2416 if (object_offset < object_size) {
2417 uint64_t pointer_value;
2418 memcpy(&pointer_value, object_addr + object_offset,
2419 sizeof(uint64_t));
2420 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2421 sys::swapByteOrder(pointer_value);
2422 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2423 selref = true;
2424 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2425 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2426 classref = true;
2427 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2428 ReferenceValue + 8 < Sec.addr + Sec.size) {
2429 msgref = true;
2430 memcpy(&pointer_value, object_addr + object_offset + 8,
2431 sizeof(uint64_t));
2432 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2433 sys::swapByteOrder(pointer_value);
2434 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2435 cfstring = true;
2436 return pointer_value;
2437 } else {
2438 return 0;
2439 }
2440 }
2441 }
2442 }
2443 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002444 }
2445 return 0;
2446}
2447
2448// get_pointer_64 returns a pointer to the bytes in the object file at the
2449// Address from a section in the Mach-O file. And indirectly returns the
2450// offset into the section, number of bytes left in the section past the offset
2451// and which section is was being referenced. If the Address is not in a
2452// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002453static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2454 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002455 DisassembleInfo *info,
2456 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002457 offset = 0;
2458 left = 0;
2459 S = SectionRef();
2460 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2461 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2462 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002463 if (SectSize == 0)
2464 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002465 if (objc_only) {
2466 StringRef SectName;
2467 ((*(info->Sections))[SectIdx]).getName(SectName);
2468 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2469 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2470 if (SegName != "__OBJC" && SectName != "__cstring")
2471 continue;
2472 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002473 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2474 S = (*(info->Sections))[SectIdx];
2475 offset = Address - SectAddress;
2476 left = SectSize - offset;
2477 StringRef SectContents;
2478 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2479 return SectContents.data() + offset;
2480 }
2481 }
2482 return nullptr;
2483}
2484
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002485static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2486 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002487 DisassembleInfo *info,
2488 bool objc_only = false) {
2489 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002490}
2491
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002492// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2493// the symbol indirectly through n_value. Based on the relocation information
2494// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002495// If no relocation information is found and a non-zero ReferenceValue for the
2496// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002497static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2498 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002499 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002500 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002501 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002502 return nullptr;
2503
2504 // See if there is an external relocation entry at the sect_offset.
2505 bool reloc_found = false;
2506 DataRefImpl Rel;
2507 MachO::any_relocation_info RE;
2508 bool isExtern = false;
2509 SymbolRef Symbol;
2510 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002511 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002512 if (RelocOffset == sect_offset) {
2513 Rel = Reloc.getRawDataRefImpl();
2514 RE = info->O->getRelocation(Rel);
2515 if (info->O->isRelocationScattered(RE))
2516 continue;
2517 isExtern = info->O->getPlainRelocationExternal(RE);
2518 if (isExtern) {
2519 symbol_iterator RelocSym = Reloc.getSymbol();
2520 Symbol = *RelocSym;
2521 }
2522 reloc_found = true;
2523 break;
2524 }
2525 }
2526 // If there is an external relocation entry for a symbol in this section
2527 // at this section_offset then use that symbol's value for the n_value
2528 // and return its name.
2529 const char *SymbolName = nullptr;
2530 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002531 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002532 Expected<StringRef> NameOrError = Symbol.getName();
2533 if (!NameOrError) {
2534 std::string Buf;
2535 raw_string_ostream OS(Buf);
2536 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2537 OS.flush();
2538 report_fatal_error(Buf);
2539 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002540 StringRef Name = *NameOrError;
2541 if (!Name.empty()) {
2542 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002543 return SymbolName;
2544 }
2545 }
2546
2547 // TODO: For fully linked images, look through the external relocation
2548 // entries off the dynamic symtab command. For these the r_offset is from the
2549 // start of the first writeable segment in the Mach-O file. So the offset
2550 // to this section from that segment is passed to this routine by the caller,
2551 // as the database_offset. Which is the difference of the section's starting
2552 // address and the first writable segment.
2553 //
2554 // NOTE: need add passing the database_offset to this routine.
2555
Kevin Enderby0fc11822015-04-01 20:57:01 +00002556 // We did not find an external relocation entry so look up the ReferenceValue
2557 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002558 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002559
2560 return SymbolName;
2561}
2562
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002563static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2564 DisassembleInfo *info,
2565 uint32_t ReferenceValue) {
2566 uint64_t n_value64;
2567 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2568}
2569
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002570// These are structs in the Objective-C meta data and read to produce the
2571// comments for disassembly. While these are part of the ABI they are no
2572// public defintions. So the are here not in include/llvm/Support/MachO.h .
2573
2574// The cfstring object in a 64-bit Mach-O file.
2575struct cfstring64_t {
2576 uint64_t isa; // class64_t * (64-bit pointer)
2577 uint64_t flags; // flag bits
2578 uint64_t characters; // char * (64-bit pointer)
2579 uint64_t length; // number of non-NULL characters in above
2580};
2581
2582// The class object in a 64-bit Mach-O file.
2583struct class64_t {
2584 uint64_t isa; // class64_t * (64-bit pointer)
2585 uint64_t superclass; // class64_t * (64-bit pointer)
2586 uint64_t cache; // Cache (64-bit pointer)
2587 uint64_t vtable; // IMP * (64-bit pointer)
2588 uint64_t data; // class_ro64_t * (64-bit pointer)
2589};
2590
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002591struct class32_t {
2592 uint32_t isa; /* class32_t * (32-bit pointer) */
2593 uint32_t superclass; /* class32_t * (32-bit pointer) */
2594 uint32_t cache; /* Cache (32-bit pointer) */
2595 uint32_t vtable; /* IMP * (32-bit pointer) */
2596 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2597};
2598
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002599struct class_ro64_t {
2600 uint32_t flags;
2601 uint32_t instanceStart;
2602 uint32_t instanceSize;
2603 uint32_t reserved;
2604 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2605 uint64_t name; // const char * (64-bit pointer)
2606 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2607 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2608 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2609 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2610 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2611};
2612
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002613struct class_ro32_t {
2614 uint32_t flags;
2615 uint32_t instanceStart;
2616 uint32_t instanceSize;
2617 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2618 uint32_t name; /* const char * (32-bit pointer) */
2619 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2620 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2621 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2622 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2623 uint32_t baseProperties; /* const struct objc_property_list *
2624 (32-bit pointer) */
2625};
2626
2627/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002628#define RO_META (1 << 0)
2629#define RO_ROOT (1 << 1)
2630#define RO_HAS_CXX_STRUCTORS (1 << 2)
2631
2632struct method_list64_t {
2633 uint32_t entsize;
2634 uint32_t count;
2635 /* struct method64_t first; These structures follow inline */
2636};
2637
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002638struct method_list32_t {
2639 uint32_t entsize;
2640 uint32_t count;
2641 /* struct method32_t first; These structures follow inline */
2642};
2643
Kevin Enderby0fc11822015-04-01 20:57:01 +00002644struct method64_t {
2645 uint64_t name; /* SEL (64-bit pointer) */
2646 uint64_t types; /* const char * (64-bit pointer) */
2647 uint64_t imp; /* IMP (64-bit pointer) */
2648};
2649
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002650struct method32_t {
2651 uint32_t name; /* SEL (32-bit pointer) */
2652 uint32_t types; /* const char * (32-bit pointer) */
2653 uint32_t imp; /* IMP (32-bit pointer) */
2654};
2655
Kevin Enderby0fc11822015-04-01 20:57:01 +00002656struct protocol_list64_t {
2657 uint64_t count; /* uintptr_t (a 64-bit value) */
2658 /* struct protocol64_t * list[0]; These pointers follow inline */
2659};
2660
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002661struct protocol_list32_t {
2662 uint32_t count; /* uintptr_t (a 32-bit value) */
2663 /* struct protocol32_t * list[0]; These pointers follow inline */
2664};
2665
Kevin Enderby0fc11822015-04-01 20:57:01 +00002666struct protocol64_t {
2667 uint64_t isa; /* id * (64-bit pointer) */
2668 uint64_t name; /* const char * (64-bit pointer) */
2669 uint64_t protocols; /* struct protocol_list64_t *
2670 (64-bit pointer) */
2671 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2672 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2673 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2674 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2675 uint64_t instanceProperties; /* struct objc_property_list *
2676 (64-bit pointer) */
2677};
2678
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002679struct protocol32_t {
2680 uint32_t isa; /* id * (32-bit pointer) */
2681 uint32_t name; /* const char * (32-bit pointer) */
2682 uint32_t protocols; /* struct protocol_list_t *
2683 (32-bit pointer) */
2684 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2685 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2686 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2687 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2688 uint32_t instanceProperties; /* struct objc_property_list *
2689 (32-bit pointer) */
2690};
2691
Kevin Enderby0fc11822015-04-01 20:57:01 +00002692struct ivar_list64_t {
2693 uint32_t entsize;
2694 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002695 /* struct ivar64_t first; These structures follow inline */
2696};
2697
2698struct ivar_list32_t {
2699 uint32_t entsize;
2700 uint32_t count;
2701 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002702};
2703
2704struct ivar64_t {
2705 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2706 uint64_t name; /* const char * (64-bit pointer) */
2707 uint64_t type; /* const char * (64-bit pointer) */
2708 uint32_t alignment;
2709 uint32_t size;
2710};
2711
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002712struct ivar32_t {
2713 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2714 uint32_t name; /* const char * (32-bit pointer) */
2715 uint32_t type; /* const char * (32-bit pointer) */
2716 uint32_t alignment;
2717 uint32_t size;
2718};
2719
Kevin Enderby0fc11822015-04-01 20:57:01 +00002720struct objc_property_list64 {
2721 uint32_t entsize;
2722 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002723 /* struct objc_property64 first; These structures follow inline */
2724};
2725
2726struct objc_property_list32 {
2727 uint32_t entsize;
2728 uint32_t count;
2729 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002730};
2731
2732struct objc_property64 {
2733 uint64_t name; /* const char * (64-bit pointer) */
2734 uint64_t attributes; /* const char * (64-bit pointer) */
2735};
2736
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002737struct objc_property32 {
2738 uint32_t name; /* const char * (32-bit pointer) */
2739 uint32_t attributes; /* const char * (32-bit pointer) */
2740};
2741
Kevin Enderby0fc11822015-04-01 20:57:01 +00002742struct category64_t {
2743 uint64_t name; /* const char * (64-bit pointer) */
2744 uint64_t cls; /* struct class_t * (64-bit pointer) */
2745 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2746 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2747 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2748 uint64_t instanceProperties; /* struct objc_property_list *
2749 (64-bit pointer) */
2750};
2751
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002752struct category32_t {
2753 uint32_t name; /* const char * (32-bit pointer) */
2754 uint32_t cls; /* struct class_t * (32-bit pointer) */
2755 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2756 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2757 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2758 uint32_t instanceProperties; /* struct objc_property_list *
2759 (32-bit pointer) */
2760};
2761
Kevin Enderby0fc11822015-04-01 20:57:01 +00002762struct objc_image_info64 {
2763 uint32_t version;
2764 uint32_t flags;
2765};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002766struct objc_image_info32 {
2767 uint32_t version;
2768 uint32_t flags;
2769};
Kevin Enderby846c0002015-04-16 17:19:59 +00002770struct imageInfo_t {
2771 uint32_t version;
2772 uint32_t flags;
2773};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002774/* masks for objc_image_info.flags */
2775#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2776#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2777
2778struct message_ref64 {
2779 uint64_t imp; /* IMP (64-bit pointer) */
2780 uint64_t sel; /* SEL (64-bit pointer) */
2781};
2782
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002783struct message_ref32 {
2784 uint32_t imp; /* IMP (32-bit pointer) */
2785 uint32_t sel; /* SEL (32-bit pointer) */
2786};
2787
Kevin Enderby846c0002015-04-16 17:19:59 +00002788// Objective-C 1 (32-bit only) meta data structs.
2789
2790struct objc_module_t {
2791 uint32_t version;
2792 uint32_t size;
2793 uint32_t name; /* char * (32-bit pointer) */
2794 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2795};
2796
2797struct objc_symtab_t {
2798 uint32_t sel_ref_cnt;
2799 uint32_t refs; /* SEL * (32-bit pointer) */
2800 uint16_t cls_def_cnt;
2801 uint16_t cat_def_cnt;
2802 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2803};
2804
2805struct objc_class_t {
2806 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2807 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2808 uint32_t name; /* const char * (32-bit pointer) */
2809 int32_t version;
2810 int32_t info;
2811 int32_t instance_size;
2812 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2813 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2814 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2815 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2816};
2817
2818#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2819// class is not a metaclass
2820#define CLS_CLASS 0x1
2821// class is a metaclass
2822#define CLS_META 0x2
2823
2824struct objc_category_t {
2825 uint32_t category_name; /* char * (32-bit pointer) */
2826 uint32_t class_name; /* char * (32-bit pointer) */
2827 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2828 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2829 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2830};
2831
2832struct objc_ivar_t {
2833 uint32_t ivar_name; /* char * (32-bit pointer) */
2834 uint32_t ivar_type; /* char * (32-bit pointer) */
2835 int32_t ivar_offset;
2836};
2837
2838struct objc_ivar_list_t {
2839 int32_t ivar_count;
2840 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2841};
2842
2843struct objc_method_list_t {
2844 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2845 int32_t method_count;
2846 // struct objc_method_t method_list[1]; /* variable length structure */
2847};
2848
2849struct objc_method_t {
2850 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2851 uint32_t method_types; /* char * (32-bit pointer) */
2852 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2853 (32-bit pointer) */
2854};
2855
2856struct objc_protocol_list_t {
2857 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2858 int32_t count;
2859 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2860 // (32-bit pointer) */
2861};
2862
2863struct objc_protocol_t {
2864 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2865 uint32_t protocol_name; /* char * (32-bit pointer) */
2866 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2867 uint32_t instance_methods; /* struct objc_method_description_list *
2868 (32-bit pointer) */
2869 uint32_t class_methods; /* struct objc_method_description_list *
2870 (32-bit pointer) */
2871};
2872
2873struct objc_method_description_list_t {
2874 int32_t count;
2875 // struct objc_method_description_t list[1];
2876};
2877
2878struct objc_method_description_t {
2879 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2880 uint32_t types; /* char * (32-bit pointer) */
2881};
2882
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002883inline void swapStruct(struct cfstring64_t &cfs) {
2884 sys::swapByteOrder(cfs.isa);
2885 sys::swapByteOrder(cfs.flags);
2886 sys::swapByteOrder(cfs.characters);
2887 sys::swapByteOrder(cfs.length);
2888}
2889
2890inline void swapStruct(struct class64_t &c) {
2891 sys::swapByteOrder(c.isa);
2892 sys::swapByteOrder(c.superclass);
2893 sys::swapByteOrder(c.cache);
2894 sys::swapByteOrder(c.vtable);
2895 sys::swapByteOrder(c.data);
2896}
2897
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002898inline void swapStruct(struct class32_t &c) {
2899 sys::swapByteOrder(c.isa);
2900 sys::swapByteOrder(c.superclass);
2901 sys::swapByteOrder(c.cache);
2902 sys::swapByteOrder(c.vtable);
2903 sys::swapByteOrder(c.data);
2904}
2905
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002906inline void swapStruct(struct class_ro64_t &cro) {
2907 sys::swapByteOrder(cro.flags);
2908 sys::swapByteOrder(cro.instanceStart);
2909 sys::swapByteOrder(cro.instanceSize);
2910 sys::swapByteOrder(cro.reserved);
2911 sys::swapByteOrder(cro.ivarLayout);
2912 sys::swapByteOrder(cro.name);
2913 sys::swapByteOrder(cro.baseMethods);
2914 sys::swapByteOrder(cro.baseProtocols);
2915 sys::swapByteOrder(cro.ivars);
2916 sys::swapByteOrder(cro.weakIvarLayout);
2917 sys::swapByteOrder(cro.baseProperties);
2918}
2919
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002920inline void swapStruct(struct class_ro32_t &cro) {
2921 sys::swapByteOrder(cro.flags);
2922 sys::swapByteOrder(cro.instanceStart);
2923 sys::swapByteOrder(cro.instanceSize);
2924 sys::swapByteOrder(cro.ivarLayout);
2925 sys::swapByteOrder(cro.name);
2926 sys::swapByteOrder(cro.baseMethods);
2927 sys::swapByteOrder(cro.baseProtocols);
2928 sys::swapByteOrder(cro.ivars);
2929 sys::swapByteOrder(cro.weakIvarLayout);
2930 sys::swapByteOrder(cro.baseProperties);
2931}
2932
Kevin Enderby0fc11822015-04-01 20:57:01 +00002933inline void swapStruct(struct method_list64_t &ml) {
2934 sys::swapByteOrder(ml.entsize);
2935 sys::swapByteOrder(ml.count);
2936}
2937
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002938inline void swapStruct(struct method_list32_t &ml) {
2939 sys::swapByteOrder(ml.entsize);
2940 sys::swapByteOrder(ml.count);
2941}
2942
Kevin Enderby0fc11822015-04-01 20:57:01 +00002943inline void swapStruct(struct method64_t &m) {
2944 sys::swapByteOrder(m.name);
2945 sys::swapByteOrder(m.types);
2946 sys::swapByteOrder(m.imp);
2947}
2948
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002949inline void swapStruct(struct method32_t &m) {
2950 sys::swapByteOrder(m.name);
2951 sys::swapByteOrder(m.types);
2952 sys::swapByteOrder(m.imp);
2953}
2954
Kevin Enderby0fc11822015-04-01 20:57:01 +00002955inline void swapStruct(struct protocol_list64_t &pl) {
2956 sys::swapByteOrder(pl.count);
2957}
2958
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002959inline void swapStruct(struct protocol_list32_t &pl) {
2960 sys::swapByteOrder(pl.count);
2961}
2962
Kevin Enderby0fc11822015-04-01 20:57:01 +00002963inline void swapStruct(struct protocol64_t &p) {
2964 sys::swapByteOrder(p.isa);
2965 sys::swapByteOrder(p.name);
2966 sys::swapByteOrder(p.protocols);
2967 sys::swapByteOrder(p.instanceMethods);
2968 sys::swapByteOrder(p.classMethods);
2969 sys::swapByteOrder(p.optionalInstanceMethods);
2970 sys::swapByteOrder(p.optionalClassMethods);
2971 sys::swapByteOrder(p.instanceProperties);
2972}
2973
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002974inline void swapStruct(struct protocol32_t &p) {
2975 sys::swapByteOrder(p.isa);
2976 sys::swapByteOrder(p.name);
2977 sys::swapByteOrder(p.protocols);
2978 sys::swapByteOrder(p.instanceMethods);
2979 sys::swapByteOrder(p.classMethods);
2980 sys::swapByteOrder(p.optionalInstanceMethods);
2981 sys::swapByteOrder(p.optionalClassMethods);
2982 sys::swapByteOrder(p.instanceProperties);
2983}
2984
Kevin Enderby0fc11822015-04-01 20:57:01 +00002985inline void swapStruct(struct ivar_list64_t &il) {
2986 sys::swapByteOrder(il.entsize);
2987 sys::swapByteOrder(il.count);
2988}
2989
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002990inline void swapStruct(struct ivar_list32_t &il) {
2991 sys::swapByteOrder(il.entsize);
2992 sys::swapByteOrder(il.count);
2993}
2994
Kevin Enderby0fc11822015-04-01 20:57:01 +00002995inline void swapStruct(struct ivar64_t &i) {
2996 sys::swapByteOrder(i.offset);
2997 sys::swapByteOrder(i.name);
2998 sys::swapByteOrder(i.type);
2999 sys::swapByteOrder(i.alignment);
3000 sys::swapByteOrder(i.size);
3001}
3002
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003003inline void swapStruct(struct ivar32_t &i) {
3004 sys::swapByteOrder(i.offset);
3005 sys::swapByteOrder(i.name);
3006 sys::swapByteOrder(i.type);
3007 sys::swapByteOrder(i.alignment);
3008 sys::swapByteOrder(i.size);
3009}
3010
Kevin Enderby0fc11822015-04-01 20:57:01 +00003011inline void swapStruct(struct objc_property_list64 &pl) {
3012 sys::swapByteOrder(pl.entsize);
3013 sys::swapByteOrder(pl.count);
3014}
3015
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003016inline void swapStruct(struct objc_property_list32 &pl) {
3017 sys::swapByteOrder(pl.entsize);
3018 sys::swapByteOrder(pl.count);
3019}
3020
Kevin Enderby0fc11822015-04-01 20:57:01 +00003021inline void swapStruct(struct objc_property64 &op) {
3022 sys::swapByteOrder(op.name);
3023 sys::swapByteOrder(op.attributes);
3024}
3025
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003026inline void swapStruct(struct objc_property32 &op) {
3027 sys::swapByteOrder(op.name);
3028 sys::swapByteOrder(op.attributes);
3029}
3030
Kevin Enderby0fc11822015-04-01 20:57:01 +00003031inline void swapStruct(struct category64_t &c) {
3032 sys::swapByteOrder(c.name);
3033 sys::swapByteOrder(c.cls);
3034 sys::swapByteOrder(c.instanceMethods);
3035 sys::swapByteOrder(c.classMethods);
3036 sys::swapByteOrder(c.protocols);
3037 sys::swapByteOrder(c.instanceProperties);
3038}
3039
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003040inline void swapStruct(struct category32_t &c) {
3041 sys::swapByteOrder(c.name);
3042 sys::swapByteOrder(c.cls);
3043 sys::swapByteOrder(c.instanceMethods);
3044 sys::swapByteOrder(c.classMethods);
3045 sys::swapByteOrder(c.protocols);
3046 sys::swapByteOrder(c.instanceProperties);
3047}
3048
Kevin Enderby0fc11822015-04-01 20:57:01 +00003049inline void swapStruct(struct objc_image_info64 &o) {
3050 sys::swapByteOrder(o.version);
3051 sys::swapByteOrder(o.flags);
3052}
3053
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003054inline void swapStruct(struct objc_image_info32 &o) {
3055 sys::swapByteOrder(o.version);
3056 sys::swapByteOrder(o.flags);
3057}
3058
Kevin Enderby846c0002015-04-16 17:19:59 +00003059inline void swapStruct(struct imageInfo_t &o) {
3060 sys::swapByteOrder(o.version);
3061 sys::swapByteOrder(o.flags);
3062}
3063
Kevin Enderby0fc11822015-04-01 20:57:01 +00003064inline void swapStruct(struct message_ref64 &mr) {
3065 sys::swapByteOrder(mr.imp);
3066 sys::swapByteOrder(mr.sel);
3067}
3068
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003069inline void swapStruct(struct message_ref32 &mr) {
3070 sys::swapByteOrder(mr.imp);
3071 sys::swapByteOrder(mr.sel);
3072}
3073
Kevin Enderby846c0002015-04-16 17:19:59 +00003074inline void swapStruct(struct objc_module_t &module) {
3075 sys::swapByteOrder(module.version);
3076 sys::swapByteOrder(module.size);
3077 sys::swapByteOrder(module.name);
3078 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003079}
Kevin Enderby846c0002015-04-16 17:19:59 +00003080
3081inline void swapStruct(struct objc_symtab_t &symtab) {
3082 sys::swapByteOrder(symtab.sel_ref_cnt);
3083 sys::swapByteOrder(symtab.refs);
3084 sys::swapByteOrder(symtab.cls_def_cnt);
3085 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003086}
Kevin Enderby846c0002015-04-16 17:19:59 +00003087
3088inline void swapStruct(struct objc_class_t &objc_class) {
3089 sys::swapByteOrder(objc_class.isa);
3090 sys::swapByteOrder(objc_class.super_class);
3091 sys::swapByteOrder(objc_class.name);
3092 sys::swapByteOrder(objc_class.version);
3093 sys::swapByteOrder(objc_class.info);
3094 sys::swapByteOrder(objc_class.instance_size);
3095 sys::swapByteOrder(objc_class.ivars);
3096 sys::swapByteOrder(objc_class.methodLists);
3097 sys::swapByteOrder(objc_class.cache);
3098 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003099}
Kevin Enderby846c0002015-04-16 17:19:59 +00003100
3101inline void swapStruct(struct objc_category_t &objc_category) {
3102 sys::swapByteOrder(objc_category.category_name);
3103 sys::swapByteOrder(objc_category.class_name);
3104 sys::swapByteOrder(objc_category.instance_methods);
3105 sys::swapByteOrder(objc_category.class_methods);
3106 sys::swapByteOrder(objc_category.protocols);
3107}
3108
3109inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3110 sys::swapByteOrder(objc_ivar_list.ivar_count);
3111}
3112
3113inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3114 sys::swapByteOrder(objc_ivar.ivar_name);
3115 sys::swapByteOrder(objc_ivar.ivar_type);
3116 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003117}
Kevin Enderby846c0002015-04-16 17:19:59 +00003118
3119inline void swapStruct(struct objc_method_list_t &method_list) {
3120 sys::swapByteOrder(method_list.obsolete);
3121 sys::swapByteOrder(method_list.method_count);
3122}
3123
3124inline void swapStruct(struct objc_method_t &method) {
3125 sys::swapByteOrder(method.method_name);
3126 sys::swapByteOrder(method.method_types);
3127 sys::swapByteOrder(method.method_imp);
3128}
3129
3130inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3131 sys::swapByteOrder(protocol_list.next);
3132 sys::swapByteOrder(protocol_list.count);
3133}
3134
3135inline void swapStruct(struct objc_protocol_t &protocol) {
3136 sys::swapByteOrder(protocol.isa);
3137 sys::swapByteOrder(protocol.protocol_name);
3138 sys::swapByteOrder(protocol.protocol_list);
3139 sys::swapByteOrder(protocol.instance_methods);
3140 sys::swapByteOrder(protocol.class_methods);
3141}
3142
3143inline void swapStruct(struct objc_method_description_list_t &mdl) {
3144 sys::swapByteOrder(mdl.count);
3145}
3146
3147inline void swapStruct(struct objc_method_description_t &md) {
3148 sys::swapByteOrder(md.name);
3149 sys::swapByteOrder(md.types);
3150}
3151
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003152static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3153 struct DisassembleInfo *info);
3154
3155// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3156// to an Objective-C class and returns the class name. It is also passed the
3157// address of the pointer, so when the pointer is zero as it can be in an .o
3158// file, that is used to look for an external relocation entry with a symbol
3159// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003160static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3161 uint64_t ReferenceValue,
3162 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003163 const char *r;
3164 uint32_t offset, left;
3165 SectionRef S;
3166
3167 // The pointer_value can be 0 in an object file and have a relocation
3168 // entry for the class symbol at the ReferenceValue (the address of the
3169 // pointer).
3170 if (pointer_value == 0) {
3171 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3172 if (r == nullptr || left < sizeof(uint64_t))
3173 return nullptr;
3174 uint64_t n_value;
3175 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3176 if (symbol_name == nullptr)
3177 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003178 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003179 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3180 return class_name + 2;
3181 else
3182 return nullptr;
3183 }
3184
3185 // The case were the pointer_value is non-zero and points to a class defined
3186 // in this Mach-O file.
3187 r = get_pointer_64(pointer_value, offset, left, S, info);
3188 if (r == nullptr || left < sizeof(struct class64_t))
3189 return nullptr;
3190 struct class64_t c;
3191 memcpy(&c, r, sizeof(struct class64_t));
3192 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3193 swapStruct(c);
3194 if (c.data == 0)
3195 return nullptr;
3196 r = get_pointer_64(c.data, offset, left, S, info);
3197 if (r == nullptr || left < sizeof(struct class_ro64_t))
3198 return nullptr;
3199 struct class_ro64_t cro;
3200 memcpy(&cro, r, sizeof(struct class_ro64_t));
3201 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3202 swapStruct(cro);
3203 if (cro.name == 0)
3204 return nullptr;
3205 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3206 return name;
3207}
3208
3209// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3210// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003211static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3212 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003213 const char *r, *name;
3214 uint32_t offset, left;
3215 SectionRef S;
3216 struct cfstring64_t cfs;
3217 uint64_t cfs_characters;
3218
3219 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3220 if (r == nullptr || left < sizeof(struct cfstring64_t))
3221 return nullptr;
3222 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3223 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3224 swapStruct(cfs);
3225 if (cfs.characters == 0) {
3226 uint64_t n_value;
3227 const char *symbol_name = get_symbol_64(
3228 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3229 if (symbol_name == nullptr)
3230 return nullptr;
3231 cfs_characters = n_value;
3232 } else
3233 cfs_characters = cfs.characters;
3234 name = get_pointer_64(cfs_characters, offset, left, S, info);
3235
3236 return name;
3237}
3238
3239// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3240// of a pointer to an Objective-C selector reference when the pointer value is
3241// zero as in a .o file and is likely to have a external relocation entry with
3242// who's symbol's n_value is the real pointer to the selector name. If that is
3243// the case the real pointer to the selector name is returned else 0 is
3244// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003245static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3246 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003247 uint32_t offset, left;
3248 SectionRef S;
3249
3250 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3251 if (r == nullptr || left < sizeof(uint64_t))
3252 return 0;
3253 uint64_t n_value;
3254 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3255 if (symbol_name == nullptr)
3256 return 0;
3257 return n_value;
3258}
3259
Kevin Enderby0fc11822015-04-01 20:57:01 +00003260static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3261 const char *sectname) {
3262 for (const SectionRef &Section : O->sections()) {
3263 StringRef SectName;
3264 Section.getName(SectName);
3265 DataRefImpl Ref = Section.getRawDataRefImpl();
3266 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3267 if (SegName == segname && SectName == sectname)
3268 return Section;
3269 }
3270 return SectionRef();
3271}
3272
3273static void
3274walk_pointer_list_64(const char *listname, const SectionRef S,
3275 MachOObjectFile *O, struct DisassembleInfo *info,
3276 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3277 if (S == SectionRef())
3278 return;
3279
3280 StringRef SectName;
3281 S.getName(SectName);
3282 DataRefImpl Ref = S.getRawDataRefImpl();
3283 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3284 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3285
3286 StringRef BytesStr;
3287 S.getContents(BytesStr);
3288 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3289
3290 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3291 uint32_t left = S.getSize() - i;
3292 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3293 uint64_t p = 0;
3294 memcpy(&p, Contents + i, size);
3295 if (i + sizeof(uint64_t) > S.getSize())
3296 outs() << listname << " list pointer extends past end of (" << SegName
3297 << "," << SectName << ") section\n";
3298 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3299
3300 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3301 sys::swapByteOrder(p);
3302
3303 uint64_t n_value = 0;
3304 const char *name = get_symbol_64(i, S, info, n_value, p);
3305 if (name == nullptr)
3306 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3307
3308 if (n_value != 0) {
3309 outs() << format("0x%" PRIx64, n_value);
3310 if (p != 0)
3311 outs() << " + " << format("0x%" PRIx64, p);
3312 } else
3313 outs() << format("0x%" PRIx64, p);
3314 if (name != nullptr)
3315 outs() << " " << name;
3316 outs() << "\n";
3317
3318 p += n_value;
3319 if (func)
3320 func(p, info);
3321 }
3322}
3323
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003324static void
3325walk_pointer_list_32(const char *listname, const SectionRef S,
3326 MachOObjectFile *O, struct DisassembleInfo *info,
3327 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3328 if (S == SectionRef())
3329 return;
3330
3331 StringRef SectName;
3332 S.getName(SectName);
3333 DataRefImpl Ref = S.getRawDataRefImpl();
3334 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3335 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3336
3337 StringRef BytesStr;
3338 S.getContents(BytesStr);
3339 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3340
3341 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3342 uint32_t left = S.getSize() - i;
3343 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3344 uint32_t p = 0;
3345 memcpy(&p, Contents + i, size);
3346 if (i + sizeof(uint32_t) > S.getSize())
3347 outs() << listname << " list pointer extends past end of (" << SegName
3348 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003349 uint32_t Address = S.getAddress() + i;
3350 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003351
3352 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3353 sys::swapByteOrder(p);
3354 outs() << format("0x%" PRIx32, p);
3355
3356 const char *name = get_symbol_32(i, S, info, p);
3357 if (name != nullptr)
3358 outs() << " " << name;
3359 outs() << "\n";
3360
3361 if (func)
3362 func(p, info);
3363 }
3364}
3365
3366static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003367 if (layout_map == nullptr)
3368 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003369 outs() << " layout map: ";
3370 do {
3371 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3372 left--;
3373 layout_map++;
3374 } while (*layout_map != '\0' && left != 0);
3375 outs() << "\n";
3376}
3377
Kevin Enderby0fc11822015-04-01 20:57:01 +00003378static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3379 uint32_t offset, left;
3380 SectionRef S;
3381 const char *layout_map;
3382
3383 if (p == 0)
3384 return;
3385 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003386 print_layout_map(layout_map, left);
3387}
3388
3389static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3390 uint32_t offset, left;
3391 SectionRef S;
3392 const char *layout_map;
3393
3394 if (p == 0)
3395 return;
3396 layout_map = get_pointer_32(p, offset, left, S, info);
3397 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003398}
3399
3400static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3401 const char *indent) {
3402 struct method_list64_t ml;
3403 struct method64_t m;
3404 const char *r;
3405 uint32_t offset, xoffset, left, i;
3406 SectionRef S, xS;
3407 const char *name, *sym_name;
3408 uint64_t n_value;
3409
3410 r = get_pointer_64(p, offset, left, S, info);
3411 if (r == nullptr)
3412 return;
3413 memset(&ml, '\0', sizeof(struct method_list64_t));
3414 if (left < sizeof(struct method_list64_t)) {
3415 memcpy(&ml, r, left);
3416 outs() << " (method_list_t entends past the end of the section)\n";
3417 } else
3418 memcpy(&ml, r, sizeof(struct method_list64_t));
3419 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3420 swapStruct(ml);
3421 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3422 outs() << indent << "\t\t count " << ml.count << "\n";
3423
3424 p += sizeof(struct method_list64_t);
3425 offset += sizeof(struct method_list64_t);
3426 for (i = 0; i < ml.count; i++) {
3427 r = get_pointer_64(p, offset, left, S, info);
3428 if (r == nullptr)
3429 return;
3430 memset(&m, '\0', sizeof(struct method64_t));
3431 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003432 memcpy(&m, r, left);
3433 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003434 } else
3435 memcpy(&m, r, sizeof(struct method64_t));
3436 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3437 swapStruct(m);
3438
3439 outs() << indent << "\t\t name ";
3440 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3441 info, n_value, m.name);
3442 if (n_value != 0) {
3443 if (info->verbose && sym_name != nullptr)
3444 outs() << sym_name;
3445 else
3446 outs() << format("0x%" PRIx64, n_value);
3447 if (m.name != 0)
3448 outs() << " + " << format("0x%" PRIx64, m.name);
3449 } else
3450 outs() << format("0x%" PRIx64, m.name);
3451 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3452 if (name != nullptr)
3453 outs() << format(" %.*s", left, name);
3454 outs() << "\n";
3455
3456 outs() << indent << "\t\t types ";
3457 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3458 info, n_value, m.types);
3459 if (n_value != 0) {
3460 if (info->verbose && sym_name != nullptr)
3461 outs() << sym_name;
3462 else
3463 outs() << format("0x%" PRIx64, n_value);
3464 if (m.types != 0)
3465 outs() << " + " << format("0x%" PRIx64, m.types);
3466 } else
3467 outs() << format("0x%" PRIx64, m.types);
3468 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3469 if (name != nullptr)
3470 outs() << format(" %.*s", left, name);
3471 outs() << "\n";
3472
3473 outs() << indent << "\t\t imp ";
3474 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3475 n_value, m.imp);
3476 if (info->verbose && name == nullptr) {
3477 if (n_value != 0) {
3478 outs() << format("0x%" PRIx64, n_value) << " ";
3479 if (m.imp != 0)
3480 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3481 } else
3482 outs() << format("0x%" PRIx64, m.imp) << " ";
3483 }
3484 if (name != nullptr)
3485 outs() << name;
3486 outs() << "\n";
3487
3488 p += sizeof(struct method64_t);
3489 offset += sizeof(struct method64_t);
3490 }
3491}
3492
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003493static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3494 const char *indent) {
3495 struct method_list32_t ml;
3496 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003497 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003498 uint32_t offset, xoffset, left, i;
3499 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003500
3501 r = get_pointer_32(p, offset, left, S, info);
3502 if (r == nullptr)
3503 return;
3504 memset(&ml, '\0', sizeof(struct method_list32_t));
3505 if (left < sizeof(struct method_list32_t)) {
3506 memcpy(&ml, r, left);
3507 outs() << " (method_list_t entends past the end of the section)\n";
3508 } else
3509 memcpy(&ml, r, sizeof(struct method_list32_t));
3510 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3511 swapStruct(ml);
3512 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3513 outs() << indent << "\t\t count " << ml.count << "\n";
3514
3515 p += sizeof(struct method_list32_t);
3516 offset += sizeof(struct method_list32_t);
3517 for (i = 0; i < ml.count; i++) {
3518 r = get_pointer_32(p, offset, left, S, info);
3519 if (r == nullptr)
3520 return;
3521 memset(&m, '\0', sizeof(struct method32_t));
3522 if (left < sizeof(struct method32_t)) {
3523 memcpy(&ml, r, left);
3524 outs() << indent << " (method_t entends past the end of the section)\n";
3525 } else
3526 memcpy(&m, r, sizeof(struct method32_t));
3527 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3528 swapStruct(m);
3529
3530 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3531 name = get_pointer_32(m.name, xoffset, left, xS, info);
3532 if (name != nullptr)
3533 outs() << format(" %.*s", left, name);
3534 outs() << "\n";
3535
3536 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3537 name = get_pointer_32(m.types, xoffset, left, xS, info);
3538 if (name != nullptr)
3539 outs() << format(" %.*s", left, name);
3540 outs() << "\n";
3541
3542 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3543 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3544 m.imp);
3545 if (name != nullptr)
3546 outs() << " " << name;
3547 outs() << "\n";
3548
3549 p += sizeof(struct method32_t);
3550 offset += sizeof(struct method32_t);
3551 }
3552}
3553
Kevin Enderby846c0002015-04-16 17:19:59 +00003554static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3555 uint32_t offset, left, xleft;
3556 SectionRef S;
3557 struct objc_method_list_t method_list;
3558 struct objc_method_t method;
3559 const char *r, *methods, *name, *SymbolName;
3560 int32_t i;
3561
3562 r = get_pointer_32(p, offset, left, S, info, true);
3563 if (r == nullptr)
3564 return true;
3565
3566 outs() << "\n";
3567 if (left > sizeof(struct objc_method_list_t)) {
3568 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3569 } else {
3570 outs() << "\t\t objc_method_list extends past end of the section\n";
3571 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3572 memcpy(&method_list, r, left);
3573 }
3574 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3575 swapStruct(method_list);
3576
3577 outs() << "\t\t obsolete "
3578 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3579 outs() << "\t\t method_count " << method_list.method_count << "\n";
3580
3581 methods = r + sizeof(struct objc_method_list_t);
3582 for (i = 0; i < method_list.method_count; i++) {
3583 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3584 outs() << "\t\t remaining method's extend past the of the section\n";
3585 break;
3586 }
3587 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3588 sizeof(struct objc_method_t));
3589 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3590 swapStruct(method);
3591
3592 outs() << "\t\t method_name "
3593 << format("0x%08" PRIx32, method.method_name);
3594 if (info->verbose) {
3595 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3596 if (name != nullptr)
3597 outs() << format(" %.*s", xleft, name);
3598 else
3599 outs() << " (not in an __OBJC section)";
3600 }
3601 outs() << "\n";
3602
3603 outs() << "\t\t method_types "
3604 << format("0x%08" PRIx32, method.method_types);
3605 if (info->verbose) {
3606 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3607 if (name != nullptr)
3608 outs() << format(" %.*s", xleft, name);
3609 else
3610 outs() << " (not in an __OBJC section)";
3611 }
3612 outs() << "\n";
3613
3614 outs() << "\t\t method_imp "
3615 << format("0x%08" PRIx32, method.method_imp) << " ";
3616 if (info->verbose) {
3617 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3618 if (SymbolName != nullptr)
3619 outs() << SymbolName;
3620 }
3621 outs() << "\n";
3622 }
3623 return false;
3624}
3625
Kevin Enderby0fc11822015-04-01 20:57:01 +00003626static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3627 struct protocol_list64_t pl;
3628 uint64_t q, n_value;
3629 struct protocol64_t pc;
3630 const char *r;
3631 uint32_t offset, xoffset, left, i;
3632 SectionRef S, xS;
3633 const char *name, *sym_name;
3634
3635 r = get_pointer_64(p, offset, left, S, info);
3636 if (r == nullptr)
3637 return;
3638 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3639 if (left < sizeof(struct protocol_list64_t)) {
3640 memcpy(&pl, r, left);
3641 outs() << " (protocol_list_t entends past the end of the section)\n";
3642 } else
3643 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3644 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3645 swapStruct(pl);
3646 outs() << " count " << pl.count << "\n";
3647
3648 p += sizeof(struct protocol_list64_t);
3649 offset += sizeof(struct protocol_list64_t);
3650 for (i = 0; i < pl.count; i++) {
3651 r = get_pointer_64(p, offset, left, S, info);
3652 if (r == nullptr)
3653 return;
3654 q = 0;
3655 if (left < sizeof(uint64_t)) {
3656 memcpy(&q, r, left);
3657 outs() << " (protocol_t * entends past the end of the section)\n";
3658 } else
3659 memcpy(&q, r, sizeof(uint64_t));
3660 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3661 sys::swapByteOrder(q);
3662
3663 outs() << "\t\t list[" << i << "] ";
3664 sym_name = get_symbol_64(offset, S, info, n_value, q);
3665 if (n_value != 0) {
3666 if (info->verbose && sym_name != nullptr)
3667 outs() << sym_name;
3668 else
3669 outs() << format("0x%" PRIx64, n_value);
3670 if (q != 0)
3671 outs() << " + " << format("0x%" PRIx64, q);
3672 } else
3673 outs() << format("0x%" PRIx64, q);
3674 outs() << " (struct protocol_t *)\n";
3675
3676 r = get_pointer_64(q + n_value, offset, left, S, info);
3677 if (r == nullptr)
3678 return;
3679 memset(&pc, '\0', sizeof(struct protocol64_t));
3680 if (left < sizeof(struct protocol64_t)) {
3681 memcpy(&pc, r, left);
3682 outs() << " (protocol_t entends past the end of the section)\n";
3683 } else
3684 memcpy(&pc, r, sizeof(struct protocol64_t));
3685 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3686 swapStruct(pc);
3687
3688 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3689
3690 outs() << "\t\t\t name ";
3691 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3692 info, n_value, pc.name);
3693 if (n_value != 0) {
3694 if (info->verbose && sym_name != nullptr)
3695 outs() << sym_name;
3696 else
3697 outs() << format("0x%" PRIx64, n_value);
3698 if (pc.name != 0)
3699 outs() << " + " << format("0x%" PRIx64, pc.name);
3700 } else
3701 outs() << format("0x%" PRIx64, pc.name);
3702 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3703 if (name != nullptr)
3704 outs() << format(" %.*s", left, name);
3705 outs() << "\n";
3706
3707 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3708
3709 outs() << "\t\t instanceMethods ";
3710 sym_name =
3711 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3712 S, info, n_value, pc.instanceMethods);
3713 if (n_value != 0) {
3714 if (info->verbose && sym_name != nullptr)
3715 outs() << sym_name;
3716 else
3717 outs() << format("0x%" PRIx64, n_value);
3718 if (pc.instanceMethods != 0)
3719 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3720 } else
3721 outs() << format("0x%" PRIx64, pc.instanceMethods);
3722 outs() << " (struct method_list_t *)\n";
3723 if (pc.instanceMethods + n_value != 0)
3724 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3725
3726 outs() << "\t\t classMethods ";
3727 sym_name =
3728 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3729 info, n_value, pc.classMethods);
3730 if (n_value != 0) {
3731 if (info->verbose && sym_name != nullptr)
3732 outs() << sym_name;
3733 else
3734 outs() << format("0x%" PRIx64, n_value);
3735 if (pc.classMethods != 0)
3736 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3737 } else
3738 outs() << format("0x%" PRIx64, pc.classMethods);
3739 outs() << " (struct method_list_t *)\n";
3740 if (pc.classMethods + n_value != 0)
3741 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3742
3743 outs() << "\t optionalInstanceMethods "
3744 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3745 outs() << "\t optionalClassMethods "
3746 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3747 outs() << "\t instanceProperties "
3748 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3749
3750 p += sizeof(uint64_t);
3751 offset += sizeof(uint64_t);
3752 }
3753}
3754
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003755static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3756 struct protocol_list32_t pl;
3757 uint32_t q;
3758 struct protocol32_t pc;
3759 const char *r;
3760 uint32_t offset, xoffset, left, i;
3761 SectionRef S, xS;
3762 const char *name;
3763
3764 r = get_pointer_32(p, offset, left, S, info);
3765 if (r == nullptr)
3766 return;
3767 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3768 if (left < sizeof(struct protocol_list32_t)) {
3769 memcpy(&pl, r, left);
3770 outs() << " (protocol_list_t entends past the end of the section)\n";
3771 } else
3772 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3773 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3774 swapStruct(pl);
3775 outs() << " count " << pl.count << "\n";
3776
3777 p += sizeof(struct protocol_list32_t);
3778 offset += sizeof(struct protocol_list32_t);
3779 for (i = 0; i < pl.count; i++) {
3780 r = get_pointer_32(p, offset, left, S, info);
3781 if (r == nullptr)
3782 return;
3783 q = 0;
3784 if (left < sizeof(uint32_t)) {
3785 memcpy(&q, r, left);
3786 outs() << " (protocol_t * entends past the end of the section)\n";
3787 } else
3788 memcpy(&q, r, sizeof(uint32_t));
3789 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3790 sys::swapByteOrder(q);
3791 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3792 << " (struct protocol_t *)\n";
3793 r = get_pointer_32(q, offset, left, S, info);
3794 if (r == nullptr)
3795 return;
3796 memset(&pc, '\0', sizeof(struct protocol32_t));
3797 if (left < sizeof(struct protocol32_t)) {
3798 memcpy(&pc, r, left);
3799 outs() << " (protocol_t entends past the end of the section)\n";
3800 } else
3801 memcpy(&pc, r, sizeof(struct protocol32_t));
3802 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3803 swapStruct(pc);
3804 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3805 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3806 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3807 if (name != nullptr)
3808 outs() << format(" %.*s", left, name);
3809 outs() << "\n";
3810 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3811 outs() << "\t\t instanceMethods "
3812 << format("0x%" PRIx32, pc.instanceMethods)
3813 << " (struct method_list_t *)\n";
3814 if (pc.instanceMethods != 0)
3815 print_method_list32_t(pc.instanceMethods, info, "\t");
3816 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3817 << " (struct method_list_t *)\n";
3818 if (pc.classMethods != 0)
3819 print_method_list32_t(pc.classMethods, info, "\t");
3820 outs() << "\t optionalInstanceMethods "
3821 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3822 outs() << "\t optionalClassMethods "
3823 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3824 outs() << "\t instanceProperties "
3825 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3826 p += sizeof(uint32_t);
3827 offset += sizeof(uint32_t);
3828 }
3829}
3830
Kevin Enderby846c0002015-04-16 17:19:59 +00003831static void print_indent(uint32_t indent) {
3832 for (uint32_t i = 0; i < indent;) {
3833 if (indent - i >= 8) {
3834 outs() << "\t";
3835 i += 8;
3836 } else {
3837 for (uint32_t j = i; j < indent; j++)
3838 outs() << " ";
3839 return;
3840 }
3841 }
3842}
3843
3844static bool print_method_description_list(uint32_t p, uint32_t indent,
3845 struct DisassembleInfo *info) {
3846 uint32_t offset, left, xleft;
3847 SectionRef S;
3848 struct objc_method_description_list_t mdl;
3849 struct objc_method_description_t md;
3850 const char *r, *list, *name;
3851 int32_t i;
3852
3853 r = get_pointer_32(p, offset, left, S, info, true);
3854 if (r == nullptr)
3855 return true;
3856
3857 outs() << "\n";
3858 if (left > sizeof(struct objc_method_description_list_t)) {
3859 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3860 } else {
3861 print_indent(indent);
3862 outs() << " objc_method_description_list extends past end of the section\n";
3863 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3864 memcpy(&mdl, r, left);
3865 }
3866 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3867 swapStruct(mdl);
3868
3869 print_indent(indent);
3870 outs() << " count " << mdl.count << "\n";
3871
3872 list = r + sizeof(struct objc_method_description_list_t);
3873 for (i = 0; i < mdl.count; i++) {
3874 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3875 print_indent(indent);
3876 outs() << " remaining list entries extend past the of the section\n";
3877 break;
3878 }
3879 print_indent(indent);
3880 outs() << " list[" << i << "]\n";
3881 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3882 sizeof(struct objc_method_description_t));
3883 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3884 swapStruct(md);
3885
3886 print_indent(indent);
3887 outs() << " name " << format("0x%08" PRIx32, md.name);
3888 if (info->verbose) {
3889 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3890 if (name != nullptr)
3891 outs() << format(" %.*s", xleft, name);
3892 else
3893 outs() << " (not in an __OBJC section)";
3894 }
3895 outs() << "\n";
3896
3897 print_indent(indent);
3898 outs() << " types " << format("0x%08" PRIx32, md.types);
3899 if (info->verbose) {
3900 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3901 if (name != nullptr)
3902 outs() << format(" %.*s", xleft, name);
3903 else
3904 outs() << " (not in an __OBJC section)";
3905 }
3906 outs() << "\n";
3907 }
3908 return false;
3909}
3910
3911static bool print_protocol_list(uint32_t p, uint32_t indent,
3912 struct DisassembleInfo *info);
3913
3914static bool print_protocol(uint32_t p, uint32_t indent,
3915 struct DisassembleInfo *info) {
3916 uint32_t offset, left;
3917 SectionRef S;
3918 struct objc_protocol_t protocol;
3919 const char *r, *name;
3920
3921 r = get_pointer_32(p, offset, left, S, info, true);
3922 if (r == nullptr)
3923 return true;
3924
3925 outs() << "\n";
3926 if (left >= sizeof(struct objc_protocol_t)) {
3927 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3928 } else {
3929 print_indent(indent);
3930 outs() << " Protocol extends past end of the section\n";
3931 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3932 memcpy(&protocol, r, left);
3933 }
3934 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3935 swapStruct(protocol);
3936
3937 print_indent(indent);
3938 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3939 << "\n";
3940
3941 print_indent(indent);
3942 outs() << " protocol_name "
3943 << format("0x%08" PRIx32, protocol.protocol_name);
3944 if (info->verbose) {
3945 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3946 if (name != nullptr)
3947 outs() << format(" %.*s", left, name);
3948 else
3949 outs() << " (not in an __OBJC section)";
3950 }
3951 outs() << "\n";
3952
3953 print_indent(indent);
3954 outs() << " protocol_list "
3955 << format("0x%08" PRIx32, protocol.protocol_list);
3956 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3957 outs() << " (not in an __OBJC section)\n";
3958
3959 print_indent(indent);
3960 outs() << " instance_methods "
3961 << format("0x%08" PRIx32, protocol.instance_methods);
3962 if (print_method_description_list(protocol.instance_methods, indent, info))
3963 outs() << " (not in an __OBJC section)\n";
3964
3965 print_indent(indent);
3966 outs() << " class_methods "
3967 << format("0x%08" PRIx32, protocol.class_methods);
3968 if (print_method_description_list(protocol.class_methods, indent, info))
3969 outs() << " (not in an __OBJC section)\n";
3970
3971 return false;
3972}
3973
3974static bool print_protocol_list(uint32_t p, uint32_t indent,
3975 struct DisassembleInfo *info) {
3976 uint32_t offset, left, l;
3977 SectionRef S;
3978 struct objc_protocol_list_t protocol_list;
3979 const char *r, *list;
3980 int32_t i;
3981
3982 r = get_pointer_32(p, offset, left, S, info, true);
3983 if (r == nullptr)
3984 return true;
3985
3986 outs() << "\n";
3987 if (left > sizeof(struct objc_protocol_list_t)) {
3988 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
3989 } else {
3990 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
3991 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
3992 memcpy(&protocol_list, r, left);
3993 }
3994 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3995 swapStruct(protocol_list);
3996
3997 print_indent(indent);
3998 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
3999 << "\n";
4000 print_indent(indent);
4001 outs() << " count " << protocol_list.count << "\n";
4002
4003 list = r + sizeof(struct objc_protocol_list_t);
4004 for (i = 0; i < protocol_list.count; i++) {
4005 if ((i + 1) * sizeof(uint32_t) > left) {
4006 outs() << "\t\t remaining list entries extend past the of the section\n";
4007 break;
4008 }
4009 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4010 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4011 sys::swapByteOrder(l);
4012
4013 print_indent(indent);
4014 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4015 if (print_protocol(l, indent, info))
4016 outs() << "(not in an __OBJC section)\n";
4017 }
4018 return false;
4019}
4020
Kevin Enderby0fc11822015-04-01 20:57:01 +00004021static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4022 struct ivar_list64_t il;
4023 struct ivar64_t i;
4024 const char *r;
4025 uint32_t offset, xoffset, left, j;
4026 SectionRef S, xS;
4027 const char *name, *sym_name, *ivar_offset_p;
4028 uint64_t ivar_offset, n_value;
4029
4030 r = get_pointer_64(p, offset, left, S, info);
4031 if (r == nullptr)
4032 return;
4033 memset(&il, '\0', sizeof(struct ivar_list64_t));
4034 if (left < sizeof(struct ivar_list64_t)) {
4035 memcpy(&il, r, left);
4036 outs() << " (ivar_list_t entends past the end of the section)\n";
4037 } else
4038 memcpy(&il, r, sizeof(struct ivar_list64_t));
4039 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4040 swapStruct(il);
4041 outs() << " entsize " << il.entsize << "\n";
4042 outs() << " count " << il.count << "\n";
4043
4044 p += sizeof(struct ivar_list64_t);
4045 offset += sizeof(struct ivar_list64_t);
4046 for (j = 0; j < il.count; j++) {
4047 r = get_pointer_64(p, offset, left, S, info);
4048 if (r == nullptr)
4049 return;
4050 memset(&i, '\0', sizeof(struct ivar64_t));
4051 if (left < sizeof(struct ivar64_t)) {
4052 memcpy(&i, r, left);
4053 outs() << " (ivar_t entends past the end of the section)\n";
4054 } else
4055 memcpy(&i, r, sizeof(struct ivar64_t));
4056 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4057 swapStruct(i);
4058
4059 outs() << "\t\t\t offset ";
4060 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4061 info, n_value, i.offset);
4062 if (n_value != 0) {
4063 if (info->verbose && sym_name != nullptr)
4064 outs() << sym_name;
4065 else
4066 outs() << format("0x%" PRIx64, n_value);
4067 if (i.offset != 0)
4068 outs() << " + " << format("0x%" PRIx64, i.offset);
4069 } else
4070 outs() << format("0x%" PRIx64, i.offset);
4071 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4072 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4073 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4074 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4075 sys::swapByteOrder(ivar_offset);
4076 outs() << " " << ivar_offset << "\n";
4077 } else
4078 outs() << "\n";
4079
4080 outs() << "\t\t\t name ";
4081 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4082 n_value, i.name);
4083 if (n_value != 0) {
4084 if (info->verbose && sym_name != nullptr)
4085 outs() << sym_name;
4086 else
4087 outs() << format("0x%" PRIx64, n_value);
4088 if (i.name != 0)
4089 outs() << " + " << format("0x%" PRIx64, i.name);
4090 } else
4091 outs() << format("0x%" PRIx64, i.name);
4092 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4093 if (name != nullptr)
4094 outs() << format(" %.*s", left, name);
4095 outs() << "\n";
4096
4097 outs() << "\t\t\t type ";
4098 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4099 n_value, i.name);
4100 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4101 if (n_value != 0) {
4102 if (info->verbose && sym_name != nullptr)
4103 outs() << sym_name;
4104 else
4105 outs() << format("0x%" PRIx64, n_value);
4106 if (i.type != 0)
4107 outs() << " + " << format("0x%" PRIx64, i.type);
4108 } else
4109 outs() << format("0x%" PRIx64, i.type);
4110 if (name != nullptr)
4111 outs() << format(" %.*s", left, name);
4112 outs() << "\n";
4113
4114 outs() << "\t\t\talignment " << i.alignment << "\n";
4115 outs() << "\t\t\t size " << i.size << "\n";
4116
4117 p += sizeof(struct ivar64_t);
4118 offset += sizeof(struct ivar64_t);
4119 }
4120}
4121
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004122static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4123 struct ivar_list32_t il;
4124 struct ivar32_t i;
4125 const char *r;
4126 uint32_t offset, xoffset, left, j;
4127 SectionRef S, xS;
4128 const char *name, *ivar_offset_p;
4129 uint32_t ivar_offset;
4130
4131 r = get_pointer_32(p, offset, left, S, info);
4132 if (r == nullptr)
4133 return;
4134 memset(&il, '\0', sizeof(struct ivar_list32_t));
4135 if (left < sizeof(struct ivar_list32_t)) {
4136 memcpy(&il, r, left);
4137 outs() << " (ivar_list_t entends past the end of the section)\n";
4138 } else
4139 memcpy(&il, r, sizeof(struct ivar_list32_t));
4140 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4141 swapStruct(il);
4142 outs() << " entsize " << il.entsize << "\n";
4143 outs() << " count " << il.count << "\n";
4144
4145 p += sizeof(struct ivar_list32_t);
4146 offset += sizeof(struct ivar_list32_t);
4147 for (j = 0; j < il.count; j++) {
4148 r = get_pointer_32(p, offset, left, S, info);
4149 if (r == nullptr)
4150 return;
4151 memset(&i, '\0', sizeof(struct ivar32_t));
4152 if (left < sizeof(struct ivar32_t)) {
4153 memcpy(&i, r, left);
4154 outs() << " (ivar_t entends past the end of the section)\n";
4155 } else
4156 memcpy(&i, r, sizeof(struct ivar32_t));
4157 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4158 swapStruct(i);
4159
4160 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4161 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4162 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4163 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4164 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4165 sys::swapByteOrder(ivar_offset);
4166 outs() << " " << ivar_offset << "\n";
4167 } else
4168 outs() << "\n";
4169
4170 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4171 name = get_pointer_32(i.name, xoffset, left, xS, info);
4172 if (name != nullptr)
4173 outs() << format(" %.*s", left, name);
4174 outs() << "\n";
4175
4176 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4177 name = get_pointer_32(i.type, xoffset, left, xS, info);
4178 if (name != nullptr)
4179 outs() << format(" %.*s", left, name);
4180 outs() << "\n";
4181
4182 outs() << "\t\t\talignment " << i.alignment << "\n";
4183 outs() << "\t\t\t size " << i.size << "\n";
4184
4185 p += sizeof(struct ivar32_t);
4186 offset += sizeof(struct ivar32_t);
4187 }
4188}
4189
Kevin Enderby0fc11822015-04-01 20:57:01 +00004190static void print_objc_property_list64(uint64_t p,
4191 struct DisassembleInfo *info) {
4192 struct objc_property_list64 opl;
4193 struct objc_property64 op;
4194 const char *r;
4195 uint32_t offset, xoffset, left, j;
4196 SectionRef S, xS;
4197 const char *name, *sym_name;
4198 uint64_t n_value;
4199
4200 r = get_pointer_64(p, offset, left, S, info);
4201 if (r == nullptr)
4202 return;
4203 memset(&opl, '\0', sizeof(struct objc_property_list64));
4204 if (left < sizeof(struct objc_property_list64)) {
4205 memcpy(&opl, r, left);
4206 outs() << " (objc_property_list entends past the end of the section)\n";
4207 } else
4208 memcpy(&opl, r, sizeof(struct objc_property_list64));
4209 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4210 swapStruct(opl);
4211 outs() << " entsize " << opl.entsize << "\n";
4212 outs() << " count " << opl.count << "\n";
4213
4214 p += sizeof(struct objc_property_list64);
4215 offset += sizeof(struct objc_property_list64);
4216 for (j = 0; j < opl.count; j++) {
4217 r = get_pointer_64(p, offset, left, S, info);
4218 if (r == nullptr)
4219 return;
4220 memset(&op, '\0', sizeof(struct objc_property64));
4221 if (left < sizeof(struct objc_property64)) {
4222 memcpy(&op, r, left);
4223 outs() << " (objc_property entends past the end of the section)\n";
4224 } else
4225 memcpy(&op, r, sizeof(struct objc_property64));
4226 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4227 swapStruct(op);
4228
4229 outs() << "\t\t\t name ";
4230 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4231 info, n_value, op.name);
4232 if (n_value != 0) {
4233 if (info->verbose && sym_name != nullptr)
4234 outs() << sym_name;
4235 else
4236 outs() << format("0x%" PRIx64, n_value);
4237 if (op.name != 0)
4238 outs() << " + " << format("0x%" PRIx64, op.name);
4239 } else
4240 outs() << format("0x%" PRIx64, op.name);
4241 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4242 if (name != nullptr)
4243 outs() << format(" %.*s", left, name);
4244 outs() << "\n";
4245
4246 outs() << "\t\t\tattributes ";
4247 sym_name =
4248 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4249 info, n_value, op.attributes);
4250 if (n_value != 0) {
4251 if (info->verbose && sym_name != nullptr)
4252 outs() << sym_name;
4253 else
4254 outs() << format("0x%" PRIx64, n_value);
4255 if (op.attributes != 0)
4256 outs() << " + " << format("0x%" PRIx64, op.attributes);
4257 } else
4258 outs() << format("0x%" PRIx64, op.attributes);
4259 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4260 if (name != nullptr)
4261 outs() << format(" %.*s", left, name);
4262 outs() << "\n";
4263
4264 p += sizeof(struct objc_property64);
4265 offset += sizeof(struct objc_property64);
4266 }
4267}
4268
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004269static void print_objc_property_list32(uint32_t p,
4270 struct DisassembleInfo *info) {
4271 struct objc_property_list32 opl;
4272 struct objc_property32 op;
4273 const char *r;
4274 uint32_t offset, xoffset, left, j;
4275 SectionRef S, xS;
4276 const char *name;
4277
4278 r = get_pointer_32(p, offset, left, S, info);
4279 if (r == nullptr)
4280 return;
4281 memset(&opl, '\0', sizeof(struct objc_property_list32));
4282 if (left < sizeof(struct objc_property_list32)) {
4283 memcpy(&opl, r, left);
4284 outs() << " (objc_property_list entends past the end of the section)\n";
4285 } else
4286 memcpy(&opl, r, sizeof(struct objc_property_list32));
4287 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4288 swapStruct(opl);
4289 outs() << " entsize " << opl.entsize << "\n";
4290 outs() << " count " << opl.count << "\n";
4291
4292 p += sizeof(struct objc_property_list32);
4293 offset += sizeof(struct objc_property_list32);
4294 for (j = 0; j < opl.count; j++) {
4295 r = get_pointer_32(p, offset, left, S, info);
4296 if (r == nullptr)
4297 return;
4298 memset(&op, '\0', sizeof(struct objc_property32));
4299 if (left < sizeof(struct objc_property32)) {
4300 memcpy(&op, r, left);
4301 outs() << " (objc_property entends past the end of the section)\n";
4302 } else
4303 memcpy(&op, r, sizeof(struct objc_property32));
4304 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4305 swapStruct(op);
4306
4307 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4308 name = get_pointer_32(op.name, xoffset, left, xS, info);
4309 if (name != nullptr)
4310 outs() << format(" %.*s", left, name);
4311 outs() << "\n";
4312
4313 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4314 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4315 if (name != nullptr)
4316 outs() << format(" %.*s", left, name);
4317 outs() << "\n";
4318
4319 p += sizeof(struct objc_property32);
4320 offset += sizeof(struct objc_property32);
4321 }
4322}
4323
Richard Smith81ff44d2015-10-09 22:09:56 +00004324static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004325 bool &is_meta_class) {
4326 struct class_ro64_t cro;
4327 const char *r;
4328 uint32_t offset, xoffset, left;
4329 SectionRef S, xS;
4330 const char *name, *sym_name;
4331 uint64_t n_value;
4332
4333 r = get_pointer_64(p, offset, left, S, info);
4334 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004335 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004336 memset(&cro, '\0', sizeof(struct class_ro64_t));
4337 if (left < sizeof(struct class_ro64_t)) {
4338 memcpy(&cro, r, left);
4339 outs() << " (class_ro_t entends past the end of the section)\n";
4340 } else
4341 memcpy(&cro, r, sizeof(struct class_ro64_t));
4342 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4343 swapStruct(cro);
4344 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4345 if (cro.flags & RO_META)
4346 outs() << " RO_META";
4347 if (cro.flags & RO_ROOT)
4348 outs() << " RO_ROOT";
4349 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4350 outs() << " RO_HAS_CXX_STRUCTORS";
4351 outs() << "\n";
4352 outs() << " instanceStart " << cro.instanceStart << "\n";
4353 outs() << " instanceSize " << cro.instanceSize << "\n";
4354 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4355 << "\n";
4356 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4357 << "\n";
4358 print_layout_map64(cro.ivarLayout, info);
4359
4360 outs() << " name ";
4361 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4362 info, n_value, cro.name);
4363 if (n_value != 0) {
4364 if (info->verbose && sym_name != nullptr)
4365 outs() << sym_name;
4366 else
4367 outs() << format("0x%" PRIx64, n_value);
4368 if (cro.name != 0)
4369 outs() << " + " << format("0x%" PRIx64, cro.name);
4370 } else
4371 outs() << format("0x%" PRIx64, cro.name);
4372 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4373 if (name != nullptr)
4374 outs() << format(" %.*s", left, name);
4375 outs() << "\n";
4376
4377 outs() << " baseMethods ";
4378 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4379 S, info, n_value, cro.baseMethods);
4380 if (n_value != 0) {
4381 if (info->verbose && sym_name != nullptr)
4382 outs() << sym_name;
4383 else
4384 outs() << format("0x%" PRIx64, n_value);
4385 if (cro.baseMethods != 0)
4386 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4387 } else
4388 outs() << format("0x%" PRIx64, cro.baseMethods);
4389 outs() << " (struct method_list_t *)\n";
4390 if (cro.baseMethods + n_value != 0)
4391 print_method_list64_t(cro.baseMethods + n_value, info, "");
4392
4393 outs() << " baseProtocols ";
4394 sym_name =
4395 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4396 info, n_value, cro.baseProtocols);
4397 if (n_value != 0) {
4398 if (info->verbose && sym_name != nullptr)
4399 outs() << sym_name;
4400 else
4401 outs() << format("0x%" PRIx64, n_value);
4402 if (cro.baseProtocols != 0)
4403 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4404 } else
4405 outs() << format("0x%" PRIx64, cro.baseProtocols);
4406 outs() << "\n";
4407 if (cro.baseProtocols + n_value != 0)
4408 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4409
4410 outs() << " ivars ";
4411 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004412 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004413 if (n_value != 0) {
4414 if (info->verbose && sym_name != nullptr)
4415 outs() << sym_name;
4416 else
4417 outs() << format("0x%" PRIx64, n_value);
4418 if (cro.ivars != 0)
4419 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4420 } else
4421 outs() << format("0x%" PRIx64, cro.ivars);
4422 outs() << "\n";
4423 if (cro.ivars + n_value != 0)
4424 print_ivar_list64_t(cro.ivars + n_value, info);
4425
4426 outs() << " weakIvarLayout ";
4427 sym_name =
4428 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4429 info, n_value, cro.weakIvarLayout);
4430 if (n_value != 0) {
4431 if (info->verbose && sym_name != nullptr)
4432 outs() << sym_name;
4433 else
4434 outs() << format("0x%" PRIx64, n_value);
4435 if (cro.weakIvarLayout != 0)
4436 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4437 } else
4438 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4439 outs() << "\n";
4440 print_layout_map64(cro.weakIvarLayout + n_value, info);
4441
4442 outs() << " baseProperties ";
4443 sym_name =
4444 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4445 info, n_value, cro.baseProperties);
4446 if (n_value != 0) {
4447 if (info->verbose && sym_name != nullptr)
4448 outs() << sym_name;
4449 else
4450 outs() << format("0x%" PRIx64, n_value);
4451 if (cro.baseProperties != 0)
4452 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4453 } else
4454 outs() << format("0x%" PRIx64, cro.baseProperties);
4455 outs() << "\n";
4456 if (cro.baseProperties + n_value != 0)
4457 print_objc_property_list64(cro.baseProperties + n_value, info);
4458
Rafael Espindolab9091322015-10-24 23:19:10 +00004459 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004460 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004461}
4462
Richard Smith81ff44d2015-10-09 22:09:56 +00004463static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004464 bool &is_meta_class) {
4465 struct class_ro32_t cro;
4466 const char *r;
4467 uint32_t offset, xoffset, left;
4468 SectionRef S, xS;
4469 const char *name;
4470
4471 r = get_pointer_32(p, offset, left, S, info);
4472 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004473 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004474 memset(&cro, '\0', sizeof(struct class_ro32_t));
4475 if (left < sizeof(struct class_ro32_t)) {
4476 memcpy(&cro, r, left);
4477 outs() << " (class_ro_t entends past the end of the section)\n";
4478 } else
4479 memcpy(&cro, r, sizeof(struct class_ro32_t));
4480 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4481 swapStruct(cro);
4482 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4483 if (cro.flags & RO_META)
4484 outs() << " RO_META";
4485 if (cro.flags & RO_ROOT)
4486 outs() << " RO_ROOT";
4487 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4488 outs() << " RO_HAS_CXX_STRUCTORS";
4489 outs() << "\n";
4490 outs() << " instanceStart " << cro.instanceStart << "\n";
4491 outs() << " instanceSize " << cro.instanceSize << "\n";
4492 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4493 << "\n";
4494 print_layout_map32(cro.ivarLayout, info);
4495
4496 outs() << " name " << format("0x%" PRIx32, cro.name);
4497 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4498 if (name != nullptr)
4499 outs() << format(" %.*s", left, name);
4500 outs() << "\n";
4501
4502 outs() << " baseMethods "
4503 << format("0x%" PRIx32, cro.baseMethods)
4504 << " (struct method_list_t *)\n";
4505 if (cro.baseMethods != 0)
4506 print_method_list32_t(cro.baseMethods, info, "");
4507
4508 outs() << " baseProtocols "
4509 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4510 if (cro.baseProtocols != 0)
4511 print_protocol_list32_t(cro.baseProtocols, info);
4512 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4513 << "\n";
4514 if (cro.ivars != 0)
4515 print_ivar_list32_t(cro.ivars, info);
4516 outs() << " weakIvarLayout "
4517 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4518 print_layout_map32(cro.weakIvarLayout, info);
4519 outs() << " baseProperties "
4520 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4521 if (cro.baseProperties != 0)
4522 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004523 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004524 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004525}
4526
Kevin Enderby0fc11822015-04-01 20:57:01 +00004527static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4528 struct class64_t c;
4529 const char *r;
4530 uint32_t offset, left;
4531 SectionRef S;
4532 const char *name;
4533 uint64_t isa_n_value, n_value;
4534
4535 r = get_pointer_64(p, offset, left, S, info);
4536 if (r == nullptr || left < sizeof(struct class64_t))
4537 return;
4538 memset(&c, '\0', sizeof(struct class64_t));
4539 if (left < sizeof(struct class64_t)) {
4540 memcpy(&c, r, left);
4541 outs() << " (class_t entends past the end of the section)\n";
4542 } else
4543 memcpy(&c, r, sizeof(struct class64_t));
4544 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4545 swapStruct(c);
4546
4547 outs() << " isa " << format("0x%" PRIx64, c.isa);
4548 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4549 isa_n_value, c.isa);
4550 if (name != nullptr)
4551 outs() << " " << name;
4552 outs() << "\n";
4553
4554 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4555 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4556 n_value, c.superclass);
4557 if (name != nullptr)
4558 outs() << " " << name;
4559 outs() << "\n";
4560
4561 outs() << " cache " << format("0x%" PRIx64, c.cache);
4562 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4563 n_value, c.cache);
4564 if (name != nullptr)
4565 outs() << " " << name;
4566 outs() << "\n";
4567
4568 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4569 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4570 n_value, c.vtable);
4571 if (name != nullptr)
4572 outs() << " " << name;
4573 outs() << "\n";
4574
4575 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4576 n_value, c.data);
4577 outs() << " data ";
4578 if (n_value != 0) {
4579 if (info->verbose && name != nullptr)
4580 outs() << name;
4581 else
4582 outs() << format("0x%" PRIx64, n_value);
4583 if (c.data != 0)
4584 outs() << " + " << format("0x%" PRIx64, c.data);
4585 } else
4586 outs() << format("0x%" PRIx64, c.data);
4587 outs() << " (struct class_ro_t *)";
4588
4589 // This is a Swift class if some of the low bits of the pointer are set.
4590 if ((c.data + n_value) & 0x7)
4591 outs() << " Swift class";
4592 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004593 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004594 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4595 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004596
Kevin Enderbyaac75382015-10-08 16:56:35 +00004597 if (!is_meta_class &&
4598 c.isa + isa_n_value != p &&
4599 c.isa + isa_n_value != 0 &&
4600 info->depth < 100) {
4601 info->depth++;
4602 outs() << "Meta Class\n";
4603 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004604 }
4605}
4606
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004607static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4608 struct class32_t c;
4609 const char *r;
4610 uint32_t offset, left;
4611 SectionRef S;
4612 const char *name;
4613
4614 r = get_pointer_32(p, offset, left, S, info);
4615 if (r == nullptr)
4616 return;
4617 memset(&c, '\0', sizeof(struct class32_t));
4618 if (left < sizeof(struct class32_t)) {
4619 memcpy(&c, r, left);
4620 outs() << " (class_t entends past the end of the section)\n";
4621 } else
4622 memcpy(&c, r, sizeof(struct class32_t));
4623 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4624 swapStruct(c);
4625
4626 outs() << " isa " << format("0x%" PRIx32, c.isa);
4627 name =
4628 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4629 if (name != nullptr)
4630 outs() << " " << name;
4631 outs() << "\n";
4632
4633 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4634 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4635 c.superclass);
4636 if (name != nullptr)
4637 outs() << " " << name;
4638 outs() << "\n";
4639
4640 outs() << " cache " << format("0x%" PRIx32, c.cache);
4641 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4642 c.cache);
4643 if (name != nullptr)
4644 outs() << " " << name;
4645 outs() << "\n";
4646
4647 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4648 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4649 c.vtable);
4650 if (name != nullptr)
4651 outs() << " " << name;
4652 outs() << "\n";
4653
4654 name =
4655 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4656 outs() << " data " << format("0x%" PRIx32, c.data)
4657 << " (struct class_ro_t *)";
4658
4659 // This is a Swift class if some of the low bits of the pointer are set.
4660 if (c.data & 0x3)
4661 outs() << " Swift class";
4662 outs() << "\n";
4663 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004664 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4665 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004666
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004667 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004668 outs() << "Meta Class\n";
4669 print_class32_t(c.isa, info);
4670 }
4671}
4672
Kevin Enderby846c0002015-04-16 17:19:59 +00004673static void print_objc_class_t(struct objc_class_t *objc_class,
4674 struct DisassembleInfo *info) {
4675 uint32_t offset, left, xleft;
4676 const char *name, *p, *ivar_list;
4677 SectionRef S;
4678 int32_t i;
4679 struct objc_ivar_list_t objc_ivar_list;
4680 struct objc_ivar_t ivar;
4681
4682 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4683 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4684 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4685 if (name != nullptr)
4686 outs() << format(" %.*s", left, name);
4687 else
4688 outs() << " (not in an __OBJC section)";
4689 }
4690 outs() << "\n";
4691
4692 outs() << "\t super_class "
4693 << format("0x%08" PRIx32, objc_class->super_class);
4694 if (info->verbose) {
4695 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4696 if (name != nullptr)
4697 outs() << format(" %.*s", left, name);
4698 else
4699 outs() << " (not in an __OBJC section)";
4700 }
4701 outs() << "\n";
4702
4703 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4704 if (info->verbose) {
4705 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4706 if (name != nullptr)
4707 outs() << format(" %.*s", left, name);
4708 else
4709 outs() << " (not in an __OBJC section)";
4710 }
4711 outs() << "\n";
4712
4713 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4714 << "\n";
4715
4716 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4717 if (info->verbose) {
4718 if (CLS_GETINFO(objc_class, CLS_CLASS))
4719 outs() << " CLS_CLASS";
4720 else if (CLS_GETINFO(objc_class, CLS_META))
4721 outs() << " CLS_META";
4722 }
4723 outs() << "\n";
4724
4725 outs() << "\t instance_size "
4726 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4727
4728 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4729 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4730 if (p != nullptr) {
4731 if (left > sizeof(struct objc_ivar_list_t)) {
4732 outs() << "\n";
4733 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4734 } else {
4735 outs() << " (entends past the end of the section)\n";
4736 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4737 memcpy(&objc_ivar_list, p, left);
4738 }
4739 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4740 swapStruct(objc_ivar_list);
4741 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4742 ivar_list = p + sizeof(struct objc_ivar_list_t);
4743 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4744 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4745 outs() << "\t\t remaining ivar's extend past the of the section\n";
4746 break;
4747 }
4748 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4749 sizeof(struct objc_ivar_t));
4750 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4751 swapStruct(ivar);
4752
4753 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4754 if (info->verbose) {
4755 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4756 if (name != nullptr)
4757 outs() << format(" %.*s", xleft, name);
4758 else
4759 outs() << " (not in an __OBJC section)";
4760 }
4761 outs() << "\n";
4762
4763 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4764 if (info->verbose) {
4765 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4766 if (name != nullptr)
4767 outs() << format(" %.*s", xleft, name);
4768 else
4769 outs() << " (not in an __OBJC section)";
4770 }
4771 outs() << "\n";
4772
4773 outs() << "\t\t ivar_offset "
4774 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4775 }
4776 } else {
4777 outs() << " (not in an __OBJC section)\n";
4778 }
4779
4780 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4781 if (print_method_list(objc_class->methodLists, info))
4782 outs() << " (not in an __OBJC section)\n";
4783
4784 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4785 << "\n";
4786
4787 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4788 if (print_protocol_list(objc_class->protocols, 16, info))
4789 outs() << " (not in an __OBJC section)\n";
4790}
4791
4792static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4793 struct DisassembleInfo *info) {
4794 uint32_t offset, left;
4795 const char *name;
4796 SectionRef S;
4797
4798 outs() << "\t category name "
4799 << format("0x%08" PRIx32, objc_category->category_name);
4800 if (info->verbose) {
4801 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4802 true);
4803 if (name != nullptr)
4804 outs() << format(" %.*s", left, name);
4805 else
4806 outs() << " (not in an __OBJC section)";
4807 }
4808 outs() << "\n";
4809
4810 outs() << "\t\t class name "
4811 << format("0x%08" PRIx32, objc_category->class_name);
4812 if (info->verbose) {
4813 name =
4814 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4815 if (name != nullptr)
4816 outs() << format(" %.*s", left, name);
4817 else
4818 outs() << " (not in an __OBJC section)";
4819 }
4820 outs() << "\n";
4821
4822 outs() << "\t instance methods "
4823 << format("0x%08" PRIx32, objc_category->instance_methods);
4824 if (print_method_list(objc_category->instance_methods, info))
4825 outs() << " (not in an __OBJC section)\n";
4826
4827 outs() << "\t class methods "
4828 << format("0x%08" PRIx32, objc_category->class_methods);
4829 if (print_method_list(objc_category->class_methods, info))
4830 outs() << " (not in an __OBJC section)\n";
4831}
4832
Kevin Enderby0fc11822015-04-01 20:57:01 +00004833static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4834 struct category64_t c;
4835 const char *r;
4836 uint32_t offset, xoffset, left;
4837 SectionRef S, xS;
4838 const char *name, *sym_name;
4839 uint64_t n_value;
4840
4841 r = get_pointer_64(p, offset, left, S, info);
4842 if (r == nullptr)
4843 return;
4844 memset(&c, '\0', sizeof(struct category64_t));
4845 if (left < sizeof(struct category64_t)) {
4846 memcpy(&c, r, left);
4847 outs() << " (category_t entends past the end of the section)\n";
4848 } else
4849 memcpy(&c, r, sizeof(struct category64_t));
4850 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4851 swapStruct(c);
4852
4853 outs() << " name ";
4854 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4855 info, n_value, c.name);
4856 if (n_value != 0) {
4857 if (info->verbose && sym_name != nullptr)
4858 outs() << sym_name;
4859 else
4860 outs() << format("0x%" PRIx64, n_value);
4861 if (c.name != 0)
4862 outs() << " + " << format("0x%" PRIx64, c.name);
4863 } else
4864 outs() << format("0x%" PRIx64, c.name);
4865 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4866 if (name != nullptr)
4867 outs() << format(" %.*s", left, name);
4868 outs() << "\n";
4869
4870 outs() << " cls ";
4871 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4872 n_value, c.cls);
4873 if (n_value != 0) {
4874 if (info->verbose && sym_name != nullptr)
4875 outs() << sym_name;
4876 else
4877 outs() << format("0x%" PRIx64, n_value);
4878 if (c.cls != 0)
4879 outs() << " + " << format("0x%" PRIx64, c.cls);
4880 } else
4881 outs() << format("0x%" PRIx64, c.cls);
4882 outs() << "\n";
4883 if (c.cls + n_value != 0)
4884 print_class64_t(c.cls + n_value, info);
4885
4886 outs() << " instanceMethods ";
4887 sym_name =
4888 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4889 info, n_value, c.instanceMethods);
4890 if (n_value != 0) {
4891 if (info->verbose && sym_name != nullptr)
4892 outs() << sym_name;
4893 else
4894 outs() << format("0x%" PRIx64, n_value);
4895 if (c.instanceMethods != 0)
4896 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4897 } else
4898 outs() << format("0x%" PRIx64, c.instanceMethods);
4899 outs() << "\n";
4900 if (c.instanceMethods + n_value != 0)
4901 print_method_list64_t(c.instanceMethods + n_value, info, "");
4902
4903 outs() << " classMethods ";
4904 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4905 S, info, n_value, c.classMethods);
4906 if (n_value != 0) {
4907 if (info->verbose && sym_name != nullptr)
4908 outs() << sym_name;
4909 else
4910 outs() << format("0x%" PRIx64, n_value);
4911 if (c.classMethods != 0)
4912 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4913 } else
4914 outs() << format("0x%" PRIx64, c.classMethods);
4915 outs() << "\n";
4916 if (c.classMethods + n_value != 0)
4917 print_method_list64_t(c.classMethods + n_value, info, "");
4918
4919 outs() << " protocols ";
4920 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4921 info, n_value, c.protocols);
4922 if (n_value != 0) {
4923 if (info->verbose && sym_name != nullptr)
4924 outs() << sym_name;
4925 else
4926 outs() << format("0x%" PRIx64, n_value);
4927 if (c.protocols != 0)
4928 outs() << " + " << format("0x%" PRIx64, c.protocols);
4929 } else
4930 outs() << format("0x%" PRIx64, c.protocols);
4931 outs() << "\n";
4932 if (c.protocols + n_value != 0)
4933 print_protocol_list64_t(c.protocols + n_value, info);
4934
4935 outs() << "instanceProperties ";
4936 sym_name =
4937 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4938 S, info, n_value, c.instanceProperties);
4939 if (n_value != 0) {
4940 if (info->verbose && sym_name != nullptr)
4941 outs() << sym_name;
4942 else
4943 outs() << format("0x%" PRIx64, n_value);
4944 if (c.instanceProperties != 0)
4945 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4946 } else
4947 outs() << format("0x%" PRIx64, c.instanceProperties);
4948 outs() << "\n";
4949 if (c.instanceProperties + n_value != 0)
4950 print_objc_property_list64(c.instanceProperties + n_value, info);
4951}
4952
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004953static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4954 struct category32_t c;
4955 const char *r;
4956 uint32_t offset, left;
4957 SectionRef S, xS;
4958 const char *name;
4959
4960 r = get_pointer_32(p, offset, left, S, info);
4961 if (r == nullptr)
4962 return;
4963 memset(&c, '\0', sizeof(struct category32_t));
4964 if (left < sizeof(struct category32_t)) {
4965 memcpy(&c, r, left);
4966 outs() << " (category_t entends past the end of the section)\n";
4967 } else
4968 memcpy(&c, r, sizeof(struct category32_t));
4969 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4970 swapStruct(c);
4971
4972 outs() << " name " << format("0x%" PRIx32, c.name);
4973 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4974 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004975 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004976 outs() << " " << name;
4977 outs() << "\n";
4978
4979 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4980 if (c.cls != 0)
4981 print_class32_t(c.cls, info);
4982 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4983 << "\n";
4984 if (c.instanceMethods != 0)
4985 print_method_list32_t(c.instanceMethods, info, "");
4986 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4987 << "\n";
4988 if (c.classMethods != 0)
4989 print_method_list32_t(c.classMethods, info, "");
4990 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4991 if (c.protocols != 0)
4992 print_protocol_list32_t(c.protocols, info);
4993 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4994 << "\n";
4995 if (c.instanceProperties != 0)
4996 print_objc_property_list32(c.instanceProperties, info);
4997}
4998
Kevin Enderby0fc11822015-04-01 20:57:01 +00004999static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5000 uint32_t i, left, offset, xoffset;
5001 uint64_t p, n_value;
5002 struct message_ref64 mr;
5003 const char *name, *sym_name;
5004 const char *r;
5005 SectionRef xS;
5006
5007 if (S == SectionRef())
5008 return;
5009
5010 StringRef SectName;
5011 S.getName(SectName);
5012 DataRefImpl Ref = S.getRawDataRefImpl();
5013 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5014 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5015 offset = 0;
5016 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5017 p = S.getAddress() + i;
5018 r = get_pointer_64(p, offset, left, S, info);
5019 if (r == nullptr)
5020 return;
5021 memset(&mr, '\0', sizeof(struct message_ref64));
5022 if (left < sizeof(struct message_ref64)) {
5023 memcpy(&mr, r, left);
5024 outs() << " (message_ref entends past the end of the section)\n";
5025 } else
5026 memcpy(&mr, r, sizeof(struct message_ref64));
5027 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5028 swapStruct(mr);
5029
5030 outs() << " imp ";
5031 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5032 n_value, mr.imp);
5033 if (n_value != 0) {
5034 outs() << format("0x%" PRIx64, n_value) << " ";
5035 if (mr.imp != 0)
5036 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5037 } else
5038 outs() << format("0x%" PRIx64, mr.imp) << " ";
5039 if (name != nullptr)
5040 outs() << " " << name;
5041 outs() << "\n";
5042
5043 outs() << " sel ";
5044 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5045 info, n_value, mr.sel);
5046 if (n_value != 0) {
5047 if (info->verbose && sym_name != nullptr)
5048 outs() << sym_name;
5049 else
5050 outs() << format("0x%" PRIx64, n_value);
5051 if (mr.sel != 0)
5052 outs() << " + " << format("0x%" PRIx64, mr.sel);
5053 } else
5054 outs() << format("0x%" PRIx64, mr.sel);
5055 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5056 if (name != nullptr)
5057 outs() << format(" %.*s", left, name);
5058 outs() << "\n";
5059
5060 offset += sizeof(struct message_ref64);
5061 }
5062}
5063
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005064static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5065 uint32_t i, left, offset, xoffset, p;
5066 struct message_ref32 mr;
5067 const char *name, *r;
5068 SectionRef xS;
5069
5070 if (S == SectionRef())
5071 return;
5072
5073 StringRef SectName;
5074 S.getName(SectName);
5075 DataRefImpl Ref = S.getRawDataRefImpl();
5076 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5077 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5078 offset = 0;
5079 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5080 p = S.getAddress() + i;
5081 r = get_pointer_32(p, offset, left, S, info);
5082 if (r == nullptr)
5083 return;
5084 memset(&mr, '\0', sizeof(struct message_ref32));
5085 if (left < sizeof(struct message_ref32)) {
5086 memcpy(&mr, r, left);
5087 outs() << " (message_ref entends past the end of the section)\n";
5088 } else
5089 memcpy(&mr, r, sizeof(struct message_ref32));
5090 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5091 swapStruct(mr);
5092
5093 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5094 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5095 mr.imp);
5096 if (name != nullptr)
5097 outs() << " " << name;
5098 outs() << "\n";
5099
5100 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5101 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5102 if (name != nullptr)
5103 outs() << " " << name;
5104 outs() << "\n";
5105
5106 offset += sizeof(struct message_ref32);
5107 }
5108}
5109
Kevin Enderby0fc11822015-04-01 20:57:01 +00005110static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5111 uint32_t left, offset, swift_version;
5112 uint64_t p;
5113 struct objc_image_info64 o;
5114 const char *r;
5115
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005116 if (S == SectionRef())
5117 return;
5118
Kevin Enderby0fc11822015-04-01 20:57:01 +00005119 StringRef SectName;
5120 S.getName(SectName);
5121 DataRefImpl Ref = S.getRawDataRefImpl();
5122 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5123 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5124 p = S.getAddress();
5125 r = get_pointer_64(p, offset, left, S, info);
5126 if (r == nullptr)
5127 return;
5128 memset(&o, '\0', sizeof(struct objc_image_info64));
5129 if (left < sizeof(struct objc_image_info64)) {
5130 memcpy(&o, r, left);
5131 outs() << " (objc_image_info entends past the end of the section)\n";
5132 } else
5133 memcpy(&o, r, sizeof(struct objc_image_info64));
5134 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5135 swapStruct(o);
5136 outs() << " version " << o.version << "\n";
5137 outs() << " flags " << format("0x%" PRIx32, o.flags);
5138 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5139 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5140 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5141 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5142 swift_version = (o.flags >> 8) & 0xff;
5143 if (swift_version != 0) {
5144 if (swift_version == 1)
5145 outs() << " Swift 1.0";
5146 else if (swift_version == 2)
5147 outs() << " Swift 1.1";
5148 else
5149 outs() << " unknown future Swift version (" << swift_version << ")";
5150 }
5151 outs() << "\n";
5152}
5153
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005154static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5155 uint32_t left, offset, swift_version, p;
5156 struct objc_image_info32 o;
5157 const char *r;
5158
Kevin Enderby19be2512016-04-21 19:49:29 +00005159 if (S == SectionRef())
5160 return;
5161
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005162 StringRef SectName;
5163 S.getName(SectName);
5164 DataRefImpl Ref = S.getRawDataRefImpl();
5165 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5166 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5167 p = S.getAddress();
5168 r = get_pointer_32(p, offset, left, S, info);
5169 if (r == nullptr)
5170 return;
5171 memset(&o, '\0', sizeof(struct objc_image_info32));
5172 if (left < sizeof(struct objc_image_info32)) {
5173 memcpy(&o, r, left);
5174 outs() << " (objc_image_info entends past the end of the section)\n";
5175 } else
5176 memcpy(&o, r, sizeof(struct objc_image_info32));
5177 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5178 swapStruct(o);
5179 outs() << " version " << o.version << "\n";
5180 outs() << " flags " << format("0x%" PRIx32, o.flags);
5181 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5182 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5183 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5184 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5185 swift_version = (o.flags >> 8) & 0xff;
5186 if (swift_version != 0) {
5187 if (swift_version == 1)
5188 outs() << " Swift 1.0";
5189 else if (swift_version == 2)
5190 outs() << " Swift 1.1";
5191 else
5192 outs() << " unknown future Swift version (" << swift_version << ")";
5193 }
5194 outs() << "\n";
5195}
5196
Kevin Enderby846c0002015-04-16 17:19:59 +00005197static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5198 uint32_t left, offset, p;
5199 struct imageInfo_t o;
5200 const char *r;
5201
5202 StringRef SectName;
5203 S.getName(SectName);
5204 DataRefImpl Ref = S.getRawDataRefImpl();
5205 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5206 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5207 p = S.getAddress();
5208 r = get_pointer_32(p, offset, left, S, info);
5209 if (r == nullptr)
5210 return;
5211 memset(&o, '\0', sizeof(struct imageInfo_t));
5212 if (left < sizeof(struct imageInfo_t)) {
5213 memcpy(&o, r, left);
5214 outs() << " (imageInfo entends past the end of the section)\n";
5215 } else
5216 memcpy(&o, r, sizeof(struct imageInfo_t));
5217 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5218 swapStruct(o);
5219 outs() << " version " << o.version << "\n";
5220 outs() << " flags " << format("0x%" PRIx32, o.flags);
5221 if (o.flags & 0x1)
5222 outs() << " F&C";
5223 if (o.flags & 0x2)
5224 outs() << " GC";
5225 if (o.flags & 0x4)
5226 outs() << " GC-only";
5227 else
5228 outs() << " RR";
5229 outs() << "\n";
5230}
5231
Kevin Enderby0fc11822015-04-01 20:57:01 +00005232static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5233 SymbolAddressMap AddrMap;
5234 if (verbose)
5235 CreateSymbolAddressMap(O, &AddrMap);
5236
5237 std::vector<SectionRef> Sections;
5238 for (const SectionRef &Section : O->sections()) {
5239 StringRef SectName;
5240 Section.getName(SectName);
5241 Sections.push_back(Section);
5242 }
5243
5244 struct DisassembleInfo info;
5245 // Set up the block of info used by the Symbolizer call backs.
5246 info.verbose = verbose;
5247 info.O = O;
5248 info.AddrMap = &AddrMap;
5249 info.Sections = &Sections;
5250 info.class_name = nullptr;
5251 info.selector_name = nullptr;
5252 info.method = nullptr;
5253 info.demangled_name = nullptr;
5254 info.bindtable = nullptr;
5255 info.adrp_addr = 0;
5256 info.adrp_inst = 0;
5257
Kevin Enderbyaac75382015-10-08 16:56:35 +00005258 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005259 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5260 if (CL == SectionRef())
5261 CL = get_section(O, "__DATA", "__objc_classlist");
5262 info.S = CL;
5263 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005264
Davide Italiano62507042015-12-11 22:27:59 +00005265 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5266 if (CR == SectionRef())
5267 CR = get_section(O, "__DATA", "__objc_classrefs");
5268 info.S = CR;
5269 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005270
Davide Italiano62507042015-12-11 22:27:59 +00005271 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5272 if (SR == SectionRef())
5273 SR = get_section(O, "__DATA", "__objc_superrefs");
5274 info.S = SR;
5275 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005276
Davide Italiano62507042015-12-11 22:27:59 +00005277 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5278 if (CA == SectionRef())
5279 CA = get_section(O, "__DATA", "__objc_catlist");
5280 info.S = CA;
5281 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005282
Davide Italiano62507042015-12-11 22:27:59 +00005283 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5284 if (PL == SectionRef())
5285 PL = get_section(O, "__DATA", "__objc_protolist");
5286 info.S = PL;
5287 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005288
Davide Italiano62507042015-12-11 22:27:59 +00005289 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5290 if (MR == SectionRef())
5291 MR = get_section(O, "__DATA", "__objc_msgrefs");
5292 info.S = MR;
5293 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005294
Davide Italiano62507042015-12-11 22:27:59 +00005295 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5296 if (II == SectionRef())
5297 II = get_section(O, "__DATA", "__objc_imageinfo");
5298 info.S = II;
5299 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005300
5301 if (info.bindtable != nullptr)
5302 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005303}
5304
5305static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005306 SymbolAddressMap AddrMap;
5307 if (verbose)
5308 CreateSymbolAddressMap(O, &AddrMap);
5309
5310 std::vector<SectionRef> Sections;
5311 for (const SectionRef &Section : O->sections()) {
5312 StringRef SectName;
5313 Section.getName(SectName);
5314 Sections.push_back(Section);
5315 }
5316
5317 struct DisassembleInfo info;
5318 // Set up the block of info used by the Symbolizer call backs.
5319 info.verbose = verbose;
5320 info.O = O;
5321 info.AddrMap = &AddrMap;
5322 info.Sections = &Sections;
5323 info.class_name = nullptr;
5324 info.selector_name = nullptr;
5325 info.method = nullptr;
5326 info.demangled_name = nullptr;
5327 info.bindtable = nullptr;
5328 info.adrp_addr = 0;
5329 info.adrp_inst = 0;
5330
5331 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5332 if (CL != SectionRef()) {
5333 info.S = CL;
5334 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5335 } else {
5336 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5337 info.S = CL;
5338 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5339 }
5340
5341 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5342 if (CR != SectionRef()) {
5343 info.S = CR;
5344 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5345 } else {
5346 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5347 info.S = CR;
5348 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5349 }
5350
5351 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5352 if (SR != SectionRef()) {
5353 info.S = SR;
5354 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5355 } else {
5356 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5357 info.S = SR;
5358 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5359 }
5360
5361 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5362 if (CA != SectionRef()) {
5363 info.S = CA;
5364 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5365 } else {
5366 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5367 info.S = CA;
5368 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5369 }
5370
5371 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5372 if (PL != SectionRef()) {
5373 info.S = PL;
5374 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5375 } else {
5376 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5377 info.S = PL;
5378 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5379 }
5380
5381 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5382 if (MR != SectionRef()) {
5383 info.S = MR;
5384 print_message_refs32(MR, &info);
5385 } else {
5386 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5387 info.S = MR;
5388 print_message_refs32(MR, &info);
5389 }
5390
5391 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5392 if (II != SectionRef()) {
5393 info.S = II;
5394 print_image_info32(II, &info);
5395 } else {
5396 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5397 info.S = II;
5398 print_image_info32(II, &info);
5399 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005400}
5401
5402static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005403 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5404 const char *r, *name, *defs;
5405 struct objc_module_t module;
5406 SectionRef S, xS;
5407 struct objc_symtab_t symtab;
5408 struct objc_class_t objc_class;
5409 struct objc_category_t objc_category;
5410
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005411 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005412 S = get_section(O, "__OBJC", "__module_info");
5413 if (S == SectionRef())
5414 return false;
5415
5416 SymbolAddressMap AddrMap;
5417 if (verbose)
5418 CreateSymbolAddressMap(O, &AddrMap);
5419
5420 std::vector<SectionRef> Sections;
5421 for (const SectionRef &Section : O->sections()) {
5422 StringRef SectName;
5423 Section.getName(SectName);
5424 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005425 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005426
5427 struct DisassembleInfo info;
5428 // Set up the block of info used by the Symbolizer call backs.
5429 info.verbose = verbose;
5430 info.O = O;
5431 info.AddrMap = &AddrMap;
5432 info.Sections = &Sections;
5433 info.class_name = nullptr;
5434 info.selector_name = nullptr;
5435 info.method = nullptr;
5436 info.demangled_name = nullptr;
5437 info.bindtable = nullptr;
5438 info.adrp_addr = 0;
5439 info.adrp_inst = 0;
5440
5441 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5442 p = S.getAddress() + i;
5443 r = get_pointer_32(p, offset, left, S, &info, true);
5444 if (r == nullptr)
5445 return true;
5446 memset(&module, '\0', sizeof(struct objc_module_t));
5447 if (left < sizeof(struct objc_module_t)) {
5448 memcpy(&module, r, left);
5449 outs() << " (module extends past end of __module_info section)\n";
5450 } else
5451 memcpy(&module, r, sizeof(struct objc_module_t));
5452 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5453 swapStruct(module);
5454
5455 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5456 outs() << " version " << module.version << "\n";
5457 outs() << " size " << module.size << "\n";
5458 outs() << " name ";
5459 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5460 if (name != nullptr)
5461 outs() << format("%.*s", left, name);
5462 else
5463 outs() << format("0x%08" PRIx32, module.name)
5464 << "(not in an __OBJC section)";
5465 outs() << "\n";
5466
5467 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5468 if (module.symtab == 0 || r == nullptr) {
5469 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5470 << " (not in an __OBJC section)\n";
5471 continue;
5472 }
5473 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5474 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5475 defs_left = 0;
5476 defs = nullptr;
5477 if (left < sizeof(struct objc_symtab_t)) {
5478 memcpy(&symtab, r, left);
5479 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5480 } else {
5481 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5482 if (left > sizeof(struct objc_symtab_t)) {
5483 defs_left = left - sizeof(struct objc_symtab_t);
5484 defs = r + sizeof(struct objc_symtab_t);
5485 }
5486 }
5487 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5488 swapStruct(symtab);
5489
5490 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5491 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5492 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5493 if (r == nullptr)
5494 outs() << " (not in an __OBJC section)";
5495 outs() << "\n";
5496 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5497 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5498 if (symtab.cls_def_cnt > 0)
5499 outs() << "\tClass Definitions\n";
5500 for (j = 0; j < symtab.cls_def_cnt; j++) {
5501 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5502 outs() << "\t(remaining class defs entries entends past the end of the "
5503 << "section)\n";
5504 break;
5505 }
5506 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5507 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5508 sys::swapByteOrder(def);
5509
5510 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5511 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5512 if (r != nullptr) {
5513 if (left > sizeof(struct objc_class_t)) {
5514 outs() << "\n";
5515 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5516 } else {
5517 outs() << " (entends past the end of the section)\n";
5518 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5519 memcpy(&objc_class, r, left);
5520 }
5521 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5522 swapStruct(objc_class);
5523 print_objc_class_t(&objc_class, &info);
5524 } else {
5525 outs() << "(not in an __OBJC section)\n";
5526 }
5527
5528 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5529 outs() << "\tMeta Class";
5530 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5531 if (r != nullptr) {
5532 if (left > sizeof(struct objc_class_t)) {
5533 outs() << "\n";
5534 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5535 } else {
5536 outs() << " (entends past the end of the section)\n";
5537 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5538 memcpy(&objc_class, r, left);
5539 }
5540 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5541 swapStruct(objc_class);
5542 print_objc_class_t(&objc_class, &info);
5543 } else {
5544 outs() << "(not in an __OBJC section)\n";
5545 }
5546 }
5547 }
5548 if (symtab.cat_def_cnt > 0)
5549 outs() << "\tCategory Definitions\n";
5550 for (j = 0; j < symtab.cat_def_cnt; j++) {
5551 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5552 outs() << "\t(remaining category defs entries entends past the end of "
5553 << "the section)\n";
5554 break;
5555 }
5556 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5557 sizeof(uint32_t));
5558 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5559 sys::swapByteOrder(def);
5560
5561 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5562 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5563 << format("0x%08" PRIx32, def);
5564 if (r != nullptr) {
5565 if (left > sizeof(struct objc_category_t)) {
5566 outs() << "\n";
5567 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5568 } else {
5569 outs() << " (entends past the end of the section)\n";
5570 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5571 memcpy(&objc_category, r, left);
5572 }
5573 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5574 swapStruct(objc_category);
5575 print_objc_objc_category_t(&objc_category, &info);
5576 } else {
5577 outs() << "(not in an __OBJC section)\n";
5578 }
5579 }
5580 }
5581 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5582 if (II != SectionRef())
5583 print_image_info(II, &info);
5584
5585 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005586}
5587
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005588static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5589 uint32_t size, uint32_t addr) {
5590 SymbolAddressMap AddrMap;
5591 CreateSymbolAddressMap(O, &AddrMap);
5592
5593 std::vector<SectionRef> Sections;
5594 for (const SectionRef &Section : O->sections()) {
5595 StringRef SectName;
5596 Section.getName(SectName);
5597 Sections.push_back(Section);
5598 }
5599
5600 struct DisassembleInfo info;
5601 // Set up the block of info used by the Symbolizer call backs.
5602 info.verbose = true;
5603 info.O = O;
5604 info.AddrMap = &AddrMap;
5605 info.Sections = &Sections;
5606 info.class_name = nullptr;
5607 info.selector_name = nullptr;
5608 info.method = nullptr;
5609 info.demangled_name = nullptr;
5610 info.bindtable = nullptr;
5611 info.adrp_addr = 0;
5612 info.adrp_inst = 0;
5613
5614 const char *p;
5615 struct objc_protocol_t protocol;
5616 uint32_t left, paddr;
5617 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5618 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5619 left = size - (p - sect);
5620 if (left < sizeof(struct objc_protocol_t)) {
5621 outs() << "Protocol extends past end of __protocol section\n";
5622 memcpy(&protocol, p, left);
5623 } else
5624 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5625 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5626 swapStruct(protocol);
5627 paddr = addr + (p - sect);
5628 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5629 if (print_protocol(paddr, 0, &info))
5630 outs() << "(not in an __OBJC section)\n";
5631 }
5632}
5633
Kevin Enderby0fc11822015-04-01 20:57:01 +00005634static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
5635 if (O->is64Bit())
5636 printObjc2_64bit_MetaData(O, verbose);
5637 else {
5638 MachO::mach_header H;
5639 H = O->getHeader();
5640 if (H.cputype == MachO::CPU_TYPE_ARM)
5641 printObjc2_32bit_MetaData(O, verbose);
5642 else {
5643 // This is the 32-bit non-arm cputype case. Which is normally
5644 // the first Objective-C ABI. But it may be the case of a
5645 // binary for the iOS simulator which is the second Objective-C
5646 // ABI. In that case printObjc1_32bit_MetaData() will determine that
5647 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005648 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00005649 printObjc2_32bit_MetaData(O, verbose);
5650 }
5651 }
5652}
5653
Kevin Enderbybf246f52014-09-24 23:08:22 +00005654// GuessLiteralPointer returns a string which for the item in the Mach-O file
5655// for the address passed in as ReferenceValue for printing as a comment with
5656// the instruction and also returns the corresponding type of that item
5657// indirectly through ReferenceType.
5658//
5659// If ReferenceValue is an address of literal cstring then a pointer to the
5660// cstring is returned and ReferenceType is set to
5661// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
5662//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005663// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
5664// Class ref that name is returned and the ReferenceType is set accordingly.
5665//
5666// Lastly, literals which are Symbol address in a literal pool are looked for
5667// and if found the symbol name is returned and ReferenceType is set to
5668// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
5669//
5670// If there is no item in the Mach-O file for the address passed in as
5671// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005672static const char *GuessLiteralPointer(uint64_t ReferenceValue,
5673 uint64_t ReferencePC,
5674 uint64_t *ReferenceType,
5675 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005676 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005677 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
5678 uint64_t sect_addr = info->S.getAddress();
5679 uint64_t sect_offset = ReferencePC - sect_addr;
5680 bool reloc_found = false;
5681 DataRefImpl Rel;
5682 MachO::any_relocation_info RE;
5683 bool isExtern = false;
5684 SymbolRef Symbol;
5685 for (const RelocationRef &Reloc : info->S.relocations()) {
5686 uint64_t RelocOffset = Reloc.getOffset();
5687 if (RelocOffset == sect_offset) {
5688 Rel = Reloc.getRawDataRefImpl();
5689 RE = info->O->getRelocation(Rel);
5690 if (info->O->isRelocationScattered(RE))
5691 continue;
5692 isExtern = info->O->getPlainRelocationExternal(RE);
5693 if (isExtern) {
5694 symbol_iterator RelocSym = Reloc.getSymbol();
5695 Symbol = *RelocSym;
5696 }
5697 reloc_found = true;
5698 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005699 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005700 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00005701 // If there is an external relocation entry for a symbol in a section
5702 // then used that symbol's value for the value of the reference.
5703 if (reloc_found && isExtern) {
5704 if (info->O->getAnyRelocationPCRel(RE)) {
5705 unsigned Type = info->O->getAnyRelocationType(RE);
5706 if (Type == MachO::X86_64_RELOC_SIGNED) {
5707 ReferenceValue = Symbol.getValue();
5708 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005709 }
5710 }
5711 }
5712
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005713 // Look for literals such as Objective-C CFStrings refs, Selector refs,
5714 // Message refs and Class refs.
5715 bool classref, selref, msgref, cfstring;
5716 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
5717 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00005718 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005719 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
5720 // And the pointer_value in that section is typically zero as it will be
5721 // set by dyld as part of the "bind information".
5722 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
5723 if (name != nullptr) {
5724 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00005725 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005726 if (class_name != nullptr && class_name[1] == '_' &&
5727 class_name[2] != '\0') {
5728 info->class_name = class_name + 2;
5729 return name;
5730 }
5731 }
5732 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005733
David Blaikie33dd45d02015-03-23 18:39:02 +00005734 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005735 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
5736 const char *name =
5737 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
5738 if (name != nullptr)
5739 info->class_name = name;
5740 else
5741 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00005742 return name;
5743 }
5744
David Blaikie33dd45d02015-03-23 18:39:02 +00005745 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005746 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
5747 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
5748 return name;
5749 }
5750
David Blaikie33dd45d02015-03-23 18:39:02 +00005751 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005752 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
5753
5754 if (pointer_value != 0)
5755 ReferenceValue = pointer_value;
5756
5757 const char *name = GuessCstringPointer(ReferenceValue, info);
5758 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00005759 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005760 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
5761 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00005762 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005763 info->class_name = nullptr;
5764 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
5765 info->selector_name = name;
5766 } else
5767 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
5768 return name;
5769 }
5770
5771 // Lastly look for an indirect symbol with this ReferenceValue which is in
5772 // a literal pool. If found return that symbol name.
5773 name = GuessIndirectSymbol(ReferenceValue, info);
5774 if (name) {
5775 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
5776 return name;
5777 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005778
5779 return nullptr;
5780}
5781
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005782// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00005783// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005784// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
5785// is created and returns the symbol name that matches the ReferenceValue or
5786// nullptr if none. The ReferenceType is passed in for the IN type of
5787// reference the instruction is making from the values in defined in the header
5788// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
5789// Out type and the ReferenceName will also be set which is added as a comment
5790// to the disassembled instruction.
5791//
Kevin Enderby04bf6932014-10-28 23:39:46 +00005792#if HAVE_CXXABI_H
5793// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005794// returned through ReferenceName and ReferenceType is set to
5795// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00005796#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005797//
5798// When this is called to get a symbol name for a branch target then the
5799// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
5800// SymbolValue will be looked for in the indirect symbol table to determine if
5801// it is an address for a symbol stub. If so then the symbol name for that
5802// stub is returned indirectly through ReferenceName and then ReferenceType is
5803// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
5804//
Kevin Enderbybf246f52014-09-24 23:08:22 +00005805// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005806// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
5807// SymbolValue is checked to be an address of literal pointer, symbol pointer,
5808// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005809// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00005810static const char *SymbolizerSymbolLookUp(void *DisInfo,
5811 uint64_t ReferenceValue,
5812 uint64_t *ReferenceType,
5813 uint64_t ReferencePC,
5814 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005815 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00005816 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00005817 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005818 *ReferenceName = nullptr;
5819 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005820 return nullptr;
5821 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00005822
Kevin Enderbyf6d25852015-01-31 00:37:11 +00005823 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00005824
Kevin Enderby85974882014-09-26 22:20:44 +00005825 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
5826 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005827 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005828 method_reference(info, ReferenceType, ReferenceName);
5829 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
5830 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
5831 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00005832#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005833 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00005834 if (info->demangled_name != nullptr)
5835 free(info->demangled_name);
5836 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005837 info->demangled_name =
5838 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005839 if (info->demangled_name != nullptr) {
5840 *ReferenceName = info->demangled_name;
5841 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5842 } else
5843 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5844 } else
5845#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005846 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5847 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
5848 *ReferenceName =
5849 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00005850 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005851 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00005852 else
5853 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005854 // If this is arm64 and the reference is an adrp instruction save the
5855 // instruction, passed in ReferenceValue and the address of the instruction
5856 // for use later if we see and add immediate instruction.
5857 } else if (info->O->getArch() == Triple::aarch64 &&
5858 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
5859 info->adrp_inst = ReferenceValue;
5860 info->adrp_addr = ReferencePC;
5861 SymbolName = nullptr;
5862 *ReferenceName = nullptr;
5863 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5864 // If this is arm64 and reference is an add immediate instruction and we
5865 // have
5866 // seen an adrp instruction just before it and the adrp's Xd register
5867 // matches
5868 // this add's Xn register reconstruct the value being referenced and look to
5869 // see if it is a literal pointer. Note the add immediate instruction is
5870 // passed in ReferenceValue.
5871 } else if (info->O->getArch() == Triple::aarch64 &&
5872 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
5873 ReferencePC - 4 == info->adrp_addr &&
5874 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5875 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5876 uint32_t addxri_inst;
5877 uint64_t adrp_imm, addxri_imm;
5878
5879 adrp_imm =
5880 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5881 if (info->adrp_inst & 0x0200000)
5882 adrp_imm |= 0xfffffffffc000000LL;
5883
5884 addxri_inst = ReferenceValue;
5885 addxri_imm = (addxri_inst >> 10) & 0xfff;
5886 if (((addxri_inst >> 22) & 0x3) == 1)
5887 addxri_imm <<= 12;
5888
5889 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5890 (adrp_imm << 12) + addxri_imm;
5891
5892 *ReferenceName =
5893 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5894 if (*ReferenceName == nullptr)
5895 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5896 // If this is arm64 and the reference is a load register instruction and we
5897 // have seen an adrp instruction just before it and the adrp's Xd register
5898 // matches this add's Xn register reconstruct the value being referenced and
5899 // look to see if it is a literal pointer. Note the load register
5900 // instruction is passed in ReferenceValue.
5901 } else if (info->O->getArch() == Triple::aarch64 &&
5902 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
5903 ReferencePC - 4 == info->adrp_addr &&
5904 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
5905 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
5906 uint32_t ldrxui_inst;
5907 uint64_t adrp_imm, ldrxui_imm;
5908
5909 adrp_imm =
5910 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
5911 if (info->adrp_inst & 0x0200000)
5912 adrp_imm |= 0xfffffffffc000000LL;
5913
5914 ldrxui_inst = ReferenceValue;
5915 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
5916
5917 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
5918 (adrp_imm << 12) + (ldrxui_imm << 3);
5919
5920 *ReferenceName =
5921 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5922 if (*ReferenceName == nullptr)
5923 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5924 }
5925 // If this arm64 and is an load register (PC-relative) instruction the
5926 // ReferenceValue is the PC plus the immediate value.
5927 else if (info->O->getArch() == Triple::aarch64 &&
5928 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
5929 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
5930 *ReferenceName =
5931 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
5932 if (*ReferenceName == nullptr)
5933 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00005934 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00005935#if HAVE_CXXABI_H
5936 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
5937 if (info->demangled_name != nullptr)
5938 free(info->demangled_name);
5939 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005940 info->demangled_name =
5941 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00005942 if (info->demangled_name != nullptr) {
5943 *ReferenceName = info->demangled_name;
5944 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
5945 }
5946 }
5947#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005948 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00005949 *ReferenceName = nullptr;
5950 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
5951 }
5952
5953 return SymbolName;
5954}
5955
Kevin Enderbybf246f52014-09-24 23:08:22 +00005956/// \brief Emits the comments that are stored in the CommentStream.
5957/// Each comment in the CommentStream must end with a newline.
5958static void emitComments(raw_svector_ostream &CommentStream,
5959 SmallString<128> &CommentsToEmit,
5960 formatted_raw_ostream &FormattedOS,
5961 const MCAsmInfo &MAI) {
5962 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00005963 StringRef Comments = CommentsToEmit.str();
5964 // Get the default information for printing a comment.
5965 const char *CommentBegin = MAI.getCommentString();
5966 unsigned CommentColumn = MAI.getCommentColumn();
5967 bool IsFirst = true;
5968 while (!Comments.empty()) {
5969 if (!IsFirst)
5970 FormattedOS << '\n';
5971 // Emit a line of comments.
5972 FormattedOS.PadToColumn(CommentColumn);
5973 size_t Position = Comments.find('\n');
5974 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
5975 // Move after the newline character.
5976 Comments = Comments.substr(Position + 1);
5977 IsFirst = false;
5978 }
5979 FormattedOS.flush();
5980
5981 // Tell the comment stream that the vector changed underneath it.
5982 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00005983}
5984
Kevin Enderby95df54c2015-02-04 01:01:38 +00005985static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
5986 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005987 const char *McpuDefault = nullptr;
5988 const Target *ThumbTarget = nullptr;
5989 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00005990 if (!TheTarget) {
5991 // GetTarget prints out stuff.
5992 return;
5993 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005994 if (MCPU.empty() && McpuDefault)
5995 MCPU = McpuDefault;
5996
Ahmed Charles56440fd2014-03-06 05:51:42 +00005997 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00005998 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00005999 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006000 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006001
Kevin Enderbyc9595622014-08-06 23:24:41 +00006002 // Package up features to be passed to target/subtarget
6003 std::string FeaturesStr;
6004 if (MAttrs.size()) {
6005 SubtargetFeatures Features;
6006 for (unsigned i = 0; i != MAttrs.size(); ++i)
6007 Features.AddFeature(MAttrs[i]);
6008 FeaturesStr = Features.getString();
6009 }
6010
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006011 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006012 std::unique_ptr<const MCRegisterInfo> MRI(
6013 TheTarget->createMCRegInfo(TripleName));
6014 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006015 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006016 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006017 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006018 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006019 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006020 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006021 std::unique_ptr<MCSymbolizer> Symbolizer;
6022 struct DisassembleInfo SymbolizerInfo;
6023 std::unique_ptr<MCRelocationInfo> RelInfo(
6024 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6025 if (RelInfo) {
6026 Symbolizer.reset(TheTarget->createMCSymbolizer(
6027 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006028 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006029 DisAsm->setSymbolizer(std::move(Symbolizer));
6030 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006031 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006032 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006033 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006034 // Set the display preference for hex vs. decimal immediates.
6035 IP->setPrintImmHex(PrintImmHex);
6036 // Comment stream and backing vector.
6037 SmallString<128> CommentsToEmit;
6038 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006039 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6040 // if it is done then arm64 comments for string literals don't get printed
6041 // and some constant get printed instead and not setting it causes intel
6042 // (32-bit and 64-bit) comments printed with different spacing before the
6043 // comment causing different diffs with the 'C' disassembler library API.
6044 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006045
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006046 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006047 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006048 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006049 return;
6050 }
6051
Tim Northover09ca33e2016-04-22 23:23:31 +00006052 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006053 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6054 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6055 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006056 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006057 std::unique_ptr<MCInstPrinter> ThumbIP;
6058 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006059 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6060 struct DisassembleInfo ThumbSymbolizerInfo;
6061 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006062 if (ThumbTarget) {
6063 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6064 ThumbAsmInfo.reset(
6065 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6066 ThumbSTI.reset(
6067 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6068 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6069 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006070 MCContext *PtrThumbCtx = ThumbCtx.get();
6071 ThumbRelInfo.reset(
6072 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6073 if (ThumbRelInfo) {
6074 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6075 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006076 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006077 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6078 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006079 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6080 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006081 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6082 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006083 // Set the display preference for hex vs. decimal immediates.
6084 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006085 }
6086
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006087 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006088 errs() << "error: couldn't initialize disassembler for target "
6089 << ThumbTripleName << '\n';
6090 return;
6091 }
6092
Charles Davis8bdfafd2013-09-01 04:28:48 +00006093 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006094
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006095 // FIXME: Using the -cfg command line option, this code used to be able to
6096 // annotate relocations with the referenced symbol's name, and if this was
6097 // inside a __[cf]string section, the data it points to. This is now replaced
6098 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006099 std::vector<SectionRef> Sections;
6100 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006101 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006102 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006103
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006104 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006105 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006106
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006107 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006108 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006109
Kevin Enderby273ae012013-06-06 17:20:50 +00006110 // Build a data in code table that is sorted on by the address of each entry.
6111 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006112 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006113 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006114 else
6115 BaseAddress = BaseSegmentAddress;
6116 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006117 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006118 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006119 uint32_t Offset;
6120 DI->getOffset(Offset);
6121 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6122 }
6123 array_pod_sort(Dices.begin(), Dices.end());
6124
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006125#ifndef NDEBUG
6126 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6127#else
6128 raw_ostream &DebugOut = nulls();
6129#endif
6130
Ahmed Charles56440fd2014-03-06 05:51:42 +00006131 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006132 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006133 // Try to find debug info and set up the DIContext for it.
6134 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006135 // A separate DSym file path was specified, parse it as a macho file,
6136 // get the sections and supply it to the section name parsing machinery.
6137 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006138 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006139 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006140 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006141 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006142 return;
6143 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006144 DbgObj =
6145 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6146 .get()
6147 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006148 }
6149
Eric Christopher7370b552012-11-12 21:40:38 +00006150 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006151 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006152 }
6153
Colin LeMahieufcc32762015-07-29 19:08:10 +00006154 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006155 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006156
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006157 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006158 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006159 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6160 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006161
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006162 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006163
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006164 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006165 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006166 continue;
6167
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006168 StringRef BytesStr;
6169 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006170 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6171 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006172 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006173
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006174 bool symbolTableWorked = false;
6175
Kevin Enderbybf246f52014-09-24 23:08:22 +00006176 // Create a map of symbol addresses to symbol names for use by
6177 // the SymbolizerSymbolLookUp() routine.
6178 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006179 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006180 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006181 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6182 if (!STOrErr) {
6183 std::string Buf;
6184 raw_string_ostream OS(Buf);
6185 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6186 OS.flush();
6187 report_fatal_error(Buf);
6188 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006189 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006190 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6191 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006192 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006193 Expected<StringRef> SymNameOrErr = Symbol.getName();
6194 if (!SymNameOrErr) {
6195 std::string Buf;
6196 raw_string_ostream OS(Buf);
6197 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6198 OS.flush();
6199 report_fatal_error(Buf);
6200 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006201 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006202 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006203 if (!DisSymName.empty() && DisSymName == SymName)
6204 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006205 }
6206 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006207 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006208 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6209 return;
6210 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006211 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006212 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006213 SymbolizerInfo.O = MachOOF;
6214 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006215 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006216 SymbolizerInfo.Sections = &Sections;
6217 SymbolizerInfo.class_name = nullptr;
6218 SymbolizerInfo.selector_name = nullptr;
6219 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006220 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006221 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006222 SymbolizerInfo.adrp_addr = 0;
6223 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006224 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006225 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006226 ThumbSymbolizerInfo.O = MachOOF;
6227 ThumbSymbolizerInfo.S = Sections[SectIdx];
6228 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6229 ThumbSymbolizerInfo.Sections = &Sections;
6230 ThumbSymbolizerInfo.class_name = nullptr;
6231 ThumbSymbolizerInfo.selector_name = nullptr;
6232 ThumbSymbolizerInfo.method = nullptr;
6233 ThumbSymbolizerInfo.demangled_name = nullptr;
6234 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006235 ThumbSymbolizerInfo.adrp_addr = 0;
6236 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006237
Kevin Enderby4b627be2016-04-28 20:14:13 +00006238 unsigned int Arch = MachOOF->getArch();
6239
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006240 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006241 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006242 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6243 if (!SymNameOrErr) {
6244 std::string Buf;
6245 raw_string_ostream OS(Buf);
6246 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6247 OS.flush();
6248 report_fatal_error(Buf);
6249 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006250 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006251
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006252 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6253 if (!STOrErr) {
6254 std::string Buf;
6255 raw_string_ostream OS(Buf);
6256 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6257 OS.flush();
6258 report_fatal_error(Buf);
6259 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006260 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006261 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006262 continue;
6263
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006264 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006265 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00006266 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006267 continue;
6268
Kevin Enderby6a221752015-03-17 17:10:57 +00006269 // If we are only disassembling one symbol see if this is that symbol.
6270 if (!DisSymName.empty() && DisSymName != SymName)
6271 continue;
6272
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006273 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006274 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006275 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006276 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006277
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006278 // Stop disassembling either at the beginning of the next symbol or at
6279 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006280 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006281 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006282 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006283 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006284 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6285 if (!STOrErr) {
6286 std::string Buf;
6287 raw_string_ostream OS(Buf);
6288 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6289 OS.flush();
6290 report_fatal_error(Buf);
6291 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006292 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006293 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006294 containsNextSym =
6295 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006296 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006297 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006298 break;
6299 }
6300 ++NextSymIdx;
6301 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006302
Rafael Espindola80291272014-10-08 15:28:58 +00006303 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006304 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006305 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006306
6307 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006308
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006309 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006310 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6311
6312 // We only need the dedicated Thumb target if there's a real choice
6313 // (i.e. we're not targeting M-class) and the function is Thumb.
6314 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006315
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006316 outs() << SymName << ":\n";
6317 DILineInfo lastLine;
6318 for (uint64_t Index = Start; Index < End; Index += Size) {
6319 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006320
Kevin Enderbybf246f52014-09-24 23:08:22 +00006321 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006322 if (!NoLeadingAddr) {
6323 if (FullLeadingAddr) {
6324 if (MachOOF->is64Bit())
6325 outs() << format("%016" PRIx64, PC);
6326 else
6327 outs() << format("%08" PRIx64, PC);
6328 } else {
6329 outs() << format("%8" PRIx64 ":", PC);
6330 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006331 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006332 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006333 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006334
6335 // Check the data in code table here to see if this is data not an
6336 // instruction to be disassembled.
6337 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006338 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006339 dice_table_iterator DTI =
6340 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6341 compareDiceTableEntries);
6342 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006343 uint16_t Length;
6344 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006345 uint16_t Kind;
6346 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006347 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006348 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6349 (PC == (DTI->first + Length - 1)) && (Length & 1))
6350 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006351 continue;
6352 }
6353
Kevin Enderbybf246f52014-09-24 23:08:22 +00006354 SmallVector<char, 64> AnnotationsBytes;
6355 raw_svector_ostream Annotations(AnnotationsBytes);
6356
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006357 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006358 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006359 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006360 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006361 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006362 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006363 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006364 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006365 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006366 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006367 }
6368 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006369 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006370 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006371 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006372 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006373 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006374 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006375
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006376 // Print debug info.
6377 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006378 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006379 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006380 if (dli != lastLine && dli.Line != 0)
6381 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6382 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006383 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006384 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006385 outs() << "\n";
6386 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006387 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006388 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006389 outs() << format("\t.byte 0x%02x #bad opcode\n",
6390 *(Bytes.data() + Index) & 0xff);
6391 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006392 } else if (Arch == Triple::aarch64 ||
6393 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006394 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6395 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6396 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6397 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6398 outs() << format("\t.long\t0x%08x\n", opcode);
6399 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006400 } else if (Arch == Triple::arm) {
6401 assert(IsThumb && "ARM mode should have been dealt with above");
6402 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6403 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6404 outs() << format("\t.short\t0x%04x\n", opcode);
6405 Size = 2;
6406 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006407 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6408 if (Size == 0)
6409 Size = 1; // skip illegible bytes
6410 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006411 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006412 }
6413 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006414 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006415 // Reading the symbol table didn't work, disassemble the whole section.
6416 uint64_t SectAddress = Sections[SectIdx].getAddress();
6417 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006418 uint64_t InstSize;
6419 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006420 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006421
Kevin Enderbybf246f52014-09-24 23:08:22 +00006422 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006423 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6424 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006425 if (!NoLeadingAddr) {
6426 if (FullLeadingAddr) {
6427 if (MachOOF->is64Bit())
6428 outs() << format("%016" PRIx64, PC);
6429 else
6430 outs() << format("%08" PRIx64, PC);
6431 } else {
6432 outs() << format("%8" PRIx64 ":", PC);
6433 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006434 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006435 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006436 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006437 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006438 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006439 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006440 outs() << "\n";
6441 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006442 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006443 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006444 outs() << format("\t.byte 0x%02x #bad opcode\n",
6445 *(Bytes.data() + Index) & 0xff);
6446 InstSize = 1; // skip exactly one illegible byte and move on.
6447 } else {
6448 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6449 if (InstSize == 0)
6450 InstSize = 1; // skip illegible bytes
6451 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006452 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006453 }
6454 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006455 // The TripleName's need to be reset if we are called again for a different
6456 // archtecture.
6457 TripleName = "";
6458 ThumbTripleName = "";
6459
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006460 if (SymbolizerInfo.method != nullptr)
6461 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006462 if (SymbolizerInfo.demangled_name != nullptr)
6463 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006464 if (SymbolizerInfo.bindtable != nullptr)
6465 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006466 if (ThumbSymbolizerInfo.method != nullptr)
6467 free(ThumbSymbolizerInfo.method);
6468 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6469 free(ThumbSymbolizerInfo.demangled_name);
6470 if (ThumbSymbolizerInfo.bindtable != nullptr)
6471 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006472 }
6473}
Tim Northover4bd286a2014-08-01 13:07:19 +00006474
Tim Northover39c70bb2014-08-12 11:52:59 +00006475//===----------------------------------------------------------------------===//
6476// __compact_unwind section dumping
6477//===----------------------------------------------------------------------===//
6478
Tim Northover4bd286a2014-08-01 13:07:19 +00006479namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006480
6481template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006482 using llvm::support::little;
6483 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006484
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006485 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6486 Buf += sizeof(T);
6487 return Val;
6488}
Tim Northover39c70bb2014-08-12 11:52:59 +00006489
Tim Northover4bd286a2014-08-01 13:07:19 +00006490struct CompactUnwindEntry {
6491 uint32_t OffsetInSection;
6492
6493 uint64_t FunctionAddr;
6494 uint32_t Length;
6495 uint32_t CompactEncoding;
6496 uint64_t PersonalityAddr;
6497 uint64_t LSDAAddr;
6498
6499 RelocationRef FunctionReloc;
6500 RelocationRef PersonalityReloc;
6501 RelocationRef LSDAReloc;
6502
6503 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006504 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006505 if (Is64)
6506 read<uint64_t>(Contents.data() + Offset);
6507 else
6508 read<uint32_t>(Contents.data() + Offset);
6509 }
6510
6511private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006512 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006513 FunctionAddr = readNext<UIntPtr>(Buf);
6514 Length = readNext<uint32_t>(Buf);
6515 CompactEncoding = readNext<uint32_t>(Buf);
6516 PersonalityAddr = readNext<UIntPtr>(Buf);
6517 LSDAAddr = readNext<UIntPtr>(Buf);
6518 }
6519};
6520}
6521
6522/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6523/// and data being relocated, determine the best base Name and Addend to use for
6524/// display purposes.
6525///
6526/// 1. An Extern relocation will directly reference a symbol (and the data is
6527/// then already an addend), so use that.
6528/// 2. Otherwise the data is an offset in the object file's layout; try to find
6529// a symbol before it in the same section, and use the offset from there.
6530/// 3. Finally, if all that fails, fall back to an offset from the start of the
6531/// referenced section.
6532static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6533 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006534 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006535 StringRef &Name, uint64_t &Addend) {
6536 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006537 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6538 if (!NameOrErr) {
6539 std::string Buf;
6540 raw_string_ostream OS(Buf);
6541 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6542 OS.flush();
6543 report_fatal_error(Buf);
6544 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006545 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006546 Addend = Addr;
6547 return;
6548 }
6549
6550 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006551 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006552
Rafael Espindola80291272014-10-08 15:28:58 +00006553 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006554
6555 auto Sym = Symbols.upper_bound(Addr);
6556 if (Sym == Symbols.begin()) {
6557 // The first symbol in the object is after this reference, the best we can
6558 // do is section-relative notation.
6559 RelocSection.getName(Name);
6560 Addend = Addr - SectionAddr;
6561 return;
6562 }
6563
6564 // Go back one so that SymbolAddress <= Addr.
6565 --Sym;
6566
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006567 auto SectOrErr = Sym->second.getSection();
6568 if (!SectOrErr) {
6569 std::string Buf;
6570 raw_string_ostream OS(Buf);
6571 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
6572 OS.flush();
6573 report_fatal_error(Buf);
6574 }
6575 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006576 if (RelocSection == *SymSection) {
6577 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006578 Expected<StringRef> NameOrErr = Sym->second.getName();
6579 if (!NameOrErr) {
6580 std::string Buf;
6581 raw_string_ostream OS(Buf);
6582 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6583 OS.flush();
6584 report_fatal_error(Buf);
6585 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006586 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006587 Addend = Addr - Sym->first;
6588 return;
6589 }
6590
6591 // There is a symbol before this reference, but it's in a different
6592 // section. Probably not helpful to mention it, so use the section name.
6593 RelocSection.getName(Name);
6594 Addend = Addr - SectionAddr;
6595}
6596
6597static void printUnwindRelocDest(const MachOObjectFile *Obj,
6598 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006599 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006600 StringRef Name;
6601 uint64_t Addend;
6602
Rafael Espindola854038e2015-06-26 14:51:16 +00006603 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006604 return;
6605
Tim Northover4bd286a2014-08-01 13:07:19 +00006606 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6607
6608 outs() << Name;
6609 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006610 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006611}
6612
6613static void
6614printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6615 std::map<uint64_t, SymbolRef> &Symbols,
6616 const SectionRef &CompactUnwind) {
6617
6618 assert(Obj->isLittleEndian() &&
6619 "There should not be a big-endian .o with __compact_unwind");
6620
6621 bool Is64 = Obj->is64Bit();
6622 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6623 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6624
6625 StringRef Contents;
6626 CompactUnwind.getContents(Contents);
6627
6628 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6629
6630 // First populate the initial raw offsets, encodings and so on from the entry.
6631 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6632 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6633 CompactUnwinds.push_back(Entry);
6634 }
6635
6636 // Next we need to look at the relocations to find out what objects are
6637 // actually being referred to.
6638 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006639 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006640
6641 uint32_t EntryIdx = RelocAddress / EntrySize;
6642 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
6643 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
6644
6645 if (OffsetInEntry == 0)
6646 Entry.FunctionReloc = Reloc;
6647 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
6648 Entry.PersonalityReloc = Reloc;
6649 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
6650 Entry.LSDAReloc = Reloc;
6651 else
6652 llvm_unreachable("Unexpected relocation in __compact_unwind section");
6653 }
6654
6655 // Finally, we're ready to print the data we've gathered.
6656 outs() << "Contents of __compact_unwind section:\n";
6657 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00006658 outs() << " Entry at offset "
6659 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00006660
6661 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006662 outs() << " start: " << format("0x%" PRIx64,
6663 Entry.FunctionAddr) << ' ';
6664 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00006665 outs() << '\n';
6666
6667 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006668 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
6669 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006670 // 3. The 32-bit compact encoding.
6671 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006672 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00006673
6674 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00006675 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006676 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00006677 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006678 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
6679 Entry.PersonalityAddr);
6680 outs() << '\n';
6681 }
6682
6683 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00006684 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006685 outs() << " LSDA: " << format("0x%" PRIx64,
6686 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00006687 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
6688 outs() << '\n';
6689 }
6690 }
6691}
6692
Tim Northover39c70bb2014-08-12 11:52:59 +00006693//===----------------------------------------------------------------------===//
6694// __unwind_info section dumping
6695//===----------------------------------------------------------------------===//
6696
6697static void printRegularSecondLevelUnwindPage(const char *PageStart) {
6698 const char *Pos = PageStart;
6699 uint32_t Kind = readNext<uint32_t>(Pos);
6700 (void)Kind;
6701 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
6702
6703 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6704 uint16_t NumEntries = readNext<uint16_t>(Pos);
6705
6706 Pos = PageStart + EntriesStart;
6707 for (unsigned i = 0; i < NumEntries; ++i) {
6708 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6709 uint32_t Encoding = readNext<uint32_t>(Pos);
6710
6711 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006712 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6713 << ", "
6714 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006715 }
6716}
6717
6718static void printCompressedSecondLevelUnwindPage(
6719 const char *PageStart, uint32_t FunctionBase,
6720 const SmallVectorImpl<uint32_t> &CommonEncodings) {
6721 const char *Pos = PageStart;
6722 uint32_t Kind = readNext<uint32_t>(Pos);
6723 (void)Kind;
6724 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
6725
6726 uint16_t EntriesStart = readNext<uint16_t>(Pos);
6727 uint16_t NumEntries = readNext<uint16_t>(Pos);
6728
6729 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
6730 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00006731 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
6732 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00006733
6734 Pos = PageStart + EntriesStart;
6735 for (unsigned i = 0; i < NumEntries; ++i) {
6736 uint32_t Entry = readNext<uint32_t>(Pos);
6737 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
6738 uint32_t EncodingIdx = Entry >> 24;
6739
6740 uint32_t Encoding;
6741 if (EncodingIdx < CommonEncodings.size())
6742 Encoding = CommonEncodings[EncodingIdx];
6743 else
6744 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
6745
6746 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006747 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6748 << ", "
6749 << "encoding[" << EncodingIdx
6750 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006751 }
6752}
6753
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006754static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
6755 std::map<uint64_t, SymbolRef> &Symbols,
6756 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00006757
6758 assert(Obj->isLittleEndian() &&
6759 "There should not be a big-endian .o with __unwind_info");
6760
6761 outs() << "Contents of __unwind_info section:\n";
6762
6763 StringRef Contents;
6764 UnwindInfo.getContents(Contents);
6765 const char *Pos = Contents.data();
6766
6767 //===----------------------------------
6768 // Section header
6769 //===----------------------------------
6770
6771 uint32_t Version = readNext<uint32_t>(Pos);
6772 outs() << " Version: "
6773 << format("0x%" PRIx32, Version) << '\n';
6774 assert(Version == 1 && "only understand version 1");
6775
6776 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
6777 outs() << " Common encodings array section offset: "
6778 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
6779 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
6780 outs() << " Number of common encodings in array: "
6781 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
6782
6783 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
6784 outs() << " Personality function array section offset: "
6785 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
6786 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
6787 outs() << " Number of personality functions in array: "
6788 << format("0x%" PRIx32, NumPersonalities) << '\n';
6789
6790 uint32_t IndicesStart = readNext<uint32_t>(Pos);
6791 outs() << " Index array section offset: "
6792 << format("0x%" PRIx32, IndicesStart) << '\n';
6793 uint32_t NumIndices = readNext<uint32_t>(Pos);
6794 outs() << " Number of indices in array: "
6795 << format("0x%" PRIx32, NumIndices) << '\n';
6796
6797 //===----------------------------------
6798 // A shared list of common encodings
6799 //===----------------------------------
6800
6801 // These occupy indices in the range [0, N] whenever an encoding is referenced
6802 // from a compressed 2nd level index table. In practice the linker only
6803 // creates ~128 of these, so that indices are available to embed encodings in
6804 // the 2nd level index.
6805
6806 SmallVector<uint32_t, 64> CommonEncodings;
6807 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
6808 Pos = Contents.data() + CommonEncodingsStart;
6809 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
6810 uint32_t Encoding = readNext<uint32_t>(Pos);
6811 CommonEncodings.push_back(Encoding);
6812
6813 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
6814 << '\n';
6815 }
6816
Tim Northover39c70bb2014-08-12 11:52:59 +00006817 //===----------------------------------
6818 // Personality functions used in this executable
6819 //===----------------------------------
6820
6821 // There should be only a handful of these (one per source language,
6822 // roughly). Particularly since they only get 2 bits in the compact encoding.
6823
6824 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
6825 Pos = Contents.data() + PersonalitiesStart;
6826 for (unsigned i = 0; i < NumPersonalities; ++i) {
6827 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
6828 outs() << " personality[" << i + 1
6829 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
6830 }
6831
6832 //===----------------------------------
6833 // The level 1 index entries
6834 //===----------------------------------
6835
6836 // These specify an approximate place to start searching for the more detailed
6837 // information, sorted by PC.
6838
6839 struct IndexEntry {
6840 uint32_t FunctionOffset;
6841 uint32_t SecondLevelPageStart;
6842 uint32_t LSDAStart;
6843 };
6844
6845 SmallVector<IndexEntry, 4> IndexEntries;
6846
6847 outs() << " Top level indices: (count = " << NumIndices << ")\n";
6848 Pos = Contents.data() + IndicesStart;
6849 for (unsigned i = 0; i < NumIndices; ++i) {
6850 IndexEntry Entry;
6851
6852 Entry.FunctionOffset = readNext<uint32_t>(Pos);
6853 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
6854 Entry.LSDAStart = readNext<uint32_t>(Pos);
6855 IndexEntries.push_back(Entry);
6856
6857 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006858 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
6859 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00006860 << "2nd level page offset="
6861 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006862 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006863 }
6864
Tim Northover39c70bb2014-08-12 11:52:59 +00006865 //===----------------------------------
6866 // Next come the LSDA tables
6867 //===----------------------------------
6868
6869 // The LSDA layout is rather implicit: it's a contiguous array of entries from
6870 // the first top-level index's LSDAOffset to the last (sentinel).
6871
6872 outs() << " LSDA descriptors:\n";
6873 Pos = Contents.data() + IndexEntries[0].LSDAStart;
6874 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
6875 (2 * sizeof(uint32_t));
6876 for (int i = 0; i < NumLSDAs; ++i) {
6877 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
6878 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
6879 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006880 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
6881 << ", "
6882 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00006883 }
6884
6885 //===----------------------------------
6886 // Finally, the 2nd level indices
6887 //===----------------------------------
6888
6889 // Generally these are 4K in size, and have 2 possible forms:
6890 // + Regular stores up to 511 entries with disparate encodings
6891 // + Compressed stores up to 1021 entries if few enough compact encoding
6892 // values are used.
6893 outs() << " Second level indices:\n";
6894 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
6895 // The final sentinel top-level index has no associated 2nd level page
6896 if (IndexEntries[i].SecondLevelPageStart == 0)
6897 break;
6898
6899 outs() << " Second level index[" << i << "]: "
6900 << "offset in section="
6901 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
6902 << ", "
6903 << "base function offset="
6904 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
6905
6906 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00006907 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00006908 if (Kind == 2)
6909 printRegularSecondLevelUnwindPage(Pos);
6910 else if (Kind == 3)
6911 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
6912 CommonEncodings);
6913 else
6914 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00006915 }
6916}
6917
Tim Northover4bd286a2014-08-01 13:07:19 +00006918void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
6919 std::map<uint64_t, SymbolRef> Symbols;
6920 for (const SymbolRef &SymRef : Obj->symbols()) {
6921 // Discard any undefined or absolute symbols. They're not going to take part
6922 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006923 auto SectOrErr = SymRef.getSection();
6924 if (!SectOrErr) {
6925 // TODO: Actually report errors helpfully.
6926 consumeError(SectOrErr.takeError());
6927 continue;
6928 }
6929 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006930 if (Section == Obj->section_end())
6931 continue;
6932
Rafael Espindoladea00162015-07-03 17:44:18 +00006933 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00006934 Symbols.insert(std::make_pair(Addr, SymRef));
6935 }
6936
6937 for (const SectionRef &Section : Obj->sections()) {
6938 StringRef SectName;
6939 Section.getName(SectName);
6940 if (SectName == "__compact_unwind")
6941 printMachOCompactUnwindSection(Obj, Symbols, Section);
6942 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00006943 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00006944 }
6945}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006946
6947static void PrintMachHeader(uint32_t magic, uint32_t cputype,
6948 uint32_t cpusubtype, uint32_t filetype,
6949 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
6950 bool verbose) {
6951 outs() << "Mach header\n";
6952 outs() << " magic cputype cpusubtype caps filetype ncmds "
6953 "sizeofcmds flags\n";
6954 if (verbose) {
6955 if (magic == MachO::MH_MAGIC)
6956 outs() << " MH_MAGIC";
6957 else if (magic == MachO::MH_MAGIC_64)
6958 outs() << "MH_MAGIC_64";
6959 else
6960 outs() << format(" 0x%08" PRIx32, magic);
6961 switch (cputype) {
6962 case MachO::CPU_TYPE_I386:
6963 outs() << " I386";
6964 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6965 case MachO::CPU_SUBTYPE_I386_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_X86_64:
6974 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00006975 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6976 case MachO::CPU_SUBTYPE_X86_64_ALL:
6977 outs() << " ALL";
6978 break;
6979 case MachO::CPU_SUBTYPE_X86_64_H:
6980 outs() << " Haswell";
6981 break;
6982 default:
6983 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
6984 break;
6985 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00006986 break;
6987 case MachO::CPU_TYPE_ARM:
6988 outs() << " ARM";
6989 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
6990 case MachO::CPU_SUBTYPE_ARM_ALL:
6991 outs() << " ALL";
6992 break;
6993 case MachO::CPU_SUBTYPE_ARM_V4T:
6994 outs() << " V4T";
6995 break;
6996 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
6997 outs() << " V5TEJ";
6998 break;
6999 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7000 outs() << " XSCALE";
7001 break;
7002 case MachO::CPU_SUBTYPE_ARM_V6:
7003 outs() << " V6";
7004 break;
7005 case MachO::CPU_SUBTYPE_ARM_V6M:
7006 outs() << " V6M";
7007 break;
7008 case MachO::CPU_SUBTYPE_ARM_V7:
7009 outs() << " V7";
7010 break;
7011 case MachO::CPU_SUBTYPE_ARM_V7EM:
7012 outs() << " V7EM";
7013 break;
7014 case MachO::CPU_SUBTYPE_ARM_V7K:
7015 outs() << " V7K";
7016 break;
7017 case MachO::CPU_SUBTYPE_ARM_V7M:
7018 outs() << " V7M";
7019 break;
7020 case MachO::CPU_SUBTYPE_ARM_V7S:
7021 outs() << " V7S";
7022 break;
7023 default:
7024 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7025 break;
7026 }
7027 break;
7028 case MachO::CPU_TYPE_ARM64:
7029 outs() << " ARM64";
7030 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7031 case MachO::CPU_SUBTYPE_ARM64_ALL:
7032 outs() << " ALL";
7033 break;
7034 default:
7035 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7036 break;
7037 }
7038 break;
7039 case MachO::CPU_TYPE_POWERPC:
7040 outs() << " PPC";
7041 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7042 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7043 outs() << " ALL";
7044 break;
7045 default:
7046 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7047 break;
7048 }
7049 break;
7050 case MachO::CPU_TYPE_POWERPC64:
7051 outs() << " PPC64";
7052 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7053 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7054 outs() << " ALL";
7055 break;
7056 default:
7057 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7058 break;
7059 }
7060 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007061 default:
7062 outs() << format(" %7d", cputype);
7063 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7064 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007065 }
7066 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007067 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007068 } else {
7069 outs() << format(" 0x%02" PRIx32,
7070 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7071 }
7072 switch (filetype) {
7073 case MachO::MH_OBJECT:
7074 outs() << " OBJECT";
7075 break;
7076 case MachO::MH_EXECUTE:
7077 outs() << " EXECUTE";
7078 break;
7079 case MachO::MH_FVMLIB:
7080 outs() << " FVMLIB";
7081 break;
7082 case MachO::MH_CORE:
7083 outs() << " CORE";
7084 break;
7085 case MachO::MH_PRELOAD:
7086 outs() << " PRELOAD";
7087 break;
7088 case MachO::MH_DYLIB:
7089 outs() << " DYLIB";
7090 break;
7091 case MachO::MH_DYLIB_STUB:
7092 outs() << " DYLIB_STUB";
7093 break;
7094 case MachO::MH_DYLINKER:
7095 outs() << " DYLINKER";
7096 break;
7097 case MachO::MH_BUNDLE:
7098 outs() << " BUNDLE";
7099 break;
7100 case MachO::MH_DSYM:
7101 outs() << " DSYM";
7102 break;
7103 case MachO::MH_KEXT_BUNDLE:
7104 outs() << " KEXTBUNDLE";
7105 break;
7106 default:
7107 outs() << format(" %10u", filetype);
7108 break;
7109 }
7110 outs() << format(" %5u", ncmds);
7111 outs() << format(" %10u", sizeofcmds);
7112 uint32_t f = flags;
7113 if (f & MachO::MH_NOUNDEFS) {
7114 outs() << " NOUNDEFS";
7115 f &= ~MachO::MH_NOUNDEFS;
7116 }
7117 if (f & MachO::MH_INCRLINK) {
7118 outs() << " INCRLINK";
7119 f &= ~MachO::MH_INCRLINK;
7120 }
7121 if (f & MachO::MH_DYLDLINK) {
7122 outs() << " DYLDLINK";
7123 f &= ~MachO::MH_DYLDLINK;
7124 }
7125 if (f & MachO::MH_BINDATLOAD) {
7126 outs() << " BINDATLOAD";
7127 f &= ~MachO::MH_BINDATLOAD;
7128 }
7129 if (f & MachO::MH_PREBOUND) {
7130 outs() << " PREBOUND";
7131 f &= ~MachO::MH_PREBOUND;
7132 }
7133 if (f & MachO::MH_SPLIT_SEGS) {
7134 outs() << " SPLIT_SEGS";
7135 f &= ~MachO::MH_SPLIT_SEGS;
7136 }
7137 if (f & MachO::MH_LAZY_INIT) {
7138 outs() << " LAZY_INIT";
7139 f &= ~MachO::MH_LAZY_INIT;
7140 }
7141 if (f & MachO::MH_TWOLEVEL) {
7142 outs() << " TWOLEVEL";
7143 f &= ~MachO::MH_TWOLEVEL;
7144 }
7145 if (f & MachO::MH_FORCE_FLAT) {
7146 outs() << " FORCE_FLAT";
7147 f &= ~MachO::MH_FORCE_FLAT;
7148 }
7149 if (f & MachO::MH_NOMULTIDEFS) {
7150 outs() << " NOMULTIDEFS";
7151 f &= ~MachO::MH_NOMULTIDEFS;
7152 }
7153 if (f & MachO::MH_NOFIXPREBINDING) {
7154 outs() << " NOFIXPREBINDING";
7155 f &= ~MachO::MH_NOFIXPREBINDING;
7156 }
7157 if (f & MachO::MH_PREBINDABLE) {
7158 outs() << " PREBINDABLE";
7159 f &= ~MachO::MH_PREBINDABLE;
7160 }
7161 if (f & MachO::MH_ALLMODSBOUND) {
7162 outs() << " ALLMODSBOUND";
7163 f &= ~MachO::MH_ALLMODSBOUND;
7164 }
7165 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7166 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7167 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7168 }
7169 if (f & MachO::MH_CANONICAL) {
7170 outs() << " CANONICAL";
7171 f &= ~MachO::MH_CANONICAL;
7172 }
7173 if (f & MachO::MH_WEAK_DEFINES) {
7174 outs() << " WEAK_DEFINES";
7175 f &= ~MachO::MH_WEAK_DEFINES;
7176 }
7177 if (f & MachO::MH_BINDS_TO_WEAK) {
7178 outs() << " BINDS_TO_WEAK";
7179 f &= ~MachO::MH_BINDS_TO_WEAK;
7180 }
7181 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7182 outs() << " ALLOW_STACK_EXECUTION";
7183 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7184 }
7185 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7186 outs() << " DEAD_STRIPPABLE_DYLIB";
7187 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7188 }
7189 if (f & MachO::MH_PIE) {
7190 outs() << " PIE";
7191 f &= ~MachO::MH_PIE;
7192 }
7193 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7194 outs() << " NO_REEXPORTED_DYLIBS";
7195 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7196 }
7197 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7198 outs() << " MH_HAS_TLV_DESCRIPTORS";
7199 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7200 }
7201 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7202 outs() << " MH_NO_HEAP_EXECUTION";
7203 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7204 }
7205 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7206 outs() << " APP_EXTENSION_SAFE";
7207 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7208 }
7209 if (f != 0 || flags == 0)
7210 outs() << format(" 0x%08" PRIx32, f);
7211 } else {
7212 outs() << format(" 0x%08" PRIx32, magic);
7213 outs() << format(" %7d", cputype);
7214 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7215 outs() << format(" 0x%02" PRIx32,
7216 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7217 outs() << format(" %10u", filetype);
7218 outs() << format(" %5u", ncmds);
7219 outs() << format(" %10u", sizeofcmds);
7220 outs() << format(" 0x%08" PRIx32, flags);
7221 }
7222 outs() << "\n";
7223}
7224
Kevin Enderby956366c2014-08-29 22:30:52 +00007225static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7226 StringRef SegName, uint64_t vmaddr,
7227 uint64_t vmsize, uint64_t fileoff,
7228 uint64_t filesize, uint32_t maxprot,
7229 uint32_t initprot, uint32_t nsects,
7230 uint32_t flags, uint32_t object_size,
7231 bool verbose) {
7232 uint64_t expected_cmdsize;
7233 if (cmd == MachO::LC_SEGMENT) {
7234 outs() << " cmd LC_SEGMENT\n";
7235 expected_cmdsize = nsects;
7236 expected_cmdsize *= sizeof(struct MachO::section);
7237 expected_cmdsize += sizeof(struct MachO::segment_command);
7238 } else {
7239 outs() << " cmd LC_SEGMENT_64\n";
7240 expected_cmdsize = nsects;
7241 expected_cmdsize *= sizeof(struct MachO::section_64);
7242 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7243 }
7244 outs() << " cmdsize " << cmdsize;
7245 if (cmdsize != expected_cmdsize)
7246 outs() << " Inconsistent size\n";
7247 else
7248 outs() << "\n";
7249 outs() << " segname " << SegName << "\n";
7250 if (cmd == MachO::LC_SEGMENT_64) {
7251 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7252 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7253 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007254 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7255 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007256 }
7257 outs() << " fileoff " << fileoff;
7258 if (fileoff > object_size)
7259 outs() << " (past end of file)\n";
7260 else
7261 outs() << "\n";
7262 outs() << " filesize " << filesize;
7263 if (fileoff + filesize > object_size)
7264 outs() << " (past end of file)\n";
7265 else
7266 outs() << "\n";
7267 if (verbose) {
7268 if ((maxprot &
7269 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7270 MachO::VM_PROT_EXECUTE)) != 0)
7271 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7272 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007273 outs() << " maxprot ";
7274 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7275 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7276 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007277 }
7278 if ((initprot &
7279 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7280 MachO::VM_PROT_EXECUTE)) != 0)
7281 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7282 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007283 outs() << " initprot ";
7284 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7285 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7286 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007287 }
7288 } else {
7289 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7290 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7291 }
7292 outs() << " nsects " << nsects << "\n";
7293 if (verbose) {
7294 outs() << " flags";
7295 if (flags == 0)
7296 outs() << " (none)\n";
7297 else {
7298 if (flags & MachO::SG_HIGHVM) {
7299 outs() << " HIGHVM";
7300 flags &= ~MachO::SG_HIGHVM;
7301 }
7302 if (flags & MachO::SG_FVMLIB) {
7303 outs() << " FVMLIB";
7304 flags &= ~MachO::SG_FVMLIB;
7305 }
7306 if (flags & MachO::SG_NORELOC) {
7307 outs() << " NORELOC";
7308 flags &= ~MachO::SG_NORELOC;
7309 }
7310 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7311 outs() << " PROTECTED_VERSION_1";
7312 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7313 }
7314 if (flags)
7315 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7316 else
7317 outs() << "\n";
7318 }
7319 } else {
7320 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7321 }
7322}
7323
7324static void PrintSection(const char *sectname, const char *segname,
7325 uint64_t addr, uint64_t size, uint32_t offset,
7326 uint32_t align, uint32_t reloff, uint32_t nreloc,
7327 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7328 uint32_t cmd, const char *sg_segname,
7329 uint32_t filetype, uint32_t object_size,
7330 bool verbose) {
7331 outs() << "Section\n";
7332 outs() << " sectname " << format("%.16s\n", sectname);
7333 outs() << " segname " << format("%.16s", segname);
7334 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7335 outs() << " (does not match segment)\n";
7336 else
7337 outs() << "\n";
7338 if (cmd == MachO::LC_SEGMENT_64) {
7339 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7340 outs() << " size " << format("0x%016" PRIx64, size);
7341 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007342 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7343 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007344 }
7345 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7346 outs() << " (past end of file)\n";
7347 else
7348 outs() << "\n";
7349 outs() << " offset " << offset;
7350 if (offset > object_size)
7351 outs() << " (past end of file)\n";
7352 else
7353 outs() << "\n";
7354 uint32_t align_shifted = 1 << align;
7355 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7356 outs() << " reloff " << reloff;
7357 if (reloff > object_size)
7358 outs() << " (past end of file)\n";
7359 else
7360 outs() << "\n";
7361 outs() << " nreloc " << nreloc;
7362 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7363 outs() << " (past end of file)\n";
7364 else
7365 outs() << "\n";
7366 uint32_t section_type = flags & MachO::SECTION_TYPE;
7367 if (verbose) {
7368 outs() << " type";
7369 if (section_type == MachO::S_REGULAR)
7370 outs() << " S_REGULAR\n";
7371 else if (section_type == MachO::S_ZEROFILL)
7372 outs() << " S_ZEROFILL\n";
7373 else if (section_type == MachO::S_CSTRING_LITERALS)
7374 outs() << " S_CSTRING_LITERALS\n";
7375 else if (section_type == MachO::S_4BYTE_LITERALS)
7376 outs() << " S_4BYTE_LITERALS\n";
7377 else if (section_type == MachO::S_8BYTE_LITERALS)
7378 outs() << " S_8BYTE_LITERALS\n";
7379 else if (section_type == MachO::S_16BYTE_LITERALS)
7380 outs() << " S_16BYTE_LITERALS\n";
7381 else if (section_type == MachO::S_LITERAL_POINTERS)
7382 outs() << " S_LITERAL_POINTERS\n";
7383 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7384 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7385 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7386 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7387 else if (section_type == MachO::S_SYMBOL_STUBS)
7388 outs() << " S_SYMBOL_STUBS\n";
7389 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7390 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7391 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7392 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7393 else if (section_type == MachO::S_COALESCED)
7394 outs() << " S_COALESCED\n";
7395 else if (section_type == MachO::S_INTERPOSING)
7396 outs() << " S_INTERPOSING\n";
7397 else if (section_type == MachO::S_DTRACE_DOF)
7398 outs() << " S_DTRACE_DOF\n";
7399 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7400 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7401 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7402 outs() << " S_THREAD_LOCAL_REGULAR\n";
7403 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7404 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7405 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7406 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7407 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7408 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7409 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7410 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7411 else
7412 outs() << format("0x%08" PRIx32, section_type) << "\n";
7413 outs() << "attributes";
7414 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7415 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7416 outs() << " PURE_INSTRUCTIONS";
7417 if (section_attributes & MachO::S_ATTR_NO_TOC)
7418 outs() << " NO_TOC";
7419 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7420 outs() << " STRIP_STATIC_SYMS";
7421 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7422 outs() << " NO_DEAD_STRIP";
7423 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7424 outs() << " LIVE_SUPPORT";
7425 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7426 outs() << " SELF_MODIFYING_CODE";
7427 if (section_attributes & MachO::S_ATTR_DEBUG)
7428 outs() << " DEBUG";
7429 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7430 outs() << " SOME_INSTRUCTIONS";
7431 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7432 outs() << " EXT_RELOC";
7433 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7434 outs() << " LOC_RELOC";
7435 if (section_attributes == 0)
7436 outs() << " (none)";
7437 outs() << "\n";
7438 } else
7439 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7440 outs() << " reserved1 " << reserved1;
7441 if (section_type == MachO::S_SYMBOL_STUBS ||
7442 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7443 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7444 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7445 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7446 outs() << " (index into indirect symbol table)\n";
7447 else
7448 outs() << "\n";
7449 outs() << " reserved2 " << reserved2;
7450 if (section_type == MachO::S_SYMBOL_STUBS)
7451 outs() << " (size of stubs)\n";
7452 else
7453 outs() << "\n";
7454}
7455
David Majnemer73cc6ff2014-11-13 19:48:56 +00007456static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007457 uint32_t object_size) {
7458 outs() << " cmd LC_SYMTAB\n";
7459 outs() << " cmdsize " << st.cmdsize;
7460 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7461 outs() << " Incorrect size\n";
7462 else
7463 outs() << "\n";
7464 outs() << " symoff " << st.symoff;
7465 if (st.symoff > object_size)
7466 outs() << " (past end of file)\n";
7467 else
7468 outs() << "\n";
7469 outs() << " nsyms " << st.nsyms;
7470 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007471 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007472 big_size = st.nsyms;
7473 big_size *= sizeof(struct MachO::nlist_64);
7474 big_size += st.symoff;
7475 if (big_size > object_size)
7476 outs() << " (past end of file)\n";
7477 else
7478 outs() << "\n";
7479 } else {
7480 big_size = st.nsyms;
7481 big_size *= sizeof(struct MachO::nlist);
7482 big_size += st.symoff;
7483 if (big_size > object_size)
7484 outs() << " (past end of file)\n";
7485 else
7486 outs() << "\n";
7487 }
7488 outs() << " stroff " << st.stroff;
7489 if (st.stroff > object_size)
7490 outs() << " (past end of file)\n";
7491 else
7492 outs() << "\n";
7493 outs() << " strsize " << st.strsize;
7494 big_size = st.stroff;
7495 big_size += st.strsize;
7496 if (big_size > object_size)
7497 outs() << " (past end of file)\n";
7498 else
7499 outs() << "\n";
7500}
7501
7502static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7503 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007504 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007505 outs() << " cmd LC_DYSYMTAB\n";
7506 outs() << " cmdsize " << dyst.cmdsize;
7507 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7508 outs() << " Incorrect size\n";
7509 else
7510 outs() << "\n";
7511 outs() << " ilocalsym " << dyst.ilocalsym;
7512 if (dyst.ilocalsym > nsyms)
7513 outs() << " (greater than the number of symbols)\n";
7514 else
7515 outs() << "\n";
7516 outs() << " nlocalsym " << dyst.nlocalsym;
7517 uint64_t big_size;
7518 big_size = dyst.ilocalsym;
7519 big_size += dyst.nlocalsym;
7520 if (big_size > nsyms)
7521 outs() << " (past the end of the symbol table)\n";
7522 else
7523 outs() << "\n";
7524 outs() << " iextdefsym " << dyst.iextdefsym;
7525 if (dyst.iextdefsym > nsyms)
7526 outs() << " (greater than the number of symbols)\n";
7527 else
7528 outs() << "\n";
7529 outs() << " nextdefsym " << dyst.nextdefsym;
7530 big_size = dyst.iextdefsym;
7531 big_size += dyst.nextdefsym;
7532 if (big_size > nsyms)
7533 outs() << " (past the end of the symbol table)\n";
7534 else
7535 outs() << "\n";
7536 outs() << " iundefsym " << dyst.iundefsym;
7537 if (dyst.iundefsym > nsyms)
7538 outs() << " (greater than the number of symbols)\n";
7539 else
7540 outs() << "\n";
7541 outs() << " nundefsym " << dyst.nundefsym;
7542 big_size = dyst.iundefsym;
7543 big_size += dyst.nundefsym;
7544 if (big_size > nsyms)
7545 outs() << " (past the end of the symbol table)\n";
7546 else
7547 outs() << "\n";
7548 outs() << " tocoff " << dyst.tocoff;
7549 if (dyst.tocoff > object_size)
7550 outs() << " (past end of file)\n";
7551 else
7552 outs() << "\n";
7553 outs() << " ntoc " << dyst.ntoc;
7554 big_size = dyst.ntoc;
7555 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7556 big_size += dyst.tocoff;
7557 if (big_size > object_size)
7558 outs() << " (past end of file)\n";
7559 else
7560 outs() << "\n";
7561 outs() << " modtaboff " << dyst.modtaboff;
7562 if (dyst.modtaboff > object_size)
7563 outs() << " (past end of file)\n";
7564 else
7565 outs() << "\n";
7566 outs() << " nmodtab " << dyst.nmodtab;
7567 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007568 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007569 modtabend = dyst.nmodtab;
7570 modtabend *= sizeof(struct MachO::dylib_module_64);
7571 modtabend += dyst.modtaboff;
7572 } else {
7573 modtabend = dyst.nmodtab;
7574 modtabend *= sizeof(struct MachO::dylib_module);
7575 modtabend += dyst.modtaboff;
7576 }
7577 if (modtabend > object_size)
7578 outs() << " (past end of file)\n";
7579 else
7580 outs() << "\n";
7581 outs() << " extrefsymoff " << dyst.extrefsymoff;
7582 if (dyst.extrefsymoff > object_size)
7583 outs() << " (past end of file)\n";
7584 else
7585 outs() << "\n";
7586 outs() << " nextrefsyms " << dyst.nextrefsyms;
7587 big_size = dyst.nextrefsyms;
7588 big_size *= sizeof(struct MachO::dylib_reference);
7589 big_size += dyst.extrefsymoff;
7590 if (big_size > object_size)
7591 outs() << " (past end of file)\n";
7592 else
7593 outs() << "\n";
7594 outs() << " indirectsymoff " << dyst.indirectsymoff;
7595 if (dyst.indirectsymoff > object_size)
7596 outs() << " (past end of file)\n";
7597 else
7598 outs() << "\n";
7599 outs() << " nindirectsyms " << dyst.nindirectsyms;
7600 big_size = dyst.nindirectsyms;
7601 big_size *= sizeof(uint32_t);
7602 big_size += dyst.indirectsymoff;
7603 if (big_size > object_size)
7604 outs() << " (past end of file)\n";
7605 else
7606 outs() << "\n";
7607 outs() << " extreloff " << dyst.extreloff;
7608 if (dyst.extreloff > object_size)
7609 outs() << " (past end of file)\n";
7610 else
7611 outs() << "\n";
7612 outs() << " nextrel " << dyst.nextrel;
7613 big_size = dyst.nextrel;
7614 big_size *= sizeof(struct MachO::relocation_info);
7615 big_size += dyst.extreloff;
7616 if (big_size > object_size)
7617 outs() << " (past end of file)\n";
7618 else
7619 outs() << "\n";
7620 outs() << " locreloff " << dyst.locreloff;
7621 if (dyst.locreloff > object_size)
7622 outs() << " (past end of file)\n";
7623 else
7624 outs() << "\n";
7625 outs() << " nlocrel " << dyst.nlocrel;
7626 big_size = dyst.nlocrel;
7627 big_size *= sizeof(struct MachO::relocation_info);
7628 big_size += dyst.locreloff;
7629 if (big_size > object_size)
7630 outs() << " (past end of file)\n";
7631 else
7632 outs() << "\n";
7633}
7634
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007635static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
7636 uint32_t object_size) {
7637 if (dc.cmd == MachO::LC_DYLD_INFO)
7638 outs() << " cmd LC_DYLD_INFO\n";
7639 else
7640 outs() << " cmd LC_DYLD_INFO_ONLY\n";
7641 outs() << " cmdsize " << dc.cmdsize;
7642 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
7643 outs() << " Incorrect size\n";
7644 else
7645 outs() << "\n";
7646 outs() << " rebase_off " << dc.rebase_off;
7647 if (dc.rebase_off > object_size)
7648 outs() << " (past end of file)\n";
7649 else
7650 outs() << "\n";
7651 outs() << " rebase_size " << dc.rebase_size;
7652 uint64_t big_size;
7653 big_size = dc.rebase_off;
7654 big_size += dc.rebase_size;
7655 if (big_size > object_size)
7656 outs() << " (past end of file)\n";
7657 else
7658 outs() << "\n";
7659 outs() << " bind_off " << dc.bind_off;
7660 if (dc.bind_off > object_size)
7661 outs() << " (past end of file)\n";
7662 else
7663 outs() << "\n";
7664 outs() << " bind_size " << dc.bind_size;
7665 big_size = dc.bind_off;
7666 big_size += dc.bind_size;
7667 if (big_size > object_size)
7668 outs() << " (past end of file)\n";
7669 else
7670 outs() << "\n";
7671 outs() << " weak_bind_off " << dc.weak_bind_off;
7672 if (dc.weak_bind_off > object_size)
7673 outs() << " (past end of file)\n";
7674 else
7675 outs() << "\n";
7676 outs() << " weak_bind_size " << dc.weak_bind_size;
7677 big_size = dc.weak_bind_off;
7678 big_size += dc.weak_bind_size;
7679 if (big_size > object_size)
7680 outs() << " (past end of file)\n";
7681 else
7682 outs() << "\n";
7683 outs() << " lazy_bind_off " << dc.lazy_bind_off;
7684 if (dc.lazy_bind_off > object_size)
7685 outs() << " (past end of file)\n";
7686 else
7687 outs() << "\n";
7688 outs() << " lazy_bind_size " << dc.lazy_bind_size;
7689 big_size = dc.lazy_bind_off;
7690 big_size += dc.lazy_bind_size;
7691 if (big_size > object_size)
7692 outs() << " (past end of file)\n";
7693 else
7694 outs() << "\n";
7695 outs() << " export_off " << dc.export_off;
7696 if (dc.export_off > object_size)
7697 outs() << " (past end of file)\n";
7698 else
7699 outs() << "\n";
7700 outs() << " export_size " << dc.export_size;
7701 big_size = dc.export_off;
7702 big_size += dc.export_size;
7703 if (big_size > object_size)
7704 outs() << " (past end of file)\n";
7705 else
7706 outs() << "\n";
7707}
7708
7709static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
7710 const char *Ptr) {
7711 if (dyld.cmd == MachO::LC_ID_DYLINKER)
7712 outs() << " cmd LC_ID_DYLINKER\n";
7713 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
7714 outs() << " cmd LC_LOAD_DYLINKER\n";
7715 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
7716 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
7717 else
7718 outs() << " cmd ?(" << dyld.cmd << ")\n";
7719 outs() << " cmdsize " << dyld.cmdsize;
7720 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
7721 outs() << " Incorrect size\n";
7722 else
7723 outs() << "\n";
7724 if (dyld.name >= dyld.cmdsize)
7725 outs() << " name ?(bad offset " << dyld.name << ")\n";
7726 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007727 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007728 outs() << " name " << P << " (offset " << dyld.name << ")\n";
7729 }
7730}
7731
7732static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
7733 outs() << " cmd LC_UUID\n";
7734 outs() << " cmdsize " << uuid.cmdsize;
7735 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
7736 outs() << " Incorrect size\n";
7737 else
7738 outs() << "\n";
7739 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00007740 for (int i = 0; i < 16; ++i) {
7741 outs() << format("%02" PRIX32, uuid.uuid[i]);
7742 if (i == 3 || i == 5 || i == 7 || i == 9)
7743 outs() << "-";
7744 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007745 outs() << "\n";
7746}
7747
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007748static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00007749 outs() << " cmd LC_RPATH\n";
7750 outs() << " cmdsize " << rpath.cmdsize;
7751 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
7752 outs() << " Incorrect size\n";
7753 else
7754 outs() << "\n";
7755 if (rpath.path >= rpath.cmdsize)
7756 outs() << " path ?(bad offset " << rpath.path << ")\n";
7757 else {
7758 const char *P = (const char *)(Ptr) + rpath.path;
7759 outs() << " path " << P << " (offset " << rpath.path << ")\n";
7760 }
7761}
7762
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007763static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00007764 StringRef LoadCmdName;
7765 switch (vd.cmd) {
7766 case MachO::LC_VERSION_MIN_MACOSX:
7767 LoadCmdName = "LC_VERSION_MIN_MACOSX";
7768 break;
7769 case MachO::LC_VERSION_MIN_IPHONEOS:
7770 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
7771 break;
7772 case MachO::LC_VERSION_MIN_TVOS:
7773 LoadCmdName = "LC_VERSION_MIN_TVOS";
7774 break;
7775 case MachO::LC_VERSION_MIN_WATCHOS:
7776 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
7777 break;
7778 default:
7779 llvm_unreachable("Unknown version min load command");
7780 }
7781
7782 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007783 outs() << " cmdsize " << vd.cmdsize;
7784 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
7785 outs() << " Incorrect size\n";
7786 else
7787 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00007788 outs() << " version "
7789 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
7790 << MachOObjectFile::getVersionMinMinor(vd, false);
7791 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
7792 if (Update != 0)
7793 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007794 outs() << "\n";
7795 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00007796 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007797 else {
Davide Italiano56baef32015-08-26 12:26:11 +00007798 outs() << " sdk "
7799 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
7800 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007801 }
Davide Italiano56baef32015-08-26 12:26:11 +00007802 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
7803 if (Update != 0)
7804 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007805 outs() << "\n";
7806}
7807
7808static void PrintSourceVersionCommand(MachO::source_version_command sd) {
7809 outs() << " cmd LC_SOURCE_VERSION\n";
7810 outs() << " cmdsize " << sd.cmdsize;
7811 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
7812 outs() << " Incorrect size\n";
7813 else
7814 outs() << "\n";
7815 uint64_t a = (sd.version >> 40) & 0xffffff;
7816 uint64_t b = (sd.version >> 30) & 0x3ff;
7817 uint64_t c = (sd.version >> 20) & 0x3ff;
7818 uint64_t d = (sd.version >> 10) & 0x3ff;
7819 uint64_t e = sd.version & 0x3ff;
7820 outs() << " version " << a << "." << b;
7821 if (e != 0)
7822 outs() << "." << c << "." << d << "." << e;
7823 else if (d != 0)
7824 outs() << "." << c << "." << d;
7825 else if (c != 0)
7826 outs() << "." << c;
7827 outs() << "\n";
7828}
7829
7830static void PrintEntryPointCommand(MachO::entry_point_command ep) {
7831 outs() << " cmd LC_MAIN\n";
7832 outs() << " cmdsize " << ep.cmdsize;
7833 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
7834 outs() << " Incorrect size\n";
7835 else
7836 outs() << "\n";
7837 outs() << " entryoff " << ep.entryoff << "\n";
7838 outs() << " stacksize " << ep.stacksize << "\n";
7839}
7840
Kevin Enderby0804f4672014-12-16 23:25:52 +00007841static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
7842 uint32_t object_size) {
7843 outs() << " cmd LC_ENCRYPTION_INFO\n";
7844 outs() << " cmdsize " << ec.cmdsize;
7845 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
7846 outs() << " Incorrect size\n";
7847 else
7848 outs() << "\n";
7849 outs() << " cryptoff " << ec.cryptoff;
7850 if (ec.cryptoff > object_size)
7851 outs() << " (past end of file)\n";
7852 else
7853 outs() << "\n";
7854 outs() << " cryptsize " << ec.cryptsize;
7855 if (ec.cryptsize > object_size)
7856 outs() << " (past end of file)\n";
7857 else
7858 outs() << "\n";
7859 outs() << " cryptid " << ec.cryptid << "\n";
7860}
7861
Kevin Enderby57538292014-12-17 01:01:30 +00007862static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007863 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00007864 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
7865 outs() << " cmdsize " << ec.cmdsize;
7866 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
7867 outs() << " Incorrect size\n";
7868 else
7869 outs() << "\n";
7870 outs() << " cryptoff " << ec.cryptoff;
7871 if (ec.cryptoff > object_size)
7872 outs() << " (past end of file)\n";
7873 else
7874 outs() << "\n";
7875 outs() << " cryptsize " << ec.cryptsize;
7876 if (ec.cryptsize > object_size)
7877 outs() << " (past end of file)\n";
7878 else
7879 outs() << "\n";
7880 outs() << " cryptid " << ec.cryptid << "\n";
7881 outs() << " pad " << ec.pad << "\n";
7882}
7883
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007884static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
7885 const char *Ptr) {
7886 outs() << " cmd LC_LINKER_OPTION\n";
7887 outs() << " cmdsize " << lo.cmdsize;
7888 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
7889 outs() << " Incorrect size\n";
7890 else
7891 outs() << "\n";
7892 outs() << " count " << lo.count << "\n";
7893 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
7894 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
7895 uint32_t i = 0;
7896 while (left > 0) {
7897 while (*string == '\0' && left > 0) {
7898 string++;
7899 left--;
7900 }
7901 if (left > 0) {
7902 i++;
7903 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00007904 uint32_t NullPos = StringRef(string, left).find('\0');
7905 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007906 string += len;
7907 left -= len;
7908 }
7909 }
7910 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007911 outs() << " count " << lo.count << " does not match number of strings "
7912 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00007913}
7914
Kevin Enderbyb4b79312014-12-18 19:24:35 +00007915static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
7916 const char *Ptr) {
7917 outs() << " cmd LC_SUB_FRAMEWORK\n";
7918 outs() << " cmdsize " << sub.cmdsize;
7919 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
7920 outs() << " Incorrect size\n";
7921 else
7922 outs() << "\n";
7923 if (sub.umbrella < sub.cmdsize) {
7924 const char *P = Ptr + sub.umbrella;
7925 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
7926 } else {
7927 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
7928 }
7929}
7930
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00007931static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
7932 const char *Ptr) {
7933 outs() << " cmd LC_SUB_UMBRELLA\n";
7934 outs() << " cmdsize " << sub.cmdsize;
7935 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
7936 outs() << " Incorrect size\n";
7937 else
7938 outs() << "\n";
7939 if (sub.sub_umbrella < sub.cmdsize) {
7940 const char *P = Ptr + sub.sub_umbrella;
7941 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
7942 } else {
7943 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
7944 }
7945}
7946
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007947static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00007948 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007949 outs() << " cmd LC_SUB_LIBRARY\n";
7950 outs() << " cmdsize " << sub.cmdsize;
7951 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
7952 outs() << " Incorrect size\n";
7953 else
7954 outs() << "\n";
7955 if (sub.sub_library < sub.cmdsize) {
7956 const char *P = Ptr + sub.sub_library;
7957 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
7958 } else {
7959 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
7960 }
7961}
7962
Kevin Enderby186eac32014-12-19 21:06:24 +00007963static void PrintSubClientCommand(MachO::sub_client_command sub,
7964 const char *Ptr) {
7965 outs() << " cmd LC_SUB_CLIENT\n";
7966 outs() << " cmdsize " << sub.cmdsize;
7967 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
7968 outs() << " Incorrect size\n";
7969 else
7970 outs() << "\n";
7971 if (sub.client < sub.cmdsize) {
7972 const char *P = Ptr + sub.client;
7973 outs() << " client " << P << " (offset " << sub.client << ")\n";
7974 } else {
7975 outs() << " client ?(bad offset " << sub.client << ")\n";
7976 }
7977}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00007978
Kevin Enderby52e4ce42014-12-19 22:25:22 +00007979static void PrintRoutinesCommand(MachO::routines_command r) {
7980 outs() << " cmd LC_ROUTINES\n";
7981 outs() << " cmdsize " << r.cmdsize;
7982 if (r.cmdsize != sizeof(struct MachO::routines_command))
7983 outs() << " Incorrect size\n";
7984 else
7985 outs() << "\n";
7986 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
7987 outs() << " init_module " << r.init_module << "\n";
7988 outs() << " reserved1 " << r.reserved1 << "\n";
7989 outs() << " reserved2 " << r.reserved2 << "\n";
7990 outs() << " reserved3 " << r.reserved3 << "\n";
7991 outs() << " reserved4 " << r.reserved4 << "\n";
7992 outs() << " reserved5 " << r.reserved5 << "\n";
7993 outs() << " reserved6 " << r.reserved6 << "\n";
7994}
7995
7996static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
7997 outs() << " cmd LC_ROUTINES_64\n";
7998 outs() << " cmdsize " << r.cmdsize;
7999 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8000 outs() << " Incorrect size\n";
8001 else
8002 outs() << "\n";
8003 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8004 outs() << " init_module " << r.init_module << "\n";
8005 outs() << " reserved1 " << r.reserved1 << "\n";
8006 outs() << " reserved2 " << r.reserved2 << "\n";
8007 outs() << " reserved3 " << r.reserved3 << "\n";
8008 outs() << " reserved4 " << r.reserved4 << "\n";
8009 outs() << " reserved5 " << r.reserved5 << "\n";
8010 outs() << " reserved6 " << r.reserved6 << "\n";
8011}
8012
Kevin Enderby48ef5342014-12-23 22:56:39 +00008013static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8014 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8015 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8016 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8017 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8018 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8019 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8020 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8021 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8022 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8023 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8024 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8025 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8026 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8027 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8028 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8029 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8030 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8031 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8032 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8033 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8034 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8035}
8036
Kevin Enderby227df342014-12-23 23:43:59 +00008037static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008038 uint32_t f;
8039 outs() << "\t mmst_reg ";
8040 for (f = 0; f < 10; f++)
8041 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8042 outs() << "\n";
8043 outs() << "\t mmst_rsrv ";
8044 for (f = 0; f < 6; f++)
8045 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8046 outs() << "\n";
8047}
8048
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008049static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008050 uint32_t f;
8051 outs() << "\t xmm_reg ";
8052 for (f = 0; f < 16; f++)
8053 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8054 outs() << "\n";
8055}
8056
8057static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8058 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8059 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8060 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8061 outs() << " denorm " << fpu.fpu_fcw.denorm;
8062 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8063 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8064 outs() << " undfl " << fpu.fpu_fcw.undfl;
8065 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8066 outs() << "\t\t pc ";
8067 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8068 outs() << "FP_PREC_24B ";
8069 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8070 outs() << "FP_PREC_53B ";
8071 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8072 outs() << "FP_PREC_64B ";
8073 else
8074 outs() << fpu.fpu_fcw.pc << " ";
8075 outs() << "rc ";
8076 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8077 outs() << "FP_RND_NEAR ";
8078 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8079 outs() << "FP_RND_DOWN ";
8080 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8081 outs() << "FP_RND_UP ";
8082 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008083 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008084 outs() << "\n";
8085 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8086 outs() << " denorm " << fpu.fpu_fsw.denorm;
8087 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8088 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8089 outs() << " undfl " << fpu.fpu_fsw.undfl;
8090 outs() << " precis " << fpu.fpu_fsw.precis;
8091 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8092 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8093 outs() << " c0 " << fpu.fpu_fsw.c0;
8094 outs() << " c1 " << fpu.fpu_fsw.c1;
8095 outs() << " c2 " << fpu.fpu_fsw.c2;
8096 outs() << " tos " << fpu.fpu_fsw.tos;
8097 outs() << " c3 " << fpu.fpu_fsw.c3;
8098 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8099 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8100 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8101 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8102 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8103 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8104 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8105 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8106 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8107 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8108 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8109 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8110 outs() << "\n";
8111 outs() << "\t fpu_stmm0:\n";
8112 Print_mmst_reg(fpu.fpu_stmm0);
8113 outs() << "\t fpu_stmm1:\n";
8114 Print_mmst_reg(fpu.fpu_stmm1);
8115 outs() << "\t fpu_stmm2:\n";
8116 Print_mmst_reg(fpu.fpu_stmm2);
8117 outs() << "\t fpu_stmm3:\n";
8118 Print_mmst_reg(fpu.fpu_stmm3);
8119 outs() << "\t fpu_stmm4:\n";
8120 Print_mmst_reg(fpu.fpu_stmm4);
8121 outs() << "\t fpu_stmm5:\n";
8122 Print_mmst_reg(fpu.fpu_stmm5);
8123 outs() << "\t fpu_stmm6:\n";
8124 Print_mmst_reg(fpu.fpu_stmm6);
8125 outs() << "\t fpu_stmm7:\n";
8126 Print_mmst_reg(fpu.fpu_stmm7);
8127 outs() << "\t fpu_xmm0:\n";
8128 Print_xmm_reg(fpu.fpu_xmm0);
8129 outs() << "\t fpu_xmm1:\n";
8130 Print_xmm_reg(fpu.fpu_xmm1);
8131 outs() << "\t fpu_xmm2:\n";
8132 Print_xmm_reg(fpu.fpu_xmm2);
8133 outs() << "\t fpu_xmm3:\n";
8134 Print_xmm_reg(fpu.fpu_xmm3);
8135 outs() << "\t fpu_xmm4:\n";
8136 Print_xmm_reg(fpu.fpu_xmm4);
8137 outs() << "\t fpu_xmm5:\n";
8138 Print_xmm_reg(fpu.fpu_xmm5);
8139 outs() << "\t fpu_xmm6:\n";
8140 Print_xmm_reg(fpu.fpu_xmm6);
8141 outs() << "\t fpu_xmm7:\n";
8142 Print_xmm_reg(fpu.fpu_xmm7);
8143 outs() << "\t fpu_xmm8:\n";
8144 Print_xmm_reg(fpu.fpu_xmm8);
8145 outs() << "\t fpu_xmm9:\n";
8146 Print_xmm_reg(fpu.fpu_xmm9);
8147 outs() << "\t fpu_xmm10:\n";
8148 Print_xmm_reg(fpu.fpu_xmm10);
8149 outs() << "\t fpu_xmm11:\n";
8150 Print_xmm_reg(fpu.fpu_xmm11);
8151 outs() << "\t fpu_xmm12:\n";
8152 Print_xmm_reg(fpu.fpu_xmm12);
8153 outs() << "\t fpu_xmm13:\n";
8154 Print_xmm_reg(fpu.fpu_xmm13);
8155 outs() << "\t fpu_xmm14:\n";
8156 Print_xmm_reg(fpu.fpu_xmm14);
8157 outs() << "\t fpu_xmm15:\n";
8158 Print_xmm_reg(fpu.fpu_xmm15);
8159 outs() << "\t fpu_rsrv4:\n";
8160 for (uint32_t f = 0; f < 6; f++) {
8161 outs() << "\t ";
8162 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008163 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008164 outs() << "\n";
8165 }
8166 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8167 outs() << "\n";
8168}
8169
8170static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8171 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8172 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8173 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8174}
8175
8176static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8177 bool isLittleEndian, uint32_t cputype) {
8178 if (t.cmd == MachO::LC_THREAD)
8179 outs() << " cmd LC_THREAD\n";
8180 else if (t.cmd == MachO::LC_UNIXTHREAD)
8181 outs() << " cmd LC_UNIXTHREAD\n";
8182 else
8183 outs() << " cmd " << t.cmd << " (unknown)\n";
8184 outs() << " cmdsize " << t.cmdsize;
8185 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8186 outs() << " Incorrect size\n";
8187 else
8188 outs() << "\n";
8189
8190 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8191 const char *end = Ptr + t.cmdsize;
8192 uint32_t flavor, count, left;
8193 if (cputype == MachO::CPU_TYPE_X86_64) {
8194 while (begin < end) {
8195 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8196 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8197 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008198 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008199 flavor = 0;
8200 begin = end;
8201 }
8202 if (isLittleEndian != sys::IsLittleEndianHost)
8203 sys::swapByteOrder(flavor);
8204 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8205 memcpy((char *)&count, begin, sizeof(uint32_t));
8206 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008207 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008208 count = 0;
8209 begin = end;
8210 }
8211 if (isLittleEndian != sys::IsLittleEndianHost)
8212 sys::swapByteOrder(count);
8213 if (flavor == MachO::x86_THREAD_STATE64) {
8214 outs() << " flavor x86_THREAD_STATE64\n";
8215 if (count == MachO::x86_THREAD_STATE64_COUNT)
8216 outs() << " count x86_THREAD_STATE64_COUNT\n";
8217 else
8218 outs() << " count " << count
8219 << " (not x86_THREAD_STATE64_COUNT)\n";
8220 MachO::x86_thread_state64_t cpu64;
8221 left = end - begin;
8222 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8223 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8224 begin += sizeof(MachO::x86_thread_state64_t);
8225 } else {
8226 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8227 memcpy(&cpu64, begin, left);
8228 begin += left;
8229 }
8230 if (isLittleEndian != sys::IsLittleEndianHost)
8231 swapStruct(cpu64);
8232 Print_x86_thread_state64_t(cpu64);
8233 } else if (flavor == MachO::x86_THREAD_STATE) {
8234 outs() << " flavor x86_THREAD_STATE\n";
8235 if (count == MachO::x86_THREAD_STATE_COUNT)
8236 outs() << " count x86_THREAD_STATE_COUNT\n";
8237 else
8238 outs() << " count " << count
8239 << " (not x86_THREAD_STATE_COUNT)\n";
8240 struct MachO::x86_thread_state_t ts;
8241 left = end - begin;
8242 if (left >= sizeof(MachO::x86_thread_state_t)) {
8243 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8244 begin += sizeof(MachO::x86_thread_state_t);
8245 } else {
8246 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8247 memcpy(&ts, begin, left);
8248 begin += left;
8249 }
8250 if (isLittleEndian != sys::IsLittleEndianHost)
8251 swapStruct(ts);
8252 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8253 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8254 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8255 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8256 else
8257 outs() << "tsh.count " << ts.tsh.count
8258 << " (not x86_THREAD_STATE64_COUNT\n";
8259 Print_x86_thread_state64_t(ts.uts.ts64);
8260 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008261 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8262 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008263 }
8264 } else if (flavor == MachO::x86_FLOAT_STATE) {
8265 outs() << " flavor x86_FLOAT_STATE\n";
8266 if (count == MachO::x86_FLOAT_STATE_COUNT)
8267 outs() << " count x86_FLOAT_STATE_COUNT\n";
8268 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008269 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008270 struct MachO::x86_float_state_t fs;
8271 left = end - begin;
8272 if (left >= sizeof(MachO::x86_float_state_t)) {
8273 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8274 begin += sizeof(MachO::x86_float_state_t);
8275 } else {
8276 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8277 memcpy(&fs, begin, left);
8278 begin += left;
8279 }
8280 if (isLittleEndian != sys::IsLittleEndianHost)
8281 swapStruct(fs);
8282 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8283 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008284 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008285 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8286 else
8287 outs() << "fsh.count " << fs.fsh.count
8288 << " (not x86_FLOAT_STATE64_COUNT\n";
8289 Print_x86_float_state_t(fs.ufs.fs64);
8290 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008291 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8292 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008293 }
8294 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8295 outs() << " flavor x86_EXCEPTION_STATE\n";
8296 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8297 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8298 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008299 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008300 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8301 struct MachO::x86_exception_state_t es;
8302 left = end - begin;
8303 if (left >= sizeof(MachO::x86_exception_state_t)) {
8304 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8305 begin += sizeof(MachO::x86_exception_state_t);
8306 } else {
8307 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8308 memcpy(&es, begin, left);
8309 begin += left;
8310 }
8311 if (isLittleEndian != sys::IsLittleEndianHost)
8312 swapStruct(es);
8313 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8314 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008315 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008316 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8317 else
8318 outs() << "\t esh.count " << es.esh.count
8319 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8320 Print_x86_exception_state_t(es.ues.es64);
8321 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008322 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8323 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008324 }
8325 } else {
8326 outs() << " flavor " << flavor << " (unknown)\n";
8327 outs() << " count " << count << "\n";
8328 outs() << " state (unknown)\n";
8329 begin += count * sizeof(uint32_t);
8330 }
8331 }
8332 } else {
8333 while (begin < end) {
8334 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8335 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8336 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008337 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008338 flavor = 0;
8339 begin = end;
8340 }
8341 if (isLittleEndian != sys::IsLittleEndianHost)
8342 sys::swapByteOrder(flavor);
8343 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8344 memcpy((char *)&count, begin, sizeof(uint32_t));
8345 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008346 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008347 count = 0;
8348 begin = end;
8349 }
8350 if (isLittleEndian != sys::IsLittleEndianHost)
8351 sys::swapByteOrder(count);
8352 outs() << " flavor " << flavor << "\n";
8353 outs() << " count " << count << "\n";
8354 outs() << " state (Unknown cputype/cpusubtype)\n";
8355 begin += count * sizeof(uint32_t);
8356 }
8357 }
8358}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008359
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008360static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8361 if (dl.cmd == MachO::LC_ID_DYLIB)
8362 outs() << " cmd LC_ID_DYLIB\n";
8363 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8364 outs() << " cmd LC_LOAD_DYLIB\n";
8365 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8366 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8367 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8368 outs() << " cmd LC_REEXPORT_DYLIB\n";
8369 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8370 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8371 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8372 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8373 else
8374 outs() << " cmd " << dl.cmd << " (unknown)\n";
8375 outs() << " cmdsize " << dl.cmdsize;
8376 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8377 outs() << " Incorrect size\n";
8378 else
8379 outs() << "\n";
8380 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008381 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008382 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8383 } else {
8384 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8385 }
8386 outs() << " time stamp " << dl.dylib.timestamp << " ";
8387 time_t t = dl.dylib.timestamp;
8388 outs() << ctime(&t);
8389 outs() << " current version ";
8390 if (dl.dylib.current_version == 0xffffffff)
8391 outs() << "n/a\n";
8392 else
8393 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8394 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8395 << (dl.dylib.current_version & 0xff) << "\n";
8396 outs() << "compatibility version ";
8397 if (dl.dylib.compatibility_version == 0xffffffff)
8398 outs() << "n/a\n";
8399 else
8400 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8401 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8402 << (dl.dylib.compatibility_version & 0xff) << "\n";
8403}
8404
8405static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8406 uint32_t object_size) {
8407 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008408 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008409 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8410 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8411 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8412 outs() << " cmd LC_FUNCTION_STARTS\n";
8413 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8414 outs() << " cmd LC_DATA_IN_CODE\n";
8415 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8416 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8417 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8418 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8419 else
8420 outs() << " cmd " << ld.cmd << " (?)\n";
8421 outs() << " cmdsize " << ld.cmdsize;
8422 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8423 outs() << " Incorrect size\n";
8424 else
8425 outs() << "\n";
8426 outs() << " dataoff " << ld.dataoff;
8427 if (ld.dataoff > object_size)
8428 outs() << " (past end of file)\n";
8429 else
8430 outs() << "\n";
8431 outs() << " datasize " << ld.datasize;
8432 uint64_t big_size = ld.dataoff;
8433 big_size += ld.datasize;
8434 if (big_size > object_size)
8435 outs() << " (past end of file)\n";
8436 else
8437 outs() << "\n";
8438}
8439
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008440static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8441 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008442 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008443 unsigned Index = 0;
8444 for (const auto &Command : Obj->load_commands()) {
8445 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008446 if (Command.C.cmd == MachO::LC_SEGMENT) {
8447 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8448 const char *sg_segname = SLC.segname;
8449 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8450 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8451 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8452 verbose);
8453 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008454 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008455 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8456 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8457 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8458 }
8459 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8460 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8461 const char *sg_segname = SLC_64.segname;
8462 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8463 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8464 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8465 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8466 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8467 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8468 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8469 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8470 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8471 sg_segname, filetype, Buf.size(), verbose);
8472 }
8473 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8474 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008475 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008476 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8477 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8478 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008479 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8480 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008481 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8482 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8483 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8484 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8485 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8486 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8487 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8488 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8489 PrintDyldLoadCommand(Dyld, Command.Ptr);
8490 } else if (Command.C.cmd == MachO::LC_UUID) {
8491 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8492 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008493 } else if (Command.C.cmd == MachO::LC_RPATH) {
8494 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8495 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008496 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008497 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8498 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8499 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008500 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8501 PrintVersionMinLoadCommand(Vd);
8502 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8503 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8504 PrintSourceVersionCommand(Sd);
8505 } else if (Command.C.cmd == MachO::LC_MAIN) {
8506 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8507 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008508 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008509 MachO::encryption_info_command Ei =
8510 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008511 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008512 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008513 MachO::encryption_info_command_64 Ei =
8514 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008515 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008516 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008517 MachO::linker_option_command Lo =
8518 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008519 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008520 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8521 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8522 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008523 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8524 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8525 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008526 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8527 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8528 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008529 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8530 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8531 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008532 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8533 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8534 PrintRoutinesCommand(Rc);
8535 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8536 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8537 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008538 } else if (Command.C.cmd == MachO::LC_THREAD ||
8539 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8540 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8541 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008542 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8543 Command.C.cmd == MachO::LC_ID_DYLIB ||
8544 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8545 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8546 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8547 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008548 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8549 PrintDylibCommand(Dl, Command.Ptr);
8550 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8551 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8552 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8553 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8554 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8555 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8556 MachO::linkedit_data_command Ld =
8557 Obj->getLinkeditDataLoadCommand(Command);
8558 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008559 } else {
8560 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8561 << ")\n";
8562 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8563 // TODO: get and print the raw bytes of the load command.
8564 }
8565 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00008566 }
8567}
8568
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008569static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008570 if (Obj->is64Bit()) {
8571 MachO::mach_header_64 H_64;
8572 H_64 = Obj->getHeader64();
8573 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
8574 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
8575 } else {
8576 MachO::mach_header H;
8577 H = Obj->getHeader();
8578 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
8579 H.sizeofcmds, H.flags, verbose);
8580 }
8581}
8582
8583void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
8584 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008585 PrintMachHeader(file, !NonVerbose);
8586}
8587
8588void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
8589 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00008590 uint32_t filetype = 0;
8591 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00008592 if (file->is64Bit()) {
8593 MachO::mach_header_64 H_64;
8594 H_64 = file->getHeader64();
8595 filetype = H_64.filetype;
8596 cputype = H_64.cputype;
8597 } else {
8598 MachO::mach_header H;
8599 H = file->getHeader();
8600 filetype = H.filetype;
8601 cputype = H.cputype;
8602 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008603 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008604}
Nick Kledzikd04bc352014-08-30 00:20:14 +00008605
8606//===----------------------------------------------------------------------===//
8607// export trie dumping
8608//===----------------------------------------------------------------------===//
8609
8610void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008611 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
8612 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008613 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
8614 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
8615 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8616 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
8617 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
8618 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
8619 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
8620 if (ReExport)
8621 outs() << "[re-export] ";
8622 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008623 outs() << format("0x%08llX ",
8624 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008625 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00008626 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008627 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00008628 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008629 if (WeakDef) {
8630 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008631 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008632 }
8633 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008634 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008635 outs() << ", ";
8636 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008637 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008638 }
8639 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008640 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008641 outs() << ", ";
8642 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008643 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008644 }
8645 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008646 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00008647 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008648 outs() << format("resolver=0x%08llX", Entry.other());
8649 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00008650 }
8651 outs() << "]";
8652 }
8653 if (ReExport) {
8654 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008655 int Ordinal = Entry.other() - 1;
8656 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
8657 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00008658 outs() << " (from " << DylibName << ")";
8659 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00008660 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00008661 }
8662 outs() << "\n";
8663 }
8664}
Nick Kledzikac431442014-09-12 21:34:15 +00008665
Nick Kledzikac431442014-09-12 21:34:15 +00008666//===----------------------------------------------------------------------===//
8667// rebase table dumping
8668//===----------------------------------------------------------------------===//
8669
8670namespace {
8671class SegInfo {
8672public:
8673 SegInfo(const object::MachOObjectFile *Obj);
8674
8675 StringRef segmentName(uint32_t SegIndex);
8676 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
8677 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008678 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00008679
8680private:
8681 struct SectionInfo {
8682 uint64_t Address;
8683 uint64_t Size;
8684 StringRef SectionName;
8685 StringRef SegmentName;
8686 uint64_t OffsetInSegment;
8687 uint64_t SegmentStartAddress;
8688 uint32_t SegmentIndex;
8689 };
8690 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
8691 SmallVector<SectionInfo, 32> Sections;
8692};
8693}
8694
8695SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
8696 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00008697 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00008698 StringRef CurSegName;
8699 uint64_t CurSegAddress;
8700 for (const SectionRef &Section : Obj->sections()) {
8701 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00008702 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00008703 Info.Address = Section.getAddress();
8704 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00008705 Info.SegmentName =
8706 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
8707 if (!Info.SegmentName.equals(CurSegName)) {
8708 ++CurSegIndex;
8709 CurSegName = Info.SegmentName;
8710 CurSegAddress = Info.Address;
8711 }
8712 Info.SegmentIndex = CurSegIndex - 1;
8713 Info.OffsetInSegment = Info.Address - CurSegAddress;
8714 Info.SegmentStartAddress = CurSegAddress;
8715 Sections.push_back(Info);
8716 }
8717}
8718
8719StringRef SegInfo::segmentName(uint32_t SegIndex) {
8720 for (const SectionInfo &SI : Sections) {
8721 if (SI.SegmentIndex == SegIndex)
8722 return SI.SegmentName;
8723 }
8724 llvm_unreachable("invalid segIndex");
8725}
8726
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008727bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
8728 uint64_t OffsetInSeg) {
8729 for (const SectionInfo &SI : Sections) {
8730 if (SI.SegmentIndex != SegIndex)
8731 continue;
8732 if (SI.OffsetInSegment > OffsetInSeg)
8733 continue;
8734 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8735 continue;
8736 return true;
8737 }
8738 return false;
8739}
8740
Nick Kledzikac431442014-09-12 21:34:15 +00008741const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
8742 uint64_t OffsetInSeg) {
8743 for (const SectionInfo &SI : Sections) {
8744 if (SI.SegmentIndex != SegIndex)
8745 continue;
8746 if (SI.OffsetInSegment > OffsetInSeg)
8747 continue;
8748 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
8749 continue;
8750 return SI;
8751 }
8752 llvm_unreachable("segIndex and offset not in any section");
8753}
8754
8755StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
8756 return findSection(SegIndex, OffsetInSeg).SectionName;
8757}
8758
8759uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
8760 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
8761 return SI.SegmentStartAddress + OffsetInSeg;
8762}
8763
8764void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
8765 // Build table of sections so names can used in final output.
8766 SegInfo sectionTable(Obj);
8767
8768 outs() << "segment section address type\n";
8769 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
8770 uint32_t SegIndex = Entry.segmentIndex();
8771 uint64_t OffsetInSeg = Entry.segmentOffset();
8772 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8773 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8774 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8775
8776 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008777 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
8778 SegmentName.str().c_str(), SectionName.str().c_str(),
8779 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00008780 }
8781}
Nick Kledzik56ebef42014-09-16 01:41:51 +00008782
8783static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
8784 StringRef DylibName;
8785 switch (Ordinal) {
8786 case MachO::BIND_SPECIAL_DYLIB_SELF:
8787 return "this-image";
8788 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
8789 return "main-executable";
8790 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
8791 return "flat-namespace";
8792 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00008793 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008794 std::error_code EC =
8795 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00008796 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00008797 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00008798 return DylibName;
8799 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00008800 }
Nick Kledzikabd29872014-09-16 22:03:13 +00008801 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008802}
8803
8804//===----------------------------------------------------------------------===//
8805// bind table dumping
8806//===----------------------------------------------------------------------===//
8807
8808void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
8809 // Build table of sections so names can used in final output.
8810 SegInfo sectionTable(Obj);
8811
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008812 outs() << "segment section address type "
8813 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008814 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
8815 uint32_t SegIndex = Entry.segmentIndex();
8816 uint64_t OffsetInSeg = Entry.segmentOffset();
8817 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8818 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8819 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8820
8821 // Table lines look like:
8822 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008823 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00008824 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008825 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008826 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008827 << left_justify(SectionName, 18) << " "
8828 << format_hex(Address, 10, true) << " "
8829 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008830 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008831 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008832 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008833 }
8834}
8835
8836//===----------------------------------------------------------------------===//
8837// lazy bind table dumping
8838//===----------------------------------------------------------------------===//
8839
8840void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
8841 // Build table of sections so names can used in final output.
8842 SegInfo sectionTable(Obj);
8843
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008844 outs() << "segment section address "
8845 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008846 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
8847 uint32_t SegIndex = Entry.segmentIndex();
8848 uint64_t OffsetInSeg = Entry.segmentOffset();
8849 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8850 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8851 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8852
8853 // Table lines look like:
8854 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008855 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008856 << left_justify(SectionName, 18) << " "
8857 << format_hex(Address, 10, true) << " "
8858 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008859 << Entry.symbolName() << "\n";
8860 }
8861}
8862
Nick Kledzik56ebef42014-09-16 01:41:51 +00008863//===----------------------------------------------------------------------===//
8864// weak bind table dumping
8865//===----------------------------------------------------------------------===//
8866
8867void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
8868 // Build table of sections so names can used in final output.
8869 SegInfo sectionTable(Obj);
8870
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008871 outs() << "segment section address "
8872 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008873 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
8874 // Strong symbols don't have a location to update.
8875 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008876 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00008877 << Entry.symbolName() << "\n";
8878 continue;
8879 }
8880 uint32_t SegIndex = Entry.segmentIndex();
8881 uint64_t OffsetInSeg = Entry.segmentOffset();
8882 StringRef SegmentName = sectionTable.segmentName(SegIndex);
8883 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
8884 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8885
8886 // Table lines look like:
8887 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008888 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00008889 << left_justify(SectionName, 18) << " "
8890 << format_hex(Address, 10, true) << " "
8891 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008892 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
8893 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00008894 }
8895}
8896
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008897// get_dyld_bind_info_symbolname() is used for disassembly and passed an
8898// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
8899// information for that address. If the address is found its binding symbol
8900// name is returned. If not nullptr is returned.
8901static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
8902 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00008903 if (info->bindtable == nullptr) {
8904 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008905 SegInfo sectionTable(info->O);
8906 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
8907 uint32_t SegIndex = Entry.segmentIndex();
8908 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00008909 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
8910 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008911 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
8912 const char *SymbolName = nullptr;
8913 StringRef name = Entry.symbolName();
8914 if (!name.empty())
8915 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00008916 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008917 }
8918 }
Kevin Enderby078be602014-10-23 19:53:12 +00008919 for (bind_table_iterator BI = info->bindtable->begin(),
8920 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00008921 BI != BE; ++BI) {
8922 uint64_t Address = BI->first;
8923 if (ReferenceValue == Address) {
8924 const char *SymbolName = BI->second;
8925 return SymbolName;
8926 }
8927 }
8928 return nullptr;
8929}